{"text": "# -*- coding: utf-8 -*-\n# Licensed under a 3-clause BSD style license - see LICENSE.rst\nfrom __future__ import (\n absolute_import,\n division,\n print_function,\n unicode_literals,\n)\nimport numpy as np\nfrom .extern.validator import (\n validate_scalar,\n validate_array,\n validate_physical_type,\n)\n\nfrom .utils import trapz_loglog\nfrom .model_utils import memoize\n\nfrom astropy.extern import six\nfrom collections import OrderedDict\nimport os\nfrom astropy.utils.data import get_pkg_data_filename\nimport warnings\nimport logging\n\n# Constants and units\nfrom astropy import units as u\n\n# import constant values from astropy.constants\nfrom astropy.constants import c, m_e, hbar, sigma_sb, e, m_p, alpha\n\n__all__ = [\n \"Synchrotron\",\n \"InverseCompton\",\n \"PionDecay\",\n \"Bremsstrahlung\",\n \"PionDecayKelner06\",\n]\n\n# Get a new logger to avoid changing the level of the astropy logger\nlog = logging.getLogger(\"naima.radiative\")\nlog.setLevel(logging.INFO)\n\ne = e.gauss\n\nmec2 = (m_e * c ** 2).cgs\nmec2_unit = u.Unit(mec2)\n\nar = (4 * sigma_sb / c).to(\"erg/(cm3 K4)\")\nr0 = (e ** 2 / mec2).to(\"cm\")\n\n\ndef _validate_ene(ene):\n from astropy.table import Table\n\n if isinstance(ene, dict) or isinstance(ene, Table):\n try:\n ene = validate_array(\n \"energy\", u.Quantity(ene[\"energy\"]), physical_type=\"energy\"\n )\n except KeyError:\n raise TypeError(\"Table or dict does not have 'energy' column\")\n else:\n if not isinstance(ene, u.Quantity):\n ene = u.Quantity(ene)\n validate_physical_type(\"energy\", ene, physical_type=\"energy\")\n\n return ene\n\n\nclass BaseRadiative(object):\n \"\"\"Base class for radiative models\n\n This class implements the flux, sed methods and subclasses must implement\n the spectrum method which returns the intrinsic differential spectrum.\n \"\"\"\n\n def __init__(self, particle_distribution):\n self.particle_distribution = particle_distribution\n try:\n # Check first for the amplitude attribute, which will be present if\n # the particle distribution is a function from naima.models\n pd = self.particle_distribution.amplitude\n validate_physical_type(\n \"Particle distribution\",\n pd,\n physical_type=\"differential energy\",\n )\n except (AttributeError, TypeError):\n # otherwise check the output\n pd = self.particle_distribution([0.1, 1, 10] * u.TeV)\n validate_physical_type(\n \"Particle distribution\",\n pd,\n physical_type=\"differential energy\",\n )\n\n @memoize\n def flux(self, photon_energy, distance=1 * u.kpc):\n \"\"\"Differential flux at a given distance from the source.\n\n Parameters\n ----------\n photon_energy : :class:`~astropy.units.Quantity` float or array\n Photon energy array.\n\n distance : :class:`~astropy.units.Quantity` float, optional\n Distance to the source. If set to 0, the intrinsic differential\n luminosity will be returned. Default is 1 kpc.\n \"\"\"\n\n spec = self._spectrum(photon_energy)\n\n if distance != 0:\n distance = validate_scalar(\n \"distance\", distance, physical_type=\"length\"\n )\n spec /= 4 * np.pi * distance.to(\"cm\") ** 2\n out_unit = \"1/(s cm2 eV)\"\n else:\n out_unit = \"1/(s eV)\"\n\n return spec.to(out_unit)\n\n def sed(self, photon_energy, distance=1 * u.kpc):\n \"\"\"Spectral energy distribution at a given distance from the source.\n\n Parameters\n ----------\n photon_energy : :class:`~astropy.units.Quantity` float or array\n Photon energy array.\n\n distance : :class:`~astropy.units.Quantity` float, optional\n Distance to the source. If set to 0, the intrinsic luminosity will\n be returned. Default is 1 kpc.\n \"\"\"\n if distance != 0:\n out_unit = \"erg/(cm2 s)\"\n else:\n out_unit = \"erg/s\"\n\n photon_energy = _validate_ene(photon_energy)\n\n sed = (self.flux(photon_energy, distance) * photon_energy ** 2.0).to(\n out_unit\n )\n\n return sed\n\n\nclass BaseElectron(BaseRadiative):\n \"\"\"Implements gam and nelec properties in addition to the BaseRadiative methods\n \"\"\"\n\n def __init__(self, particle_distribution):\n super(BaseElectron, self).__init__(particle_distribution)\n self.param_names = [\"Eemin\", \"Eemax\", \"nEed\"]\n self._memoize = True\n self._cache = {}\n self._queue = []\n\n @property\n def _gam(self):\n \"\"\" Lorentz factor array\n \"\"\"\n log10gmin = np.log10(self.Eemin / mec2).value\n log10gmax = np.log10(self.Eemax / mec2).value\n return np.logspace(\n log10gmin, log10gmax, int(self.nEed * (log10gmax - log10gmin))\n )\n\n @property\n def _nelec(self):\n \"\"\" Particles per unit lorentz factor\n \"\"\"\n pd = self.particle_distribution(self._gam * mec2)\n return pd.to(1 / mec2_unit).value\n\n @property\n def We(self):\n \"\"\" Total energy in electrons used for the radiative calculation\n \"\"\"\n We = trapz_loglog(self._gam * self._nelec, self._gam * mec2)\n return We\n\n def compute_We(self, Eemin=None, Eemax=None):\n \"\"\" Total energy in electrons between energies Eemin and Eemax\n\n Parameters\n ----------\n Eemin : :class:`~astropy.units.Quantity` float, optional\n Minimum electron energy for energy content calculation.\n\n Eemax : :class:`~astropy.units.Quantity` float, optional\n Maximum electron energy for energy content calculation.\n \"\"\"\n if Eemin is None and Eemax is None:\n We = self.We\n else:\n if Eemax is None:\n Eemax = self.Eemax\n if Eemin is None:\n Eemin = self.Eemin\n\n log10gmin = np.log10(Eemin / mec2).value\n log10gmax = np.log10(Eemax / mec2).value\n gam = np.logspace(\n log10gmin, log10gmax, int(self.nEed * (log10gmax - log10gmin))\n )\n nelec = (\n self.particle_distribution(gam * mec2).to(1 / mec2_unit).value\n )\n We = trapz_loglog(gam * nelec, gam * mec2)\n\n return We\n\n def set_We(self, We, Eemin=None, Eemax=None, amplitude_name=None):\n \"\"\" Normalize particle distribution so that the total energy in electrons\n between Eemin and Eemax is We\n\n Parameters\n ----------\n We : :class:`~astropy.units.Quantity` float\n Desired energy in electrons.\n\n Eemin : :class:`~astropy.units.Quantity` float, optional\n Minimum electron energy for energy content calculation.\n\n Eemax : :class:`~astropy.units.Quantity` float, optional\n Maximum electron energy for energy content calculation.\n\n amplitude_name : str, optional\n Name of the amplitude parameter of the particle distribution. It\n must be accesible as an attribute of the distribution function.\n Defaults to ``amplitude``.\n \"\"\"\n\n We = validate_scalar(\"We\", We, physical_type=\"energy\")\n oldWe = self.compute_We(Eemin=Eemin, Eemax=Eemax)\n\n if amplitude_name is None:\n try:\n self.particle_distribution.amplitude *= (\n We / oldWe\n ).decompose()\n except AttributeError:\n log.error(\n \"The particle distribution does not have an attribute\"\n \" called amplitude to modify its normalization: you can\"\n \" set the name with the amplitude_name parameter of set_We\"\n )\n else:\n oldampl = getattr(self.particle_distribution, amplitude_name)\n setattr(\n self.particle_distribution,\n amplitude_name,\n oldampl * (We / oldWe).decompose(),\n )\n\n\nclass Synchrotron(BaseElectron):\n \"\"\"Synchrotron emission from an electron population.\n\n This class uses the approximation of the synchrotron emissivity in a\n random magnetic field of Aharonian, Kelner, and Prosekin 2010, PhysRev D\n 82, 3002 (`arXiv:1006.1045 `_).\n\n Parameters\n ----------\n particle_distribution : function\n Particle distribution function, taking electron energies as a\n `~astropy.units.Quantity` array or float, and returning the particle\n energy density in units of number of electrons per unit energy as a\n `~astropy.units.Quantity` array or float.\n\n B : :class:`~astropy.units.Quantity` float instance, optional\n Isotropic magnetic field strength. Default: equipartition\n with CMB (3.24e-6 G)\n\n Other parameters\n ----------------\n Eemin : :class:`~astropy.units.Quantity` float instance, optional\n Minimum electron energy for the electron distribution. Default is 1\n GeV.\n\n Eemax : :class:`~astropy.units.Quantity` float instance, optional\n Maximum electron energy for the electron distribution. Default is 510\n TeV.\n\n nEed : scalar\n Number of points per decade in energy for the electron energy and\n distribution arrays. Default is 100.\n \"\"\"\n\n def __init__(self, particle_distribution, B=3.24e-6 * u.G, **kwargs):\n super(Synchrotron, self).__init__(particle_distribution)\n self.B = validate_scalar(\"B\", B, physical_type=\"magnetic flux density\")\n self.Eemin = 1 * u.GeV\n self.Eemax = 1e9 * mec2\n self.nEed = 100\n self.param_names += [\"B\"]\n self.__dict__.update(**kwargs)\n\n def _spectrum(self, photon_energy):\n \"\"\"Compute intrinsic synchrotron differential spectrum for energies in\n ``photon_energy``\n\n Compute synchrotron for random magnetic field according to\n approximation of Aharonian, Kelner, and Prosekin 2010, PhysRev D 82,\n 3002 (`arXiv:1006.1045 `_).\n\n Parameters\n ----------\n photon_energy : :class:`~astropy.units.Quantity` instance\n Photon energy array.\n \"\"\"\n\n outspecene = _validate_ene(photon_energy)\n\n from scipy.special import cbrt\n\n def Gtilde(x):\n \"\"\"\n AKP10 Eq. D7\n\n Factor ~2 performance gain in using cbrt(x)**n vs x**(n/3.)\n Invoking crbt only once reduced time by ~40%\n \"\"\"\n cb = cbrt(x)\n gt1 = 1.808 * cb / np.sqrt(1 + 3.4 * cb ** 2.0)\n gt2 = 1 + 2.210 * cb ** 2.0 + 0.347 * cb ** 4.0\n gt3 = 1 + 1.353 * cb ** 2.0 + 0.217 * cb ** 4.0\n return gt1 * (gt2 / gt3) * np.exp(-x)\n\n log.debug(\"calc_sy: Starting synchrotron computation with AKB2010...\")\n\n # strip units, ensuring correct conversion\n # astropy units do not convert correctly for gyroradius calculation\n # when using cgs (SI is fine, see\n # https://github.com/astropy/astropy/issues/1687)\n CS1_0 = np.sqrt(3) * e.value ** 3 * self.B.to(\"G\").value\n CS1_1 = (\n 2\n * np.pi\n * m_e.cgs.value\n * c.cgs.value ** 2\n * hbar.cgs.value\n * outspecene.to(\"erg\").value\n )\n CS1 = CS1_0 / CS1_1\n\n # Critical energy, erg\n Ec = (\n 3\n * e.value\n * hbar.cgs.value\n * self.B.to(\"G\").value\n * self._gam ** 2\n )\n Ec /= 2 * (m_e * c).cgs.value\n\n EgEc = outspecene.to(\"erg\").value / np.vstack(Ec)\n dNdE = CS1 * Gtilde(EgEc)\n # return units\n spec = (\n trapz_loglog(np.vstack(self._nelec) * dNdE, self._gam, axis=0)\n / u.s\n / u.erg\n )\n spec = spec.to(\"1/(s eV)\")\n\n return spec\n\n\ndef G12(x, a):\n \"\"\"\n Eqs 20, 24, 25 of Khangulyan et al (2014)\n \"\"\"\n alpha, a, beta, b = a\n pi26 = np.pi ** 2 / 6.0\n G = (pi26 + x) * np.exp(-x)\n tmp = 1 + b * x ** beta\n g = 1.0 / (a * x ** alpha / tmp + 1.0)\n return G * g\n\n\ndef G34(x, a):\n \"\"\"\n Eqs 20, 24, 25 of Khangulyan et al (2014)\n \"\"\"\n alpha, a, beta, b, c = a\n pi26 = np.pi ** 2 / 6.0\n tmp = (1 + c * x) / (1 + pi26 * c * x)\n G = pi26 * tmp * np.exp(-x)\n tmp = 1 + b * x ** beta\n g = 1.0 / (a * x ** alpha / tmp + 1.0)\n return G * g\n\n\nclass InverseCompton(BaseElectron):\n \"\"\"Inverse Compton emission from an electron population.\n\n If you use this class in your research, please consult and cite\n `Khangulyan, D., Aharonian, F.A., & Kelner, S.R. 2014, Astrophysical\n Journal, 783, 100 `_\n\n Parameters\n ----------\n particle_distribution : function\n Particle distribution function, taking electron energies as a\n `~astropy.units.Quantity` array or float, and returning the particle\n energy density in units of number of electrons per unit energy as a\n `~astropy.units.Quantity` array or float.\n\n seed_photon_fields : string or iterable of strings (optional)\n A list of gray-body or non-thermal seed photon fields to use for IC\n calculation. Each of the items of the iterable can be either:\n\n * A string equal to ``CMB`` (default), ``NIR``, or ``FIR``, for which\n radiation fields with temperatures of 2.72 K, 30 K, and 3000 K, and\n energy densities of 0.261, 0.5, and 1 eV/cm³ will be used (these are\n the GALPROP values for a location at a distance of 6.5 kpc from the\n galactic center).\n\n * A list of length three (isotropic source) or four (anisotropic\n source) composed of:\n\n 1. A name for the seed photon field.\n 2. Its temperature (thermal source) or energy (monochromatic or\n non-thermal source) as a :class:`~astropy.units.Quantity`\n instance.\n 3. Its photon field energy density as a\n :class:`~astropy.units.Quantity` instance.\n 4. Optional: The angle between the seed photon direction and the\n scattered photon direction as a :class:`~astropy.units.Quantity`\n float instance.\n\n Other parameters\n ----------------\n Eemin : :class:`~astropy.units.Quantity` float instance, optional\n Minimum electron energy for the electron distribution. Default is 1\n GeV.\n\n Eemax : :class:`~astropy.units.Quantity` float instance, optional\n Maximum electron energy for the electron distribution. Default is 510\n TeV.\n\n nEed : scalar\n Number of points per decade in energy for the electron energy and\n distribution arrays. Default is 300.\n \"\"\"\n\n def __init__(\n self, particle_distribution, seed_photon_fields=[\"CMB\"], **kwargs\n ):\n super(InverseCompton, self).__init__(particle_distribution)\n self.seed_photon_fields = self._process_input_seed(seed_photon_fields)\n self.Eemin = 1 * u.GeV\n self.Eemax = 1e9 * mec2\n self.nEed = 100\n self.param_names += [\"seed_photon_fields\"]\n self.__dict__.update(**kwargs)\n\n @staticmethod\n def _process_input_seed(seed_photon_fields):\n \"\"\"\n take input list of seed_photon_fields and fix them into usable format\n \"\"\"\n\n Tcmb = 2.72548 * u.K # 0.00057 K\n Tfir = 30 * u.K\n ufir = 0.5 * u.eV / u.cm ** 3\n Tnir = 3000 * u.K\n unir = 1.0 * u.eV / u.cm ** 3\n\n # Allow for seed_photon_fields definitions of the type 'CMB-NIR-FIR' or\n # 'CMB'\n if type(seed_photon_fields) != list:\n seed_photon_fields = seed_photon_fields.split(\"-\")\n\n result = OrderedDict()\n\n for idx, inseed in enumerate(seed_photon_fields):\n seed = {}\n if isinstance(inseed, six.string_types):\n name = inseed\n seed[\"type\"] = \"thermal\"\n if inseed == \"CMB\":\n seed[\"T\"] = Tcmb\n seed[\"u\"] = ar * Tcmb ** 4\n seed[\"isotropic\"] = True\n elif inseed == \"FIR\":\n seed[\"T\"] = Tfir\n seed[\"u\"] = ufir\n seed[\"isotropic\"] = True\n elif inseed == \"NIR\":\n seed[\"T\"] = Tnir\n seed[\"u\"] = unir\n seed[\"isotropic\"] = True\n else:\n log.warning(\n \"Will not use seed {0} because it is not \"\n \"CMB, FIR or NIR\".format(inseed)\n )\n raise TypeError\n elif type(inseed) == list and (\n len(inseed) == 3 or len(inseed) == 4\n ):\n isotropic = len(inseed) == 3\n\n if isotropic:\n name, T, uu = inseed\n seed[\"isotropic\"] = True\n else:\n name, T, uu, theta = inseed\n seed[\"isotropic\"] = False\n seed[\"theta\"] = validate_scalar(\n \"{0}-theta\".format(name), theta, physical_type=\"angle\"\n )\n\n thermal = T.unit.physical_type == \"temperature\"\n\n if thermal:\n seed[\"type\"] = \"thermal\"\n validate_scalar(\n \"{0}-T\".format(name),\n T,\n domain=\"positive\",\n physical_type=\"temperature\",\n )\n seed[\"T\"] = T\n if uu == 0:\n seed[\"u\"] = ar * T ** 4\n else:\n # pressure has same physical type as energy density\n validate_scalar(\n \"{0}-u\".format(name),\n uu,\n domain=\"positive\",\n physical_type=\"pressure\",\n )\n seed[\"u\"] = uu\n else:\n seed[\"type\"] = \"array\"\n # Ensure everything is in arrays\n T = u.Quantity((T,)).flatten()\n uu = u.Quantity((uu,)).flatten()\n\n seed[\"energy\"] = validate_array(\n \"{0}-energy\".format(name),\n T,\n domain=\"positive\",\n physical_type=\"energy\",\n )\n\n if np.isscalar(seed[\"energy\"]) or seed[\"energy\"].size == 1:\n seed[\"photon_density\"] = validate_scalar(\n \"{0}-density\".format(name),\n uu,\n domain=\"positive\",\n physical_type=\"pressure\",\n )\n else:\n if uu.unit.physical_type == \"pressure\":\n uu /= seed[\"energy\"] ** 2\n seed[\"photon_density\"] = validate_array(\n \"{0}-density\".format(name),\n uu,\n domain=\"positive\",\n physical_type=\"differential number density\",\n )\n else:\n raise TypeError(\n \"Unable to process seed photon\"\n \" field: {0}\".format(inseed)\n )\n\n result[name] = seed\n\n return result\n\n @staticmethod\n def _iso_ic_on_planck(\n electron_energy, soft_photon_temperature, gamma_energy\n ):\n \"\"\"\n IC cross-section for isotropic interaction with a blackbody photon\n spectrum following Eq. 14 of Khangulyan, Aharonian, and Kelner 2014,\n ApJ 783, 100 (`arXiv:1310.7971 `_).\n\n `electron_energy` and `gamma_energy` are in units of m_ec^2\n `soft_photon_temperature` is in units of K\n \"\"\"\n Ktomec2 = 1.6863699549e-10\n soft_photon_temperature *= Ktomec2\n\n gamma_energy = np.vstack(gamma_energy)\n # Parameters from Eqs 26, 27\n a3 = [0.606, 0.443, 1.481, 0.540, 0.319]\n a4 = [0.461, 0.726, 1.457, 0.382, 6.620]\n z = gamma_energy / electron_energy\n x = z / (1 - z) / (4.0 * electron_energy * soft_photon_temperature)\n # Eq. 14\n cross_section = z ** 2 / (2 * (1 - z)) * G34(x, a3) + G34(x, a4)\n tmp = (soft_photon_temperature / electron_energy) ** 2\n # r0 = (e**2 / m_e / c**2).to('cm')\n # (2 * r0 ** 2 * m_e ** 3 * c ** 4 / (pi * hbar ** 3)).cgs\n tmp *= 2.6318735743809104e16\n cross_section = tmp * cross_section\n cc = (gamma_energy < electron_energy) * (electron_energy > 1)\n return np.where(cc, cross_section, np.zeros_like(cross_section))\n\n @staticmethod\n def _ani_ic_on_planck(\n electron_energy, soft_photon_temperature, gamma_energy, theta\n ):\n \"\"\"\n IC cross-section for anisotropic interaction with a blackbody photon\n spectrum following Eq. 11 of Khangulyan, Aharonian, and Kelner 2014,\n ApJ 783, 100 (`arXiv:1310.7971 `_).\n\n `electron_energy` and `gamma_energy` are in units of m_ec^2\n `soft_photon_temperature` is in units of K\n `theta` is in radians\n \"\"\"\n Ktomec2 = 1.6863699549e-10\n soft_photon_temperature *= Ktomec2\n\n gamma_energy = gamma_energy[:, None]\n # Parameters from Eqs 21, 22\n a1 = [0.857, 0.153, 1.840, 0.254]\n a2 = [0.691, 1.330, 1.668, 0.534]\n z = gamma_energy / electron_energy\n ttheta = (\n 2.0\n * electron_energy\n * soft_photon_temperature\n * (1.0 - np.cos(theta))\n )\n x = z / (1 - z) / ttheta\n # Eq. 11\n cross_section = z ** 2 / (2 * (1 - z)) * G12(x, a1) + G12(x, a2)\n tmp = (soft_photon_temperature / electron_energy) ** 2\n # r0 = (e**2 / m_e / c**2).to('cm')\n # (2 * r0 ** 2 * m_e ** 3 * c ** 4 / (pi * hbar ** 3)).cgs\n tmp *= 2.6318735743809104e16\n cross_section = tmp * cross_section\n cc = (gamma_energy < electron_energy) * (electron_energy > 1)\n return np.where(cc, cross_section, np.zeros_like(cross_section))\n\n @staticmethod\n def _iso_ic_on_monochromatic(\n electron_energy, seed_energy, seed_edensity, gamma_energy\n ):\n \"\"\"\n IC cross-section for an isotropic interaction with a monochromatic\n photon spectrum following Eq. 22 of Aharonian & Atoyan 1981, Ap&SS 79,\n 321 (`http://adsabs.harvard.edu/abs/1981Ap%26SS..79..321A`_)\n \"\"\"\n photE0 = (seed_energy / mec2).decompose().value\n phn = seed_edensity\n\n # electron_energy = electron_energy[:, None]\n gamma_energy = gamma_energy[:, None]\n photE0 = photE0[:, None, None]\n phn = phn[:, None, None]\n\n b = 4 * photE0 * electron_energy\n w = gamma_energy / electron_energy\n q = w / (b * (1 - w))\n fic = (\n 2 * q * np.log(q)\n + (1 + 2 * q) * (1 - q)\n + (1.0 / 2.0) * (b * q) ** 2 * (1 - q) / (1 + b * q)\n )\n\n gamint = (\n fic\n * heaviside(1 - q)\n * heaviside(q - 1.0 / (4 * electron_energy ** 2))\n )\n gamint[np.isnan(gamint)] = 0.0\n\n if phn.size > 1:\n phn = phn.to(1 / (mec2_unit * u.cm ** 3)).value\n gamint = trapz_loglog(gamint * phn / photE0, photE0, axis=0) # 1/s\n else:\n phn = phn.to(mec2_unit / u.cm ** 3).value\n gamint *= phn / photE0 ** 2\n gamint = gamint.squeeze()\n\n # gamint /= mec2.to('erg').value\n\n # r0 = (e**2 / m_e / c**2).to('cm')\n # sigt = ((8 * np.pi) / 3 * r0**2).cgs\n sigt = 6.652458734983284e-25\n c = 29979245800.0\n\n gamint *= (3.0 / 4.0) * sigt * c / electron_energy ** 2\n\n return gamint\n\n def _calc_specic(self, seed, outspecene):\n log.debug(\n \"_calc_specic: Computing IC on {0} seed photons...\".format(seed)\n )\n\n Eph = (outspecene / mec2).decompose().value\n # Catch numpy RuntimeWarnings of overflowing exp (which are then\n # discarded anyway)\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n if self.seed_photon_fields[seed][\"type\"] == \"thermal\":\n T = self.seed_photon_fields[seed][\"T\"]\n uf = (\n self.seed_photon_fields[seed][\"u\"] / (ar * T ** 4)\n ).decompose()\n if self.seed_photon_fields[seed][\"isotropic\"]:\n gamint = self._iso_ic_on_planck(\n self._gam, T.to(\"K\").value, Eph\n )\n else:\n theta = (\n self.seed_photon_fields[seed][\"theta\"].to(\"rad\").value\n )\n gamint = self._ani_ic_on_planck(\n self._gam, T.to(\"K\").value, Eph, theta\n )\n else:\n uf = 1\n gamint = self._iso_ic_on_monochromatic(\n self._gam,\n self.seed_photon_fields[seed][\"energy\"],\n self.seed_photon_fields[seed][\"photon_density\"],\n Eph,\n )\n\n lum = uf * Eph * trapz_loglog(self._nelec * gamint, self._gam)\n lum = lum * u.Unit(\"1/s\")\n\n return lum / outspecene # return differential spectrum in 1/s/eV\n\n def _spectrum(self, photon_energy):\n \"\"\"Compute differential IC spectrum for energies in ``photon_energy``.\n\n Compute IC spectrum using IC cross-section for isotropic interaction\n with a blackbody photon spectrum following Khangulyan, Aharonian, and\n Kelner 2014, ApJ 783, 100 (`arXiv:1310.7971\n `_).\n\n Parameters\n ----------\n photon_energy : :class:`~astropy.units.Quantity` instance\n Photon energy array.\n \"\"\"\n outspecene = _validate_ene(photon_energy)\n\n self.specic = []\n\n for seed in self.seed_photon_fields:\n # Call actual computation, detached to allow changes in subclasses\n self.specic.append(\n self._calc_specic(seed, outspecene).to(\"1/(s eV)\")\n )\n\n return np.sum(u.Quantity(self.specic), axis=0)\n\n def flux(self, photon_energy, distance=1 * u.kpc, seed=None):\n \"\"\"Differential flux at a given distance from the source from a single\n seed photon field\n\n Parameters\n ----------\n photon_energy : :class:`~astropy.units.Quantity` float or array\n Photon energy array.\n\n distance : :class:`~astropy.units.Quantity` float, optional\n Distance to the source. If set to 0, the intrinsic luminosity will\n be returned. Default is 1 kpc.\n\n seed : int, str or None\n Number or name of seed photon field for which the IC contribution\n is required. If set to None it will return the sum of all\n contributions (default).\n \"\"\"\n model = super(InverseCompton, self).flux(\n photon_energy, distance=distance\n )\n\n if seed is not None:\n # Test seed argument\n if not isinstance(seed, int):\n if seed not in self.seed_photon_fields:\n raise ValueError(\n \"Provided seed photon field name is not in\"\n \" the definition of the InverseCompton instance\"\n )\n else:\n seed = list(self.seed_photon_fields.keys()).index(seed)\n elif seed > len(self.seed_photon_fields):\n raise ValueError(\n \"Provided seed photon field number is larger\"\n \" than the number of seed photon fields defined in the\"\n \" InverseCompton instance\"\n )\n\n if distance != 0:\n distance = validate_scalar(\n \"distance\", distance, physical_type=\"length\"\n )\n dfac = 4 * np.pi * distance.to(\"cm\") ** 2\n out_unit = \"1/(s cm2 eV)\"\n else:\n dfac = 1\n out_unit = \"1/(s eV)\"\n\n model = (self.specic[seed] / dfac).to(out_unit)\n\n return model\n\n def sed(self, photon_energy, distance=1 * u.kpc, seed=None):\n \"\"\"Spectral energy distribution at a given distance from the source\n\n Parameters\n ----------\n photon_energy : :class:`~astropy.units.Quantity` float or array\n Photon energy array.\n\n distance : :class:`~astropy.units.Quantity` float, optional\n Distance to the source. If set to 0, the intrinsic luminosity will\n be returned. Default is 1 kpc.\n\n seed : int, str or None\n Number or name of seed photon field for which the IC contribution\n is required. If set to None it will return the sum of all\n contributions (default).\n \"\"\"\n sed = super(InverseCompton, self).sed(photon_energy, distance=distance)\n\n if seed is not None:\n if distance != 0:\n out_unit = \"erg/(cm2 s)\"\n else:\n out_unit = \"erg/s\"\n\n sed = (\n self.flux(photon_energy, distance=distance, seed=seed)\n * photon_energy ** 2.0\n ).to(out_unit)\n\n return sed\n\n\nclass Bremsstrahlung(BaseElectron):\n \"\"\"\n Bremsstrahlung radiation on a completely ionised gas.\n\n This class uses the cross-section approximation of `Baring, M.G., Ellison,\n D.C., Reynolds, S.P., Grenier, I.A., & Goret, P. 1999, Astrophysical\n Journal, 513, 311 `_.\n\n The default weights are assuming a completely ionised target gas with ISM\n abundances. If pure electron-electron bremsstrahlung is desired, ``n0`` can\n be set to the electron density, ``weight_ep`` to 0 and ``weight_ee`` to 1.\n\n Parameters\n ----------\n n0 : :class:`~astropy.units.Quantity` float\n Total ion number density.\n\n Other parameters\n ----------------\n weight_ee : float\n Weight of electron-electron bremsstrahlung. Defined as :math:`\\sum_i\n Z_i X_i`, default is 1.088.\n weight_ep : float\n Weight of electron-proton bremsstrahlung. Defined as :math:`\\sum_i\n Z_i^2 X_i`, default is 1.263.\n \"\"\"\n\n def __init__(self, particle_distribution, n0=1 / u.cm ** 3, **kwargs):\n super(Bremsstrahlung, self).__init__(particle_distribution)\n self.n0 = n0\n self.Eemin = 100 * u.MeV\n self.Eemax = 1e9 * mec2\n self.nEed = 300\n # compute ee and ep weights from H and He abundances in ISM assumin\n # ionized medium\n Y = np.array([1.0, 9.59e-2])\n Z = np.array([1, 2])\n N = np.sum(Y)\n X = Y / N\n self.weight_ee = np.sum(Z * X)\n self.weight_ep = np.sum(Z ** 2 * X)\n self.param_names += [\"n0\", \"weight_ee\", \"weight_ep\"]\n self.__dict__.update(**kwargs)\n\n @staticmethod\n def _sigma_1(gam, eps):\n \"\"\"\n gam and eps in units of m_e c^2\n Eq. A2 of Baring et al. (1999)\n Return in units of cm2 / mec2\n \"\"\"\n s1 = 4 * r0 ** 2 * alpha / eps / mec2_unit\n s2 = 1 + (1.0 / 3.0 - eps / gam) * (1 - eps / gam)\n s3 = np.log(2 * gam * (gam - eps) / eps) - 1.0 / 2.0\n s3[np.where(gam < eps)] = 0.0\n return s1 * s2 * s3\n\n @staticmethod\n def _sigma_2(gam, eps):\n \"\"\"\n gam and eps in units of m_e c^2\n Eq. A3 of Baring et al. (1999)\n Return in units of cm2 / mec2\n \"\"\"\n s0 = r0 ** 2 * alpha / (3 * eps) / mec2_unit\n\n s1_1 = 16 * (1 - eps + eps ** 2) * np.log(gam / eps)\n s1_2 = -1 / eps ** 2 + 3 / eps - 4 - 4 * eps - 8 * eps ** 2\n s1_3 = -2 * (1 - 2 * eps) * np.log(1 - 2 * eps)\n s1_4 = 1 / (4 * eps ** 3) - 1 / (2 * eps ** 2) + 3 / eps - 2 + 4 * eps\n s1 = s1_1 + s1_2 + s1_3 * s1_4\n\n s2_1 = 2 / eps\n s2_2 = (4 - 1 / eps + 1 / (4 * eps ** 2)) * np.log(2 * gam)\n s2_3 = -2 + 2 / eps - 5 / (8 * eps ** 2)\n s2 = s2_1 * (s2_2 + s2_3)\n\n return s0 * np.where(eps <= 0.5, s1, s2) * heaviside(gam - eps)\n\n def _sigma_ee_rel(self, gam, eps):\n \"\"\"\n Eq. A1, A4 of Baring et al. (1999)\n Use for Ee > 2 MeV\n \"\"\"\n A = 1 - 8 / 3 * (gam - 1) ** 0.2 / (gam + 1) * (eps / gam) ** (\n 1.0 / 3.0\n )\n\n return (self._sigma_1(gam, eps) + self._sigma_2(gam, eps)) * A\n\n @staticmethod\n def _F(x, gam):\n \"\"\"\n Eqs. A6, A7 of Baring et al. (1999)\n \"\"\"\n beta = np.sqrt(1 - gam ** -2)\n B = 1 + 0.5 * (gam ** 2 - 1)\n C = 10 * x * gam * beta * (2 + gam * beta)\n C /= 1 + x ** 2 * (gam ** 2 - 1)\n\n F_1 = (17 - 3 * x ** 2 / (2 - x) ** 2 - C) * np.sqrt(1 - x)\n F_2 = 12 * (2 - x) - 7 * x ** 2 / (2 - x) - 3 * x ** 4 / (2 - x) ** 3\n F_3 = np.log((1 + np.sqrt(1 - x)) / np.sqrt(x))\n\n return B * F_1 + F_2 * F_3\n\n def _sigma_ee_nonrel(self, gam, eps):\n \"\"\"\n Eq. A5 of Baring et al. (1999)\n Use for Ee < 2 MeV\n \"\"\"\n s0 = 4 * r0 ** 2 * alpha / (15 * eps)\n x = 4 * eps / (gam ** 2 - 1)\n sigma_nonrel = s0 * self._F(x, gam)\n sigma_nonrel[np.where(eps >= 0.25 * (gam ** 2 - 1.0))] = 0.0\n sigma_nonrel[np.where(gam * np.ones_like(eps) < 1.0)] = 0.0\n return sigma_nonrel / mec2_unit\n\n def _sigma_ee(self, gam, Eph):\n eps = (Eph / mec2).decompose().value\n # initialize shape and units of cross section\n sigma = np.zeros_like(gam * eps) * u.Unit(u.cm ** 2 / Eph.unit)\n gam_trans = (2 * u.MeV / mec2).decompose().value\n # Non relativistic below 2 MeV\n if np.any(gam <= gam_trans):\n nr_matrix = np.where(gam * np.ones_like(gam * eps) <= gam_trans)\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n sigma[nr_matrix] = self._sigma_ee_nonrel(gam, eps)[nr_matrix]\n # Relativistic above 2 MeV\n if np.any(gam > gam_trans):\n rel_matrix = np.where(gam * np.ones_like(gam * eps) > gam_trans)\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n sigma[rel_matrix] = self._sigma_ee_rel(gam, eps)[rel_matrix]\n\n return sigma.to(u.cm ** 2 / Eph.unit)\n\n def _sigma_ep(self, gam, eps):\n \"\"\"\n Using sigma_1 only applies to the ultrarelativistic regime.\n Eph > 10 MeV\n ToDo: add complete e-p cross-section\n \"\"\"\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n return self._sigma_1(gam, eps)\n\n def _emiss_ee(self, Eph):\n \"\"\"\n Electron-electron bremsstrahlung emissivity per unit photon energy\n \"\"\"\n if self.weight_ee == 0.0:\n return np.zeros_like(Eph)\n\n gam = np.vstack(self._gam)\n # compute integral with electron distribution\n emiss = c.cgs * trapz_loglog(\n np.vstack(self._nelec) * self._sigma_ee(gam, Eph),\n self._gam,\n axis=0,\n )\n return emiss\n\n def _emiss_ep(self, Eph):\n \"\"\"\n Electron-proton bremsstrahlung emissivity per unit photon energy\n \"\"\"\n if self.weight_ep == 0.0:\n return np.zeros_like(Eph)\n\n gam = np.vstack(self._gam)\n eps = (Eph / mec2).decompose().value\n # compute integral with electron distribution\n emiss = c.cgs * trapz_loglog(\n np.vstack(self._nelec) * self._sigma_ep(gam, eps),\n self._gam,\n axis=0,\n ).to(u.cm ** 2 / Eph.unit)\n return emiss\n\n def _spectrum(self, photon_energy):\n \"\"\"Compute differential bremsstrahlung spectrum for energies in\n ``photon_energy``.\n\n Parameters\n ----------\n photon_energy : :class:`~astropy.units.Quantity` instance\n Photon energy array.\n \"\"\"\n\n Eph = _validate_ene(photon_energy)\n\n spec = self.n0 * (\n self.weight_ee * self._emiss_ee(Eph)\n + self.weight_ep * self._emiss_ep(Eph)\n )\n\n return spec\n\n\nclass BaseProton(BaseRadiative):\n \"\"\"Implements compute_Wp at arbitrary energies\n \"\"\"\n\n def __init__(self, particle_distribution):\n super(BaseProton, self).__init__(particle_distribution)\n self.param_names = [\"Epmin\", \"Epmax\", \"nEpd\"]\n self._memoize = True\n self._cache = {}\n self._queue = []\n\n @property\n def _Ep(self):\n \"\"\" Proton energy array in GeV\n \"\"\"\n return np.logspace(\n np.log10(self.Epmin.to(\"GeV\").value),\n np.log10(self.Epmax.to(\"GeV\").value),\n int(self.nEpd * (np.log10(self.Epmax / self.Epmin))),\n )\n\n @property\n def _J(self):\n \"\"\" Particles per unit proton energy in particles per GeV\n \"\"\"\n pd = self.particle_distribution(self._Ep * u.GeV)\n return pd.to(\"1/GeV\").value\n\n @property\n def Wp(self):\n \"\"\"Total energy in protons\n \"\"\"\n Wp = trapz_loglog(self._Ep * self._J, self._Ep) * u.GeV\n return Wp.to(\"erg\")\n\n def compute_Wp(self, Epmin=None, Epmax=None):\n \"\"\" Total energy in protons between energies Epmin and Epmax\n\n Parameters\n ----------\n Epmin : :class:`~astropy.units.Quantity` float, optional\n Minimum proton energy for energy content calculation.\n\n Epmax : :class:`~astropy.units.Quantity` float, optional\n Maximum proton energy for energy content calculation.\n \"\"\"\n if Epmin is None and Epmax is None:\n Wp = self.Wp\n else:\n if Epmax is None:\n Epmax = self.Epmax\n if Epmin is None:\n Epmin = self.Epmin\n\n log10Epmin = np.log10(Epmin.to(\"GeV\").value)\n log10Epmax = np.log10(Epmax.to(\"GeV\").value)\n Ep = (\n np.logspace(\n log10Epmin,\n log10Epmax,\n int(self.nEpd * (log10Epmax - log10Epmin)),\n )\n * u.GeV\n )\n pdist = self.particle_distribution(Ep)\n Wp = trapz_loglog(Ep * pdist, Ep).to(\"erg\")\n\n return Wp\n\n def set_Wp(self, Wp, Epmin=None, Epmax=None, amplitude_name=None):\n \"\"\" Normalize particle distribution so that the total energy in protons\n between Epmin and Epmax is Wp\n\n Parameters\n ----------\n Wp : :class:`~astropy.units.Quantity` float\n Desired energy in protons.\n\n Epmin : :class:`~astropy.units.Quantity` float, optional\n Minimum proton energy for energy content calculation.\n\n Epmax : :class:`~astropy.units.Quantity` float, optional\n Maximum proton energy for energy content calculation.\n\n amplitude_name : str, optional\n Name of the amplitude parameter of the particle distribution. It\n must be accesible as an attribute of the distribution function.\n Defaults to ``amplitude``.\n \"\"\"\n\n Wp = validate_scalar(\"Wp\", Wp, physical_type=\"energy\")\n oldWp = self.compute_Wp(Epmin=Epmin, Epmax=Epmax)\n\n if amplitude_name is None:\n try:\n self.particle_distribution.amplitude *= (\n Wp / oldWp\n ).decompose()\n except AttributeError:\n log.error(\n \"The particle distribution does not have an attribute\"\n \" called amplitude to modify its normalization: you can\"\n \" set the name with the amplitude_name parameter of set_Wp\"\n )\n else:\n oldampl = getattr(self.particle_distribution, amplitude_name)\n setattr(\n self.particle_distribution,\n amplitude_name,\n oldampl * (Wp / oldWp).decompose(),\n )\n\n\nclass PionDecay(BaseProton):\n r\"\"\"Pion decay gamma-ray emission from a proton population.\n\n Compute gamma-ray spectrum arising from the interaction of a relativistic\n proton distribution with stationary target protons using the\n parametrization of Kafexhiu et al. (2014).\n\n If you use this class in your research, please consult and cite `Kafexhiu,\n E., Aharonian, F., Taylor, A.M., & Vila, G.S. 2014, Physical Review D, 90,\n 123014 `_.\n\n\n Parameters\n ----------\n particle_distribution : function\n Particle distribution function, taking proton energies as a\n `~astropy.units.Quantity` array or float, and returning the particle\n energy density in units of number of protons per unit energy as a\n `~astropy.units.Quantity` array or float.\n\n nh : `~astropy.units.Quantity`\n Number density of the target protons. Default is :math:`1\n \\mathrm{cm}^{-3}`.\n\n nuclear_enhancement : bool\n Whether to apply the energy-dependent nuclear enhancement factor\n considering a target gas with local ISM abundances. See Section IV of\n Kafexhiu et al. (2014) for details. Here the proton-nucleus inelastic\n cross section of Sihver et al. (1993, PhysRevC 47, 1225) is used.\n\n Other parameters\n ----------------\n Epmin : `~astropy.units.Quantity` float\n Minimum proton energy for the proton distribution. Default is 1.22 GeV,\n the dynamical threshold for pion production in pp interactions.\n\n Epmax : `~astropy.units.Quantity` float\n Minimum proton energy for the proton\n distribution. Default is 10 PeV.\n\n nEpd : scalar\n Number of points per decade in energy for the proton energy and\n distribution arrays. Default is 100.\n\n hiEmodel : str\n Monte Carlo model to use for computation of high-energy differential\n cross section. Can be one of ``Geant4``, ``Pythia8``, ``SIBYLL``, or\n ``QGSJET``. See Kafexhiu et al. (2014) for details. Default is\n ``Pythia8``.\n\n useLUT : bool\n Whether to use a lookup table for the differential cross section. The\n only lookup table packaged with naima is for the Pythia 8 model and\n ISM nuclear enhancement factor.\n \"\"\"\n\n def __init__(\n self,\n particle_distribution,\n nh=1.0 / u.cm ** 3,\n nuclear_enhancement=True,\n **kwargs\n ):\n super(PionDecay, self).__init__(particle_distribution)\n self.nh = validate_scalar(\"nh\", nh, physical_type=\"number density\")\n self.nuclear_enhancement = nuclear_enhancement\n self.useLUT = True\n self.hiEmodel = \"Pythia8\"\n self.Epmin = (\n self._m_p + self._Tth + 1e-4\n ) * u.GeV # Threshold energy ~1.22 GeV\n self.Epmax = 10 * u.PeV # 10 PeV\n self.nEpd = 100\n self.param_names += [\"nh\", \"nuclear_enhancement\", \"useLUT\", \"hiEmodel\"]\n self.__dict__.update(**kwargs)\n\n # define model parameters from tables\n # yapf: disable\n #\n # Table IV\n _a = {}\n _a['Geant4'] = [0.728, 0.596, 0.491, 0.2503, 0.117] # Tp > 5\n _a['Pythia8'] = [0.652, 0.0016, 0.488, 0.1928, 0.483] # Tp > 50\n _a['SIBYLL'] = [5.436, 0.254, 0.072, 0.075, 0.166] # Tp > 100\n _a['QGSJET'] = [0.908, 0.0009, 6.089, 0.176, 0.448] # Tp > 100\n #\n # table V data\n # note that np.nan indicate that functions of Tp are needed and are defined\n # as need in function F\n # parameter order is lambda, alpha, beta, gamma\n _F_mp = {}\n _F_mp['ExpData'] = [1.0, 1.0, np.nan, 0.0] # Tth <= Tp <= 1.0\n _F_mp['Geant4_0'] = [3.0, 1.0, np.nan, np.nan] # 1.0 < Tp <= 4.0\n _F_mp['Geant4_1'] = [3.0, 1.0, np.nan, np.nan] # 4.0 < Tp <= 20.0\n _F_mp['Geant4_2'] = [3.0, 0.5, 4.2, 1.0] # 20.0 < Tp <= 100\n _F_mp['Geant4'] = [3.0, 0.5, 4.9, 1.0] # Tp > 100\n _F_mp['Pythia8'] = [3.5, 0.5, 4.0, 1.0] # Tp > 50\n _F_mp['SIBYLL'] = [3.55, 0.5, 3.6, 1.0] # Tp > 100\n _F_mp['QGSJET'] = [3.55, 0.5, 4.5, 1.0] # Tp > 100\n #\n # Table VII\n _b = {}\n _b['Geant4_0'] = [9.53, 0.52, 0.054] # 1 <= Tp < 5\n _b['Geant4'] = [9.13, 0.35, 9.7e-3] # Tp >= 5\n _b['Pythia8'] = [9.06, 0.3795, 0.01105] # Tp > 50\n _b['SIBYLL'] = [10.77, 0.412, 0.01264] # Tp > 100\n _b['QGSJET'] = [13.16, 0.4419, 0.01439] # Tp > 100\n # yapf: enable\n\n # energy at which each of the hiE models start being valid\n _Etrans = {\"Pythia8\": 50, \"SIBYLL\": 100, \"QGSJET\": 100, \"Geant4\": 100}\n #\n _m_p = (m_p * c ** 2).to(\"GeV\").value\n _m_pi = 0.1349766 # GeV/c2\n _Tth = 0.27966184\n\n def _sigma_inel(self, Tp):\n \"\"\"\n Inelastic cross-section for p-p interaction. KATV14 Eq. 1\n\n Parameters\n ----------\n Tp : float\n Kinetic energy of proton (i.e. Ep - m_p*c**2) [GeV]\n\n Returns\n -------\n sigma_inel : float\n Inelastic cross-section for p-p interaction [1/cm2].\n\n \"\"\"\n L = np.log(Tp / self._Tth)\n sigma = 30.7 - 0.96 * L + 0.18 * L ** 2\n sigma *= (1 - (self._Tth / Tp) ** 1.9) ** 3\n return sigma * 1e-27 # convert from mbarn to cm-2\n\n def _sigma_pi_loE(self, Tp):\n \"\"\"\n inclusive cross section for Tth < Tp < 2 GeV\n Fit from experimental data\n \"\"\"\n m_p = self._m_p\n m_pi = self._m_pi\n Mres = 1.1883 # GeV\n Gres = 0.2264 # GeV\n s = 2 * m_p * (Tp + 2 * m_p) # center of mass energy\n gamma = np.sqrt(Mres ** 2 * (Mres ** 2 + Gres ** 2))\n K = np.sqrt(8) * Mres * Gres * gamma\n K /= np.pi * np.sqrt(Mres ** 2 + gamma)\n\n fBW = m_p * K\n fBW /= (\n (np.sqrt(s) - m_p) ** 2 - Mres ** 2\n ) ** 2 + Mres ** 2 * Gres ** 2\n\n mu = np.sqrt(\n (s - m_pi ** 2 - 4 * m_p ** 2) ** 2 - 16 * m_pi ** 2 * m_p ** 2\n )\n mu /= 2 * m_pi * np.sqrt(s)\n\n sigma0 = 7.66e-3 # mb\n\n sigma1pi = sigma0 * mu ** 1.95 * (1 + mu + mu ** 5) * fBW ** 1.86\n\n # two pion production\n sigma2pi = 5.7 # mb\n sigma2pi /= 1 + np.exp(-9.3 * (Tp - 1.4))\n\n E2pith = 0.56 # GeV\n sigma2pi[np.where(Tp < E2pith)] = 0.0\n\n return (sigma1pi + sigma2pi) * 1e-27 # return in cm-2\n\n def _sigma_pi_midE(self, Tp):\n \"\"\"\n Geant 4.10.0 model for 2 GeV < Tp < 5 GeV\n \"\"\"\n m_p = self._m_p\n Qp = (Tp - self._Tth) / m_p\n multip = -6e-3 + 0.237 * Qp - 0.023 * Qp ** 2\n return self._sigma_inel(Tp) * multip\n\n def _sigma_pi_hiE(self, Tp, a):\n \"\"\"\n General expression for Tp > 5 GeV (Eq 7)\n \"\"\"\n m_p = self._m_p\n csip = (Tp - 3.0) / m_p\n m1 = a[0] * csip ** a[3] * (1 + np.exp(-a[1] * csip ** a[4]))\n m2 = 1 - np.exp(-a[2] * csip ** 0.25)\n multip = m1 * m2\n return self._sigma_inel(Tp) * multip\n\n def _sigma_pi(self, Tp):\n sigma = np.zeros_like(Tp)\n\n # for E<2GeV\n idx1 = np.where(Tp < 2.0)\n sigma[idx1] = self._sigma_pi_loE(Tp[idx1])\n # for 2GeV<=E<5GeV\n idx2 = np.where((Tp >= 2.0) * (Tp < 5.0))\n sigma[idx2] = self._sigma_pi_midE(Tp[idx2])\n # for 5GeV<=E= 5.0) * (Tp < self._Etrans[self.hiEmodel]))\n sigma[idx3] = self._sigma_pi_hiE(Tp[idx3], self._a[\"Geant4\"])\n # for E>=Etrans\n idx4 = np.where((Tp >= self._Etrans[self.hiEmodel]))\n sigma[idx4] = self._sigma_pi_hiE(Tp[idx4], self._a[self.hiEmodel])\n\n return sigma\n\n def _b_params(self, Tp):\n b0 = 5.9\n hiE = np.where(Tp >= 1.0)\n TphiE = Tp[hiE]\n b1 = np.zeros(TphiE.size)\n b2 = np.zeros(TphiE.size)\n b3 = np.zeros(TphiE.size)\n\n idx = np.where(TphiE < 5.0)\n b1[idx], b2[idx], b3[idx] = self._b[\"Geant4_0\"]\n\n idx = np.where(TphiE >= 5.0)\n b1[idx], b2[idx], b3[idx] = self._b[\"Geant4\"]\n\n idx = np.where(TphiE >= self._Etrans[self.hiEmodel])\n b1[idx], b2[idx], b3[idx] = self._b[self.hiEmodel]\n\n return b0, b1, b2, b3\n\n def _calc_EpimaxLAB(self, Tp):\n m_p = self._m_p\n m_pi = self._m_pi\n # Eq 10\n s = 2 * m_p * (Tp + 2 * m_p) # center of mass energy\n EpiCM = (s - 4 * m_p ** 2 + m_pi ** 2) / (2 * np.sqrt(s))\n PpiCM = np.sqrt(EpiCM ** 2 - m_pi ** 2)\n gCM = (Tp + 2 * m_p) / np.sqrt(s)\n betaCM = np.sqrt(1 - gCM ** -2)\n EpimaxLAB = gCM * (EpiCM + PpiCM * betaCM)\n\n return EpimaxLAB\n\n def _calc_Egmax(self, Tp):\n m_pi = self._m_pi\n EpimaxLAB = self._calc_EpimaxLAB(Tp)\n gpiLAB = EpimaxLAB / m_pi\n betapiLAB = np.sqrt(1 - gpiLAB ** -2)\n Egmax = (m_pi / 2) * gpiLAB * (1 + betapiLAB)\n\n return Egmax\n\n def _Amax(self, Tp):\n m_p = self._m_p\n loE = np.where(Tp < 1.0)\n hiE = np.where(Tp >= 1.0)\n\n Amax = np.zeros(Tp.size)\n\n b = self._b_params(Tp)\n\n EpimaxLAB = self._calc_EpimaxLAB(Tp)\n Amax[loE] = b[0] * self._sigma_pi(Tp[loE]) / EpimaxLAB[loE]\n thetap = Tp / m_p\n Amax[hiE] = (\n b[1]\n * thetap[hiE] ** -b[2]\n * np.exp(b[3] * np.log(thetap[hiE]) ** 2)\n * self._sigma_pi(Tp[hiE])\n / m_p\n )\n\n return Amax\n\n def _F_func(self, Tp, Egamma, modelparams):\n lamb, alpha, beta, gamma = modelparams\n m_pi = self._m_pi\n # Eq 9\n Egmax = self._calc_Egmax(Tp)\n Yg = Egamma + m_pi ** 2 / (4 * Egamma)\n Ygmax = Egmax + m_pi ** 2 / (4 * Egmax)\n Xg = (Yg - m_pi) / (Ygmax - m_pi)\n # zero out invalid fields (Egamma > Egmax -> Xg > 1)\n Xg[np.where(Xg > 1)] = 1.0\n # Eq 11\n C = lamb * m_pi / Ygmax\n F = (1 - Xg ** alpha) ** beta\n F /= (1 + Xg / C) ** gamma\n #\n return F\n\n def _kappa(self, Tp):\n thetap = Tp / self._m_p\n return 3.29 - thetap ** -1.5 / 5.0\n\n def _mu(self, Tp):\n q = (Tp - 1.0) / self._m_p\n x = 5.0 / 4.0\n return x * q ** x * np.exp(-x * q)\n\n def _F(self, Tp, Egamma):\n F = np.zeros_like(Tp)\n # below Tth\n F[np.where(Tp < self._Tth)] = 0.0\n\n # Tth <= E <= 1GeV: Experimental data\n idx = np.where((Tp >= self._Tth) * (Tp <= 1.0))\n if idx[0].size > 0:\n kappa = self._kappa(Tp[idx])\n mp = self._F_mp[\"ExpData\"]\n mp[2] = kappa\n F[idx] = self._F_func(Tp[idx], Egamma, mp)\n\n # 1GeV < Tp < 4 GeV: Geant4 model 0\n idx = np.where((Tp > 1.0) * (Tp <= 4.0))\n if idx[0].size > 0:\n mp = self._F_mp[\"Geant4_0\"]\n mu = self._mu(Tp[idx])\n mp[2] = mu + 2.45\n mp[3] = mu + 1.45\n F[idx] = self._F_func(Tp[idx], Egamma, mp)\n\n # 4 GeV < Tp < 20 GeV\n idx = np.where((Tp > 4.0) * (Tp <= 20.0))\n if idx[0].size > 0:\n mp = self._F_mp[\"Geant4_1\"]\n mu = self._mu(Tp[idx])\n mp[2] = 1.5 * mu + 4.95\n mp[3] = mu + 1.50\n F[idx] = self._F_func(Tp[idx], Egamma, mp)\n\n # 20 GeV < Tp < 100 GeV\n idx = np.where((Tp > 20.0) * (Tp <= 100.0))\n if idx[0].size > 0:\n mp = self._F_mp[\"Geant4_2\"]\n F[idx] = self._F_func(Tp[idx], Egamma, mp)\n\n # Tp > Etrans\n idx = np.where(Tp > self._Etrans[self.hiEmodel])\n if idx[0].size > 0:\n mp = self._F_mp[self.hiEmodel]\n F[idx] = self._F_func(Tp[idx], Egamma, mp)\n\n return F\n\n def _diffsigma(self, Ep, Egamma):\n \"\"\"\n Differential cross section\n\n dsigma/dEg = Amax(Tp) * F(Tp,Egamma)\n \"\"\"\n Tp = Ep - self._m_p\n\n diffsigma = self._Amax(Tp) * self._F(Tp, Egamma)\n\n if self.nuclear_enhancement:\n diffsigma *= self._nuclear_factor(Tp)\n\n return diffsigma\n\n def _nuclear_factor(self, Tp):\n \"\"\"\n Compute nuclear enhancement factor\n \"\"\"\n sigmaRpp = 10 * np.pi * 1e-27\n sigmainel = self._sigma_inel(Tp)\n sigmainel0 = self._sigma_inel(1e3) # at 1e3 GeV\n f = sigmainel / sigmainel0\n f2 = np.where(f > 1, f, 1.0)\n G = 1.0 + np.log(f2)\n # epsilon factors computed from Eqs 21 to 23 with local ISM abundances\n epsC = 1.37\n eps1 = 0.29\n eps2 = 0.1\n\n epstotal = np.where(\n Tp > self._Tth,\n epsC + (eps1 + eps2) * sigmaRpp * G / sigmainel,\n 0.0,\n )\n\n if np.any(Tp < 1.0):\n # nuclear enhancement factor diverges towards Tp = Tth, fix Tp<1 to\n # eps(1.0) = 1.91\n loE = np.where((Tp > self._Tth) * (Tp < 1.0))\n epstotal[loE] = 1.9141\n\n return epstotal\n\n def _loadLUT(self, LUT_fname):\n try:\n filename = get_pkg_data_filename(os.path.join(\"data\", LUT_fname))\n self.diffsigma = LookupTable(filename)\n except IOError:\n warnings.warn(\n \"LUT {0} not found, reverting to useLUT = False\".format(\n LUT_fname\n )\n )\n self.diffsigma = self._diffsigma\n self.useLUT = False\n\n def _spectrum(self, photon_energy):\n \"\"\"\n Compute differential spectrum from pp interactions using the\n parametrization of Kafexhiu, E., Aharonian, F., Taylor, A.~M., and\n Vila, G.~S.\\ 2014, `arXiv:1406.7369\n `_.\n\n Parameters\n ----------\n photon_energy : :class:`~astropy.units.Quantity` instance\n Photon energy array.\n \"\"\"\n\n # Load LUT if available, otherwise use self._diffsigma\n if self.useLUT:\n LUT_base = \"PionDecayKafexhiu14_LUT_\"\n if self.nuclear_enhancement:\n LUT_base += \"NucEnh_\"\n LUT_fname = LUT_base + \"{0}.npz\".format(self.hiEmodel)\n # only reload LUT if it has changed or hasn't been loaded yet\n try:\n if os.path.basename(self.diffsigma.fname) != LUT_fname:\n self._loadLUT(LUT_fname)\n except AttributeError:\n self._loadLUT(LUT_fname)\n else:\n self.diffsigma = self._diffsigma\n\n Egamma = _validate_ene(photon_energy).to(\"GeV\")\n Ep = self._Ep * u.GeV\n J = self._J * u.Unit(\"1/GeV\")\n\n specpp = []\n for Eg in Egamma:\n diffsigma = self.diffsigma(Ep.value, Eg.value) * u.Unit(\"cm2/GeV\")\n specpp.append(trapz_loglog(diffsigma * J, Ep))\n\n self.specpp = u.Quantity(specpp)\n\n self.specpp *= self.nh * c.cgs\n\n return self.specpp.to(\"1/(s eV)\")\n\n\ndef heaviside(x):\n return (np.sign(x) + 1) / 2.0\n\n\nclass PionDecayKelner06(BaseRadiative):\n r\"\"\"Pion decay gamma-ray emission from a proton population.\n\n Compute gamma-ray spectrum arising from the interaction of a relativistic\n proton distribution with stationary target protons.\n\n Parameters\n ----------\n particle_distribution : function\n Particle distribution function, taking proton energies as a\n `~astropy.units.Quantity` array or float, and returning the particle\n energy density in units of number of protons per unit energy as a\n `~astropy.units.Quantity` array or float.\n\n nh : `~astropy.units.Quantity`\n Number density of the target protons. Default is :math:`1 cm^{-3}`.\n\n Other parameters\n ----------------\n Etrans : `~astropy.units.Quantity`\n For photon energies below ``Etrans``, the delta-functional\n approximation is used for the spectral calculation, and the full\n calculation is used at higher energies. Default is 0.1 TeV.\n\n References\n ----------\n Kelner, S.R., Aharonian, F.A., and Bugayov, V.V., 2006 PhysRevD 74, 034018\n (`arXiv:astro-ph/0606058 `_).\n\n \"\"\"\n\n # This class doesn't inherit from BaseProton\n param_names = [\"nh\", \"Etrans\"]\n _memoize = True\n _cache = {}\n _queue = []\n\n def __init__(\n self,\n particle_distribution,\n nh=1.0 / u.cm ** 3,\n Etrans=0.1 * u.TeV,\n **kwargs\n ):\n self.particle_distribution = particle_distribution\n self.nh = validate_scalar(\"nh\", nh, physical_type=\"number density\")\n self.Etrans = validate_scalar(\n \"Etrans\", Etrans, domain=\"positive\", physical_type=\"energy\"\n )\n\n self.__dict__.update(**kwargs)\n\n def _particle_distribution(self, E):\n return self.particle_distribution(E * u.TeV).to(\"1/TeV\").value\n\n def _Fgamma(self, x, Ep):\n \"\"\"\n KAB06 Eq.58\n\n Note: Quantities are not used in this function\n\n Parameters\n ----------\n x : float\n Egamma/Eprot\n Ep : float\n Eprot [TeV]\n \"\"\"\n L = np.log(Ep)\n B = 1.30 + 0.14 * L + 0.011 * L ** 2 # Eq59\n beta = (1.79 + 0.11 * L + 0.008 * L ** 2) ** -1 # Eq60\n k = (0.801 + 0.049 * L + 0.014 * L ** 2) ** -1 # Eq61\n xb = x ** beta\n\n F1 = B * (np.log(x) / x) * ((1 - xb) / (1 + k * xb * (1 - xb))) ** 4\n F2 = (\n 1.0 / np.log(x)\n - (4 * beta * xb) / (1 - xb)\n - (4 * k * beta * xb * (1 - 2 * xb)) / (1 + k * xb * (1 - xb))\n )\n\n return F1 * F2\n\n def _sigma_inel(self, Ep):\n \"\"\"\n Inelastic cross-section for p-p interaction. KAB06 Eq. 73, 79\n\n Note: Quantities are not used in this function\n\n Parameters\n ----------\n Ep : float\n Eprot [TeV]\n\n Returns\n -------\n sigma_inel : float\n Inelastic cross-section for p-p interaction [1/cm2].\n\n \"\"\"\n L = np.log(Ep)\n sigma = 34.3 + 1.88 * L + 0.25 * L ** 2\n if Ep <= 0.1:\n Eth = 1.22e-3\n sigma *= (1 - (Eth / Ep) ** 4) ** 2 * heaviside(Ep - Eth)\n return sigma * 1e-27 # convert from mbarn to cm2\n\n def _photon_integrand(self, x, Egamma):\n \"\"\"\n Integrand of Eq. 72\n \"\"\"\n try:\n return (\n self._sigma_inel(Egamma / x)\n * self._particle_distribution((Egamma / x))\n * self._Fgamma(x, Egamma / x)\n / x\n )\n except ZeroDivisionError:\n return np.nan\n\n def _calc_specpp_hiE(self, Egamma):\n \"\"\"\n Spectrum computed as in Eq. 42 for Egamma >= 0.1 TeV\n \"\"\"\n # Fixed quad with n=40 is about 15 times faster and is always within\n # 0.5% of the result of adaptive quad for Egamma>0.1\n # WARNING: It also produces artifacts for steep distributions (e.g.\n # Maxwellian) at ~500 GeV. Reverting to adaptative quadrature\n # from scipy.integrate import fixed_quad\n # result=c*fixed_quad(self._photon_integrand, 0., 1., args = [Egamma,\n # ], n = 40)[0]\n from scipy.integrate import quad\n\n Egamma = Egamma.to(\"TeV\").value\n specpp = (\n c.cgs.value\n * quad(\n self._photon_integrand,\n 0.0,\n 1.0,\n args=Egamma,\n epsrel=1e-3,\n epsabs=0,\n )[0]\n )\n\n return specpp * u.Unit(\"1/(s TeV)\")\n\n # variables for delta integrand\n _c = c.cgs.value\n _Kpi = 0.17\n _mp = (m_p * c ** 2).to(\"TeV\").value\n _m_pi = 1.349766e-4 # TeV/c2\n\n def _delta_integrand(self, Epi):\n Ep0 = self._mp + Epi / self._Kpi\n qpi = (\n self._c\n * (self.nhat / self._Kpi)\n * self._sigma_inel(Ep0)\n * self._particle_distribution(Ep0)\n )\n return qpi / np.sqrt(Epi ** 2 - self._m_pi ** 2)\n\n def _calc_specpp_loE(self, Egamma):\n \"\"\"\n Delta-functional approximation for low energies Egamma < 0.1 TeV\n \"\"\"\n from scipy.integrate import quad\n\n Egamma = Egamma.to(\"TeV\").value\n Epimin = Egamma + self._m_pi ** 2 / (4 * Egamma)\n\n result = (\n 2\n * quad(\n self._delta_integrand, Epimin, np.inf, epsrel=1e-3, epsabs=0\n )[0]\n )\n\n return result * u.Unit(\"1/(s TeV)\")\n\n @property\n def Wp(self):\n \"\"\"Total energy in protons above 1.22 GeV threshold (erg).\n \"\"\"\n from scipy.integrate import quad\n\n Eth = 1.22e-3\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n Wp = quad(\n lambda x: x * self._particle_distribution(x), Eth, np.Inf\n )[0]\n\n return (Wp * u.TeV).to(\"erg\")\n\n def _spectrum(self, photon_energy):\n \"\"\"\n Compute differential spectrum from pp interactions using Eq.71 and\n Eq.58 of Kelner, S.R., Aharonian, F.A., and Bugayov, V.V., 2006\n PhysRevD 74, 034018 (`arXiv:astro-ph/0606058\n `_).\n\n Parameters\n ----------\n photon_energy : :class:`~astropy.units.Quantity` instance\n Photon energy array.\n \"\"\"\n\n outspecene = _validate_ene(photon_energy)\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n self.nhat = 1.0 # initial value, works for index~2.1\n if np.any(outspecene < self.Etrans) and np.any(\n outspecene >= self.Etrans\n ):\n # compute value of nhat so that delta functional matches\n # accurate calculation at 0.1TeV\n full = self._calc_specpp_hiE(self.Etrans)\n delta = self._calc_specpp_loE(self.Etrans)\n self.nhat *= (full / delta).decompose().value\n\n self.specpp = np.zeros(len(outspecene)) * u.Unit(\"1/(s TeV)\")\n\n for i, Egamma in enumerate(outspecene):\n if Egamma >= self.Etrans:\n self.specpp[i] = self._calc_specpp_hiE(Egamma)\n else:\n self.specpp[i] = self._calc_specpp_loE(Egamma)\n\n density_factor = (self.nh / (1 * u.Unit(\"1/cm3\"))).decompose().value\n\n return density_factor * self.specpp.to(\"1/(s eV)\")\n\n\nclass LookupTable(object):\n \"\"\"\n Helper class for two-dimensional look up table\n\n Lookup table should be saved as an npz file with numpy.savez or\n numpy.savez_compressed. The file should have three arrays:\n\n * X: log10(x)\n * Y: log10(y)\n * lut: log10(z)\n\n The instantiated object can be called with arguments (x,y), and the\n interpolated value of z will be returned. The interpolation is done through\n a cubic spline in semi-logarithmic space.\n \"\"\"\n\n def __init__(self, filename):\n from scipy.interpolate import RectBivariateSpline\n\n f_lut = np.load(filename)\n X = f_lut.f.X\n Y = f_lut.f.Y\n lut = f_lut.f.lut\n self.int_lut = RectBivariateSpline(X, Y, 10 ** lut, kx=3, ky=3, s=0)\n self.fname = filename\n\n def __call__(self, X, Y):\n return self.int_lut(np.log10(X), np.log10(Y)).flatten()\n\n\ndef _calc_lut_pp(args): # pragma: no cover\n epr, eph, hiEmodel, nuc = args\n from .models import PowerLaw\n\n pl = PowerLaw(1 / u.eV, 1 * u.TeV, 0.0)\n pp = PionDecay(pl, hiEmodel=hiEmodel, nuclear_enhancement=nuc)\n\n diffsigma = pp._diffsigma(epr.to(\"GeV\").value, eph.to(\"GeV\").value)\n\n return diffsigma\n\n\ndef generate_lut_pp(\n Ep=np.logspace(0.085623713910610105, 7, 800) * u.GeV,\n Eg=np.logspace(-5, 3, 1024) * u.TeV,\n out_base=\"PionDecayKafexhiu14_LUT_\",\n hiEmodel=None,\n nuclear_enhancement=True,\n): # pragma: no cover\n from emcee.interruptible_pool import InterruptiblePool as Pool\n\n pool = Pool()\n if hiEmodel is None:\n hiEmodel = [\"Geant4\", \"Pythia8\", \"SIBYLL\", \"QGSJET\"]\n elif type(hiEmodel) is str:\n hiEmodel = [hiEmodel]\n\n if nuclear_enhancement:\n out_base += \"NucEnh_\"\n\n for model in hiEmodel:\n out_file = out_base + model + \".npz\"\n print(\"Saving LUT for model {0} in {1}...\".format(model, out_file))\n args = [(Ep, eg, model, nuclear_enhancement) for eg in Eg]\n diffsigma_list = pool.map(_calc_lut_pp, args)\n\n diffsigma = np.array(diffsigma_list).T\n\n np.savez_compressed(\n out_file,\n X=np.log10(Ep.to(\"GeV\").value),\n Y=np.log10(Eg.to(\"GeV\").value),\n lut=np.log10(diffsigma),\n )\n", "meta": {"hexsha": "40fe77f95fd9d54c9838caca9db6870c2c74f097", "size": 65190, "ext": "py", "lang": "Python", "max_stars_repo_path": "naima/radiative.py", "max_stars_repo_name": "fossabot/naima", "max_stars_repo_head_hexsha": "577ea915ba6902822e67eb658edc2a3e7e859526", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "naima/radiative.py", "max_issues_repo_name": "fossabot/naima", "max_issues_repo_head_hexsha": "577ea915ba6902822e67eb658edc2a3e7e859526", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "naima/radiative.py", "max_forks_repo_name": "fossabot/naima", "max_forks_repo_head_hexsha": "577ea915ba6902822e67eb658edc2a3e7e859526", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7597099948, "max_line_length": 83, "alphanum_fraction": 0.5379812855, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 18372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771035, "lm_q2_score": 0.27825680567280014, "lm_q1q2_score": 0.149975745178648}} {"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: fangping wan\r\n\"\"\"\r\nimport numpy as np\r\nimport pickle\r\nimport tensorflow as tf\r\nfrom sklearn.metrics import roc_auc_score\r\nfrom sklearn.metrics import average_precision_score\r\nfrom sklearn.cross_validation import KFold, train_test_split, StratifiedKFold\r\nimport sys\r\nfrom optparse import OptionParser\r\nimport utils\r\nfrom utils import *\r\n\r\nparser = OptionParser()\r\nparser.add_option(\"-d\", \"--d\", default=512, help=\"The embedding dimension d\")\r\nparser.add_option(\"-n\",\"--n\",default=1, help=\"global norm to be clipped\")\r\nparser.add_option(\"-k\",\"--k\",default=256, help=\"The dimension of project matrices k\")\r\nparser.add_option(\"-r\",\"--r\",default = 1, help=\"Repetition times\")\r\nparser.add_option(\"-l\",\"--l\",default = 0.0,help=\"l2 coefficient\")\r\nparser.add_option(\"-p\",\"--p\",default = 25,help=\"period to evaluate\")\r\nparser.add_option(\"-e\",\"--e\",default = 5000,help=\"epoch num\")\r\n(opts, args) = parser.parse_args()\r\n\r\n\r\n#load network\r\ndrug_chemical = np.load('../data/Drug_simi_net.npy')\r\nprint np.shape(drug_chemical)\r\nprotein_protein = np.load('../data/PPI_net.npy')\r\nprint np.shape(protein_protein)\r\nprotein_sequence = np.load('../data/new_all_human_seq.npy')\r\nprint np.shape(protein_sequence)\r\nvirus_sequence = np.load('../data/all_seq_virus.npy')\r\nprint np.shape(virus_sequence)\r\n\r\nvirus_protein = np.load('../data/VHI_net.npy')\r\nprint np.shape(virus_protein)\r\nprotein_virus = virus_protein.T\r\n\r\n\r\n#normalize network for mean pooling aggregation\r\ndrug_chemical_normalize = row_normalize(drug_chemical,True)\r\nprotein_protein_normalize = row_normalize(protein_protein,True)\r\nprotein_sequence_normalize = row_normalize(protein_sequence,True)\r\nvirus_sequence_normalize = row_normalize(virus_sequence,True)\r\nvirus_protein_normalize = row_normalize(virus_protein,False)\r\nprotein_virus_normalize = row_normalize(protein_virus,False)\r\n\r\n#define computation graph\r\nnum_drug = len(drug_chemical)\r\nnum_protein = len(protein_protein_normalize)\r\nnum_virus = len(virus_sequence_normalize)\r\n\r\n\r\ndim_drug = int(opts.d)\r\ndim_protein = int(opts.d)\r\ndim_virus = int(opts.d)\r\n\r\ndim_pred = int(opts.k)\r\ndim_pass = int(opts.d)\r\n\r\nclass Model(object):\r\n def __init__(self):\r\n self._build_model()\r\n \r\n def _build_model(self):\r\n #inputs\r\n\r\n self.drug_chemical = tf.placeholder(tf.float32, [num_drug, num_drug])\r\n self.drug_chemical_normalize = tf.placeholder(tf.float32, [num_drug, num_drug])\r\n\r\n\r\n self.protein_protein = tf.placeholder(tf.float32, [num_protein, num_protein])\r\n self.protein_protein_normalize = tf.placeholder(tf.float32, [num_protein, num_protein])\r\n self.protein_protein_pos_idx = tf.placeholder(tf.int32, [None, 2])\r\n self.protein_protein_neg_idx = tf.placeholder(tf.int32, [None, 2])\r\n\r\n self.protein_sequence = tf.placeholder(tf.float32, [num_protein, num_protein])\r\n self.protein_sequence_normalize = tf.placeholder(tf.float32, [num_protein, num_protein])\r\n\r\n\r\n self.virus_sequence = tf.placeholder(tf.float32, [num_virus, num_virus])\r\n self.virus_sequence_normalize = tf.placeholder(tf.float32, [num_virus, num_virus])\r\n\r\n\r\n self.virus_protein = tf.placeholder(tf.float32, [num_virus, num_protein])\r\n self.virus_protein_normalize = tf.placeholder(tf.float32, [num_virus, num_protein])\r\n self.virus_protein_pos_idx = tf.placeholder(tf.int32, [None, 2])\r\n self.virus_protein_neg_idx = tf.placeholder(tf.int32, [None, 2])\r\n\r\n self.protein_virus = tf.placeholder(tf.float32, [num_protein, num_virus])\r\n self.protein_virus_normalize = tf.placeholder(tf.float32, [num_protein, num_virus])\r\n\r\n\r\n self.drug_protein = tf.placeholder(tf.float32, [num_drug, num_virus + num_protein])\r\n self.drug_protein_normalize = tf.placeholder(tf.float32, [num_drug, num_virus + num_protein])\r\n self.drug_protein_pos_idx = tf.placeholder(tf.int32, [None, 2])\r\n self.drug_protein_neg_idx = tf.placeholder(tf.int32, [None, 2])\r\n\r\n\r\n self.protein_drug = tf.placeholder(tf.float32, [num_protein, num_drug])\r\n self.protein_drug_normalize = tf.placeholder(tf.float32, [num_protein, num_drug])\r\n\r\n self.virus_drug = tf.placeholder(tf.float32, [num_virus, num_drug])\r\n self.virus_drug_normalize = tf.placeholder(tf.float32, [num_virus, num_drug])\r\n\r\n\r\n self.drug_protein_mask = tf.placeholder(tf.float32, [num_drug, num_virus + num_protein])\r\n\r\n\r\n\r\n #features\r\n self.drug_embedding = weight_variable([num_drug,dim_drug])\r\n self.protein_embedding = weight_variable([num_protein,dim_protein])\r\n self.virus_embedding = weight_variable([num_virus,dim_virus])\r\n\r\n tf.add_to_collection('loss_reg', tf.contrib.layers.l2_regularizer(1.0)(self.drug_embedding))\r\n tf.add_to_collection('loss_reg', tf.contrib.layers.l2_regularizer(1.0)(self.protein_embedding))\r\n tf.add_to_collection('loss_reg', tf.contrib.layers.l2_regularizer(1.0)(self.virus_embedding))\r\n\r\n #feature passing weights (maybe different types of nodes can use different weights)\r\n W0 = weight_variable([dim_pass+dim_drug, dim_drug])\r\n b0 = bias_variable([dim_drug])\r\n tf.add_to_collection('loss_reg', tf.contrib.layers.l2_regularizer(1.0)(W0))\r\n\r\n W1 = weight_variable([dim_pass+dim_drug, dim_drug])\r\n b1 = bias_variable([dim_drug])\r\n tf.add_to_collection('loss_reg', tf.contrib.layers.l2_regularizer(1.0)(W1))\r\n\r\n\r\n combined_emb = tf.concat([self.virus_embedding, self.protein_embedding], axis=0)\r\n\r\n #passing 1 times (can be easily extended to multiple passes)\r\n drug_vector1 = tf.nn.l2_normalize(tf.nn.relu(tf.matmul(\r\n tf.concat([\r\n tf.matmul(self.drug_chemical_normalize, a_layer(self.drug_embedding, dim_pass)) + \\\r\n tf.matmul(self.drug_protein_normalize, a_layer(combined_emb, dim_pass)), \\\r\n self.drug_embedding], axis=1), W0)+b0+self.drug_embedding),dim=1)\r\n\r\n protein_vector1 = tf.nn.l2_normalize(tf.nn.relu(tf.matmul(\r\n tf.concat([\r\n tf.matmul(self.protein_protein_normalize, a_layer(self.protein_embedding, dim_pass)) + \\\r\n tf.matmul(self.protein_sequence_normalize, a_layer(self.protein_embedding, dim_pass)) + \\\r\n tf.matmul(self.protein_virus_normalize, a_layer(self.virus_embedding, dim_pass)) + \\\r\n tf.matmul(self.protein_drug_normalize, a_layer(self.drug_embedding, dim_pass)), \\\r\n self.protein_embedding], axis=1), W0)+b0+self.protein_embedding),dim=1)\r\n\r\n\r\n virus_vector1 = tf.nn.l2_normalize(tf.nn.relu(tf.matmul(\r\n tf.concat([\r\n tf.matmul(self.virus_sequence_normalize, a_layer(self.virus_embedding, dim_pass)) + \\\r\n tf.matmul(self.virus_protein_normalize, a_layer(self.protein_embedding, dim_pass)) + \\\r\n tf.matmul(self.virus_drug_normalize, a_layer(self.drug_embedding, dim_pass)), \\\r\n self.virus_embedding], axis=1), W0)+b0+self.virus_embedding),dim=1)\r\n\r\n\r\n self.drug_representation_ = drug_vector1\r\n self.protein_representation_ = protein_vector1\r\n self.virus_representation_ = virus_vector1\r\n\r\n combined_emb_ = tf.concat([self.protein_representation_, self.virus_representation_], axis=0)\r\n\r\n #passing 2 times (can be easily extended to multiple passes)\r\n\r\n drug_vector2 = tf.nn.l2_normalize(tf.nn.relu(tf.matmul(\r\n tf.concat([\r\n tf.matmul(self.drug_chemical_normalize, a_layer(self.drug_representation_, dim_pass)) + \\\r\n tf.matmul(self.drug_protein_normalize, a_layer(combined_emb_, dim_pass)), \\\r\n self.drug_representation_], axis=1), W1)+b1+self.drug_representation_),dim=1)\r\n\r\n protein_vector2 = tf.nn.l2_normalize(tf.nn.relu(tf.matmul(\r\n tf.concat([\r\n tf.matmul(self.protein_protein_normalize, a_layer(self.protein_representation_, dim_pass)) + \\\r\n tf.matmul(self.protein_sequence_normalize, a_layer(self.protein_representation_, dim_pass)) + \\\r\n tf.matmul(self.protein_virus_normalize, a_layer(self.virus_representation_, dim_pass)) + \\\r\n tf.matmul(self.protein_drug_normalize, a_layer(self.drug_representation_, dim_pass)), \\\r\n self.protein_representation_], axis=1), W1)+b1+self.protein_representation_),dim=1)\r\n\r\n virus_vector2 = tf.nn.l2_normalize(tf.nn.relu(tf.matmul(\r\n tf.concat([\r\n tf.matmul(self.virus_sequence_normalize, a_layer(self.virus_representation_, dim_pass)) + \\\r\n tf.matmul(self.virus_protein_normalize, a_layer(self.protein_representation_, dim_pass)) + \\\r\n tf.matmul(self.virus_drug_normalize, a_layer(self.drug_representation_, dim_pass)), \\\r\n self.virus_representation_], axis=1), W1)+b1+self.virus_representation_),dim=1)\r\n\r\n\r\n\r\n self.drug_representation = drug_vector2\r\n self.protein_representation = protein_vector2\r\n self.virus_representation = virus_vector2\r\n\r\n\r\n\r\n combined_emb2 = tf.concat([self.virus_representation, self.protein_representation], axis=0)\r\n #reconstructing networks\r\n\r\n self.drug_chemical_reconstruct = bi_layer(self.drug_representation,self.drug_representation, sym=True, dim_pred=dim_pred)\r\n self.drug_chemical_reconstruct_loss = square_loss(self.drug_chemical_reconstruct, self.drug_chemical)\r\n\r\n\r\n self.protein_protein_reconstruct = bi_layer(self.protein_representation,self.protein_representation, sym=True, dim_pred=dim_pred)\r\n self.protein_protein_reconstruct_loss = rank_loss(self.protein_protein_reconstruct, self.protein_protein_pos_idx, self.protein_protein_neg_idx)\r\n\r\n self.protein_sequence_reconstruct = bi_layer(self.protein_representation,self.protein_representation, sym=True, dim_pred=dim_pred)\r\n self.protein_sequence_reconstruct_loss = square_loss(self.protein_sequence_reconstruct, self.protein_sequence)\r\n\r\n\r\n self.virus_sequence_reconstruct = bi_layer(self.virus_representation,self.virus_representation, sym=True, dim_pred=dim_pred)\r\n self.virus_sequence_reconstruct_loss = square_loss(self.virus_sequence_reconstruct, self.virus_sequence)\r\n\r\n self.virus_protein_reconstruct = bi_layer(self.virus_representation,self.protein_representation, sym=False, dim_pred=dim_pred)\r\n self.virus_protein_reconstruct_loss = rank_loss(self.virus_protein_reconstruct, self.virus_protein_pos_idx, self.virus_protein_neg_idx)\r\n\r\n\r\n self.drug_protein_reconstruct = bi_layer(self.drug_representation, combined_emb2, sym=False, dim_pred=dim_pred)\r\n self.drug_protein_reconstruct_loss = rank_loss(self.drug_protein_reconstruct, self.drug_protein_pos_idx, self.drug_protein_neg_idx)\r\n\r\n self.l2_loss = tf.add_n(tf.get_collection(\"loss_reg\"))\r\n\r\n self.loss = self.drug_protein_reconstruct_loss + 1.0*(self.drug_chemical_reconstruct_loss+\r\n self.protein_protein_reconstruct_loss+self.protein_sequence_reconstruct_loss+\r\n self.virus_sequence_reconstruct_loss+self.virus_protein_reconstruct_loss) + float(opts.l)*self.l2_loss\r\n\r\n\r\n\r\ngraph = tf.get_default_graph()\r\nwith graph.as_default():\r\n model = Model()\r\n learning_rate = tf.placeholder(tf.float32, [])\r\n total_loss = model.loss\r\n dti_loss = model.drug_protein_reconstruct_loss\r\n\r\n optimize = tf.train.AdamOptimizer(learning_rate)\r\n gradients, variables = zip(*optimize.compute_gradients(total_loss))\r\n gradients, _ = tf.clip_by_global_norm(gradients, float(opts.n))\r\n optimizer = optimize.apply_gradients(zip(gradients, variables))\r\n saver = tf.train.Saver()\r\n\r\n DTI_pred = model.drug_protein_reconstruct\r\n\r\n\r\ndef train_and_evaluate(DTItrain, DTIvalid, DTItest, graph, verbose=True, num_steps = 5000):\r\n\r\n DTI_test_mask = np.zeros((num_drug,num_virus + num_protein))\r\n for ele in DTItest:\r\n DTI_test_mask[ele[0],ele[1]] = 1\r\n\r\n drug_protein = np.zeros((num_drug,num_virus + num_protein))\r\n DTI_mask = np.zeros((num_drug,num_virus + num_protein))\r\n for ele in DTItrain:\r\n drug_protein[ele[0],ele[1]] = ele[2]\r\n DTI_mask[ele[0],ele[1]] = 1\r\n protein_drug = drug_protein.T[num_virus:]\r\n virus_drug = drug_protein.T[:num_virus]\r\n\r\n aux_matrix_dti = np.zeros((num_drug,num_virus + num_protein)) \r\n for ele in DTItrain:\r\n aux_matrix_dti[ele[0],ele[1]] = ele[2]\r\n for ele in DTIvalid:\r\n aux_matrix_dti[ele[0],ele[1]] = -1\r\n for ele in DTItest:\r\n aux_matrix_dti[ele[0],ele[1]] = -1\r\n\r\n drug_protein_normalize = row_normalize(drug_protein,False)\r\n protein_drug_normalize = row_normalize(protein_drug,False)\r\n virus_drug_normalize = row_normalize(virus_drug,False)\r\n\r\n\r\n lr = 0.001\r\n best_valid_aupr = 0\r\n best_pred = 0\r\n with tf.Session(graph=graph) as sess:\r\n tf.initialize_all_variables().run()\r\n for i in range(num_steps):\r\n\r\n\r\n protein_protein_pos_idx, protein_protein_neg_idx = sample(protein_protein)\r\n virus_protein_pos_idx, virus_protein_neg_idx = sample(virus_protein)\r\n drug_protein_pos_idx, drug_protein_neg_idx = sample(aux_matrix_dti)\r\n\r\n _, tloss, dtiloss, results_dti = sess.run([optimizer,total_loss,dti_loss, DTI_pred], \\\r\n feed_dict={\r\n model.drug_chemical:drug_chemical, model.drug_chemical_normalize:drug_chemical_normalize,\\\r\n model.protein_protein:protein_protein, model.protein_protein_normalize:protein_protein_normalize,\\\r\n model.protein_sequence:protein_sequence, model.protein_sequence_normalize:protein_sequence_normalize,\\\r\n model.virus_sequence:virus_sequence, model.virus_sequence_normalize:virus_sequence_normalize,\\\r\n model.virus_protein:virus_protein, model.virus_protein_normalize:virus_protein_normalize,\\\r\n model.protein_virus:protein_virus, model.protein_virus_normalize:protein_virus_normalize,\\\r\n\r\n\r\n\r\n model.drug_protein:drug_protein, model.drug_protein_normalize:drug_protein_normalize,\\\r\n model.protein_drug:protein_drug, model.protein_drug_normalize:protein_drug_normalize,\\\r\n model.virus_drug:virus_drug, model.virus_drug_normalize:virus_drug_normalize,\\\r\n\r\n\r\n model.drug_protein_mask:DTI_mask,\\\r\n learning_rate: lr,\\\r\n model.protein_protein_pos_idx : protein_protein_pos_idx,\\\r\n model.protein_protein_neg_idx : protein_protein_neg_idx,\\\r\n model.virus_protein_pos_idx : virus_protein_pos_idx,\\\r\n model.virus_protein_neg_idx : virus_protein_neg_idx,\\\r\n\r\n\r\n model.drug_protein_pos_idx : drug_protein_pos_idx,\\\r\n model.drug_protein_neg_idx : drug_protein_neg_idx\r\n })\r\n\r\n #every opts.p steps of gradient descent, evaluate the performance, other choices of this number are possible\r\n if (i+1) % int(opts.p) == 0 and verbose == True:\r\n print ('step',(i+1),'total and dtiloss',tloss, dtiloss)\r\n pred_list = []\r\n ground_truth = []\r\n for ele in DTItrain:\r\n pred_list.append(results_dti[ele[0],ele[1]])\r\n ground_truth.append(ele[2])\r\n DTItrain_auc = roc_auc_score(ground_truth, pred_list)\r\n DTItrain_aupr = average_precision_score(ground_truth, pred_list)\r\n\r\n pred_list = []\r\n ground_truth = []\r\n for ele in DTIvalid:\r\n pred_list.append(results_dti[ele[0],ele[1]])\r\n ground_truth.append(ele[2])\r\n DTIvalid_auc = roc_auc_score(ground_truth, pred_list)\r\n DTIvalid_aupr = average_precision_score(ground_truth, pred_list)\r\n\r\n if DTIvalid_aupr >= best_valid_aupr:\r\n best_valid_aupr = DTIvalid_aupr\r\n best_pred = results_dti\r\n #save_path = saver.save(sess, './model_'+str(opts.i)+'_'+str(r+1))\r\n\r\n\r\n v_pred_list = []\r\n v_ground_truth = []\r\n h_pred_list = []\r\n h_ground_truth = []\r\n for ele in DTItest:\r\n if ele[1] < num_virus:\r\n v_pred_list.append(results_dti[ele[0],ele[1]])\r\n v_ground_truth.append(ele[2])\r\n else:\r\n h_pred_list.append(results_dti[ele[0],ele[1]])\r\n h_ground_truth.append(ele[2])\r\n\r\n v_test_auc = roc_auc_score(v_ground_truth, v_pred_list)\r\n v_test_aupr = average_precision_score(v_ground_truth, v_pred_list)\r\n h_test_auc = roc_auc_score(h_ground_truth, h_pred_list)\r\n h_test_aupr = average_precision_score(h_ground_truth, h_pred_list)\r\n\r\n\r\n\r\n print ('DTI train auc aupr,', DTItrain_auc, DTItrain_aupr, 'DTI valid auc aupr,', DTIvalid_auc, DTIvalid_aupr)\r\n print ('Test virus dti auc, aupr', v_test_auc, v_test_aupr, 'Test human dti auc, aupr', h_test_auc, h_test_aupr)\r\n return best_pred, DTI_test_mask\r\n\r\n\r\nfor r in range(int(opts.r)):\r\n print ('repetition round',r+1)\r\n\r\n virus_dti = np.load('../data/VDTI_net.npy')\r\n human_dti = np.load('../data/HDTI_net.npy')\r\n print (np.shape(virus_dti), np.shape(human_dti))\r\n network_dti = np.hstack([virus_dti, human_dti])\r\n\r\n whole_positive_index_dti = []\r\n whole_negative_index_dti = []\r\n for i in range(np.shape(network_dti)[0]):\r\n for j in range(np.shape(network_dti)[1]):\r\n if int(network_dti[i][j]) == 1:\r\n whole_positive_index_dti.append([i,j])\r\n elif int(network_dti[i][j]) == 0:\r\n whole_negative_index_dti.append([i,j])\r\n\r\n negative_sample_index_dti = np.random.choice(np.arange(len(whole_negative_index_dti)),size=10*len(whole_positive_index_dti),replace=False)\r\n\r\n data_set_dti = np.zeros((len(negative_sample_index_dti)+len(whole_positive_index_dti),3),dtype=int)\r\n count = 0\r\n for i in whole_positive_index_dti:\r\n data_set_dti[count][0] = i[0]\r\n data_set_dti[count][1] = i[1]\r\n data_set_dti[count][2] = 1\r\n count += 1\r\n for i in negative_sample_index_dti:\r\n data_set_dti[count][0] = whole_negative_index_dti[i][0]\r\n data_set_dti[count][1] = whole_negative_index_dti[i][1]\r\n data_set_dti[count][2] = 0\r\n count += 1\r\n\r\n rs = np.random.randint(0,1000,1)[0]\r\n kf = StratifiedKFold(data_set_dti[:,2], n_folds=10, shuffle=True, random_state=rs)\r\n\r\n counter = 0\r\n for train_index, test_index in kf:\r\n DTItrain, DTItest = data_set_dti[train_index], data_set_dti[test_index]\r\n DTItrain, DTIvalid = train_test_split(DTItrain, test_size=0.05, random_state=rs)\r\n\r\n\r\n best_pred, test_mask = train_and_evaluate(DTItrain, DTIvalid, DTItest, graph=graph, num_steps=int(opts.e))\r\n \r\n counter += 1\r\n np.save('../output/NeoDTI_pred_rep_'+str(r+1)+'_fold_'+str(counter), best_pred)\r\n np.save('../output/NeoDTI_mask_rep_'+str(r+1)+'_fold_'+str(counter), test_mask)\r\nprint ('all finished')\r\n", "meta": {"hexsha": "63a20dd1d81da44ad98ccf7aa1e70957d06042f1", "size": 19829, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/NeoDTI_for_COVID19.py", "max_stars_repo_name": "FangpingWan/CoV-DTI", "max_stars_repo_head_hexsha": "ec01c3ecccd83643ad631d2bcc72ea2d130c547b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NeoDTI_for_COVID19.py", "max_issues_repo_name": "FangpingWan/CoV-DTI", "max_issues_repo_head_hexsha": "ec01c3ecccd83643ad631d2bcc72ea2d130c547b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-12T02:11:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T02:15:12.000Z", "max_forks_repo_path": "src/NeoDTI_for_COVID19.py", "max_forks_repo_name": "FangpingWan/CoV-DTI", "max_forks_repo_head_hexsha": "ec01c3ecccd83643ad631d2bcc72ea2d130c547b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.8399014778, "max_line_length": 152, "alphanum_fraction": 0.6643804529, "include": true, "reason": "import numpy", "num_tokens": 4665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.2974699363766584, "lm_q1q2_score": 0.14989693648709115}} {"text": "#!/usr/bin/env python3\n# Christopher Vollmers\n# Roger Volden\n\nimport sys\nimport numpy as np\n\ncontent_file = sys.argv[1]\nout_path = sys.argv[2]\ncutoff = float(sys.argv[3])\ngenome_file = sys.argv[4]\nrefine = sys.argv[5]\n\nminimum_read_count = 3\nminimum_read_coverage = 2\nsplice_site_width = 5\n\ndef scan_for_best_bin(entry, distance_range, iterator_shift, density_dict,\n base_cutoff_min, base_cutoff_max,\n peak_areas, chromosome, side):\n '''\n Inputs:\n entry (dict): bound:[features] for whichever chromosome\n distance_range (list): double the splice site width\n iterator_shift (int): determines which way you iterate (f/r)\n density_dict (dict): same as histo_left/right_bases but for a chromosome\n base_cutoff_min (int, 0): arbitrary lower cutoff\n base_cutoff_max (int, 5): arbitrary upper cutoff\n peak_areas (dict): keeps track of chromosome regions with peaks\n chromosome (str): which chromosome\n side (str): which direction to look (l/r)\n Outputs:\n best_extra_list (list): should be int, counts how many features\n peak_center (int): position of the center of the peak\n bases (list): distance b/w aligned blocks\n coverage_area (list): contains positions that were covered\n best_direction_l/r (dict): keeps track of highest counts in dist range\n '''\n\n best_extra_list, peak_center, bases = [], 0, []\n coverage_area, best_direction_l, best_direction_r = [], [], []\n for x in distance_range:\n extra_list_bases, extra_list_expression = [], []\n direction_l, direction_r = {}, {}\n coverage_set = []\n called = False\n for y in distance_range:\n try:\n called = peak_areas[chromosome][side][entry+x+y]\n except KeyError:\n pass\n if not called:\n highest_y, highest_y_pos = 0, 0\n for y in distance_range:\n try:\n for item in density_dict[entry+x+y]:\n extra_list_bases.append(item[0])\n extra_list_expression.append(1)\n if not direction_l.get(item[4]):\n direction_l[item[4]] = 1\n else:\n direction_l[item[4]] += 1\n if not direction_r.get(item[5]):\n direction_r[item[5]] = 1\n else:\n direction_r[item[5]] += 1\n for covered_position in item[3]:\n coverage_set.append(covered_position)\n except:\n pass\n\n if base_cutoff_min <= np.median(extra_list_bases) <= base_cutoff_max:\n if sum(extra_list_expression) > sum(best_extra_list):\n best_extra_list = extra_list_expression\n peak_center = entry + x\n bases = extra_list_bases\n coverage_area = coverage_set\n best_direction_l = direction_l\n best_direction_r = direction_r\n\n return best_extra_list, peak_center, bases, coverage_area, \\\n best_direction_l, best_direction_r\n\ndef determine_coverage(coverage_area, chromosome, reverse,\n peak_center, histo_coverage):\n '''\n Inputs:\n coverage_area (list): contains positions that were covered\n chromosome (str): which chromosome\n reverse (bool): determines which way you read the sequence\n peak_center (int): position of the center of the peak\n histo_coverage (dict): approximate positions of alignment starts\n Outputs:\n coverage (int): how many times the most covered feature was covered\n coverage_area (list): contains positions that were covered\n '''\n\n coverage = [0]\n coverage_area2 = []\n for covered_position in set(coverage_area):\n if coverage_area.count(covered_position) > 1:\n coverage_area2.append(covered_position)\n\n coverage_area = sorted(coverage_area2, reverse=reverse)\n counter = 0\n for base_f in coverage_area:\n count = 0\n if not reverse:\n if base_f > peak_center:\n count = 1\n elif reverse:\n if base_f < peak_center:\n count = 1\n if count == 1:\n if counter <= 3:\n counter += 1\n base_f = myround(base_f)\n try:\n coverage.append(histo_coverage[chromosome][base_f])\n except KeyError:\n pass\n else:\n break\n coverage = max(coverage)\n return coverage, coverage_area\n\ndef read_seq_file(inFile):\n '''Reads in FASTA files, returns a dict of header:sequence'''\n readDict = {}\n for line in open(inFile):\n line = line.rstrip()\n if not line:\n continue\n if line.startswith('>'):\n readDict[line[1:]] = ''\n lastHead = line[1:]\n else:\n readDict[lastHead] += line\n return readDict\n\ndef myround(x, base=10):\n '''Rounds to the nearest base'''\n return int(base * round(float(x)/base))\n\ndef find_peaks(density_dict, out, peaks, reverse, cutoff, base_cutoff_min,\n base_cutoff_max, histo_coverage, side, peak_areas, chromosome):\n '''\n Inputs:\n density_dict (dict): same as histo_left/right_bases but for a chromosome\n out (file): output bed file\n peaks (int): how many peaks\n reverse (bool): determines which way you read the sequence\n cutoff (float): inversely proportional to coverage\n base_cutoff_min (int, 0): arbitrary lower cutoff\n base_cutoff_max (int, 5): arbitrary upper cutoff\n histo_coverage (dict): approximate positions of alignment starts\n side (str): which direction to look (l/r)\n peak_areas (dict): keeps track of chromosome regions with peaks\n chromosome (str): which chromosome\n Outputs:\n peaks and peak_areas\n '''\n\n if not reverse:\n distance_range = range(-splice_site_width, splice_site_width)\n iterator_shift = 1\n if reverse:\n distance_range = range(splice_site_width, -splice_site_width, -1)\n iterator_shift =- 1\n\n entry_list = []\n for entry in density_dict:\n entry_list.append([entry, density_dict[entry]])\n\n for entry, density in sorted(entry_list,\n key=lambda x: sum(np.array(x[1])[:,2]),\n reverse=True):\n if len(density) >= minimum_read_count:\n if not peak_areas[chromosome][side].get(entry):\n\n best_extra_list, peak_center, bases, \\\n coverage_area, best_direction_l, best_direction_r \\\n = scan_for_best_bin(entry, distance_range, iterator_shift,\n density_dict, base_cutoff_min,\n base_cutoff_max, peak_areas,\n chromosome, side)\n\n coverage, coverage_area \\\n = determine_coverage(coverage_area, chromosome, reverse,\n peak_center, histo_coverage)\n\n if coverage > 0:\n proportion = round(sum(best_extra_list)/coverage, 3)\n print(chromosome + '\\t' + str(peak_center - 1) + '\\t'\n + str(peak_center + 1) + '\\t' + str(proportion))\n if proportion > cutoff:\n try:\n Left_TSS = best_direction_l['TSS']\n except:\n Left_TSS = 0\n try:\n Left_TES = best_direction_l['TES']\n except:\n Left_TES = 0\n try:\n Right_TSS = best_direction_r['TSS']\n except:\n Right_TSS = 0\n try:\n Right_TES = best_direction_r['TES']\n except:\n Right_TES = 0\n Left_to_Right = Left_TSS + Right_TES\n Right_to_Left = Left_TES + Right_TSS\n Type = '-'\n\n if Left_to_Right < Right_to_Left and reverse:\n Type = '3'\n elif Left_to_Right < Right_to_Left and not reverse:\n Type = '5'\n elif Left_to_Right > Right_to_Left and reverse:\n Type = '5'\n elif Left_to_Right > Right_to_Left and not reverse:\n Type = '3'\n\n if Type != '-':\n peaks += 1\n out.write(chromosome + '\\t'\n + str(peak_center-splice_site_width)\n + '\\t' + str(peak_center+splice_site_width)\n + '\\t' + str(Type) + side + str(peaks) + '_'\n + str(peak_center-splice_site_width) + '_'\n + str(peak_center+splice_site_width) + '_'\n + str(proportion) + '\\t' + str(peaks) + '\\n')\n for base in range(peak_center - splice_site_width,\n peak_center + splice_site_width):\n peak_areas[chromosome][side][base] = 1\n else:\n break\n\n return peaks, peak_areas\n\ndef collect_reads(content_file):\n '''\n Takes a content file and returns\n histo_left/right_bases (dict): information around upper/lower bounds\n chromosome_list (set): chromosomes with decent alignments\n histo_coverage (dict): approximate positions of alignment starts\n '''\n\n histo_left_bases, histo_right_bases = {}, {}\n chromosome_list_left, chromosome_list_right = set(), set()\n histo_coverage = {}\n base_cutoff_min, base_cutoff_max = 0, 5\n\n for line in open(content_file):\n total = 0\n b = line.strip().split('\\t')\n infile = b[0]\n\n length = 0\n\n for line in open(infile):\n total += 1\n a = line.strip().split('\\t')\n chromosome = a[13]\n\n if not histo_coverage.get(chromosome):\n histo_coverage[chromosome] = {}\n # matches, dir, query seq name\n score, direction, name = int(a[0]), a[8], a[9]\n coverage = int(name.split('_')[3])\n # collect necessary info from psl file\n if coverage >= minimum_read_coverage:\n length = int(name.split('_')[5].split('|')[0])\n begin, span = int(a[15]), int(a[16])\n blocksizes = a[18].split(',')[:-1]\n blockstarts = a[20].split(',')[:-1]\n readstarts = a[19].split(',')[:-1]\n\n # account for direction in naming\n if direction == '+':\n start_seq, end_seq = 'S', 'E'\n left_match, right_match = 'TSS', 'TES'\n\n else:\n start_seq, end_seq= 'E', 'S'\n left_match, right_match = 'TES', 'TSS'\n\n coverage_set = set()\n previous_blocksize, previous_start = -1, -1\n previous_blockend = np.inf\n intron, indel, indel1 = 0, 0, 0\n low_bounds, up_bounds = [], []\n aligned_bases = 0\n # for each alignment block\n for x in range(0, len(blocksizes)):\n blockstart = int(blockstarts[x])\n blocksize = int(blocksizes[x])\n readstart = int(readstarts[x])\n aligned_bases += blocksize\n blockend = blockstart + blocksize\n # only take alignment blocks >10bp\n if blocksize > 10:\n for y in range(0, blocksize, 10):\n rounded = myround(blockstart + y)\n coverage_set.add(rounded)\n for yy in range(y, blocksize):\n rounded = myround(blockstart + yy)\n coverage_set.add(rounded)\n if previous_start == -1:\n previous_start = blockstart\n min_length = 10\n\n if blockstart - previous_blockend > 20:\n previous_start = blockstart\n\n if blockend - previous_start > min_length:\n if intron == 1:\n up_bounds.append([previous_start, indel1, blockend])\n low_bounds.append([remember_blockend,\n remember_indel1, remember_start])\n intron = 0\n else:\n try:\n next_blockstart = int(blockstarts[x+1])\n next_blocksize = int(blocksizes[x+1])\n next_readstart = int(readstarts[x+1])\n\n insert = next_blockstart - blockend\n if insert > 50:\n indel1 = next_readstart \\\n - (readstart + blocksize)\n remember_blockend = blockend\n remember_indel1 = indel1\n remember_start = previous_start\n intron = 1\n previous_start = next_blockstart\n blockend = next_blockstart\n except:\n pass\n previous_blockend = blockend\n\n for rounded in coverage_set:\n try:\n histo_coverage[chromosome][rounded] += 1\n except:\n histo_coverage[chromosome][rounded] = 1\n\n # collect chromosome info either to the left or right of a bound\n if aligned_bases/length > 0.70:\n for low_bound, indel1, blockend in low_bounds:\n chromosome_list_left.add(chromosome)\n if not histo_left_bases.get(chromosome):\n histo_left_bases[chromosome] = {}\n if not histo_left_bases[chromosome].get(low_bound):\n histo_left_bases[chromosome][low_bound] = []\n histo_left_bases[chromosome][low_bound].append([indel1, begin,\n span, coverage_set,\n left_match,\n right_match])\n for up_bound, indel1, blockend in up_bounds:\n chromosome_list_right.add(chromosome)\n if not histo_right_bases.get(chromosome):\n histo_right_bases[chromosome] = {}\n if not histo_right_bases[chromosome].get(up_bound):\n histo_right_bases[chromosome][up_bound] = []\n histo_right_bases[chromosome][up_bound].append([indel1, begin,\n span, coverage_set,\n left_match,\n right_match])\n\n chromosome_list = chromosome_list_left & chromosome_list_right\n return histo_left_bases, histo_right_bases, chromosome_list, histo_coverage\n\ndef parse_genome(input_file, left_bounds, right_bounds):\n '''\n Takes a GTF file and dictionaries for left and right bounds\n and returns the same left and right bound dictionaries.\n\n Left/right bounds: dictionary of dictionaries of lists.\n {chromosome:{direction:[start/stop positions]}}\n '''\n\n # make a dictionary of transcript ID to its\n # chr name, start pos, stop pos, and direction\n # {transcript_ID:[(chr, start, stop, dir), (...) ...], ...}\n gene_dict = {}\n for line in open(input_file):\n a = line.strip().split('\\t')\n if len(a) > 7:\n if a[2] == 'exon':\n testKey = a[8].split('; transcript_id \"')[1].split('\"')[0]\n if not gene_dict.get(testKey):\n gene_dict[testKey] = []\n # append chr name, start pos, end pos, strand\n gene_dict[testKey].append((a[0], a[3], a[4], a[6]))\n\n read_list = []\n for transcript_id in gene_dict:\n transcript_data = gene_dict[transcript_id]\n\n chromosome = transcript_data[0][0]\n if not right_bounds.get(chromosome):\n left_bounds[chromosome], right_bounds[chromosome]= {}, {}\n left_bounds[chromosome]['5'], right_bounds[chromosome]['5'] = [], []\n left_bounds[chromosome]['3'], right_bounds[chromosome]['3'] = [], []\n\n # first start\n start = sorted(transcript_data, key=lambda x: int(x[1]))[0][1]\n # last end\n end = sorted(transcript_data, key=lambda x: int(x[2]), reverse=True)[0][2]\n\n # organize data by direction\n # only take the absolute start and absolute end for each transcript\n for entry in transcript_data:\n if entry[1] != start:\n if entry[3] == '+':\n right_bounds[chromosome]['3'].append(int(entry[1])-1)\n elif entry[3] == '-':\n right_bounds[chromosome]['5'].append(int(entry[1])-1)\n if entry[2] != end:\n if entry[3] == '+':\n left_bounds[chromosome]['5'].append(int(entry[2]))\n if entry[3] == '-':\n left_bounds[chromosome]['3'].append(int(entry[2]))\n return left_bounds, right_bounds\n\ndef make_genome_bins(bounds, side, peaks, chromosome, peak_areas):\n '''\n Takes the bounds for a chromosome, which side, the number of peaks,\n which chromosome, and peak areas and returns the number of peaks as\n well as the peak areas.\n bounds (dict): {chromosome:{direction:[start/stop positions]}}\n side (str): left or right (l/r)\n peaks (int): number of peaks\n chromosome (str): which chromosome\n peak_areas (dict): keeps track of chromosome regions with peaks\n '''\n\n for type1 in ['5', '3']:\n covered = {}\n position_list = sorted(bounds[type1], key=int)\n for index1 in range(0, len(position_list)):\n if not covered.get(index1):\n sub_list=[]\n sub_list.append(position_list[index1])\n for index2 in range(index1, len(position_list)):\n if position_list[index2] - max(sub_list) <= splice_site_width:\n sub_list.append(position_list[index2])\n covered[index2] = 1\n else:\n break\n single = 0\n if len(sub_list) > 1:\n splice_distances = []\n for splice_pos in range(0, len(sub_list)-1):\n splice_distances.append(int(sub_list[splice_pos+1])\n -int(sub_list[splice_pos]))\n if min(splice_distances) > 3:\n for x in range(0,len(sub_list),1):\n if x != 0:\n start = int(sub_list[x]\n - ((sub_list[x] - sub_list[x-1])/2))\n else:\n start = int(sub_list[x]) - 1\n if x != len(sub_list) - 1:\n end = int(sub_list[x]\n + ((sub_list[x+1] - sub_list[x])/2))\n else:\n end = int(sub_list[x]) + 1\n\n out.write(chromosome + '\\t' + str(start) + '\\t'\n + str(end) + '\\t' + type1 + side\n + str(peaks) + '_' + str(start) + '_'\n + str(end) + '_A' + '\\t' + str(peaks) + '\\n')\n for base in range(start, end):\n peak_areas[chromosome][side][base] = 1\n peaks += 1\n else:\n single = 1\n else:\n single = 1\n if single == 1:\n start = min(sub_list) - splice_site_width\n end = max(sub_list) + splice_site_width\n out.write(chromosome + '\\t' + str(start) + '\\t' + str(end)\n + '\\t' + type1 + side + str(peaks) + '_'\n + str(start) + '_' + str(end) + '_A'\n + '\\t' + str(peaks) + '\\n')\n for base in range(start-1, end+1):\n peak_areas[chromosome][side][base] = 1\n peaks += 1\n\n return peaks, peak_areas\n\nleft_bounds = {}\nright_bounds = {}\n\nleft_bounds, right_bounds = parse_genome(genome_file, left_bounds, right_bounds)\n\nLeft_Peaks = 0\nRight_Peaks = 0\n\nhisto_left_bases, histo_right_bases, \\\nchromosome_list, histo_coverage = collect_reads(content_file)\nout = open(out_path + '/SS.bed', 'w')\n\npeak_areas = {}\nprint(chromosome_list)\nfor chromosome in chromosome_list:\n peak_areas[chromosome] = {}\n peak_areas[chromosome]['l'] = {}\n peak_areas[chromosome]['r'] = {}\n print(chromosome)\n if 'g' in refine:\n Left_Peaks_old = Left_Peaks\n Right_Peaks_old = Right_Peaks\n Left_Peaks, peak_areas = make_genome_bins(left_bounds[chromosome], 'l',\n Left_Peaks, chromosome, peak_areas)\n Right_Peaks, peak_areas = make_genome_bins(right_bounds[chromosome], 'r',\n Right_Peaks, chromosome, peak_areas)\n print('Annotation-Based',\n Left_Peaks - Left_Peaks_old,\n Right_Peaks - Right_Peaks_old)\n Left_Peaks_old = Left_Peaks\n Right_Peaks_old = Right_Peaks\n Left_Peaks, peak_areas = find_peaks(histo_left_bases[chromosome],\n out, Left_Peaks, True, cutoff,\n 0, 5, histo_coverage, 'l',\n peak_areas, chromosome)\n Right_Peaks, peak_areas = find_peaks(histo_right_bases[chromosome],\n out, Right_Peaks, False, cutoff,\n 0, 5, histo_coverage, 'r',\n peak_areas, chromosome)\n print('Read-Based',\n Left_Peaks - Left_Peaks_old,\n Right_Peaks - Right_Peaks_old)\nprint(Left_Peaks)\nprint(Right_Peaks)\n", "meta": {"hexsha": "96c9583038e21b313d9141322d53fc5d87b40abd", "size": 23606, "ext": "py", "lang": "Python", "max_stars_repo_path": "spliceSites.py", "max_stars_repo_name": "rvolden/Mandalorion-Episode-II", "max_stars_repo_head_hexsha": "6219d58be7d198d249a840d147efae0cd975ed22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2018-08-25T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-10T23:00:53.000Z", "max_issues_repo_path": "spliceSites.py", "max_issues_repo_name": "rvolden/Mandalorion-Episode-II", "max_issues_repo_head_hexsha": "6219d58be7d198d249a840d147efae0cd975ed22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-07-23T06:59:18.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-13T17:34:09.000Z", "max_forks_repo_path": "spliceSites.py", "max_forks_repo_name": "rvolden/Mandalorion-Episode-II", "max_forks_repo_head_hexsha": "6219d58be7d198d249a840d147efae0cd975ed22", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-06-14T20:23:00.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-14T20:23:00.000Z", "avg_line_length": 43.6340110906, "max_line_length": 91, "alphanum_fraction": 0.4929255274, "include": true, "reason": "import numpy", "num_tokens": 4691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.29746993014852224, "lm_q1q2_score": 0.14989693334869492}} {"text": "# Authors: Stephane Gaiffas \n# License: BSD 3 clause\n\n\"\"\"\nThis module contains all required container types for nodes (including the\nnode numpy dtypes and several functions operating locally in nodes.\n\"\"\"\n\nfrom math import log\nimport numpy as np\nfrom numba import from_dtype, jit, boolean, uint8, intp, uintp, float32, void\nfrom numba.experimental import jitclass\n\nfrom ._utils import get_type, sample_without_replacement\nfrom ._tree_context import TreeClassifierContextType, TreeRegressorContextType\n\n\n# This data-type describes all the information saved about a node.\n# It's used in _tree.py where the Tree dataclass contains an attribute called nodes\n# that uses this data type.\nnode_dtype = np.dtype(\n [\n # Index of the node in the nodes array\n (\"node_id\", np.uintp),\n #\n # Index of the parent node\n (\"parent\", np.uintp),\n #\n # Index of the left child node (it's TREE_LEAF is node is a leaf)\n (\"left_child\", np.intp),\n #\n # Index of the right child node (it's TREE_LEAF is node is a leaf)\n (\"right_child\", np.intp),\n #\n # Is the node a leaf ?\n (\"is_leaf\", np.bool),\n #\n # Is the node a left child ? (it's ? for the root node)\n (\"is_left\", np.bool),\n #\n # Depth of the node in the tree\n (\"depth\", np.uintp),\n #\n # Feature used for splitting the node (it's ??? if node is a leaf)\n (\"feature\", np.uintp),\n #\n # Continuous threshold used for splitting the node (not used for now)\n (\"threshold\", np.float32),\n #\n # Index of the bin threshold used for splitting the node\n (\"bin_threshold\", np.uint8),\n #\n # Impurity of the node. Used to avoid to split a \"pure\" node (with impurity=0).\n # Note that impurity is computed using training samples (as all tree-growing\n # related things)\n (\"impurity\", np.float32),\n #\n # Validation loss of the node, computed on validation (out-of-the-bag) samples\n (\"loss_valid\", np.float32),\n #\n # Logarithm of the subtree aggregation weight\n (\"log_weight_tree\", np.float32),\n #\n # Number of training samples in the node\n (\"n_samples_train\", np.uintp),\n #\n # Number of validation (out-of-the-bag) samples in the node\n (\"n_samples_valid\", np.uintp),\n #\n # Weighted number of training samples in the node\n (\"w_samples_train\", np.float32),\n #\n # Weighted number of validation (out-of-the-bag) samples in the node\n (\"w_samples_valid\", np.float32),\n #\n # Index of the first training sample in the node. We have that\n # partition_train[start_train:end_train] contains the indexes of the node's\n # training samples\n (\"start_train\", np.uintp),\n #\n # End-index of the slice containing the node's training samples indexes\n (\"end_train\", np.uintp),\n #\n # Index of the first validation (out-of-the-bag) sample in the node. We have\n # that partition_valid[start_valid:end_valid] contains the indexes of the\n # node's validation samples\n (\"start_valid\", np.uintp),\n #\n # End-index of the slice containing the node's validation samples indexes\n (\"end_valid\", np.uintp),\n ]\n)\n\n\n# Convert this dtype to a numba-usable data-type\nnode_type = from_dtype(node_dtype)\n\n\n# TODO: many attributes are not used in the node_context ?\n\n# A node_context contains all the data required to find the best split of the node\nnode_context_type = [\n # This array contains the index of all the features. This will be modified\n # inplace when sampling features to be considered for splits\n (\"features_pool\", uintp[::1]),\n #\n # This array will contain the features sampled uniformly at random (without\n # replacement) to be considered for splits\n (\"features_sampled\", uintp[::1]),\n #\n # Do we need to perform features sampling ?\n (\"sample_features\", boolean),\n #\n # Number of training samples in the node\n (\"n_samples_train\", intp),\n #\n # Number of validation (out-of-the-bag) samples in the node\n (\"n_samples_valid\", intp),\n #\n # Weighted number of training samples in the node\n (\"w_samples_train\", float32),\n #\n # Weighted number of validation (out-of-the-bag) samples in the node\n (\"w_samples_valid\", float32),\n #\n # Index of the first training sample in the node. We have that\n # partition_train[start_train:end_train] contains the indexes of the node's\n # training samples\n (\"start_train\", intp),\n #\n # End-index of the slice containing the node's training samples indexes\n (\"end_train\", intp),\n #\n # Index of the first validation (out-of-the-bag) sample in the node. We have\n # that partition_valid[start_valid:end_valid] contains the indexes of the\n # node's validation samples\n (\"start_valid\", intp),\n #\n # End-index of the slice containing the node's validation samples indexes\n (\"end_valid\", intp),\n #\n # Validation loss of the node, computed on validation (out-of-the-bag) samples\n (\"loss_valid\", float32),\n #\n # Weighted number of training samples for each (feature, bin) in the node\n (\"w_samples_train_in_bins\", float32[:, ::1]),\n #\n # Weighted number of validation samples for each (feature, bin) in the node\n (\"w_samples_valid_in_bins\", float32[:, ::1]),\n]\n\n\nnode_classifier_context_type = [\n *node_context_type,\n #\n # Weighted number of training samples for each (feature, bin, label) in the node\n (\"y_sum\", float32[:, :, ::1]),\n #\n # Prediction produced by the node using the training data it contains\n (\"y_pred\", float32[::1]),\n]\n\n\nnode_regressor_context_type = [\n *node_context_type,\n #\n # Weighted sum of the labels for each (feature, bin) in the node\n (\"y_sum\", float32[:, ::1]),\n #\n # Weighted sum of the squared labels for each (feature, bin) in the node\n (\"y_sq_sum\", float32[:, ::1]),\n #\n # Prediction produced by the node using the training data it contains\n (\"y_pred\", float32),\n]\n\n\n@jitclass(node_classifier_context_type)\nclass NodeClassifierContext:\n \"\"\"A node_context contains all the data required to find the best split of the\n node for a classification tree.\n\n Parameters\n ----------\n tree_context : TreeClassifierContext\n An object describing the context of the tree\n\n Attributes\n ----------\n features_pool : ndarray\n Array of shape (n_features,) of intp dtype containing all the features\n indexes, namely [0, ..., n_features-1]\n\n features_sampled : ndarray\n Array of shape (max_features,) of intp dtype containing sampled features to\n be considered for possible splitting\n\n sample_features : bool\n Do we need to perform features sampling ? (This if True if n_features !=\n max_features and False otherwise)\n\n features : ndarray\n Array of shape (max_features,) of intp dtype containing the candidate features\n for splitting. These features are chosen uniformly at random each time a\n split is looked for\n\n n_samples_train : int\n Number of training samples in the node\n\n n_samples_valid : int\n Number of validation (out-of-the-bag) samples in the node\n\n w_samples_train : float\n Weighted number of training samples in the node\n\n w_samples_valid : float\n Weighted number of validation (out-of-the-bag) samples in the node\n\n start_train : int\n Index of the first training sample in the node. We have that\n partition_train[start_train:end_train] contains the indexes of the node's\n training samples\n\n end_train : int\n End-index of the slice containing the node's training samples indexes\n\n start_valid : int\n Index of the first validation (out-of-the-bag) sample in the node. We have\n that partition_valid[start_valid:end_valid] contains the indexes of the\n node's validation samples\n\n end_valid : int\n End-index of the slice containing the node's validation samples indexes\n\n loss_valid : float\n Validation loss of the node, computed on validation (out-of-the-bag) samples\n\n w_samples_train_in_bins : ndarray\n Weighted number of training samples for each (feature, bin) in the node\n\n w_samples_valid_in_bins : ndarray\n Weighted number of validation samples for each (feature, bin) in the node\n\n y_sum : ndarray\n Weighted number of training samples for each (feature, bin, label) in the node\n\n y_pred : ndarray\n Prediction produced by the node using the training data it contains\n \"\"\"\n\n def __init__(self, tree_context):\n init_node_context(tree_context, self)\n max_features = tree_context.max_features\n max_bins = tree_context.max_bins\n n_classes = tree_context.n_classes\n self.y_sum = np.empty((max_features, max_bins, n_classes), dtype=np.float32)\n self.y_pred = np.empty(n_classes, dtype=np.float32)\n\n\n@jitclass(node_regressor_context_type)\nclass NodeRegressorContext:\n \"\"\"A node_context contains all the data required to find the best split of the\n node for a regression tree.\n\n Parameters\n ----------\n tree_context : TreeRegressorContext\n An object describing the context of the tree\n\n Attributes\n ----------\n features_pool : ndarray\n Array of shape (n_features,) of intp dtype containing all the features\n indexes, namely [0, ..., n_features-1]\n\n features_sampled : ndarray\n Array of shape (max_features,) of intp dtype containing sampled features to\n be considered for possible splitting\n\n sample_features : bool\n Do we need to perform features sampling ? (This if True if n_features !=\n max_features and False otherwise)\n\n features : ndarray\n Array of shape (max_features,) of intp dtype containing the candidate features\n for splitting. These features are chosen uniformly at random each time a\n split is looked for\n\n n_samples_train : int\n Number of training samples in the node\n\n n_samples_valid : int\n Number of validation (out-of-the-bag) samples in the node\n\n w_samples_train : float\n Weighted number of training samples in the node\n\n w_samples_valid : float\n Weighted number of validation (out-of-the-bag) samples in the node\n\n start_train : int\n Index of the first training sample in the node. We have that\n partition_train[start_train:end_train] contains the indexes of the node's\n training samples\n\n end_train : int\n End-index of the slice containing the node's training samples indexes\n\n start_valid : int\n Index of the first validation (out-of-the-bag) sample in the node. We have\n that partition_valid[start_valid:end_valid] contains the indexes of the\n node's validation samples\n\n end_valid : int\n End-index of the slice containing the node's validation samples indexes\n\n loss_valid : float\n Validation loss of the node, computed on validation (out-of-the-bag) samples\n\n w_samples_train_in_bins : ndarray\n Weighted number of training samples for each (feature, bin) in the node\n\n w_samples_valid_in_bins : ndarray\n Weighted number of validation samples for each (feature, bin) in the node\n\n y_sum : ndarray\n Weighted sum of the labels for each (feature, bin) in the node\n\n y_sq_sum : ndarray\n Weighted sum of the squared labels for each (feature, bin) in the node\n\n y_pred : float\n Prediction produced by the node using the training data it contains\n \"\"\"\n\n def __init__(self, tree_context):\n init_node_context(tree_context, self)\n max_features = tree_context.max_features\n max_bins = tree_context.max_bins\n self.y_sum = np.empty((max_features, max_bins), dtype=np.float32)\n self.y_sq_sum = np.empty((max_features, max_bins), dtype=np.float32)\n self.y_pred = 0.0\n\n\nNodeClassifierContextType = get_type(NodeClassifierContext)\nNodeRegressorContextType = get_type(NodeRegressorContext)\n\n\n@jit(\n [\n void(TreeClassifierContextType, NodeClassifierContextType),\n void(TreeRegressorContextType, NodeRegressorContextType),\n ],\n nopython=True,\n nogil=True,\n)\ndef init_node_context(tree_context, node_context):\n \"\"\"A common initializer for NodeContextClassifier and NodeContextRegressor.\n Since numba's jitclass support for inheritance is inexistant, we use this\n function both in the constructors of NodeContextClassifier and NodeContextRegressor.\n\n Parameters\n ----------\n tree_context : TreeContext\n An object describing the context of the tree\n\n node_context : NodeClassifierContext or NodeRegressorContext\n The node context that we be partly initialized by this function\n \"\"\"\n max_features = tree_context.max_features\n max_bins = tree_context.max_bins\n n_features = tree_context.n_features\n # If max_features is the same as n_features, we don't need to sample features\n node_context.sample_features = max_features != n_features\n # This array contains the index of all the features. This will be modified\n # inplace when sampling features to be considered for splits\n node_context.features_pool = np.arange(0, n_features, dtype=np.uintp)\n # This array will contain the features sampled uniformly at random (without\n # replacement) to be considered for splits\n node_context.features_sampled = np.arange(0, max_features, dtype=np.uintp)\n node_context.w_samples_train_in_bins = np.empty(\n (max_features, max_bins), dtype=np.float32\n )\n node_context.w_samples_valid_in_bins = np.empty(\n (max_features, max_bins), dtype=np.float32\n )\n\n\n@jit(\n void(\n TreeClassifierContextType, NodeClassifierContextType, uintp, uintp, uintp, uintp\n ),\n nopython=True,\n nogil=True,\n boundscheck=False,\n locals={\n \"w_samples_train_in_bins\": float32[:, ::1],\n \"w_samples_valid_in_bins\": float32[:, ::1],\n \"y_sum\": float32[:, :, ::1],\n \"y_pred\": float32[::1],\n \"features\": uintp[::1],\n \"X\": uint8[:, :],\n \"y\": float32[::1],\n \"sample_weights\": float32[::1],\n \"partition_train\": uintp[::1],\n \"partition_valid\": uintp[::1],\n \"n_classes\": uintp,\n \"dirichlet\": float32,\n \"train_indices\": uintp[::1],\n \"valid_indices\": uintp[::1],\n \"w_samples_train\": float32,\n \"w_samples_valid\": float32,\n \"f\": uintp,\n \"loss_valid\": float32,\n \"feature\": uintp,\n \"sample\": uintp,\n \"bin\": uint8,\n \"label\": uintp,\n \"sample_weight\": float32,\n \"k\": uintp,\n },\n)\ndef compute_node_classifier_context(\n tree_context, node_context, start_train, end_train, start_valid, end_valid\n):\n \"\"\"Computes the node context from the data and from the tree context for\n classification. Computations are saved in the passed node_context.\n\n Parameters\n ----------\n tree_context : TreeContext\n The tree context\n\n node_context : NodeClassifierContext\n The node context that this function will compute\n\n start_train : int\n Index of the first training sample in the node. We have that\n partition_train[start_train:end_train] contains the indexes of the node's\n training samples\n\n end_train : int\n End-index of the slice containing the node's training samples indexes\n\n start_valid : int\n Index of the first validation (out-of-the-bag) sample in the node. We have\n that partition_valid[start_valid:end_valid] contains the indexes of the\n node's validation samples\n\n end_valid : int\n End-index of the slice containing the node's validation samples indexes\n \"\"\"\n # Initialize the things from the node context\n w_samples_train_in_bins = node_context.w_samples_train_in_bins\n w_samples_valid_in_bins = node_context.w_samples_valid_in_bins\n y_sum = node_context.y_sum\n y_pred = node_context.y_pred\n\n # If necessary, sample the features\n if node_context.sample_features:\n sample_without_replacement(\n node_context.features_pool, node_context.features_sampled\n )\n\n features = node_context.features_sampled\n w_samples_train_in_bins.fill(0.0)\n w_samples_valid_in_bins.fill(0.0)\n y_sum.fill(0.0)\n y_pred.fill(0.0)\n\n # Get information from the tree context\n X = tree_context.X\n y = tree_context.y\n sample_weights = tree_context.sample_weights\n partition_train = tree_context.partition_train\n partition_valid = tree_context.partition_valid\n n_classes = tree_context.n_classes\n dirichlet = tree_context.dirichlet\n\n # The indices of the training samples contained in the node\n train_indices = partition_train[start_train:end_train]\n valid_indices = partition_valid[start_valid:end_valid]\n\n # Weighted number of training and validation samples\n w_samples_train = 0.0\n w_samples_valid = 0.0\n\n # A counter for the features\n f = 0\n # The validation loss\n loss_valid = 0.0\n\n # TODO: unrolling the for loop could be faster\n # For-loop on features first and then samples (X is F-major)\n\n for feature in features:\n # Compute statistics about training samples\n for sample in train_indices:\n bin = X[sample, feature]\n label = uintp(y[sample])\n sample_weight = sample_weights[sample]\n if f == 0:\n w_samples_train += sample_weight\n y_pred[label] += sample_weight\n # One more sample in this bin for the current feature\n w_samples_train_in_bins[f, bin] += sample_weight\n # One more sample in this bin for the current feature with this label\n y_sum[f, bin, label] += sample_weight\n\n # TODO: we should put this outside so that we can change the dirichlet parameter\n # without rebuilding the tree\n # The prediction is given by the formula\n # y_k = (n_k + dirichlet) / (n_samples + dirichlet * n_classes)\n # where n_k is the number of samples with label class k\n if f == 0:\n for k in range(n_classes):\n y_pred[k] = (y_pred[k] + dirichlet) / (\n w_samples_train + n_classes * dirichlet\n )\n\n # Compute sample counts about validation samples\n for sample in valid_indices:\n bin = X[sample, feature]\n sample_weight = sample_weights[sample]\n if f == 0:\n w_samples_valid += sample_weight\n label = uintp(y[sample])\n # TODO: aggregation loss is hard-coded here. Call a function instead\n # when implementing other losses\n loss_valid += - w_samples_valid * log(y_pred[label])\n\n w_samples_valid_in_bins[f, bin] += sample_weight\n\n f += 1\n\n # Save remaining things in the node context\n node_context.n_samples_train = end_train - start_train\n node_context.n_samples_valid = end_valid - start_valid\n node_context.loss_valid = loss_valid\n node_context.w_samples_train = w_samples_train\n node_context.w_samples_valid = w_samples_valid\n\n\n@jit(\n void(\n TreeRegressorContextType, NodeRegressorContextType, uintp, uintp, uintp, uintp\n ),\n nopython=True,\n nogil=True,\n boundscheck=False,\n locals={\n \"w_samples_train_in_bins\": float32[:, ::1],\n \"w_samples_valid_in_bins\": float32[:, ::1],\n \"y_sum\": float32[:, ::1],\n \"y_sq_sum\": float32[:, ::1],\n \"y_pred\": float32,\n \"features\": uintp[::1],\n \"X\": uint8[:, :],\n \"y\": float32[::1],\n \"sample_weights\": float32[::1],\n \"partition_train\": uintp[::1],\n \"partition_valid\": uintp[::1],\n \"train_indices\": uintp[::1],\n \"valid_indices\": uintp[::1],\n \"w_samples_train\": float32,\n \"w_samples_valid\": float32,\n \"f\": uintp,\n \"loss_valid\": float32,\n \"feature\": uintp,\n \"sample\": uintp,\n \"bin\": uint8,\n \"label\": float32,\n \"sample_weight\": float32,\n \"k\": uintp,\n \"w_y\": float32,\n },\n)\ndef compute_node_regressor_context(\n tree_context, node_context, start_train, end_train, start_valid, end_valid\n):\n \"\"\"Computes the node context from the data and from the tree context for regression.\n Computations are saved in the passed node_context.\n\n Parameters\n ----------\n tree_context : TreeContext\n The tree context\n\n node_context : NodeRegressorContext\n The node context that this function will compute\n\n start_train : int\n Index of the first training sample in the node. We have that\n partition_train[start_train:end_train] contains the indexes of the node's\n training samples\n\n end_train : int\n End-index of the slice containing the node's training samples indexes\n\n start_valid : int\n Index of the first validation (out-of-the-bag) sample in the node. We have\n that partition_valid[start_valid:end_valid] contains the indexes of the\n node's validation samples\n\n end_valid : int\n End-index of the slice containing the node's validation samples indexes\n \"\"\"\n # Initialize the things from the node context\n w_samples_train_in_bins = node_context.w_samples_train_in_bins\n w_samples_valid_in_bins = node_context.w_samples_valid_in_bins\n y_sum = node_context.y_sum\n y_sq_sum = node_context.y_sq_sum\n\n # If necessary, sample the features\n if node_context.sample_features:\n sample_without_replacement(\n node_context.features_pool, node_context.features_sampled\n )\n\n features = node_context.features_sampled\n w_samples_train_in_bins.fill(0.0)\n w_samples_valid_in_bins.fill(0.0)\n y_sum.fill(0.0)\n y_sq_sum.fill(0.0)\n y_pred = 0.0\n\n # Get information from the tree context\n X = tree_context.X\n y = tree_context.y\n sample_weights = tree_context.sample_weights\n partition_train = tree_context.partition_train\n partition_valid = tree_context.partition_valid\n\n # The indices of the training samples contained in the node\n train_indices = partition_train[start_train:end_train]\n valid_indices = partition_valid[start_valid:end_valid]\n\n # Weighted number of training and validation samples\n w_samples_train = 0.0\n w_samples_valid = 0.0\n\n # A counter for the features\n f = 0\n # The validation loss\n loss_valid = 0.0\n\n # TODO: unrolling the for loop could be faster\n # For-loop on features first and then samples (X is F-major)\n\n for feature in features:\n # Compute statistics about training samples\n for sample in train_indices:\n bin = X[sample, feature]\n label = y[sample]\n sample_weight = sample_weights[sample]\n w_y = sample_weight * label\n if f == 0:\n w_samples_train += sample_weight\n y_pred += w_y\n # One more sample in this bin for the current feature\n w_samples_train_in_bins[f, bin] += sample_weight\n # One more sample in this bin for the current feature with this label\n\n y_sum[f, bin] += w_y\n y_sq_sum[f, bin] += w_y * label\n\n # The prediction is simply the weighted average of labels\n if f == 0:\n y_pred /= w_samples_train\n\n # Compute sample counts about validation samples\n for sample in valid_indices:\n bin = X[sample, feature]\n sample_weight = sample_weights[sample]\n if f == 0:\n w_samples_valid += sample_weight\n label = y[sample]\n # TODO: aggregation loss is hard-coded here. Call a function instead\n # when implementing other losses\n loss_valid += sample_weight * (label - y_pred) * (label - y_pred)\n\n w_samples_valid_in_bins[f, bin] += sample_weight\n\n f += 1\n\n # Save remaining things in the node context\n node_context.y_pred = y_pred\n node_context.n_samples_train = end_train - start_train\n node_context.n_samples_valid = end_valid - start_valid\n node_context.loss_valid = loss_valid\n node_context.w_samples_train = w_samples_train\n node_context.w_samples_valid = w_samples_valid\n", "meta": {"hexsha": "4472c17fbdc99e5cd1e95284cbb3da4c92b5a84c", "size": 24565, "ext": "py", "lang": "Python", "max_stars_repo_path": "wildwood/_node.py", "max_stars_repo_name": "yiyang-yu/wildwood", "max_stars_repo_head_hexsha": "4c0ef4ef92a8488e908803da8862605f147bb07d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "wildwood/_node.py", "max_issues_repo_name": "yiyang-yu/wildwood", "max_issues_repo_head_hexsha": "4c0ef4ef92a8488e908803da8862605f147bb07d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wildwood/_node.py", "max_forks_repo_name": "yiyang-yu/wildwood", "max_forks_repo_head_hexsha": "4c0ef4ef92a8488e908803da8862605f147bb07d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4473304473, "max_line_length": 88, "alphanum_fraction": 0.6645226949, "include": true, "reason": "import numpy,from numba", "num_tokens": 5627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244837, "lm_q2_score": 0.26284183737131667, "lm_q1q2_score": 0.14978112176881858}} {"text": "\"\"\"Spectral shaping.\"\"\"\n\nfrom scipy.interpolate import interp1d\n\nimport numpy as np\n\n# most of the contents of this file is heritage or not used. That reflects\n# a change in CGI practice. Formerly, we used CBE values for coatings, etc.\n# that posture has changed: we now lump things into a scalar value, which\n# removes the spectral shaping from anything other than the star, detector,\n# or FPM.\n\n\nCGI_PUPIL_AREA = 0.641*2.363*2.363 # 64.1% of the enclosing rectangle (close enough)\n\n# standard LOWFS bandpass, 9 wavelengths of spectral sampling\nLOWFS_LOWER = (575-64)/1e3\nLOWFS_UPPER = (575+64)/1e3\n\n\ndef mk_bandpass(n):\n \"\"\"Make a LOWFS bandpass with n wavelengths.\"\"\"\n if n == 1:\n return np.array([.575])\n\n return np.linspace(LOWFS_LOWER, LOWFS_UPPER, n)\n\n\nLOWFS_BANDPASS = mk_bandpass(9)\n\n\nCGI_BASIC_COATINGS = {\n 'HRC': 7, # = OTA+TCA, per Bijan\n 'FSS99': 7+1, # = CGI front-end + rad shield mirror (LOCAM)\n 'Al': 2, # = DM1+DM2, CGI front-end\n 'BBAR': 3, # LOWFS lenses\n}\n# additions...\n# HLC => +1 FSS99 (SPM)\n# SPC => +1 Al (SPM)\n\n\nclass ThroughputDatabase:\n \"\"\"Database of spectral throughputs.\"\"\"\n\n def __init__(self, emccd): # historical: first arg coatings\n \"\"\"Create a new database of throughputs.\n\n Parameters\n ----------\n coatings : `dict`\n keys of strings, which are the names of coatings\n values of scipy.interpolation.interp1d returns\n emccd : `scipy.interpolation.interp1d`\n interp1d of emccd data\n\n \"\"\"\n # self.coatings = coatings\n self.emccd_interpf = emccd\n\n def __call__(self, corongraph_mode, wavelengths):\n \"\"\"Spectral shape andthroughput for mode & wavelengths.\"\"\"\n # hrc = self.coatings['HRC']\n # fss99 = self.coatings['FSS99']\n # al = self.coatings['Al']\n # bbar = self.coatings['bbar']\n\n # n_hrc = CGI_BASIC_COATINGS['HRC']\n # n_fss99 = CGI_BASIC_COATINGS['FSS99']\n # n_al = CGI_BASIC_COATINGS['Al']\n # n_bbar = CGI_BASIC_COATINGS['BBAR']\n # if corongraph_mode == 'HLC':\n # # not += 1 to avoid any chance of modifying the dict\n # n_fss99 = n_fss99 + 1\n # else:\n # n_al = n_al + 1\n\n # hrc = hrc(wavelengths) ** n_hrc\n # fss99 = fss99(wavelengths) ** n_fss99\n # al = al(wavelengths) ** n_al\n # bbar = bbar(wavelengths) ** n_bbar\n emccd = self.emccd_interpf(wavelengths)\n # return hrc * fss99 * al * bbar * emccd\n corongraph_mode = corongraph_mode.upper()\n # from LOWFS_photometry 20200801, Throughput sheet. BOL REQs\n if corongraph_mode == 'HLC':\n return 0.3443 * emccd\n elif corongraph_mode == 'SPEC':\n return 0.3092 * emccd\n elif corongraph_mode == 'WFOV':\n return 0.3092 * emccd\n else:\n raise ValueError('invalid coronagraph mode: must be HLC, SPEC, or WFOV')\n\n @classmethod\n def bijan_data(cls, data_fldr):\n \"\"\"Load data from Bijan.\"\"\"\n emccd_data = np.genfromtxt(data_fldr/'emccd-spectral-qe.csv', delimiter=',', skip_header=1)\n emccd_wvl = emccd_data[:, 0]/1e3\n emccd_dat = emccd_data[:, 1]\n emccd_interpf = interp1d(emccd_wvl, emccd_dat, bounds_error=False, fill_value=0)\n\n # coating_data = np.genfromtxt(data_fldr/'coatings.csv', delimiter=',', skip_header=1)\n # coating_wvl = coating_data[:, 0]\n # coatings = {}\n # for i, lbl in enumerate(['HRC', 'FSS99', 'Al', 'BBAR']):\n # data = coating_data[:, i+1]\n # interpf = interp1d(coating_wvl, data)\n # coatings[lbl] = interpf\n\n # return ThroughputDatabase(coatings, emccd_interpf)\n return ThroughputDatabase(emccd_interpf)\n\n\nclass StellarDatabase:\n \"\"\"Database of stellar spectra.\"\"\"\n\n def __init__(self, stellar_table, stellar_labels):\n \"\"\"Create a new database of stellar throughputs.\n\n Parameters\n ----------\n stellar_table : `numpy.ndarray`\n columnnar table of stellar spectral fluxes\n stellar_labels : `numpy.ndarray`\n labels associated with the columns, as [g0v, av5], and so forth.\n The index of the label identifies its column\n\n \"\"\"\n self.stellar_interpfs = {}\n self.table = stellar_table\n self.stellar_labels = stellar_labels\n\n def __call__(self, star_type, wavelengths, lower_lim=-1, upper_lim=-1):\n \"\"\"Spectral weights associated with a given star type at a given wavelength.\"\"\"\n stellar_interpf = self.stellar_interpfs.get(star_type, None)\n if lower_lim == -1:\n lower_lim = LOWFS_LOWER\n if upper_lim == -1:\n upper_lim = LOWFS_UPPER\n\n if stellar_interpf is None:\n # this line throws value error if star_type not in list\n i = self.stellar_labels.index(star_type)\n\n # table has units of W/(m^2 m) == J/(s m^2 m)\n # => divide by J/ph, multiply by density, multiply by area\n # == ph/s.\n # this could be cleaner with astropy units, but c'est la vie\n wvl = self.table[:, 0]*1e6 # 1e6; m => um\n photon_energy = self.table[:, 1]\n dat = self.table[:, i]\n dat = dat / photon_energy * 1e-9 * CGI_PUPIL_AREA # 1e-9 = sampling density, 1 nm\n stellar_interpf = interp1d(wvl, dat)\n self.stellar_interpfs[star_type] = stellar_interpf\n\n ret = stellar_interpf(wavelengths)\n ret[wavelengths < lower_lim] = 0\n ret[wavelengths > upper_lim] = 0\n return ret\n\n def sparsity_fudge_factor(self, star_type, wavelengths, lower_lim=-1, upper_lim=-1):\n \"\"\"Fudge factor to deal with spectral sparsity for a given set of wavelengths.\"\"\"\n true = self(star_type, wavelengths, lower_lim=lower_lim, upper_lim=upper_lim).sum()\n wvl_dense = self.table[:, 0] * 1e6\n dense = self(star_type, wvl_dense, lower_lim=lower_lim, upper_lim=upper_lim).sum()\n return dense/true\n\n @classmethod\n def bijan_data(cls, data_fldr):\n \"\"\"Load data from Bijan.\"\"\"\n stellar_data = np.genfromtxt(data_fldr/'stellar-spectra.csv', delimiter=',', skip_header=1)\n labels = [\n 'wvl',\n 'photon energy',\n 'b3v',\n 'a0v',\n 'a5v',\n 'f5v',\n 'g0v',\n 'f5v',\n 'k0v',\n 'k5v',\n 'm0v',\n 'm5v'\n ]\n\n return StellarDatabase(stellar_data, labels)\n", "meta": {"hexsha": "3c387861583d8c0433512edc9846f6d04d101a3d", "size": 6599, "ext": "py", "lang": "Python", "max_stars_repo_path": "lowfsc/spectral.py", "max_stars_repo_name": "nasa-jpl/lowfssim", "max_stars_repo_head_hexsha": "e1b5f98d27574a2c139654ce573fd4032cd25d60", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-10-08T22:49:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T22:39:10.000Z", "max_issues_repo_path": "lowfsc/spectral.py", "max_issues_repo_name": "nasa-jpl/lowfssim", "max_issues_repo_head_hexsha": "e1b5f98d27574a2c139654ce573fd4032cd25d60", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lowfsc/spectral.py", "max_forks_repo_name": "nasa-jpl/lowfssim", "max_forks_repo_head_hexsha": "e1b5f98d27574a2c139654ce573fd4032cd25d60", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9153439153, "max_line_length": 99, "alphanum_fraction": 0.5973632369, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.2628418258225589, "lm_q1q2_score": 0.14978111134752323}} {"text": "# This source code is part of the Hydride package and is distributed\n# under the 3-Clause BSD License. Please see 'LICENSE.rst' for further\n# information.\n\n__name__ = \"hydride\"\n__author__ = \"Patrick Kunzmann\"\n__all__ = [\"FragmentLibrary\"]\n\nfrom os.path import join, dirname, abspath\nimport warnings\nimport pickle\nfrom biotite.structure.error import BadStructureError\nfrom biotite.structure import BondType, displacement\nimport numpy as np\n\n\nclass FragmentLibrary:\n \"\"\"\n A molecule fragment library for estimation of hydrogen positions.\n\n For each molecule added to the :class:`FragmentLibrary`,\n the molecule is split into fragments.\n Each fragment consists of\n\n - A central heavy atom,\n - bond order and position of its bonded heavy atoms and\n - and positions of bonded hydrogen atoms.\n \n The properties of the fragment (central atom element,\n central atom charge, order of connected bonds) are stored in\n a dictionary mapping these properties to heavy and hydrogen atom\n positions.\n\n If hydrogen atoms should be added to a target structure,\n the target structure is also split into fragments.\n Now the corresponding reference fragment in the library dictionary\n is accessed for each fragment.\n The corresponding atom coordinates of the reference fragment\n are superimposed [1]_ [2]_ onto the target fragment to obtain the\n hydrogen coordinates for the heavy atom.\n\n The constructor of this class creates an empty library.\n\n References\n ----------\n \n .. [1] W Kabsch,\n \"A solution for the best rotation to relate two sets of vectors.\"\n Acta Cryst, 32, 922-923 (1976).\n \n .. [2] W Kabsch,\n \"A discussion of the solution for the best rotation to relate\n two sets of vectors.\"\n Acta Cryst, 34, 827-828 (1978).\n \"\"\"\n\n _std_library = None\n\n def __init__(self):\n self._frag_dict = {}\n \n\n @staticmethod\n def standard_library():\n \"\"\"\n Get the standard :class:`FragmentLibrary`.\n The library contains fragments from all molecules in the\n *RCSB* *Chemical Component Dictionary*.\n\n Returns\n -------\n library : FragmentLibrary\n The standard library.\n \"\"\"\n if FragmentLibrary._std_library is None:\n FragmentLibrary._std_library = FragmentLibrary()\n file_name = join(dirname(abspath(__file__)), \"fragments.pickle\")\n with open(file_name, \"rb\") as fragments_file:\n FragmentLibrary._std_library._frag_dict \\\n = pickle.load(fragments_file)\n return FragmentLibrary._std_library\n \n\n def add_molecule(self, molecule):\n \"\"\"\n Add the fragments of a molecule to the library.\n\n Parameters\n ----------\n molecule : AtomArray\n A molecule, whose fragments should be added to the library.\n The structure must contain hydrogen atoms for each\n applicable heavy atom.\n The molecule must have an associated :class:`BondList`.\n The molecule must also include the *charge* annotation\n array, depicting the formal charge for each atom.\n \"\"\"\n fragments = _fragment(molecule)\n for i, fragment in enumerate(fragments):\n if fragment is None:\n continue\n (\n central_element, central_charge, stereo, bond_types,\n center_coord, heavy_coord, hydrogen_coord\n ) = fragment\n # Translate the coordinates,\n # so the central heavy atom is at origin\n centered_heavy_coord = heavy_coord - center_coord\n centered_hydrogen_coord = hydrogen_coord - center_coord\n self._frag_dict[\n (central_element, central_charge, stereo, tuple(bond_types))\n ] = (\n # Information about the origin of the fragment\n # # for debugging purposes \n molecule.res_name[i], molecule.atom_name[i],\n # The interesting information\n centered_heavy_coord, centered_hydrogen_coord\n )\n if stereo != 0:\n # Also include the opposite enantiomer in the library\n # by reflecting the coordinates along an arbitrary axis\n stereo *= -1\n refl_centered_heavy_coord = centered_heavy_coord.copy()\n refl_centered_hydrogen_coord = centered_hydrogen_coord.copy()\n refl_centered_heavy_coord[..., 0] *= -1\n refl_centered_hydrogen_coord[..., 0] *= -1\n self._frag_dict[(\n central_element, central_charge, stereo, tuple(bond_types)\n )] = (\n molecule.res_name[i], molecule.atom_name[i],\n refl_centered_heavy_coord, refl_centered_hydrogen_coord\n )\n\n\n def calculate_hydrogen_coord(self, atoms, mask=None, box=None):\n \"\"\"\n Estimate the hydrogen coordinates for each atom in a given\n structure/molecule.\n\n Parameters\n ----------\n atoms : AtomArray, shape=(n,)\n The structure to get the hydrogen atom positions for.\n The structure must not contain any hydrogen atoms.\n The structure must have an associated :class:`BondList`.\n The structure must also include the *charge* annotation\n array, depicting the formal charge for each atom.\n mask : ndarray, shape=(n,), dtype=bool\n A boolean mask that is true for each heavy atom, where\n corresponsing hydrogen atom positions should be calculated.\n By default, hydrogen atoms are calculated for all applicable\n atoms.\n box : bool or array-like, shape=(3,3), dtype=float, optional\n If this parameter is set, periodic boundary conditions are\n taken into account (minimum-image convention), based on\n the box vectors given with this parameter.\n If `box` is set to true, the box vectors are taken from the\n ``box`` attribute of `atoms` instead.\n\n Returns\n -------\n hydrogen_coord : list of (ndarray, shape=(k,3), dtype=np.float32), length=n\n A list of hydrogen coordinates for each atom in the input\n `atoms`.\n *k* is the number of hydrogen atoms for this atom.\n Each atom, that is not included in the input `mask` or which\n has no fitting fragment in the library,\n has no corresponding hydrogen coordinates, i.e. *k* is 0.\n \"\"\"\n if mask is None:\n mask = np.ones(atoms.array_length(), dtype=bool)\n\n # The target and reference heavy atom coordinates\n # for each fragment\n tar_frag_center_coord = np.zeros(\n (atoms.array_length(), 3), dtype=np.float32\n )\n tar_frag_heavy_coord = np.zeros(\n (atoms.array_length(), 3, 3), dtype=np.float32\n )\n ref_frag_heavy_coord = np.zeros(\n (atoms.array_length(), 3, 3), dtype=np.float32\n )\n # The amount of hydrogens varies for each fragment\n # -> padding with NaN\n # The maximum number of bond hydrogen atoms is 4\n ref_frag_hydrogen_coord = np.full(\n (atoms.array_length(), 4, 3), np.nan, dtype=np.float32\n )\n\n # Fill the coordinate arrays\n fragments = _fragment(atoms, mask)\n for i, fragment in enumerate(fragments):\n if fragment is None:\n # This atom is not in mask\n continue\n (\n central_element, central_charge, stereo, bond_types,\n center_coord, heavy_coord, _\n ) = fragment\n tar_frag_center_coord[i] = center_coord\n tar_frag_heavy_coord[i] = heavy_coord\n # The hydrogen_coord can be ignored:\n # In the target structure are no hydrogen atoms\n hit = self._frag_dict.get(\n (central_element, central_charge, stereo, tuple(bond_types))\n )\n if hit is None:\n warnings.warn(\n f\"Missing fragment for atom '{atoms.atom_name[i]}' \"\n f\"at position {i}\"\n )\n else:\n _, _, ref_heavy_coord, ref_hydrogen_coord = hit\n ref_frag_heavy_coord[i] = ref_heavy_coord\n ref_frag_hydrogen_coord[i, :len(ref_hydrogen_coord)] \\\n = ref_hydrogen_coord\n\n # Translate the target coordinates,\n # so the central heavy atom is at origin\n # This has already been done for the reference atoms\n # in the 'add_molecule()' method\n if box is not None:\n # Find shortest possible displacement vector for each heavy\n # atom according to minimum image convention\n if box is True:\n if atoms.box is None:\n raise ValueError(\"Input structure has no associated box\")\n box = atoms.box\n else:\n # Box vectors are given as array-like object\n box = np.asarray(box)\n tar_frag_heavy_coord = displacement(\n tar_frag_center_coord[:, np.newaxis, :], tar_frag_heavy_coord,\n box\n )\n\n # Get the rotation matrix required for superimposition of\n # the reference coord to the target coord \n matrices = _get_rotation_matrices(\n tar_frag_heavy_coord, ref_frag_heavy_coord\n )\n # Rotate the reference hydrogen atoms, so they fit the\n # target heavy atoms\n tar_frag_hydrogen_coord = _rotate(ref_frag_hydrogen_coord, matrices)\n # Translate hydrogen atoms to the position of the\n # non-centered central heavy target atom\n tar_frag_hydrogen_coord += tar_frag_center_coord[:, np.newaxis, :]\n \n # Turn into list and remove NaN paddings\n tar_frag_hydrogen_coord = [\n # If the x-coordinate is NaN it is expected that\n # y and z are also NaN\n coord[~np.isnan(coord[:, 0])] for coord in tar_frag_hydrogen_coord\n ]\n\n return tar_frag_hydrogen_coord\n\n\ndef _fragment(atoms, mask=None):\n \"\"\"\n Create fragments for the input structure/molecule.\n\n Parameters\n ----------\n atoms : AtomArray, shape=(n,)\n The structure to be fragmented.\n The structure must have an associated :class:`BondList`.\n The structure must also include the *charge* annotation\n array, depicting the formal charge for each atom.\n mask : ndarray, shape=(n,), dtype=bool\n A boolean mask that is true for each heavy atom for which a\n fragment should be created.\n \n Returns\n -------\n fragments : list of tuple(str, int, int, ndarray, ndarray, ndarray), length=n\n The fragments.\n The tuple elements are\n\n #. the central atom element,\n #. the central atom charge,\n #. the enantiomer for stereocenter\n (``-1`` and ``1`` based on a custom nomenclature),\n #. the :class:`BondType` for each bonded heavy atom,\n #. the coordinates of the central atom,\n #. 3 coordinates of bonded heavy atoms (includes padding\n values, if there are not enough heavy atoms),\n #. the coordinates of bonded hydrogen atoms.\n \n ``None`` for each atom not included by the `mask`.\n \"\"\"\n if mask is None:\n mask = np.ones(atoms.array_length(), dtype=bool)\n\n if atoms.bonds is None:\n raise BadStructureError(\n \"The input structure must have an associated BondList\"\n )\n\n fragments = [None] * atoms.array_length()\n \n all_bond_indices, all_bond_types = atoms.bonds.get_all_bonds()\n elements = atoms.element\n charges = atoms.charge\n coord = atoms.coord\n\n for i in range(atoms.array_length()):\n if not mask[i]:\n continue\n \n if elements[i] == \"H\":\n # Only create fragments for heavy atoms\n continue\n bond_indices = all_bond_indices[i]\n bond_types = all_bond_types[i]\n bond_indices = bond_indices[bond_indices != -1]\n bond_types = bond_types[bond_types != -1]\n\n heavy_mask = (elements[bond_indices] != \"H\")\n heavy_indices = bond_indices[heavy_mask]\n heavy_types = bond_types[heavy_mask]\n if (heavy_types == BondType.ANY).any():\n warnings.warn(\n f\"Atom '{atoms.atom_name[i]}' in '{atoms.res_name[i]}' has an \"\n f\"undefined bond type and is ignored\"\n )\n continue\n\n # Order the bonded atoms by their bond types\n # to remove atom order dependency in the matching step \n order = np.argsort(heavy_types)\n heavy_indices = heavy_indices[order]\n heavy_types = heavy_types[order]\n\n hydrogen_mask = ~heavy_mask\n hydrogen_coord = coord[bond_indices[hydrogen_mask]]\n\n # Special handling of nitrogen as central atom:\n # There are cases where the free electron pair can form\n # a partial double bond.\n # Although the bond order is formally 1 in this case,\n # it would enforce planar hydrogen positionioning\n # Therefore, a partial double bond is handled as bond type 7\n if elements[i] == \"N\":\n for j, remote_index in enumerate(heavy_indices):\n if heavy_types[j] != 1:\n # This handling only applies to single bonds\n continue\n rem_bond_indices = all_bond_indices[remote_index]\n rem_bond_indices = rem_bond_indices[rem_bond_indices != -1]\n rem_bond_types = all_bond_types[remote_index]\n rem_bond_types = rem_bond_types[rem_bond_types != -1]\n for rem_rem_index, bond_type in zip(\n rem_bond_indices, rem_bond_types\n ):\n # If the adjacent atom has a double bond\n # the partial double bond condition is fulfilled\n if bond_type == BondType.AROMATIC_DOUBLE or \\\n bond_type == BondType.DOUBLE:\n heavy_types[j] = 7\n\n n_heavy_bonds = np.count_nonzero(heavy_mask)\n if n_heavy_bonds == 0:\n # The orientation is arbitrary\n # -> The fragment coord is the coord of the central atom\n # 4 times repeated\n heavy_coord = np.repeat(coord[np.newaxis, i, :], 3, axis=0)\n stereo = 0\n elif n_heavy_bonds == 1:\n # Include one atom further away\n # to get an unambiguous fragment\n remote_index = heavy_indices[0]\n rem_bond_indices = all_bond_indices[remote_index]\n rem_bond_indices = rem_bond_indices[rem_bond_indices != -1]\n rem_heavy_mask = (elements[rem_bond_indices] != \"H\")\n rem_heavy_indices = rem_bond_indices[rem_heavy_mask]\n # Use the coord of any heavy atom bonded to the remote\n # atom\n rem_rem_index = rem_heavy_indices[0]\n # Include the directly bonded atom two times, to give it a\n # greater weight in superimposition\n heavy_coord = coord[[remote_index, remote_index, rem_rem_index]]\n stereo = 0\n elif n_heavy_bonds == 2:\n heavy_coord = coord[[heavy_indices[0], heavy_indices[1], i]]\n stereo = 0\n elif n_heavy_bonds == 3:\n heavy_coord = coord[heavy_indices]\n center = coord[i]\n # Determine the enantiomer of this stereocenter\n # For performance reasons, the result does not follow the\n # R/S nomenclature, but a custom -1/1 based one, which also\n # unambiguously identifies the enantiomer\n n = np.cross(heavy_coord[0] - center, heavy_coord[1] - center)\n stereo = int(np.sign(np.dot(heavy_coord[2] - center, n)))\n elif n_heavy_bonds == 4:\n # The fragment is irrelevant, as there is no bonded hydrogen\n # -> The fragment coord is the coord of the central atom\n # 4 times repeated\n heavy_coord = np.repeat(coord[np.newaxis, i, :], 3, axis=0)\n stereo = 0\n else:\n warnings.warn(\n f\"Atom '{atoms.atom_name[i]}' in \"\n f\"'{atoms.res_name[i]}' has more than 4 bonds to \"\n f\"heavy atoms ({n_heavy_bonds}) and is ignored\"\n )\n heavy_coord = np.repeat(coord[np.newaxis, i, :], 3, axis=0)\n hydrogen_coord = np.zeros((0, 3), dtype=np.float32)\n stereo = 0\n central_coord = coord[i]\n fragments[i] = (\n elements[i], charges[i], stereo, heavy_types,\n central_coord, heavy_coord, hydrogen_coord\n )\n return fragments\n\n\ndef _get_rotation_matrices(fixed, mobile):\n \"\"\"\n Get the rotation matrices to superimpose the given mobile\n coordinates into the given fixed coordinates, minimizing the RMSD.\n\n Uses the *Kabsch* algorithm.\n\n Parameters\n ----------\n fixed : ndarray, shape=(m,n,3), dtype=np.float32\n The fixed coordinates.\n mobile : ndarray, shape=(m,n,3), dtype=np.float32\n The mobile coordinates.\n \n Returns\n -------\n matrices : ndarray, shape=(m,3,3), dtype=np.float32\n The rotation matrices.\n \"\"\"\n # Calculate cross-covariance matrices\n cov = np.sum(fixed[:,:,:,np.newaxis] * mobile[:,:,np.newaxis,:], axis=1)\n v, s, w = np.linalg.svd(cov)\n # Remove possibility of reflected atom coordinates\n reflected_mask = (np.linalg.det(v) * np.linalg.det(w) < 0)\n v[reflected_mask, :, -1] *= -1\n matrices = np.matmul(v, w)\n return matrices\n\n\ndef _rotate(coord, matrices):\n \"\"\"\n Apply a rotation on given coordinates.\n\n Parameters\n ----------\n coord : ndarray, shape=(m,n,3), dtype=np.float32\n The coordinates.\n matrices : ndarray, shape=(m,3,3), dtype=np.float32\n The rotation matrices.\n \"\"\"\n return np.transpose(\n np.matmul(matrices, np.transpose(coord, axes=(0, 2, 1))),\n axes=(0, 2, 1)\n )", "meta": {"hexsha": "c8e87d6ece6ce226ac3a299b6b0212138f55385e", "size": 18304, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/hydride/fragments.py", "max_stars_repo_name": "biotite-dev/hydride", "max_stars_repo_head_hexsha": "4b5a1c4348cf8f9b0878c1480a09ffcf101cba48", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-03T15:11:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T12:32:05.000Z", "max_issues_repo_path": "src/hydride/fragments.py", "max_issues_repo_name": "biotite-dev/hydride", "max_issues_repo_head_hexsha": "4b5a1c4348cf8f9b0878c1480a09ffcf101cba48", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-02T17:35:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-02T17:35:05.000Z", "max_forks_repo_path": "src/hydride/fragments.py", "max_forks_repo_name": "biotite-dev/hydride", "max_forks_repo_head_hexsha": "4b5a1c4348cf8f9b0878c1480a09ffcf101cba48", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-14T13:26:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T13:26:56.000Z", "avg_line_length": 39.5334773218, "max_line_length": 83, "alphanum_fraction": 0.6004698427, "include": true, "reason": "import numpy", "num_tokens": 3947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.27202455109402257, "lm_q1q2_score": 0.14977871742683005}} {"text": "##############################################################################\n# pymbar: A Python Library for MBAR\n#\n# Copyright 2010-2017 University of Virginia, Memorial Sloan-Kettering Cancer Center\n# Portions of this software are Copyright (c) 2006-2007 The Regents of the University of California. All Rights Reserved.\n# Portions of this software are Copyright (c) 2007-2008 Stanford University and Columbia University.\n#\n# Authors: Michael Shirts, John Chodera\n# Contributors: Kyle Beauchamp, Levi Naden\n#\n# pymbar is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as\n# published by the Free Software Foundation, either version 2.1\n# of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with pymbar. If not, see .\n##############################################################################\n\n\"\"\"\nA module implementing the multistate Bennett acceptance ratio (MBAR) method for the analysis\nof equilibrium samples from multiple arbitrary thermodynamic states in computing equilibrium\nexpectations, free energy differences, potentials of mean force, and entropy and enthalpy contributions.\n\nPlease reference the following if you use this code in your research:\n\n[1] Shirts MR and Chodera JD. Statistically optimal analysis of samples from multiple equilibrium states.\nJ. Chem. Phys. 129:124105, 2008. http://dx.doi.org/10.1063/1.2978177\n\nThis module contains implementations of\n\n* MBAR - multistate Bennett acceptance ratio estimator\n\n\"\"\"\n\nimport math\nimport numpy as np\nimport numpy.linalg as linalg\nfrom pymbar import mbar_solvers\nfrom pymbar.utils import kln_to_kn, kn_to_n, ParameterError, logsumexp, check_w_normalized\n\nDEFAULT_SOLVER_PROTOCOL = mbar_solvers.DEFAULT_SOLVER_PROTOCOL\nDEFAULT_SUBSAMPLING_PROTOCOL = mbar_solvers.DEFAULT_SUBSAMPLING_PROTOCOL\n\n# =========================================================================\n# MBAR class definition\n# =========================================================================\n\n\nclass MBAR:\n\n \"\"\"Multistate Bennett acceptance ratio method (MBAR) for the analysis of multiple equilibrium samples.\n\n Notes\n -----\n Note that this method assumes the data are uncorrelated.\n Correlated data must be subsampled to extract uncorrelated (effectively independent) samples.\n\n References\n ----------\n\n [1] Shirts MR and Chodera JD. Statistically optimal analysis of samples from multiple equilibrium states.\n J. Chem. Phys. 129:124105, 2008\n http://dx.doi.org/10.1063/1.2978177\n \"\"\"\n #=========================================================================\n\n def __init__(self, u_kn, N_k, maximum_iterations=10000, relative_tolerance=1.0e-7, verbose=False, initial_f_k=None, solver_protocol=DEFAULT_SOLVER_PROTOCOL, initialize='zeros', x_kindices=None, subsampling=6, subsampling_protocol=DEFAULT_SUBSAMPLING_PROTOCOL, **kwargs):\n \"\"\"Initialize multistate Bennett acceptance ratio (MBAR) on a set of simulation data.\n\n Upon initialization, the dimensionless free energies for all states are computed.\n This may take anywhere from seconds to minutes, depending upon the quantity of data.\n After initialization, the computed free energies may be obtained by a call to :function:`getFreeEnergies`, or\n free energies or expectation at any state of interest can be computed by calls to :function:`computeFreeEnergy` or\n :function:`computeExpectations`.\n\n ----------\n u_kn : np.ndarray, float, shape=(K, N_max)\n ``u_kn[k,n]`` is the reduced potential energy of uncorrelated\n configuration n evaluated at state k.\n u_kln : np.ndarray, float, shape (K, L, N_max)\n if the simulation is in form ``u_kln[k,l,n]`` it is converted to ``u_kn`` format\n\n u_kn = [ u_1(x_1) u_1(x_2) u_1(x_3) . . . u_1(x_n)\n u_2(x_1) u_2(x_2) u_2(x_3) . . . u_2(x_n)\n . . .\n u_k(x_1) u_k(x_2) u_k(x_3) . . . u_k(x_n)]\n\n N_k : np.ndarray, int, shape=(K)\n ``N_k[k]`` is the number of uncorrelated snapshots sampled from state ``k``.\n Some may be zero, indicating that there are no samples from that state.\n\n We assume that the states are ordered such that the first ``N_k``\n are from the first state, the 2nd ``N_k`` the second state, and so\n forth. This only becomes important for BAR -- MBAR does not\n care which samples are from which state. We should eventually\n allow this assumption to be overwritten by parameters passed\n from above, once ``u_kln`` is phased out.\n\n maximum_iterations : int, optional\n Set to limit the maximum number of iterations performed (default 1000)\n relative_tolerance : float, optional\n Set to determine the relative tolerance convergence criteria (default 1.0e-6)\n verbosity : bool, optional\n Set to True if verbose debug output is desired (default False)\n initial_f_k : np.ndarray, float, shape=(K), optional\n Set to the initial dimensionless free energies to use as a\n guess (default None, which sets all f_k = 0)\n method : list(dict), optional, default=None\n List of dictionaries to define a sequence of solver algorithms\n and options used to estimate the dimensionless free energies.\n See `pymbar.mbar_solvers.solve_mbar()` for details. If None,\n use the developers best guess at an appropriate algorithm.\n initialize : string, optional\n If equal to 'BAR', use BAR between the pairwise state to\n initialize the free energies. Eventually, should specify a path;\n for now, it just does it zipping up the states.\n (default: 'zeros', unless specific values are passed in.)\n x_kindices\n Which state is each x from? Usually doesn't matter, but does for BAR. We assume the samples\n are in K order (the first N_k[0] samples are from the 0th state, the next N_k[1] samples from\n the 1st state, and so forth.\n\n Notes\n -----\n The reduced potential energy u_kn[k,n] = u_k(x_{ln}), where the reduced potential energy u_l(x) is defined (as in the text) by:\n u_k(x) = beta_k [ U_k(x) + p_k V(x) + mu_k' n(x) ]\n where\n beta_k = 1/(kB T_k) is the inverse temperature of condition k, where kB is Boltzmann's constant\n U_k(x) is the potential energy function for state k\n p_k is the pressure at state k (if an isobaric ensemble is specified)\n V(x) is the volume of configuration x\n mu_k is the M-vector of chemical potentials for the various species, if a (semi)grand ensemble is specified, and ' denotes transpose\n n(x) is the M-vector of numbers of the various molecular species for configuration x, corresponding to the chemical potential components of mu_m.\n x_n indicates that the samples are from k different simulations of the n states. These simulations need only be a subset of the k states.\n The configurations x_ln must be uncorrelated. This can be ensured by subsampling a correlated timeseries with a period larger than the statistical inefficiency,\n which can be estimated from the potential energy timeseries {u_k(x_ln)}_{n=1}^{N_k} using the provided utility function 'statisticalInefficiency()'.\n See the help for this function for more information.\n\n Examples\n --------\n\n >>> from pymbar import testsystems\n >>> (x_n, u_kn, N_k, s_n) = testsystems.HarmonicOscillatorsTestCase().sample(mode='u_kn')\n >>> mbar = MBAR(u_kn, N_k)\n\n \"\"\"\n for key, val in kwargs.items():\n print((\"Warning: parameter %s=%s is unrecognized and unused.\" % (key, val)))\n\n # Store local copies of necessary data.\n # N_k[k] is the number of samples from state k, some of which might be zero.\n self.N_k = np.array(N_k, dtype=np.int64)\n self.N = np.sum(self.N_k)\n\n # Get dimensions of reduced potential energy matrix, and convert to KxN form if needed.\n if len(np.shape(u_kn)) == 3:\n self.K = np.shape(u_kn)[1] # need to set self.K, and it's the second index\n u_kn = kln_to_kn(u_kn, N_k=self.N_k)\n\n # u_kn[k,n] is the reduced potential energy of sample n evaluated at state k\n self.u_kn = np.array(u_kn, dtype=np.float64)\n\n K, N = np.shape(u_kn)\n\n if verbose:\n print(\"K (total states) = %d, total samples = %d\" % (K, N))\n\n if np.sum(self.N_k) != N:\n raise ParameterError(\n 'The sum of all N_k must equal the total number of samples (length of second dimension of u_kn.')\n\n # Store local copies of other data\n self.K = K # number of thermodynamic states energies are evaluated at\n # N = \\sum_{k=1}^K N_k is the total number of samples\n self.N = N # maximum number of configurations\n\n # if not defined, identify from which state each sample comes from.\n if x_kindices is not None:\n self.x_kindices = x_kindices\n else:\n self.x_kindices = np.arange(N, dtype=np.int64)\n Nsum = 0\n for k in range(K):\n self.x_kindices[Nsum:Nsum+self.N_k[k]] = k\n Nsum += self.N_k[k]\n\n # verbosity level -- if True, will print extra debug information\n self.verbose = verbose\n\n # perform consistency checks on the data.\n\n # if, for any set of data, all reduced potential energies are the same,\n # they are probably the same state. We check to within\n # relative_tolerance.\n\n self.samestates = []\n if self.verbose:\n for k in range(K):\n for l in range(k):\n diffsum = 0\n uzero = u_kn[k, :] - u_kn[l, :]\n diffsum += np.dot(uzero, uzero)\n if (diffsum < relative_tolerance):\n self.samestates.append([k, l])\n self.samestates.append([l, k])\n print('')\n print('Warning: states %d and %d have the same energies on the dataset.' % (l, k))\n print('They are therefore likely to to be the same thermodynamic state. This can occasionally cause')\n print('numerical problems with computing the covariance of their energy difference, which must be')\n print('identically zero in any case. Consider combining them into a single state.')\n print('')\n\n # Print number of samples from each state.\n if self.verbose:\n print(\"N_k = \")\n print(self.N_k)\n\n # Determine list of k indices for which N_k != 0\n self.states_with_samples = np.where(self.N_k != 0)[0]\n self.states_with_samples = self.states_with_samples.astype(np.int64)\n\n # Number of states with samples.\n self.K_nonzero = self.states_with_samples.size\n if verbose:\n print(\"There are %d states with samples.\" % self.K_nonzero)\n\n # Initialize estimate of relative dimensionless free energy of each state to zero.\n # Note that f_k[0] will be constrained to be zero throughout.\n # this is default\n self.f_k = np.zeros([self.K], dtype=np.float64)\n\n # If an initial guess of the relative dimensionless free energies is\n # specified, start with that.\n if initial_f_k is not None:\n if self.verbose:\n print(\"Initializing f_k with provided initial guess.\")\n # Cast to np array.\n initial_f_k = np.array(initial_f_k, dtype=np.float64)\n # Check shape\n if initial_f_k.shape != self.f_k.shape:\n raise ParameterError(\n \"initial_f_k must be a %d-dimensional np array.\" % self.K)\n # Initialize f_k with provided guess.\n self.f_k = initial_f_k\n if self.verbose:\n print(self.f_k)\n # Shift all free energies such that f_0 = 0.\n self.f_k[:] = self.f_k[:] - self.f_k[0]\n else:\n # Initialize estimate of relative dimensionless free energies.\n self._initializeFreeEnergies(verbose, method=initialize)\n\n if self.verbose:\n print(\"Initial dimensionless free energies with method %s\" % (initialize))\n print(\"f_k = \")\n print(self.f_k)\n\n self.f_k = mbar_solvers.solve_mbar_with_subsampling(self.u_kn, self.N_k, self.f_k, solver_protocol, subsampling_protocol, subsampling, x_kindices=self.x_kindices)\n self.Log_W_nk = mbar_solvers.mbar_log_W_nk(self.u_kn, self.N_k, self.f_k)\n\n # Print final dimensionless free energies.\n if self.verbose:\n print(\"Final dimensionless free energies\")\n print(\"f_k = \")\n print(self.f_k)\n\n if self.verbose:\n print(\"MBAR initialization complete.\")\n\n\n @property\n def W_nk(self):\n \"\"\"Retrieve the weight matrix W_nk from the MBAR algorithm.\n\n Necessary because they are stored internally as log weights.\n\n Returns\n -------\n weights : np.ndarray, float, shape=(N, K)\n NxK matrix of weights in the MBAR covariance and averaging formulas\n\n \"\"\"\n return np.exp(self.Log_W_nk)\n\n\n #=========================================================================\n def getWeights(self):\n \"\"\"Retrieve the weight matrix W_nk from the MBAR algorithm.\n\n Necessary because they are stored internally as log weights.\n\n Returns\n -------\n weights : np.ndarray, float, shape=(N, K)\n NxK matrix of weights in the MBAR covariance and averaging formulas\n\n \"\"\"\n\n return self.W_nk\n\n #=========================================================================\n def computeEffectiveSampleNumber(self, verbose = False):\n \"\"\"\n Compute the effective sample number of each state;\n essentially, an estimate of how many samples are contributing to the average\n at given state. See pymbar/examples for a demonstration.\n\n It also counts the efficiency of the sampling, which is simply the ratio\n of the effective number of samples at a given state to the total number\n of samples collected. This is printed in verbose output, but is not\n returned for now.\n\n Returns\n -------\n N_eff : np.ndarray, float, shape=(K)\n estimated number of samples contributing to estimates at each\n state i. An estimate to how many samples collected just at state\n i would result in similar statistical efficiency as the MBAR\n simulation. Valid for both sampled states (in which the weight\n will be greater than N_k[i], and unsampled states.\n\n Parameters\n ----------\n verbose : print out information about the effective number of samples\n\n Notes\n -----\n\n # using Kish (1965) formula (Kish, Leslie (1965). Survey Sampling. New York: Wiley)\n # As the weights become more concentrated in fewer observations, the effective sample size shrinks.\n # from http://healthcare-economist.com/2013/08/22/effective-sample-size/\n # effective # of samples contributing to averages carried out at state i\n # = (\\sum_{n=1}^N w_in)^2 / \\sum_{n=1}^N w_in^2\n # = (\\sum_{n=1}^N w_in^2)^-1\n #\n # the effective sample number is most useful to diagnose when there are only a few samples\n # contributing to the averages.\n\n Examples\n --------\n\n >>> from pymbar import testsystems\n >>> [x_kn, u_kln, N_k, s_n] = testsystems.HarmonicOscillatorsTestCase().sample()\n >>> mbar = MBAR(u_kln, N_k)\n >>> N_eff = mbar.computeEffectiveSampleNumber()\n \"\"\"\n\n N_eff = np.zeros(self.K)\n for k in range(self.K):\n w = np.exp(self.Log_W_nk[:,k])\n N_eff[k] = 1/np.sum(w**2)\n if verbose:\n print(\"Effective number of sample in state %d is %10.3f\" % (k,N_eff[k]))\n print(\"Efficiency for state %d is %d/%d = %10.4f\" % (k,N_eff[k],len(w),N_eff[k]/len(w)))\n\n return N_eff\n\n #=========================================================================\n def computeOverlap(self):\n \"\"\"Compute estimate of overlap matrix between the states.\n\n Returns\n -------\n overlap_scalar : np.ndarray, float, shape=(K, K)\n One minus the largest nontrival eigenvalue\n eigenval : np.ndarray, float, shape=(K)\n The sorted (descending) eigenvalues of the overlap matrix.\n O : np.ndarray, float, shape=(K, K)\n estimated state overlap matrix: O[i,j] is an estimate\n of the probability of observing a sample from state i in state j\n\n Notes\n -----\n\n W.T * W \\approx \\int (p_i p_j /\\sum_k N_k p_k)^2 \\sum_k N_k p_k dq^N\n = \\int (p_i p_j /\\sum_k N_k p_k) dq^N\n\n Multiplying elementwise by N_i, the elements of row i give the probability\n for a sample from state i being observed in state j.\n\n Examples\n --------\n\n >>> from pymbar import testsystems\n >>> (x_kn, u_kn, N_k, s_n) = testsystems.HarmonicOscillatorsTestCase().sample(mode='u_kn')\n >>> mbar = MBAR(u_kn, N_k)\n >>> O_ij = mbar.computeOverlap()\n \"\"\"\n\n W = np.matrix(self.getWeights(), np.float64)\n O = np.multiply(self.N_k, W.T * W)\n (eigenval, eigevec) = linalg.eig(O)\n # sort in descending order\n eigenval = np.sort(eigenval)[::-1]\n overlap_scalar = 1 - eigenval[1]\n\n return overlap_scalar, eigenval, O\n\n #=========================================================================\n def getFreeEnergyDifferences(self, compute_uncertainty=True, uncertainty_method=None, warning_cutoff=1.0e-10, return_theta=False):\n \"\"\"Get the dimensionless free energy differences and uncertainties among all thermodynamic states.\n\n\n Parameters\n ----------\n compute_uncertainty : bool, optional\n If False, the uncertainties will not be computed (default: True)\n uncertainty_method : string, optional\n Choice of method used to compute asymptotic covariance method,\n or None to use default. See help for computeAsymptoticCovarianceMatrix()\n for more information on various methods. (default: svd)\n warning_cutoff : float, optional\n Warn if squared-uncertainty is negative and larger in magnitude\n than this number (default: 1.0e-10)\n return_theta : bool, optional\n Whether or not to return the theta matrix. Can be useful for complicated differences.\n\n Returns\n -------\n Deltaf_ij : np.ndarray, float, shape=(K, K)\n Deltaf_ij[i,j] is the estimated free energy difference\n dDeltaf_ij : np.ndarray, float, shape=(K, K)\n If compute_uncertainty==True,\n dDeltaf_ij[i,j] is the estimated statistical uncertainty\n (one standard deviation) in Deltaf_ij[i,j]. Otherwise None.\n (optional) Theta_ij : np.ndarray, float, shape=(K, K)\n The theta_matrix if return_theta==True, otherwise None.\n\n\n Notes\n -----\n Computation of the covariance matrix may take some time for large K.\n\n The reported statistical uncertainty should, in the asymptotic limit, reflect one standard deviation for the normal distribution of the estimate.\n The true free energy difference should fall within the interval [-df, +df] centered on the estimate 68% of the time, and within\n the interval [-2 df, +2 df] centered on the estimate 95% of the time.\n This will break down in cases where the number of samples is not large enough to reach the asymptotic normal limit.\n\n See Section III of Reference [1].\n\n Examples\n --------\n\n >>> from pymbar import testsystems\n >>> (x_n, u_kn, N_k, s_n) = testsystems.HarmonicOscillatorsTestCase().sample(mode='u_kn')\n >>> mbar = MBAR(u_kn, N_k)\n >>> Deltaf_ij, dDeltaf_ij, Theta_ij = mbar.getFreeEnergyDifferences()\n\n \"\"\"\n Deltaf_ij, dDeltaf_ij, Theta_ij = None, None, None # By default, returns None for dDelta and Theta\n\n # Compute free energy differences.\n f_i = np.matrix(self.f_k)\n Deltaf_ij = f_i - f_i.transpose()\n\n # zero out numerical error for thermodynamically identical states\n self._zerosamestates(Deltaf_ij)\n\n Deltaf_ij = np.array(Deltaf_ij) # Convert from np.matrix to np.array\n\n if compute_uncertainty or return_theta:\n # Compute asymptotic covariance matrix.\n Theta_ij = self._computeAsymptoticCovarianceMatrix(\n np.exp(self.Log_W_nk), self.N_k, method=uncertainty_method)\n\n if compute_uncertainty:\n dDeltaf_ij = self._ErrorOfDifferences(Theta_ij, warning_cutoff=warning_cutoff)\n # zero out numerical error for thermodynamically identical states\n self._zerosamestates(dDeltaf_ij)\n # Return matrix of free energy differences and uncertainties.\n dDeltaf_ij = np.array(dDeltaf_ij)\n\n if not return_theta:\n #Ensure return_theta is respected, this is a placeholder until a future fix to better handle Theta_ij is implemented\n Theta_ij = None\n\n return Deltaf_ij, dDeltaf_ij, Theta_ij\n\n\n #=========================================================================\n def computeExpectationsInner(self, A_n, u_ln, state_map,\n uncertainty_method=None,\n warning_cutoff=1.0e-10,\n return_theta=False):\n \"\"\"Compute the expectations of multiple observables of phase space functions in multiple states.\n\n Compute the expectations of multiple observables of phase\n space functions [A_0(x),A_1(x),...,A_i(x)] along with the\n covariances of their estimates at multiple states.\n\n intended as an internal function to keep all the optimized and\n robust expectation code in one place, but will leave it\n open to allow for later modifications\n\n It calculates all input observables at all states which are\n specified by the list of states in the state list.\n\n Parameters\n ----------\n A_n : np.ndarray, float, shape=(I, N)\n A_in[i,n] = A_i(x_n), the value of phase observable i for configuration n\n u_ln : np.ndarray, float, shape=(L, N)\n u_ln[l,n] is the reduced potential of configuration n at state l\n if u_ln = None, we use self.u_kn\n\n state_map : np.ndarray, int, shape (2,NS) or shape(1,NS)\n If state_map has only one dimension\n where NS is the\n total number of states we want to simulate things\n a. The list will be of the form\n [[0,1,2],[0,1,1]]. This particular example\n indicates we want to output the properties of\n three observables total: the first property A[0]\n at the 0th state, the 2nd property A[1] at the\n 1th state, and the 2nd property A[1] at the 2nd\n state. This allows us to tailor our output to a\n large number of different situations.\n\n uncertainty_method : string, optional\n Choice of method used to compute asymptotic covariance method, or None to use default\n See help for computeAsymptoticCovarianceMatrix() for more information on various methods. (default: None)\n warning_cutoff : float, optional\n Warn if squared-uncertainty is negative and larger in magnitude than this number (default: 1.0e-10)\n return_theta : bool, optional\n Whether or not to return the theta matrix. Can be useful for complicated differences of observables.\n\n Returns\n -------\n\n A_i : np.ndarray, float, shape = (I)\n A_i[i] is the estimate for the expectation of A_state_map[i](x) at the state specified by u_n[state_map[i],:]\n\n d2A_ij : np.ndarray, float, shape = (I, J)\n Ca_ij[i,j] is the COVARIANCE in the estimates of observables A_i and A_j (as determined by the state list)\n (* not the square root of anything, the full covariance matrix *)\n\n Situations this will be used for :\n * multiple observables, single state (called though computeMultipleExpectations)\n * single observable, multiple states (called through computeExpectations)\n This has two cases: observables that don't change with state, and observables that\n do change with state.\n For example, the set of energies at state k consist in energy function of state\n 1 evaluated at state 1, energies of state 2 evaluated at\n state 2, and so forth.\n * computing only free energies at new states.\n * Would require additional work to work with potentials of mean force, because we need to ignore the\n functions that are zero when integrating.\n\n Examples\n --------\n\n >>> from pymbar import testsystems\n >>> (x_n, u_kn, N_k, s_n) = testsystems.HarmonicOscillatorsTestCase().sample(mode='u_kn')\n >>> mbar = MBAR(u_kn, N_k)\n >>> A_n = np.array([x_n,x_n**2,x_n**3])\n >>> u_n = u_kn[:2,:]\n >>> state_map = np.array([[0,0],[1,0],[2,0],[2,1]],int)\n >>> [A_i, d2A_ij] = mbar.computeExpectationsInner(A_n, u_n, state_map)\n\n \"\"\"\n\n # Retrieve N and K for convenience.\n mapshape = np.shape(state_map) # number of computed expectations we desire\n # need to convert to matrix to be able to pick up D=1\n if len(mapshape) < 2:\n # if 1D, it's just a list of states\n state_list = state_map.copy()\n state_map = np.zeros([0,0],np.float64)\n S = 0\n else: # if 2D, then it's a list of observables and corresponding states\n state_list = state_map[0,:]\n S = mapshape[1]\n\n # reshape arrays explicitly into 2d (even if only one state) to make it easy to manipulate\n shapeu = np.shape(u_ln)\n if len(shapeu) == 1:\n u_ln = np.reshape(u_ln,[1,shapeu[0]])\n\n shapeA = np.shape(A_n)\n if len(shapeA) == 1:\n A_n = np.reshape(A_n,[1,shapeA[0]])\n\n K = self.K\n N = self.N # N is total number of samples\n returns = {} # dictionary we will store uncertainties in\n\n # make observables all positive, allowing us to take the logarithm, which is\n # required to prevent overflow in some examples.\n # WARNING: one issue to watch for is if one of the energies is extremely\n # low (-10^10 or lower), but most of the energies of interest are much higher.\n # This could lead to roundoff problems (check with Levi N.)\n\n L_list = np.unique(state_list)\n NL = len(L_list) # number of states we need to examine\n if S > 0:\n A_list = np.unique(state_map[1,:]) # what are the unique observables\n A_min = np.zeros([len(A_list)], dtype=np.float64)\n else:\n A_list = np.zeros(0,dtype=int)\n\n for i in A_list:\n A_min[i] = np.min(A_n[i, :]) #find the minimum\n A_n[i, :] = A_n[i,:] - (A_min[i] - 1) #all values now positive so that we can work in logarithmic scale\n\n # Augment W_nk, N_k, and c_k for q_A(x) for the observables, with one\n # row for the specified state and I rows for the observable at that\n # state.\n # log weight matrix\n msize = K + NL + S # augmented size; all of the states needed to calculate\n # the observables, and the observables themselves.\n Log_W_nk = np.zeros([N, msize], np.float64) # log weight matrix\n N_k = np.zeros([msize], np.int64) # counts\n f_k = np.zeros([msize], np.float64) # free energies\n\n # = A(x_n) exp[f_{k} - q_{k}(x_n)] / \\sum_{k'=1}^K N_{k'} exp[f_{k'} - q_{k'}(x_n)]\n # Fill in first section of matrix with existing q_k(x) from states.\n Log_W_nk[:, 0:K] = self.Log_W_nk\n N_k[0:K] = self.N_k\n f_k[0:K] = self.f_k\n\n # Pre-calculate the log denominator: Eqns 13, 14 in MBAR paper\n states_with_samples = (self.N_k > 0)\n log_denominator_n = logsumexp(self.f_k[states_with_samples] - self.u_kn[states_with_samples].T, b=self.N_k[states_with_samples], axis=1)\n # Compute row of W_nk matrix for the extra states corresponding to u_ln\n # that the state list specifies\n for l in L_list:\n la = K+l #l, augmented\n # Calculate log normalizing constants and log weights via Eqns 13, 14\n log_C_a = -logsumexp(-u_ln[l] - log_denominator_n)\n Log_W_nk[:, la] = log_C_a - u_ln[l] - log_denominator_n\n f_k[la] = log_C_a\n\n # Compute the remaining rows/columns of W_nk, and calculate\n # their normalizing constants c_k\n for s in range(S):\n sa = K+NL+s # augmented s\n l = K + state_map[0,s]\n i = state_map[1,s]\n Log_W_nk[:, sa] = np.log(A_n[i, :]) + Log_W_nk[:, l]\n f_k[sa] = -logsumexp(Log_W_nk[:, sa])\n Log_W_nk[:, sa] += f_k[sa] # normalize this row\n\n # Compute estimates of A_i[s]\n A_i = np.zeros([S], np.float64)\n for s in range(S):\n A_i[s] = np.exp(-f_k[K + NL + s])\n\n # Now that covariances are computed, add the constants back to A_i that\n # were required to enforce positivity\n for s in range(S):\n A_i[s] += (A_min[state_map[1,s]] - 1)\n\n # these values may be used outside the routine, so copy back.\n for i in A_list:\n A_n[i, :] = A_n[i,:] + (A_min[i] - 1)\n\n # expectations of the observables at these states\n if S > 0:\n returns['observables'] = A_i\n\n if return_theta:\n Theta_ij = self._computeAsymptoticCovarianceMatrix(\n np.exp(Log_W_nk), N_k, method=uncertainty_method)\n\n # Note: these variances will be the same whether or not we\n # subtract a different constant from each A_i\n # for efficency, output theta in block form\n # K*K K*S K*NL\n # Theta = K*S S*S NL*S\n # K*NL NL*S NL*NL\n\n # first the observables (S of them), then the free energies (also S of them)\n if S>0:\n si = K+NL+np.arange(S)\n else:\n si = np.zeros(0,dtype=int)\n li = K+state_list\n i = np.concatenate((si,li))\n Theta = Theta_ij[np.ix_(i, i)]\n returns['Theta'] = Theta\n if S > 0:\n # we need to return the minimum A as well\n returns['Amin'] = (A_min[state_map[1,np.arange(S)]] - 1)\n\n # free energies at these new states\n returns['free energies'] = f_k[K+state_list]\n\n # Return expectations and uncertainties.\n return returns\n\n # For reference\n # Covariance of normalization constants is cov(ln A - ln a, ln B - ln b) = (Theta(c_A,c_B)-Theta(c_A,c_b)-Theta(c_B,c_a) + Theta(c_a,c_b))\n # Covariance of the differences of observables is cov(A-B)\n # = Cov(A,A)+Cov(B,B)-2Cov(A,B) = A^2 cov(ln A - ln a, ln A - ln a)\n # + B^2 cov(ln B - ln b, ln B - ln b)\n # + 2AB cov(ln A - ln a, ln B - ln b)\n # = A^2 (Theta(c_A,c_A) + Theta(c_a,c_a) - 2Theta(c_A,c_a))\n # + B^2 (Theta(c_B,c_B) + Theta(c_b,c_b) - 2Theta(c_B,c_b))\n # + 2AB (Theta(c_A,c_B) + Theta(c_a,c_b) - Theta(c_A,c_b) - Theta(c_B,c_a))\n #\n # Covariance in two observables = Cov(A,B)\n # = cov(exp(ln c_A - ln c_a),exp(ln c_B - ln c_b))\n # = AB cov(ln c_A - ln c_a, ln c_B - ln c_b)\n # = AB ((Theta(c_A,c_B) + Theta(c_a,c_b) - Theta(c_A,c_b) - Theta(c_B,c_a))\n #\n # Covariance of the differences of observables and a free energy (a could be b, or some other value)\n # is cov(A - ln c_b).\n #\n # = Cov(exp(ln c_A - ln c_a), exp(ln c_A - ln c_a)) + Cov(c_b,c_b) - 2Cov(exp(ln c_A - ln c_a), c_b)\n # = A^2 cov(ln c_A - ln c_a, ln c_A - ln c_a) + Cov(c_b,c_b) - 2A cov(ln c_A - ln c_a, ln c_b)\n # = A^2 ((Theta(c_A,c_A) + Theta(c_a,c_a) - 2Theta(c_A,c_a)) + Theta(c_b,c_b)\n # - 2A Theta(c_A,c_b) + 2A Theta(c_a, c_b)\n #\n # if A is sampled at the same free energy as the difference, then this will become:\n # = A^2 ((Theta(c_A,c_A) + Theta(c_a,c_a) - 2Theta(c_A,c_a)) + Theta(c_a,c_a)\n # - 2A Theta(c_A,c_a) + 2A Theta(c_a, c_a)\n # = A^2 (Theta(c_A,c_A) + (A^2+2A+1)Theta(c_a,c_a) -(2A^2+2A)Theta(c_A,c_a)\n #\n\n #=========================================================================\n def computeCovarianceOfSums(self, d_ij, K, a):\n\n \"\"\"\n Inputs: d_ij: a matrix of standard deviations of the quantities f_i - f_j\n\n K: The number of states in each 'chunk', has to be constant\n\n outputs: KxK variance matrix for the sums or differences \\sum a_i df_i\n\n We wish to calculate the variance of a weighted sum of free energy differences.\n for example var(\\sum a_i df_i).\n\n We explicitly lay out the calculations for four variables (where each variable\n is a logarithm of a partion function), then generalize.\n\n The uncertainty in the sum of two weighted differences is var(a1(f_i1 - f_j1) + a2(f_i2 - f_j2)) =\n a1^2 var(f_i1 - f_j1) + a2^2 var(f_i2 - f_j2) + 2 a1 a2 cov(f_i1 - f_j1, f_i2 - f_j2)\n\n cov(f_i1 - f_j1, f_i2 - f_j2) = cov(f_i1,f_i2) - cov(f_i1,f_j2) - cov(f_j1,f_i2) + cov(f_j1,f_j2)\n\n call:\n\n f_i1 = a\n f_j1 = b\n f_i2 = c\n f_j2 = d\n\n a1^2 var(a-b) + a2^2 var(c-d) + 2a1a2 cov(a-b,c-d)\n we want 2cov(a-b,c-d) = 2cov(a,c)-2cov(a,d)-2cov(b,c)+2cov(b,d)\n since var(x-y) = var(x) + var(y) - 2cov(x,y)\n then:\n 2cov(x,y) = -var(x-y) + var(x) + var(y)\n so:\n 2cov(a,c) = -var(a-c) + var(a) + var(c)\n -2cov(a,d) = +var(a-d) - var(a) - var(d)\n -2cov(b,c) = +var(b-c) - var(b) - var(c)\n 2cov(b,d) = -var(b-d) + var(b) + var(d)\n adding up, we get:\n 2cov(a-b,c-d) = 2cov(a,c)-2cov(a,d)-2cov(b,c)+2cov(b,d) = - var(a-c) + var(a-d) + var(b-c) - var(b-d)\n\n a1^2 var(a-b)+a2^2 var(c-d)+2a1a2cov(a-b,c-d) = a1^2 var(a-b)+a2^2 var(c-d)+a1a2 [-var(a-c)+var(a-d)+var(b-c)-var(b-d)]\n var(a1(f_i1 - f_j1) + a2(f_i2 - f_j2)) =\n = a1^2 var(f_i1 - f_j1) + a2^2 var(f_i2 - f_j2) + 2a1 a2 cov(f_i1 - f_j1, f_i2 - f_j2)\n = a1^2 var(f_i1 - f_j1) + a2^2 var(f_i2 - f_j2) + a1 a2 [-var(f_i1 - f_i2) + var(f_i1 - f_j2) + var(f_j1-f_i2) - var(f_j1 - f_j2)]\n\n assume two arrays of free energy differences, and and array of constant vectors a.\n we want the variance var(\\sum_k a_k (f_i,k - f_j,k)) Each set is separated from the other by an offset K\n same process applies with the sum, with the single var tems and the pair terms\n \"\"\"\n\n # todo: vectorize this.\n var_ij = np.square(d_ij)\n d2 = np.zeros([K,K],float)\n n = len(a)\n for i in range(K):\n for j in range(K):\n for k in range(n):\n d2[i,j] += a[k]**2 * var_ij[i+k*K,j+k*K]\n for l in range(n):\n d2[i,j] += a[k] * a[l] * (-var_ij[i+k*K,i+l*K] + var_ij[i+k*K,j+l*K] + var_ij[j+k*K,i+l*K] - var_ij[j+k*K,j+l*K])\n\n return np.sqrt(d2)\n\n #=========================================================================\n def computeExpectations(self, A_n, u_kn=None, output='averages', state_dependent=False,\n compute_uncertainty=True, uncertainty_method=None,\n warning_cutoff=1.0e-10):\n \"\"\"Compute the expectation of an observable of a phase space function.\n\n Compute the expectation of an observable of a single phase space\n function A(x) at all states where potentials are generated.\n\n Parameters\n ----------\n A_n : np.ndarray, float\n A_n (N_max np float64 array) - A_n[n] = A(x_n)\n\n u_kn : np.ndarray\n u_kn (energies of state of interest length N)\n default is self.u_kn\n\n output : string, optional\n 'averages' outputs expectations of observables and 'differences' outputs\n a matrix of differences in the observables.\n\n compute_uncertainty : bool, optional\n If False, the uncertainties will not be computed (default: True)\n\n uncertainty_method : string, optional\n Choice of method used to compute asymptotic covariance method,\n or None to use default See help for _computeAsymptoticCovarianceMatrix()\n for more information on various methods. (default: None)\n\n warning_cutoff : float, optional\n Warn if squared-uncertainty is negative and larger in magnitude than this number (default: 1.0e-10)\n\n state_dependent: bool, whether the expectations are state-dependent.\n\n Returns\n -------\n A : np.ndarray, float\n if output is 'averages'\n A_i (K np float64 array) - A_i[i] is the estimate for the expectation of A(x) for state i.\n if output is 'differences'\n dA : np.ndarray, float\n dA_i (K np float64 array) - dA_i[i] is uncertainty estimate (one standard deviation) for A_i[i]\n or\n dA_ij (K np float64 array) - dA_ij[i,j] is uncertainty estimate (one standard deviation) for the difference in A beteen i and j\n or None, if compute_uncertainty is False.\n\n References\n ----------\n\n See Section IV of [1].\n\n Examples\n --------\n\n >>> from pymbar import testsystems\n >>> (x_n, u_kn, N_k, s_n) = testsystems.HarmonicOscillatorsTestCase().sample(mode='u_kn')\n >>> mbar = MBAR(u_kn, N_k)\n >>> A_n = x_n\n >>> (A_ij, dA_ij) = mbar.computeExpectations(A_n)\n >>> A_n = u_kn[0,:]\n >>> (A_ij, dA_ij) = mbar.computeExpectations(A_n, output='differences')\n \"\"\"\n\n dims = len(np.shape(A_n))\n\n if dims > 2:\n print(\"Warning: dim=3 for (state_dependent==True) matrices for observables and dim=2 for (state_dependent==False) observables are deprecated; we suggest you convert to NxK form instead of NxKxK form.\")\n\n if not state_dependent:\n if dims==2:\n A_n = kn_to_n(A_n, N_k=self.N_k)\n if u_kn is not None:\n if len(np.shape(u_kn)) == 3:\n u_kn = kln_to_kn(u_kn, N_k=self.N_k)\n elif len(np.shape(u_kn)) == 2:\n u_kn = kn_to_n(u_kn, N_k=self.N_k)\n else:\n if dims==3:\n A_n = kln_to_kn(A_n, N_k=self.N_k)\n if u_kn is not None:\n if len(np.shape(u_kn)) == 3:\n u_kn = kln_to_kn(u_kn, N_k=self.N_k)\n elif len(np.shape(u_kn)) == 2:\n u_kn = kn_to_n(u_kn, N_k=self.N_k)\n\n if u_kn is None:\n u_kn = self.u_kn\n\n # Retrieve N and K for convenience.\n N = self.N\n ushape = np.shape(u_kn)\n if len(ushape) == 1:\n K = 1\n else:\n K = np.shape(u_kn)[0] # number of potentials provided.\n\n state_map = np.zeros([2,K],int)\n if state_dependent:\n for k in range(K):\n # first property at the first state, 2nd property at the 2nd state\n state_map[0,k] = k\n state_map[1,k] = k\n else:\n # only one property, evaluate at K different states.\n for k in range(K):\n state_map[0,k] = k\n state_map[1,k] = 0\n\n inner_results = self.computeExpectationsInner(A_n,u_kn,state_map,\n return_theta=compute_uncertainty,\n uncertainty_method=uncertainty_method,\n warning_cutoff=warning_cutoff)\n\n mu, sigma = None, None\n\n if compute_uncertainty:\n # we want the theta matrix for the exponentials of the\n # observables, which means we need to make the\n # transformation.\n Adiag = np.zeros([2*K,2*K],dtype=np.float64)\n diag = np.ones(2*K,dtype=np.float64)\n diag[0:K] = diag[K:2*K] = inner_results['observables']-inner_results['Amin']\n np.fill_diagonal(Adiag,diag)\n Theta = Adiag*inner_results['Theta']*Adiag\n covA_ij = np.array(Theta[0:K,0:K]+Theta[K:2*K,K:2*K]-Theta[0:K,K:2*K]-Theta[K:2*K,0:K])\n\n if output == 'averages':\n mu = inner_results['observables']\n if compute_uncertainty:\n sigma = np.sqrt(covA_ij[0:K,0:K].diagonal())\n\n if output == 'differences':\n A_im = np.matrix(inner_results['observables'])\n A_ij = A_im - A_im.transpose()\n\n mu = np.array(A_ij)\n if compute_uncertainty:\n sigma = self._ErrorOfDifferences(covA_ij,warning_cutoff=warning_cutoff)\n\n return mu, sigma\n\n #=========================================================================\n def computeMultipleExpectations(self, A_in, u_n, compute_uncertainty=True, compute_covariance=False,\n uncertainty_method=None, warning_cutoff=1.0e-10):\n \"\"\"Compute the expectations of multiple observables of phase space functions.\n\n Compute the expectations of multiple observables of phase\n space functions [A_0(x),A_1(x),...,A_i(x)] at a single state,\n along with the error in the estimates and the uncertainty in\n the estimates. The state is specified by the choice of u_n,\n which is the energy of the n samples evaluated at a the chosen\n state.\n\n Parameters\n ----------\n A_in : np.ndarray, float, shape=(I, k, N)\n A_in[i,n] = A_i(x_n), the value of phase observable i for configuration n at state of interest\n u_n : np.ndarray, float, shape=(N)\n u_n[n] is the reduced potential of configuration n at the state of interest\n compute_uncertainty : bool, optional, default=True\n If True, calculate the uncertainty\n compute_covariance : bool, optional, default=False\n If True, calculate the covariance\n uncertainty_method : string, optional\n Choice of method used to compute asymptotic covariance method, or None to use default\n See help for computeAsymptoticCovarianceMatrix() for more information on various methods. (default: None)\n warning_cutoff : float, optional\n Warn if squared-uncertainty is negative and larger in magnitude than this number (default: 1.0e-10)\n\n Returns\n -------\n\n A_i : np.ndarray, float, shape=(I)\n A_i[i] is the estimate for the expectation of A_i(x) at the state specified by u_kn\n dA_i : np.ndarray, float, shape = (I)\n dA_i[i] is the uncertainty in the expectation of A_state_map[i](x) at the state specified by u_n[state_map[i],:]\n or None if compute_uncertainty is False\n d2A_ij : np.ndarray, float, shape=(I, I)\n d2A_ij[i,j] is the COVARIANCE in the estimates of A_i[i] and A_i[j]: we can't actually take a square root\n or None if compute_covariance is False\n\n Examples\n --------\n\n >>> from pymbar import testsystems\n >>> (x_n, u_kn, N_k, s_n) = testsystems.HarmonicOscillatorsTestCase().sample(mode='u_kn')\n >>> mbar = MBAR(u_kn, N_k)\n >>> A_in = np.array([x_n,x_n**2,x_n**3])\n >>> u_n = u_kn[0,:]\n >>> (A_i, dA_i, d2A_ij) = mbar.computeMultipleExpectations(A_in, u_kn)\n\n \"\"\"\n\n # Retrieve N and K for convenience.\n I = A_in.shape[0] # number of observables\n K = self.K\n N = self.N # N is total number of samples\n\n if len(np.shape(A_in)) == 3:\n A_in_old = A_in.copy() # convert to k by n format\n A_in = np.zeros([I, N], np.float64)\n for i in range(I):\n A_in[i,:] = kn_to_n(A_in_old[i, :, :], N_k=self.N_k)\n\n if len(np.shape(u_n)) == 2:\n u_n = kn_to_n(u_n, N_k = self.N_k)\n\n state_map = np.zeros([2,I],int)\n state_map[1,:] = np.arange(I) # same (first) state for all variables.\n\n inner_results = self.computeExpectationsInner(A_in,u_n,state_map,\n return_theta=(compute_uncertainty or compute_covariance),\n uncertainty_method=uncertainty_method,\n warning_cutoff=warning_cutoff)\n\n expectations, uncertainties, covariances = None, None, None\n expectations = inner_results['observables']\n\n if compute_uncertainty or compute_covariance:\n Adiag = np.zeros([2*I,2*I],dtype=np.float64)\n diag = np.ones(2*I,dtype=np.float64)\n diag[0:I] = diag[I:2*I] = inner_results['observables']-inner_results['Amin']\n np.fill_diagonal(Adiag,diag)\n Theta = Adiag*inner_results['Theta']*Adiag\n\n if compute_uncertainty:\n covA_ij = np.array(Theta[0:I,0:I]+Theta[I:2*I,I:2*I]-Theta[0:I,I:2*I]-Theta[I:2*I,0:I])\n uncertainties = np.sqrt(covA_ij[0:I,0:I].diagonal())\n\n if compute_covariance:\n # compute estimate of statistical covariance of the observables\n covariances = inner_results['Theta'][0:I,0:I]\n\n return expectations, uncertainties, covariances\n\n\n #=========================================================================\n def computePerturbedFreeEnergies(self, u_ln, compute_uncertainty=True, uncertainty_method=None, warning_cutoff=1.0e-10):\n \"\"\"Compute the free energies for a new set of states.\n\n Here, we desire the free energy differences among a set of new states, as well as the uncertainty estimates in these differences.\n\n Parameters\n ----------\n u_ln : np.ndarray, float, shape=(L, Nmax)\n u_ln[l,n] is the reduced potential energy of uncorrelated\n configuration n evaluated at new state k. Can be completely indepednent of the original number of states.\n compute_uncertainty : bool, optional, default=True\n If False, the uncertainties will not be computed (default: True)\n uncertainty_method : string, optional\n Choice of method used to compute asymptotic covariance method, or None to use default\n See help for computeAsymptoticCovarianceMatrix() for more information on various methods. (default: None)\n warning_cutoff : float, optional\n Warn if squared-uncertainty is negative and larger in magnitude than this number (default: 1.0e-10)\n\n Returns\n -------\n Deltaf_ij : np.ndarray, float, shape=(L, L)\n Deltaf_ij[i,j] = f_j - f_i, the dimensionless free energy difference between new states i and j\n dDeltaf_ij : np.ndarray, float, shape=(L, L)\n dDeltaf_ij[i,j] is the estimated statistical uncertainty in Deltaf_ij[i,j]\n or None if compute_uncertainty is False\n\n Examples\n --------\n >>> from pymbar import testsystems\n >>> (x_n, u_kn, N_k, s_n) = testsystems.HarmonicOscillatorsTestCase().sample(mode='u_kn')\n >>> mbar = MBAR(u_kn, N_k)\n >>> Deltaf_ij, dDeltaf_ij = mbar.computePerturbedFreeEnergies(u_kn)\n \"\"\"\n\n # Convert to np matrix.\n u_ln = np.array(u_ln, dtype=np.float64)\n\n # Get the dimensions of the matrix of reduced potential energies, and convert if necessary\n if len(np.shape(u_ln)) == 3:\n u_ln = kln_to_kn(u_ln, N_k=self.N_k)\n\n [L, N] = u_ln.shape\n\n # Check dimensions.\n if (N < self.N):\n raise \"There seems to be too few samples in u_kn. You must evaluate at the new potential with all of the samples used originally.\"\n\n state_list = np.arange(L) # need to get it into the correct shape\n A_in = np.array([0])\n inner_results = self.computeExpectationsInner(A_in, u_ln, state_list,\n return_theta=compute_uncertainty,\n uncertainty_method=uncertainty_method,\n warning_cutoff=warning_cutoff)\n\n Deltaf_ij, dDeltaf_ij = None, None\n\n f_k = np.matrix(inner_results['free energies'])\n Deltaf_ij = np.array(f_k - f_k.transpose())\n\n if (compute_uncertainty):\n dDeltaf_ij = self._ErrorOfDifferences(inner_results['Theta'],warning_cutoff=warning_cutoff)\n\n # Return matrix of free energy differences and uncertainties.\n return Deltaf_ij, dDeltaf_ij\n\n #=====================================================================\n\n def computeEntropyAndEnthalpy(self, u_kn=None, uncertainty_method=None, verbose=False, warning_cutoff=1.0e-10):\n \"\"\"Decompose free energy differences into enthalpy and entropy differences.\n\n Compute the decomposition of the free energy difference between\n states 1 and N into reduced free energy differences, reduced potential\n (enthalpy) differences, and reduced entropy (S/k) differences.\n\n Parameters\n ----------\n u_kn : float, NxK array\n The energies of the state that are being used.\n uncertainty_method : string , optional\n Choice of method used to compute asymptotic covariance method, or None to use default\n See help for computeAsymptoticCovarianceMatrix() for more information on various methods. (default: None)\n warning_cutoff : float, optional\n Warn if squared-uncertainty is negative and larger in magnitude than this number (default: 1.0e-10)\n\n Returns\n -------\n Delta_f_ij : np.ndarray, float, shape=(K, K)\n Delta_f_ij[i,j] is the dimensionless free energy difference f_j - f_i\n dDelta_f_ij : np.ndarray, float, shape=(K, K)\n uncertainty in Delta_f_ij\n Delta_u_ij : np.ndarray, float, shape=(K, K)\n Delta_u_ij[i,j] is the reduced potential energy difference u_j - u_i\n dDelta_u_ij : np.ndarray, float, shape=(K, K)\n uncertainty in Delta_f_ij\n Delta_s_ij : np.ndarray, float, shape=(K, K)\n Delta_s_ij[i,j] is the reduced entropy difference S/k between states i and j (s_j - s_i)\n dDelta_s_ij : np.ndarray, float, shape=(K, K)\n uncertainty in Delta_s_ij\n\n Examples\n --------\n\n >>> from pymbar import testsystems\n >>> (x_n, u_kn, N_k, s_n) = testsystems.HarmonicOscillatorsTestCase().sample(mode='u_kn')\n >>> mbar = MBAR(u_kn, N_k)\n >>> [Delta_f_ij, dDelta_f_ij, Delta_u_ij, dDelta_u_ij, Delta_s_ij, dDelta_s_ij] = mbar.computeEntropyAndEnthalpy()\n\n \"\"\"\n if verbose:\n print(\"Computing average energy and entropy by MBAR.\")\n\n dims = len(np.shape(u_kn))\n if dims==3:\n u_kn = kln_to_kn(u_kn, N_k=self.N_k)\n\n if u_kn is None:\n u_kn = self.u_kn\n\n # Retrieve N and K for convenience.\n [K,N] = np.shape(u_kn)\n A_in = u_kn.copy()\n state_map = np.zeros([2,K],int)\n for k in range(K):\n state_map[0,k] = k\n state_map[1,k] = k\n\n inner_results = self.computeExpectationsInner(A_in, u_kn, state_map,\n return_theta=True,\n uncertainty_method=uncertainty_method,\n warning_cutoff=warning_cutoff)\n\n # construct the covariance matrix of exp(ln c_Ua - ln c_a) - ln c_ca\n\n Theta = np.zeros([3*K,3*K],dtype=np.float64)\n Theta[0:2*K,0:2*K] = inner_results['Theta']\n Theta[2*K:3*K,:] = Theta[K:2*K,:]\n Theta[:,2*K:3*K] = Theta[:,K:2*K]\n diag = np.ones(3*K,dtype=np.float64)\n diag[0:K] = diag[K:2*K] = inner_results['observables']-inner_results['Amin']\n Adiag = np.matrix(np.zeros([3*K,3*K],dtype=np.float64))\n np.fill_diagonal(Adiag,diag)\n Theta = Adiag*Theta*Adiag\n\n # Compute reduced free energy difference.\n f_k = np.matrix(inner_results['free energies'])\n Delta_f_ij = np.array(f_k - f_k.transpose())\n # compute uncertainty matrix in free energies:\n covf = Theta[2*K:3*K,2*K:3*K]\n dDelta_f_ij = self._ErrorOfDifferences(covf,warning_cutoff=warning_cutoff)\n\n # Compute reduced enthalpy difference.\n u_k = np.matrix(inner_results['observables'])\n Delta_u_ij = np.array(u_k - u_k.transpose())\n # compute uncertainty matrix in energies:\n covu = Theta[0:K,0:K]+Theta[K:2*K,K:2*K]-Theta[0:K,K:2*K]-Theta[K:2*K,0:K]\n dDelta_u_ij = self._ErrorOfDifferences(covu,warning_cutoff=warning_cutoff)\n\n # Compute reduced entropy difference\n s_k = u_k - f_k\n Delta_s_ij = np.array(s_k - s_k.transpose())\n # compute uncertainty matrix in entropies\n #s_i = u_i - f_i\n #cov(s_i) = cov(u_i - f_i)\n # = cov(exp(ln C_a - ln c_a) + ln c_a)\n # = cov(exp(ln C_a - ln c_a), exp(ln C_a - ln c_a)) + cov(ln c_a, ln c_a)\n # + cov(exp(ln C_a - ln c_a), ln c_a) + cov(ln c_a, exp(ln C_a - ln c_a))\n # = cov(u,u) + cov(f,f)\n # + A cov(ln C_a - ln c_a, ln c_a) + A cov(ln c_a, ln C_a - ln c_a)\n # = cov(u,u) + cov(f,f)\n # + A cov(ln C_a, ln c_a) - A cov(ln c_a, ln c_a) + A cov(ln c_a, ln C_a) - A cov(ln c_a, ln c_a)\n # = cov(u,u) + cov(f,f) + A cov(ln C_a,ln c_a) + A cov(ln c_a, ln C_a) - 2A cov(ln_ca,ln_ca)\n #\n covs = covu + covf + Theta[0:K,2*K:3*K] + Theta[2*K:3*K,0:K] - Theta[K:2*K,2*K:3*K] - Theta[2*K:3*K,K:2*K]\n # note: not clear that Theta[K:2*K,2*K:3*K] and Theta[K:2*K,2*K:3*K] are symmetric?\n dDelta_s_ij = self._ErrorOfDifferences(covs,warning_cutoff=warning_cutoff)\n\n # Return expectations and uncertainties.\n return (Delta_f_ij, dDelta_f_ij, Delta_u_ij, dDelta_u_ij, Delta_s_ij, dDelta_s_ij)\n\n #=====================================================================\n\n def computePMF(self, u_n, bin_n, nbins, uncertainties='from-lowest', pmf_reference=None):\n \"\"\"Compute the free energy of occupying a number of bins.\n\n This implementation computes the expectation of an indicator-function observable for each bin.\n\n Parameters\n ----------\n u_n : np.ndarray, float, shape=(N)\n u_n[n] is the reduced potential energy of snapshot n of state k for which the PMF is to be computed.\n bin_n : np.ndarray, float, shape=(N)\n bin_n[n] is the bin index of snapshot n of state k. bin_n can assume a value in range(0,nbins)\n nbins : int\n The number of bins\n uncertainties : string, optional\n Method for reporting uncertainties (default: 'from-lowest')\n 'from-lowest' - the uncertainties in the free energy difference with lowest point on PMF are reported\n 'from-specified' - same as from lowest, but from a user specified point\n 'from-normalization' - the normalization \\sum_i p_i = 1 is used to determine uncertainties spread out through the PMF\n 'all-differences' - the nbins x nbins matrix df_ij of uncertainties in free energy differences is returned instead of df_i\n pmf_reference : int, optional\n the reference state that is zeroed when uncertainty = 'from-specified'\n\n Returns\n -------\n f_i : np.ndarray, float, shape=(K)\n f_i[i] is the dimensionless free energy of state i, relative to the state of lowest free energy\n df_i : np.ndarray, float, shape=(K)\n df_i[i] is the uncertainty in the difference of f_i with respect to the state of lowest free energy\n\n Notes\n -----\n All bins must have some samples in them from at least one of the states -- this will not work if bin_n.sum(0) == 0. Empty bins should be removed before calling computePMF().\n This method works by computing the free energy of localizing the system to each bin for the given potential by aggregating the log weights for the given potential.\n To estimate uncertainties, the NxK weight matrix W_nk is augmented to be Nx(K+nbins) in order to accomodate the normalized weights of states where\n the potential is given by u_kn within each bin and infinite potential outside the bin. The uncertainties with respect to the bin of lowest free energy\n are then computed in the standard way.\n\n Examples\n --------\n\n >>> # Generate some test data\n >>> from pymbar import testsystems\n >>> (x_n, u_kn, N_k, s_n) = testsystems.HarmonicOscillatorsTestCase().sample(mode='u_kn')\n >>> # Initialize MBAR on data.\n >>> mbar = MBAR(u_kn, N_k)\n >>> # Select the potential we want to compute the PMF for (here, condition 0).\n >>> u_n = u_kn[0, :]\n >>> # Sort into nbins equally-populated bins\n >>> nbins = 10 # number of equally-populated bins to use\n >>> import numpy as np\n >>> N_tot = N_k.sum()\n >>> x_n_sorted = np.sort(x_n) # unroll to n-indices\n >>> bins = np.append(x_n_sorted[0::int(N_tot/nbins)], x_n_sorted.max()+0.1)\n >>> bin_widths = bins[1:] - bins[0:-1]\n >>> bin_n = np.zeros(x_n.shape, np.int64)\n >>> bin_n = np.digitize(x_n, bins) - 1\n >>> # Compute PMF for these unequally-sized bins.\n >>> [f_i, df_i] = mbar.computePMF(u_n, bin_n, nbins)\n >>> # If we want to correct for unequally-spaced bins to get a PMF on uniform measure\n >>> f_i_corrected = f_i - np.log(bin_widths)\n\n \"\"\"\n\n # Verify that no PMF bins are empty -- we can't deal with empty bins,\n # because the free energy is infinite.\n for i in range(nbins):\n if np.sum(bin_n == i) == 0:\n raise ParameterError(\n \"At least one bin in provided bin_n argument has no samples. All bins must have samples for free energies to be finite. Adjust bin sizes or eliminate empty bins to ensure at least one sample per bin.\")\n K = self.K\n\n if len(np.shape(u_n)) == 2:\n u_n = kn_to_n(u_n, N_k = self.N_k)\n\n if len(np.shape(bin_n)) == 2:\n bin_n = kn_to_n(bin_n, N_k = self.N_k)\n\n # Compute unnormalized log weights for the given reduced potential\n # u_n.\n log_w_n = self._computeUnnormalizedLogWeights(u_n)\n\n # Compute the free energies for these states.\n f_i = np.zeros([nbins], np.float64)\n df_i = np.zeros([nbins], np.float64)\n for i in range(nbins):\n # Get linear n-indices of samples that fall in this bin.\n indices = np.where(bin_n == i)\n\n # Sanity check.\n if (len(indices) == 0):\n raise \"WARNING: bin %d has no samples -- all bins must have at least one sample.\" % i\n\n # Compute dimensionless free energy of occupying state i.\n f_i[i] = - logsumexp(log_w_n[indices])\n\n # Compute uncertainties by forming matrix of W_nk.\n N_k = np.zeros([self.K + nbins], np.int64)\n N_k[0:K] = self.N_k\n W_nk = np.zeros([self.N, self.K + nbins], np.float64)\n W_nk[:, 0:K] = np.exp(self.Log_W_nk)\n for i in range(nbins):\n # Get indices of samples that fall in this bin.\n indices = np.where(bin_n == i)\n\n # Compute normalized weights for this state.\n W_nk[indices, K + i] = np.exp(log_w_n[indices] + f_i[i])\n\n # Compute asymptotic covariance matrix using specified method.\n Theta_ij = self._computeAsymptoticCovarianceMatrix(W_nk, N_k)\n\n if (uncertainties == 'from-lowest') or (uncertainties == 'from-specified'):\n # Report uncertainties in free energy difference from a given point\n # on PMF.\n\n if (uncertainties == 'from-lowest'):\n # Determine bin index with lowest free energy.\n j = f_i.argmin()\n elif (uncertainties == 'from-specified'):\n if pmf_reference == None:\n raise ParameterError(\n \"no reference state specified for PMF using uncertainties = from-specified\")\n else:\n j = pmf_reference\n # Compute uncertainties with respect to difference in free energy\n # from this state j.\n for i in range(nbins):\n df_i[i] = math.sqrt(\n Theta_ij[K + i, K + i] + Theta_ij[K + j, K + j] - 2.0 * Theta_ij[K + i, K + j])\n\n # Shift free energies so that state j has zero free energy.\n f_i -= f_i[j]\n\n # Return dimensionless free energy and uncertainty.\n return (f_i, df_i)\n\n elif (uncertainties == 'all-differences'):\n # Report uncertainties in all free energy differences.\n\n diag = Theta_ij.diagonal()\n dii = diag[K, K + nbins]\n d2f_ij = dii + \\\n dii.transpose() - 2 * Theta_ij[K:K + nbins, K:K + nbins]\n\n # unsquare uncertainties\n df_ij = np.sqrt(d2f_ij)\n\n # Return dimensionless free energy and uncertainty.\n return (f_i, df_ij)\n\n elif (uncertainties == 'from-normalization'):\n # Determine uncertainties from normalization that \\sum_i p_i = 1.\n\n # Compute bin probabilities p_i\n p_i = np.exp(-f_i - logsumexp(-f_i))\n\n # todo -- eliminate triple loop over nbins!\n # Compute uncertainties in bin probabilities.\n d2p_i = np.zeros([nbins], np.float64)\n for k in range(nbins):\n for i in range(nbins):\n for j in range(nbins):\n delta_ik = 1.0 * (i == k)\n delta_jk = 1.0 * (j == k)\n d2p_i[k] += p_i[k] * (p_i[i] - delta_ik) * p_i[\n k] * (p_i[j] - delta_jk) * Theta_ij[K + i, K + j]\n\n # Transform from d2p_i to df_i\n d2f_i = d2p_i / p_i ** 2\n df_i = np.sqrt(d2f_i)\n\n # return free energy and uncertainty\n return (f_i, df_i)\n\n else:\n raise \"Uncertainty method '%s' not recognized.\" % uncertainties\n\n\n #=========================================================================\n # PRIVATE METHODS - INTERFACES ARE NOT EXPORTED\n #=========================================================================\n\n def _ErrorOfDifferences(self,cov,warning_cutoff=1.0e-10):\n \"\"\"\n inputs:\n cov is the covariance matrix of A\n\n returns the statistical error matrix of A_i - A_j\n \"\"\"\n\n diag = np.matrix(cov.diagonal())\n d2 = diag + diag.transpose() - 2 * cov\n\n # check for any numbers below zero.\n if (np.any(d2 < 0.0)):\n if (np.any(d2) < warning_cutoff):\n print(\"A squared uncertainty is negative. d2 = %e\" % d2[(np.any(d2) < warning_cutoff)])\n else:\n d2[(np.any(d2) < warning_cutoff)] = 0.0\n return np.sqrt(np.array(d2))\n\n def _pseudoinverse(self, A, tol=1.0e-10):\n \"\"\"Compute the Moore-Penrose pseudoinverse, wraps np.linalg.pinv\n\n REQUIRED ARGUMENTS\n A (np KxK matrix) - the square matrix whose pseudoinverse is to be computed\n\n RETURN VALUES\n Ainv (np KxK matrix) - the pseudoinverse\n\n OPTIONAL VALUES\n tol - the tolerance (relative to largest magnitude singlular value) below which singular values are to not be include in forming pseudoinverse (default: 1.0e-10)\n\n NOTES\n In previous versions of pymbar / Numpy, we wrote our own pseudoinverse\n because of a bug in Numpy.\n\n \"\"\"\n\n return np.linalg.pinv(A, rcond=tol)\n\n #=========================================================================\n\n def _zerosamestates(self, A):\n \"\"\"\n zeros out states that should be identical\n\n REQUIRED ARGUMENTS\n\n A: the matrix whose entries are to be zeroed.\n\n \"\"\"\n\n for pair in self.samestates:\n A[pair[0], pair[1]] = 0\n A[pair[1], pair[0]] = 0\n\n #=========================================================================\n def _computeAsymptoticCovarianceMatrix(self, W, N_k, method=None):\n \"\"\"Compute estimate of the asymptotic covariance matrix.\n\n Parameters\n ----------\n W : np.ndarray, shape=(N, K), dtype='float'\n The normalized weight matrix for snapshots and states.\n W[n, k] is the weight of snapshot n in state k.\n N_k : np.ndarray, shape=(K), dtype='int'\n N_k[k] is the number of samples from state k.\n method : string, optional, default=None\n Method used to compute the asymptotic covariance matrix.\n Must be either \"approximate\", \"svd\", or \"svd-ew\". If None,\n defaults to \"svd-ew\".\n\n Returns\n -------\n Theta: np.ndarray, shape=(K, K), dtype='float'\n Asymptotic covariance matrix\n\n Notes\n -----\n The computational costs of the various 'method' arguments varies:\n 'svd' computes the generalized inverse using the singular value decomposition -- this should be efficient yet accurate (faster)\n 'svd-ew' is the same as 'svd', but uses the eigenvalue decomposition of W'W to bypass the need to perform an SVD (fastest)\n 'approximate' only requires multiplication of KxN and NxK matrices, but is an approximate underestimate of the uncertainty.\n\n svd and svd-ew are described in appendix D of Shirts, 2007 JCP, while\n \"approximate\" in Section 4 of Kong, 2003. J. R. Statist. Soc. B.\n\n We currently recommend 'svd-ew'.\n \"\"\"\n\n # Set 'svd-ew' as default if uncertainty method specified as None.\n if method == None:\n method = 'svd-ew'\n\n # Get dimensions of weight matrix.\n [N, K] = W.shape\n\n # Check dimensions\n if(K != N_k.size):\n raise ParameterError(\n 'W must be NxK, where N_k is a K-dimensional array.')\n if(np.sum(N_k) != N):\n raise ParameterError('W must be NxK, where N = sum_k N_k.')\n\n check_w_normalized(W, N_k)\n\n # Compute estimate of asymptotic covariance matrix using specified method.\n if method == 'approximate':\n # Use fast approximate expression from Kong et al. -- this underestimates the true covariance, but may be a good approximation in some cases and requires no matrix inversions\n # Theta = P'P\n\n # Construct matrices\n W = np.matrix(W, dtype=np.float64)\n\n # Compute covariance\n Theta = W.T * W\n\n elif method == 'svd':\n # Use singular value decomposition based approach given in supplementary material to efficiently compute uncertainty\n # See Appendix D.1, Eq. D4 in [1].\n\n # Construct matrices\n Ndiag = np.matrix(np.diag(N_k), dtype=np.float64)\n W = np.matrix(W, dtype=np.float64)\n I = np.identity(K, dtype=np.float64)\n\n # Compute SVD of W\n [U, S, Vt] = linalg.svd(W, full_matrices=False) # False Avoids O(N^2) memory allocation by only calculting the active subspace of U.\n Sigma = np.matrix(np.diag(S))\n V = np.matrix(Vt).T\n\n # Compute covariance\n Theta = V * Sigma * self._pseudoinverse(\n I - Sigma * V.T * Ndiag * V * Sigma) * Sigma * V.T\n\n elif method == 'svd-ew':\n # Use singular value decomposition based approach given in supplementary material to efficiently compute uncertainty\n # The eigenvalue decomposition of W'W is used to forego computing the SVD.\n # See Appendix D.1, Eqs. D4 and D5 of [1].\n\n # Construct matrices\n Ndiag = np.matrix(np.diag(N_k), dtype=np.float64)\n W = np.matrix(W, dtype=np.float64)\n I = np.identity(K, dtype=np.float64)\n\n # Compute singular values and right singular vectors of W without using SVD\n # Instead, we compute eigenvalues and eigenvectors of W'W.\n # Note W'W = (U S V')'(U S V') = V S' U' U S V' = V (S'S) V'\n [S2, V] = linalg.eigh(W.T * W)\n # Set any slightly negative eigenvalues to zero.\n S2[np.where(S2 < 0.0)] = 0.0\n # Form matrix of singular values Sigma, and V.\n Sigma = np.matrix(np.diag(np.sqrt(S2)))\n V = np.matrix(V)\n\n # Compute covariance\n Theta = V * Sigma * self._pseudoinverse(\n I - Sigma * V.T * Ndiag * V * Sigma) * Sigma * V.T\n\n else:\n # Raise an exception.\n raise ParameterError('Method ' + method + ' unrecognized.')\n\n return Theta\n #=========================================================================\n\n def _initializeFreeEnergies(self, verbose=False, method='zeros'):\n \"\"\"\n Compute an initial guess at the relative free energies.\n\n OPTIONAL ARGUMENTS\n verbose (boolean) - If True, will print debug information (default: False)\n method (string) - Method for initializing guess at free energies.\n 'zeros' - all free energies are initially set to zero\n 'mean-reduced-potential' - the mean reduced potential is used\n\n \"\"\"\n\n if (method == 'zeros'):\n # Use zeros for initial free energies.\n if verbose:\n print(\"Initializing free energies to zero.\")\n self.f_k[:] = 0.0\n elif (method == 'mean-reduced-potential'):\n # Compute initial guess at free energies from the mean reduced\n # potential from each state\n if verbose:\n print(\"Initializing free energies with mean reduced potential for each state.\")\n means = np.zeros([self.K], float)\n for k in self.states_with_samples:\n means[k] = self.u_kn[k, 0:self.N_k[k]].mean()\n if (np.max(np.abs(means)) < 0.000001):\n print(\"Warning: All mean reduced potentials are close to zero. If you are using energy differences in the u_kln matrix, then the mean reduced potentials will be zero, and this is expected behavoir.\")\n self.f_k = means\n elif (method == 'BAR'):\n # For now, make a simple list of those states with samples.\n initialization_order = np.where(self.N_k > 0)[0]\n # Initialize all f_k to zero.\n self.f_k[:] = 0.0\n # Initialize the rest\n for index in range(0, np.size(initialization_order) - 1):\n k = initialization_order[index]\n l = initialization_order[index + 1]\n # forward work\n # here, we actually need to distinguish which states are which\n w_F = (\n self.u_kn[l,self.x_kindices==k] - self.u_kn[k,self.x_kindices==k])\n #self.u_kln[k, l, 0:self.N_k[k]] - self.u_kln[k, k, 0:self.N_k[k]])\n # reverse work\n w_R = (\n self.u_kn[k,self.x_kindices==l] - self.u_kn[l,self.x_kindices==l])\n #self.u_kln[l, k, 0:self.N_k[l]] - self.u_kln[l, l, 0:self.N_k[l]])\n\n if (len(w_F) > 0 and len(w_R) > 0):\n # BAR solution doesn't need to be incredibly accurate to\n # kickstart NR.\n import pymbar.bar\n self.f_k[l] = self.f_k[k] + pymbar.bar.BAR(\n w_F, w_R, relative_tolerance=0.000001, verbose=False, compute_uncertainty=False)\n else:\n # no states observed, so we don't need to initialize this free energy anyway, as\n # the solution is noniterative.\n self.f_k[l] = 0\n\n else:\n # The specified method is not implemented.\n raise ParameterError('Method ' + method + ' unrecognized.')\n\n # Shift all free energies such that f_0 = 0.\n self.f_k[:] = self.f_k[:] - self.f_k[0]\n\n return\n\n def _computeUnnormalizedLogWeights(self, u_n):\n \"\"\"\n Return unnormalized log weights.\n\n REQUIRED ARGUMENTS\n u_n (N np float64 array) - reduced potential energies at single state\n\n OPTIONAL ARGUMENTS\n\n RETURN VALUES\n log_w_n (N array) - unnormalized log weights of each of a number of states\n\n REFERENCE\n 'log weights' here refers to \\log [ \\sum_{k=1}^K N_k exp[f_k - (u_k(x_n) - u(x_n)] ]\n \"\"\"\n return -1. * logsumexp(self.f_k + u_n[:, np.newaxis] - self.u_kn.T, b=self.N_k, axis=1)\n", "meta": {"hexsha": "82532425f07f5a42009cb5959e193bc0ce14c15c", "size": 74867, "ext": "py", "lang": "Python", "max_stars_repo_path": "unmaintained/_GL_alt/pymbar/mbar.py", "max_stars_repo_name": "PeculiarOvertones/FHDeX", "max_stars_repo_head_hexsha": "60e285101704196db24afe8b2461283753526fc5", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-06-25T13:23:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T21:31:54.000Z", "max_issues_repo_path": "unmaintained/_GL_alt/pymbar/mbar.py", "max_issues_repo_name": "PeculiarOvertones/FHDeX", "max_issues_repo_head_hexsha": "60e285101704196db24afe8b2461283753526fc5", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 44, "max_issues_repo_issues_event_min_datetime": "2019-09-24T15:31:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T21:05:21.000Z", "max_forks_repo_path": "unmaintained/_GL_alt/pymbar/mbar.py", "max_forks_repo_name": "PeculiarOvertones/FHDeX", "max_forks_repo_head_hexsha": "60e285101704196db24afe8b2461283753526fc5", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-10-01T15:47:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T23:04:58.000Z", "avg_line_length": 45.7063492063, "max_line_length": 274, "alphanum_fraction": 0.5802556534, "include": true, "reason": "import numpy", "num_tokens": 18349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.28776782797747225, "lm_q1q2_score": 0.14950152240613887}} {"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nA Metropolis-Hastings and Gibbs samplers for a state-ful model.\n\n\"\"\"\n\nimport numpy as np\nfrom emcee import autocorr\nfrom emcee.sampler import Sampler\nimport logging\nimport h5py\nfrom Starfish import constants as C\n\nclass StateSampler(Sampler):\n \"\"\"\n The most basic possible Metropolis-Hastings style MCMC sampler, but with\n optional callbacks for acceptance and rejection.\n\n :param cov:\n The covariance matrix to use for the proposal distribution.\n\n :param dim:\n Number of dimensions in the parameter space.\n\n :param lnpostfn:\n A function that takes a vector in the parameter space as input and\n returns the natural logarithm of the posterior probability for that\n position.\n\n :param query_lnprob:\n A function which queries the model for the current lnprob value. This is\n because an intermediate sampler might have intervened.\n\n :param rejectfn: (optional)\n A function to be executed if the proposal is rejected. Generally this\n should be a function which reverts the model to the previous parameter\n values. Might need to be a closure.\n\n :param acceptfn: (optional)\n A function to be executed if the proposal is accepted.\n\n :param args: (optional)\n A list of extra positional arguments for ``lnpostfn``. ``lnpostfn``\n will be called with the sequence ``lnpostfn(p, *args, **kwargs)``.\n\n :param kwargs: (optional)\n A list of extra keyword arguments for ``lnpostfn``. ``lnpostfn``\n will be called with the sequence ``lnpostfn(p, *args, **kwargs)``.\n\n \"\"\"\n def __init__(self, lnprob, p0, cov, query_lnprob=None, rejectfn=None,\n acceptfn=None, debug=False, outdir=\"\", *args, **kwargs):\n dim = len(p0)\n super().__init__(dim, lnprob, *args, **kwargs)\n self.cov = cov\n self.p0 = p0\n self.query_lnprob = query_lnprob\n self.rejectfn = rejectfn\n self.acceptfn = acceptfn\n self.logger = logging.getLogger(self.__class__.__name__)\n self.outdir = outdir\n self.debug = debug\n if self.debug:\n self.logger.setLevel(logging.DEBUG)\n else:\n self.logger.setLevel(logging.INFO)\n\n def reset(self):\n super().reset()\n self._chain = np.empty((0, self.dim))\n self._lnprob = np.empty(0)\n\n def sample(self, p0, lnprob0=None, randomstate=None, thin=1,\n storechain=True, iterations=1, incremental_save=0, **kwargs):\n \"\"\"\n Advances the chain ``iterations`` steps as an iterator\n\n :param p0:\n The initial position vector.\n\n :param lnprob0: (optional)\n The log posterior probability at position ``p0``. If ``lnprob``\n is not provided, the initial value is calculated.\n\n :param rstate0: (optional)\n The state of the random number generator. See the\n :func:`random_state` property for details.\n\n :param iterations: (optional)\n The number of steps to run.\n\n :param thin: (optional)\n If you only want to store and yield every ``thin`` samples in the\n chain, set thin to an integer greater than 1.\n\n :param storechain: (optional)\n By default, the sampler stores (in memory) the positions and\n log-probabilities of the samples in the chain. If you are\n using another method to store the samples to a file or if you\n don't need to analyse the samples after the fact (for burn-in\n for example) set ``storechain`` to ``False``.\n\n At each iteration, this generator yields:\n\n * ``pos`` - The current positions of the chain in the parameter\n space.\n\n * ``lnprob`` - The value of the log posterior at ``pos`` .\n\n * ``rstate`` - The current state of the random number generator.\n\n \"\"\"\n\n self.random_state = randomstate\n\n p = np.array(p0)\n if lnprob0 is None:\n # See if there's something there\n lnprob0 = self.query_lnprob()\n\n # If not, we're on the first iteration\n if lnprob0 is None:\n lnprob0 = self.get_lnprob(p)\n\n # Resize the chain in advance.\n if storechain:\n N = int(iterations / thin)\n self._chain = np.concatenate((self._chain,\n np.zeros((N, self.dim))), axis=0)\n self._lnprob = np.append(self._lnprob, np.zeros(N))\n\n i0 = self.iterations\n\n # Use range instead of xrange for python 3 compatability\n for i in range(int(iterations)):\n self.iterations += 1\n\n # Since the independent nuisance sampling may have changed parameters,\n # query each process for the current lnprob\n lnprob0 = self.query_lnprob()\n self.logger.debug(\"Queried lnprob: {}\".format(lnprob0))\n\n # Calculate the proposal distribution.\n if self.dim == 1:\n q = self._random.normal(loc=p[0], scale=self.cov[0], size=(1,))\n else:\n q = self._random.multivariate_normal(p, self.cov)\n\n newlnprob = self.get_lnprob(q)\n diff = newlnprob - lnprob0\n self.logger.debug(\"old lnprob: {}\".format(lnprob0))\n self.logger.debug(\"proposed lnprob: {}\".format(newlnprob))\n\n # M-H acceptance ratio\n if diff < 0:\n diff = np.exp(diff) - self._random.rand()\n if diff < 0:\n #Reject the proposal and revert the state of the model\n self.logger.debug(\"Proposal rejected\")\n if self.rejectfn is not None:\n self.rejectfn()\n\n if diff > 0:\n #Accept the new proposal\n self.logger.debug(\"Proposal accepted\")\n p = q\n lnprob0 = newlnprob\n self.naccepted += 1\n if self.acceptfn is not None:\n self.acceptfn()\n\n if storechain and i % thin == 0:\n ind = i0 + int(i / thin)\n self._chain[ind, :] = p\n self._lnprob[ind] = lnprob0\n\n # The default of 0 evaluates to False\n if incremental_save:\n if (((i+1) % incremental_save) == 0) & (i > 0): \n np.save('chain_backup.npy', self._chain)\n\n # Heavy duty iterator action going on right here...\n yield p, lnprob0, self.random_state\n\n @property\n def acor(self):\n \"\"\"\n An estimate of the autocorrelation time for each parameter (length:\n ``dim``).\n\n \"\"\"\n return self.get_autocorr_time()\n\n def get_autocorr_time(self, window=50):\n \"\"\"\n Compute an estimate of the autocorrelation time for each parameter\n (length: ``dim``).\n\n :param window: (optional)\n The size of the windowing function. This is equivalent to the\n maximum number of lags to use. (default: 50)\n\n \"\"\"\n return autocorr.integrated_time(self.chain, axis=0, window=window)\n\n def write(self, fname=\"mc.hdf5\"):\n '''\n Write the samples to an HDF file.\n\n flatchain\n acceptance fraction\n\n Everything can be saved in the dataset self.fname\n\n '''\n\n filename = self.outdir + fname\n self.logger.debug(\"Opening {} for writing HDF5 flatchains\".format(filename))\n hdf5 = h5py.File(filename, \"w\")\n samples = self.flatchain\n\n dset = hdf5.create_dataset(\"samples\", samples.shape, compression='gzip', compression_opts=9)\n dset[:] = samples\n dset.attrs[\"acceptance\"] = \"{}\".format(self.acceptance_fraction)\n dset.attrs[\"commit\"] = \"{}\".format(C.get_git_commit())\n hdf5.close()\n\n\n# class PSampler(ParallelSampler):\n# '''\n# Subclasses the GibbsSampler in emcee\n#\n# :param cov:\n# :param starting_param_dict: the dictionary of starting parameters\n# :param cov: the MH proposal\n# :param revertfn:\n# :param acceptfn:\n# :param debug:\n#\n# '''\n#\n# def __init__(self, **kwargs):\n# self.dim = len(self.param_tuple)\n# #p0 = np.empty((self.dim,))\n# #starting_param_dict = kwargs.get(\"starting_param_dict\")\n# #for i,param in enumerate(self.param_tuple):\n# # p0[i] = starting_param_dict[param]\n#\n# kwargs.update({\"dim\":self.dim})\n# #self.spectra_list = kwargs.get(\"spectra_list\", [0])\n#\n# super(PSampler, self).__init__(**kwargs)\n#\n# #Each subclass will have to overwrite how it parses the param_dict into the correct order\n# #and sets the param_tuple\n#\n# #SUBCLASS here and define self.param_tuple\n# #SUBCLASS here and define self.lnprob\n# #SUBCLASS here and do self.revertfn\n# #then do super().__init__() to call the following code\n#\n# self.outdir = kwargs.get(\"outdir\", \"\")\n#\n# def startdict_to_tuple(self, startdict):\n# raise NotImplementedError(\"To be implemented by a subclass!\")\n#\n# def zip_p(self, p):\n# return dict(zip(self.param_tuple, p))\n#\n# def lnprob(self):\n# raise NotImplementedError(\"To be implemented by a subclass!\")\n#\n# def revertfn(self):\n# raise NotImplementedError(\"To be implemented by a subclass!\")\n#\n# def acceptfn(self):\n# raise NotImplementedError(\"To be implemented by a subclass!\")\n#\n# def write(self):\n# '''\n# Write all of the relevant sample output to an HDF file.\n#\n# Write the lnprobability to an HDF file.\n#\n# flatchain\n# acceptance fraction\n# tuple parameters as an attribute in the header from self.param_tuple\n#\n# The actual HDF5 file is structured as follows\n#\n# /\n# stellar parameters.flatchain\n# 00/\n# ...\n# 22/\n# 23/\n# global_cov.flatchain\n# regions/\n# region1.flatchain\n#\n# Everything can be saved in the dataset self.fname\n#\n# '''\n#\n# filename = self.outdir + \"flatchains.hdf5\"\n# self.logger.debug(\"Opening {} for writing HDF5 flatchains\".format(filename))\n# hdf5 = h5py.File(filename, \"w\")\n# samples = self.flatchain\n#\n# self.logger.debug(\"Creating dataset with fname:{}\".format(self.fname))\n# dset = hdf5.create_dataset(self.fname, samples.shape, compression='gzip', compression_opts=9)\n# self.logger.debug(\"Storing samples and header attributes.\")\n# dset[:] = samples\n# dset.attrs[\"parameters\"] = \"{}\".format(self.param_tuple)\n# dset.attrs[\"acceptance\"] = \"{}\".format(self.acceptance_fraction)\n# dset.attrs[\"acor\"] = \"{}\".format(self.acor)\n# dset.attrs[\"commit\"] = \"{}\".format(C.get_git_commit())\n# hdf5.close()\n#\n# #lnprobability is the lnprob at each sample\n# filename = self.outdir + \"lnprobs.hdf5\"\n# self.logger.debug(\"Opening {} for writing HDF5 lnprobs\".format(filename))\n# hdf5 = h5py.File(filename, \"w\") #creates if doesn't exist, otherwise read/write\n# lnprobs = self.lnprobability\n#\n# dset = hdf5.create_dataset(self.fname, samples.shape[:1], compression='gzip', compression_opts=9)\n# dset[:] = lnprobs\n# dset.attrs[\"commit\"] = \"{}\".format(C.get_git_commit())\n# hdf5.close()\n#\n# def plot(self, triangle_plot=False):\n# '''\n# Generate the relevant plots once the sampling is done.\n# '''\n# samples = self.flatchain\n#\n# plot_walkers(self.outdir + self.fname + \"_chain_pos.png\", samples, labels=self.param_tuple)\n#\n# if triangle_plot:\n# import triangle\n# figure = triangle.corner(samples, labels=self.param_tuple, quantiles=[0.16, 0.5, 0.84],\n# show_titles=True, title_args={\"fontsize\": 12})\n# figure.savefig(self.outdir + self.fname + \"_triangle.png\")\n#\n# plt.close(figure)\n#\n# class StellarSampler(PSampler):\n# \"\"\"\n# Subclasses the Sampler specifically for stellar parameters\n#\n# \"\"\"\n# def __init__(self, **kwargs):\n# '''\n# :param pconns: Collection of parent ends of the PIPEs\n# :type pconns: dict\n#\n# :param starting_param_dict:\n# the dictionary of starting parameters\n#\n# :param cov:\n# the MH proposal\n#\n# :param fix_logg:\n# fix logg? If so, to what value?\n#\n# :param debug:\n#\n# :param args: []\n# '''\n#\n# self.fix_logg = kwargs.get(\"fix_logg\", False)\n# starting_pram_dict = kwargs.get(\"starting_param_dict\")\n# self.param_tuple = self.startdict_to_tuple(starting_pram_dict)\n# print(\"param_tuple is {}\".format(self.param_tuple))\n# self.p0 = np.array([starting_pram_dict[key] for key in self.param_tuple])\n#\n# kwargs.update({\"p0\":self.p0, \"revertfn\":self.revertfn, \"acceptfn\": self.acceptfn, \"lnprobfn\":self.lnprob})\n# super(StellarSampler, self).__init__(**kwargs)\n#\n# #self.pconns is a dictionary of parent connections to each PIPE connecting to the child processes.\n# self.spectrum_ids = sorted(self.pconns.keys())\n# self.fname = \"stellar\"\n#\n# def startdict_to_tuple(self, startdict):\n# tup = ()\n# for param in C.stellar_parameters:\n# #check if param is in keys, if so, add to the tuple\n# if param in startdict:\n# tup += (param,)\n# return tup\n#\n# def reset(self):\n# super(StellarSampler, self).reset()\n#\n# def revertfn(self):\n# '''\n# Revert the model to the previous state of parameters, in the case of a rejected MH proposal.\n# '''\n# self.logger.debug(\"reverting stellar parameters\")\n# self.prior = self.prior_last\n#\n# #Decide we don't want these stellar params. Tell the children to reject the proposal.\n# for pconn in self.pconns.values():\n# pconn.send((\"DECIDE\", False))\n#\n# def acceptfn(self):\n# '''\n# Execute this if the MH proposal is accepted.\n# '''\n# self.logger.debug(\"accepting stellar parameters\")\n# #Decide we do want to keep these stellar params. Tell the children to accept the proposal.\n# for pconn in self.pconns.values():\n# pconn.send((\"DECIDE\", True))\n#\n# def lnprob(self, p):\n# # We want to send the same stellar parameters to each model,\n# # but also send the different vz and logOmega parameters\n# # to the separate spectra, based upon spectrum_id.\n# #self.logger.debug(\"StellarSampler lnprob p is {}\".format(p))\n#\n# #Extract only the temp, logg, Z, vsini parameters\n# if not self.fix_logg:\n# params = self.zip_p(p[:4])\n# others = p[4:]\n# else:\n# #Coming in as temp, Z, vsini, vz, logOmega...\n# params = self.zip_p(p[:3])\n# others = p[3:]\n# params.update({\"logg\": self.fix_logg})\n#\n# # Prior\n# self.prior_last = self.prior\n#\n# logg = params[\"logg\"]\n# self.prior = -0.5 * (logg - 5.0)**2/(0.05)**2\n#\n# #others should now be either [vz, logOmega] or [vz0, logOmega0, vz1, logOmega1, ...] etc. Always div by 2.\n# #split p up into [vz, logOmega], [vz, logOmega] pairs that update the other parameters.\n# #mparams is now a list of parameter dictionaries\n#\n# #Now, pack up mparams into a dictionary to send the right stellar parameters to the right subprocesses\n# mparams = {}\n# for (spectrum_id, order_id), (vz, logOmega) in zip(self.spectrum_ids, grouper(others, 2)):\n# p = params.copy()\n# p.update({\"vz\":vz, \"logOmega\":logOmega})\n# mparams[spectrum_id] = p\n#\n# self.logger.debug(\"updated lnprob params: {}\".format(mparams))\n#\n# lnps = np.empty((self.nprocs,))\n#\n# #Distribute the calculation to each process\n# self.logger.debug(\"Distributing params to children\")\n# for ((spectrum_id, order_id), pconn) in self.pconns.items():\n# #Parse the parameters into what needs to be sent to each Model here.\n# pconn.send((\"LNPROB\", mparams[spectrum_id]))\n#\n# #Collect the answer from each process\n# self.logger.debug(\"Collecting params from children\")\n# for i, pconn in enumerate(self.pconns.values()):\n# lnps[i] = pconn.recv()\n#\n# self.logger.debug(\"lnps : {}\".format(lnps))\n# s = np.sum(lnps)\n# self.logger.debug(\"sum lnps {}\".format(s))\n# return s + self.prior\n#\n#\n#\n#\n# # From emcee\n# class GibbsSampler(Sampler):\n# \"\"\"\n# The most basic possible Metropolis-Hastings style MCMC sampler, designed to be\n# encapsulated as part of a state-ful Gibbs sampler.\n#\n# :param cov:\n# The covariance matrix to use for the proposal distribution.\n#\n# :param dim:\n# Number of dimensions in the parameter space.\n#\n# :param lnpostfn:\n# A function that takes a vector in the parameter space as input and\n# returns the natural logarithm of the posterior probability for that\n# position.\n#\n# :param revertfn:\n# A function which reverts the model to the previous parameter values, in the\n# case that the proposal parameters are rejected.\n#\n# :param acceptfn:\n# A function to be executed if the proposal is accepted.\n#\n# :param resample:\n# Redraw the previous lnprob at these parameters? Designed to work with the fact that an\n# Emulator is non-deterministic and prevent it from getting caught at a maximum.\n#\n# :param args: (optional)\n# A list of extra positional arguments for ``lnpostfn``. ``lnpostfn``\n# will be called with the sequence ``lnpostfn(p, *args, **kwargs)``.\n#\n# :param kwargs: (optional)\n# A list of extra keyword arguments for ``lnpostfn``. ``lnpostfn``\n# will be called with the sequence ``lnpostfn(p, *args, **kwargs)``.\n#\n# \"\"\"\n# def __init__(self, cov, p0, *args, **kwargs):\n# super(GibbsSampler, self).__init__(*args, **kwargs)\n# self.cov = cov\n# self.p0 = p0\n# self.revertfn = kwargs.get(\"revertfn\", None)\n# self.acceptfn = kwargs.get(\"acceptfn\", None)\n# self.logger = logging.getLogger(self.__class__.__name__)\n# self.debug = kwargs.get(\"debug\", False)\n# if self.debug:\n# self.logger.setLevel(logging.DEBUG)\n# else:\n# self.logger.setLevel(logging.INFO)\n#\n# def reset(self):\n# super(GibbsSampler, self).reset()\n# self._chain = np.empty((0, self.dim))\n# self._lnprob = np.empty(0)\n#\n# def sample(self, p0, lnprob0=None, randomstate=None, thin=1,\n# storechain=True, iterations=1, **kwargs):\n# \"\"\"\n# Advances the chain ``iterations`` steps as an iterator\n#\n# :param p0:\n# The initial position vector.\n#\n# :param lnprob0: (optional)\n# The log posterior probability at position ``p0``. If ``lnprob``\n# is not provided, the initial value is calculated.\n#\n# :param rstate0: (optional)\n# The state of the random number generator. See the\n# :func:`random_state` property for details.\n#\n# :param iterations: (optional)\n# The number of steps to run.\n#\n# :param thin: (optional)\n# If you only want to store and yield every ``thin`` samples in the\n# chain, set thin to an integer greater than 1.\n#\n# :param storechain: (optional)\n# By default, the sampler stores (in memory) the positions and\n# log-probabilities of the samples in the chain. If you are\n# using another method to store the samples to a file or if you\n# don't need to analyse the samples after the fact (for burn-in\n# for example) set ``storechain`` to ``False``.\n#\n# At each iteration, this generator yields:\n#\n# * ``pos`` - The current positions of the chain in the parameter\n# space.\n#\n# * ``lnprob`` - The value of the log posterior at ``pos`` .\n#\n# * ``rstate`` - The current state of the random number generator.\n#\n# \"\"\"\n#\n# self.random_state = randomstate\n#\n# p = np.array(p0)\n# if lnprob0 is None:\n# lnprob0 = self.get_lnprob(p)\n#\n# # Resize the chain in advance.\n# if storechain:\n# N = int(iterations / thin)\n# self._chain = np.concatenate((self._chain,\n# np.zeros((N, self.dim))), axis=0)\n# self._lnprob = np.append(self._lnprob, np.zeros(N))\n#\n# i0 = self.iterations\n# # Use range instead of xrange for python 3 compatability\n# for i in range(int(iterations)):\n# self.iterations += 1\n#\n# # Calculate the proposal distribution.\n# if self.dim == 1:\n# q = self._random.normal(loc=p[0], scale=self.cov[0], size=(1,))\n# else:\n# q = self._random.multivariate_normal(p, self.cov)\n#\n# newlnprob = self.get_lnprob(q)\n# diff = newlnprob - lnprob0\n# self.logger.debug(\"old lnprob: {}\".format(lnprob0))\n# self.logger.debug(\"proposed lnprob: {}\".format(newlnprob))\n#\n# # M-H acceptance ratio\n# if diff < 0:\n# diff = np.exp(diff) - self._random.rand()\n# if diff < 0:\n# #Reject the proposal and revert the state of the model\n# self.logger.debug(\"Proposal rejected\")\n# if self.revertfn is not None:\n# self.revertfn()\n#\n# if diff > 0:\n# #Accept the new proposal\n# self.logger.debug(\"Proposal accepted\")\n# p = q\n# lnprob0 = newlnprob\n# self.naccepted += 1\n# if self.acceptfn is not None:\n# self.acceptfn()\n#\n# if storechain and i % thin == 0:\n# ind = i0 + int(i / thin)\n# self._chain[ind, :] = p\n# self._lnprob[ind] = lnprob0\n#\n# # Heavy duty iterator action going on right here...\n# yield p, lnprob0, self.random_state\n#\n# @property\n# def acor(self):\n# \"\"\"\n# An estimate of the autocorrelation time for each parameter (length:\n# ``dim``).\n#\n# \"\"\"\n# return self.get_autocorr_time()\n#\n# def get_autocorr_time(self, window=50):\n# \"\"\"\n# Compute an estimate of the autocorrelation time for each parameter\n# (length: ``dim``).\n#\n# :param window: (optional)\n# The size of the windowing function. This is equivalent to the\n# maximum number of lags to use. (default: 50)\n#\n# \"\"\"\n# return autocorr.integrated_time(self.chain, axis=0, window=window)\n#\n# class SSampler(GibbsSampler):\n# '''\n# Subclasses the GibbsSampler in emcee\n#\n# :param cov:\n# :param starting_param_dict: the dictionary of starting parameters\n# :param cov: the MH proposal\n# :param revertfn:\n# :param acceptfn:\n# :param debug:\n#\n# '''\n#\n# def __init__(self, **kwargs):\n# self.dim = len(self.param_tuple)\n# #p0 = np.empty((self.dim,))\n# #starting_param_dict = kwargs.get(\"starting_param_dict\")\n# #for i,param in enumerate(self.param_tuple):\n# # p0[i] = starting_param_dict[param]\n#\n# kwargs.update({\"dim\":self.dim})\n# #self.spectra_list = kwargs.get(\"spectra_list\", [0])\n#\n# super(Sampler, self).__init__(**kwargs)\n#\n# #Each subclass will have to overwrite how it parses the param_dict into the correct order\n# #and sets the param_tuple\n#\n# #SUBCLASS here and define self.param_tuple\n# #SUBCLASS here and define self.lnprob\n# #SUBCLASS here and do self.revertfn\n# #then do super().__init__() to call the following code\n#\n# self.outdir = kwargs.get(\"outdir\", \"\")\n#\n# def startdict_to_tuple(self, startdict):\n# raise NotImplementedError(\"To be implemented by a subclass!\")\n#\n# def zip_p(self, p):\n# return dict(zip(self.param_tuple, p))\n#\n# def lnprob(self):\n# raise NotImplementedError(\"To be implemented by a subclass!\")\n#\n# def revertfn(self):\n# raise NotImplementedError(\"To be implemented by a subclass!\")\n#\n# def acceptfn(self):\n# raise NotImplementedError(\"To be implemented by a subclass!\")\n#\n# def write(self):\n# '''\n# Write all of the relevant sample output to an HDF file.\n#\n# Write the lnprobability to an HDF file.\n#\n# flatchain\n# acceptance fraction\n# tuple parameters as an attribute in the header from self.param_tuple\n#\n# The actual HDF5 file is structured as follows\n#\n# /\n# stellar parameters.flatchain\n# 00/\n# ...\n# 22/\n# 23/\n# global_cov.flatchain\n# regions/\n# region1.flatchain\n#\n# Everything can be saved in the dataset self.fname\n#\n# '''\n#\n# filename = self.outdir + \"flatchains.hdf5\"\n# self.logger.debug(\"Opening {} for writing HDF5 flatchains\".format(filename))\n# hdf5 = h5py.File(filename, \"w\")\n# samples = self.flatchain\n#\n# self.logger.debug(\"Creating dataset with fname:{}\".format(self.fname))\n# dset = hdf5.create_dataset(self.fname, samples.shape, compression='gzip', compression_opts=9)\n# self.logger.debug(\"Storing samples and header attributes.\")\n# dset[:] = samples\n# dset.attrs[\"parameters\"] = \"{}\".format(self.param_tuple)\n# dset.attrs[\"acceptance\"] = \"{}\".format(self.acceptance_fraction)\n# dset.attrs[\"acor\"] = \"{}\".format(self.acor)\n# dset.attrs[\"commit\"] = \"{}\".format(C.get_git_commit())\n# hdf5.close()\n#\n# #lnprobability is the lnprob at each sample\n# filename = self.outdir + \"lnprobs.hdf5\"\n# self.logger.debug(\"Opening {} for writing HDF5 lnprobs\".format(filename))\n# hdf5 = h5py.File(filename, \"w\")\n# lnprobs = self.lnprobability\n#\n# dset = hdf5.create_dataset(self.fname, samples.shape[:1], compression='gzip', compression_opts=9)\n# dset[:] = lnprobs\n# dset.attrs[\"commit\"] = \"{}\".format(C.get_git_commit())\n# hdf5.close()\n#\n# def plot(self, triangle_plot=False):\n# '''\n# Generate the relevant plots once the sampling is done.\n# '''\n# samples = self.flatchain\n#\n# plot_walkers(self.outdir + self.fname + \"_chain_pos.png\", samples, labels=self.param_tuple)\n#\n# if triangle_plot:\n# import triangle\n# figure = triangle.corner(samples, labels=self.param_tuple, quantiles=[0.16, 0.5, 0.84],\n# show_titles=True, title_args={\"fontsize\": 12})\n# figure.savefig(self.outdir + self.fname + \"_triangle.png\")\n#\n# plt.close(figure)\n#\n# class NuisanceSampler(SSampler):\n# def __init__(self, **kwargs):\n# '''\n#\n# :param OrderModel: the parallel.OrderModel instance\n#\n# :param starting_param_dict: the dictionary of starting parameters\n#\n# :param cov:\n# the MH proposal\n#\n# :param debug:\n#\n# :param args: []\n#\n# '''\n#\n# starting_param_dict = kwargs.get(\"starting_param_dict\")\n# self.param_tuple = self.startdict_to_tuple(starting_param_dict)\n# print(\"param_tuple is {}\".format(self.param_tuple))\n# #print(\"param_tuple length {}\".format(len(self.param_tuple)))\n#\n# chebs = [starting_param_dict[\"cheb\"][key] for key in self.cheb_tup]\n# covs = [starting_param_dict[\"cov\"][key] for key in self.cov_tup]\n# regions = starting_param_dict[\"regions\"]\n# #print(\"initializing {}\".format(regions))\n# regs = [regions[id][kk] for id in sorted(regions) for kk in C.cov_region_parameters]\n# #print(\"regs {}\".format(regs))\n#\n# self.p0 = np.array(chebs + covs + regs)\n#\n# kwargs.update({\"p0\":self.p0, \"revertfn\":self.revertfn, \"lnprobfn\":self.lnprob})\n# super(NuisanceSampler, self).__init__(**kwargs)\n#\n# self.model = kwargs.get(\"OrderModel\")\n# spectrum_id, order_id = self.model.id\n# order = kwargs.get(\"order\", order_id)\n# #self.fname = \"{}/{}/{}\".format(spectrum_id, order, \"nuisance\")\n# self.fname = \"nuisance\"\n# self.params = None\n# self.prior_params = kwargs.get(\"prior_params\", None)\n# if self.prior_params:\n# self.sigma0 = self.prior_params[\"regions\"][\"sigma0\"]\n# self.mus = self.prior_params[\"regions\"][\"mus\"]\n# self.mu_width = self.prior_params[\"regions\"][\"mu_width\"]\n# self.sigma_knee = self.prior_params[\"regions\"][\"sigma_knee\"]\n# self.frac_global = self.prior_params[\"regions\"][\"frac_global\"]\n#\n# def startdict_to_tuple(self, startdict):\n# #This is a little more tricky than the stellar parameters.\n# #How are the keys stored and passed in the dictionary?\n# #{\"cheb\": [c0, c1, c2, ..., cn], \"cov\": [sigAmp, logAmp, l],\n# # \"regions\":{0: [logAmp, ], 1: [], N:[] }}\n#\n# #Serialize the cheb parameters\n# self.ncheb = len(startdict[\"cheb\"])\n# self.cheb_tup = (\"logc0\",) + tuple([\"c{}\".format(i) for i in range(1, self.ncheb)])\n#\n# #Serialize the covariance parameters\n# self.ncov = 3\n# cov_tup = ()\n# for param in C.cov_global_parameters:\n# #check if param is in keys, if so, add to the tuple\n# if param in startdict[\"cov\"]:\n# cov_tup += (param,)\n# self.cov_tup = cov_tup\n#\n# regions_tup = ()\n# self.regions = startdict.get(\"regions\", None)\n# if self.regions:\n# self.nregions = len(self.regions)\n# for key in sorted(self.regions.keys()):\n# for kk in C.cov_region_parameters:\n# regions_tup += (\"r{:0>2}-{}\".format(key,kk),)\n# self.regions_tup = regions_tup\n# else:\n# self.nregions = 0\n# self.regions_tup = ()\n#\n#\n# tup = self.cheb_tup + self.cov_tup + self.regions_tup\n# #This should look like\n# #tup = (\"c0\", \"c1\", ..., \"cn\", \"sigAmp\", \"logAmp\", \"l\", \"r00_logAmp\", \"r00_mu\", \"r00_sigma\",\n# # \"r01_logAmp\", ..., \"rNN_sigma\")\n# return tup\n#\n# def zip_p(self, p):\n# '''\n# Convert the vector to a dictionary\n# '''\n# cheb = dict(zip(self.cheb_tup, p[:self.ncheb]))\n# cov = dict(zip(self.cov_tup, p[self.ncheb:self.ncheb+self.ncov]))\n# regions = p[-self.nregions*3:]\n# rdict = {}\n# for i in range(self.nregions):\n# rdict[i] = dict(zip((\"logAmp\", \"mu\", \"sigma\"), regions[i*3:3*(i+1)]))\n#\n# params = {\"cheb\":cheb, \"cov\":cov, \"regions\":rdict}\n# return params\n#\n# def revertfn(self):\n# self.logger.debug(\"reverting model\")\n# self.model.prior = self.prior_last\n# self.params = self.params_last\n# self.model.revert_nuisance()\n#\n# def lnprob(self, p):\n# self.params_last = self.params\n# params = self.zip_p(p)\n# self.params = params\n# self.logger.debug(\"Updating nuisance params {}\".format(params))\n#\n# # Nuisance parameter priors implemented here\n# self.prior_last = self.model.prior\n# # Region parameter priors implemented here\n# if self.nregions > 0:\n# regions = params[\"regions\"]\n# keys = sorted(regions)\n#\n# #Unpack the region parameters into a vector of mus, amps, and sigmas\n# amps = 10**np.array([regions[key][\"logAmp\"] for key in keys])\n# cov_amp = 10**params[\"cov\"][\"logAmp\"]\n#\n# #First check to make sure that amplitude can't be some factor less than the global covariance\n# if np.any(amps < (cov_amp * self.frac_global)):\n# return -np.inf\n#\n# mus = np.array([regions[key][\"mu\"] for key in keys])\n# sigmas = np.array([regions[key][\"sigma\"] for key in keys])\n#\n# #Make sure the region hasn't strayed too far from the original specification\n# if np.any(np.abs(mus - self.mus) > self.sigma0):\n# # The region has strayed too far from the original specification\n# return -np.inf\n#\n# #Use a Gaussian prior on mu, that it keeps the region within the original setting.\n# # 1/(sqrt(2pi) * sigma) exp(-0.5 (mu-x)^2/sigma^2)\n# #-ln(sigma * sqrt(2 pi)) - 0.5 (mu - x)^2 / sigma^2\n# #width = 0.04\n# lnGauss = -0.5 * np.sum(np.abs(mus - self.mus)**2/self.mu_width**2 -\n# np.log(self.mu_width * np.sqrt(2. * np.pi)))\n#\n# # Use a ln(logistic) function on sigma, that is flat before the knee and dies off for anything\n# # greater, to prevent dilution into global cov kernel\n# lnLogistic = np.sum(np.log(-1./(1. + np.exp(self.sigma_knee - sigmas)) + 1.))\n#\n# self.model.prior = lnLogistic + lnGauss\n#\n# try:\n# self.model.update_nuisance(params)\n# lnp = self.model.evaluate() # also sets OrderModel.lnprob to proposed value. Includes self.model.prior\n# return lnp\n# except C.ModelError:\n# return -np.inf\n", "meta": {"hexsha": "691bdf7af894434b18c75fe3593731cadda8b5c7", "size": 34012, "ext": "py", "lang": "Python", "max_stars_repo_path": "Starfish/samplers.py", "max_stars_repo_name": "jason-neal/Starfish", "max_stars_repo_head_hexsha": "4ffa45e0190fb6f3262511d57d1a563e5ee711de", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-07-10T00:06:36.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-10T00:06:36.000Z", "max_issues_repo_path": "Starfish/samplers.py", "max_issues_repo_name": "jason-neal/Starfish", "max_issues_repo_head_hexsha": "4ffa45e0190fb6f3262511d57d1a563e5ee711de", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Starfish/samplers.py", "max_forks_repo_name": "jason-neal/Starfish", "max_forks_repo_head_hexsha": "4ffa45e0190fb6f3262511d57d1a563e5ee711de", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2016-06-11T09:48:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-07T19:52:41.000Z", "avg_line_length": 37.1310043668, "max_line_length": 116, "alphanum_fraction": 0.5748265318, "include": true, "reason": "import numpy", "num_tokens": 8339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.2909808785120009, "lm_q1q2_score": 0.1488997471859963}} {"text": "#!/usr/bin/python\n\n'''\nUse synthetic partial columns from GEOS-Chem to obtain cloud-sliced\nNO2 in the upper troposphere and compare this to UT NO2 obtained if\nsimply average the NO2 mixing ratios from the model over the same\npressure range (the \"truth\"). Both are obtained by Gaussian\nweighting toward the pressure center.\n\nGEOS-Chem partial columns are obtained over Europe, North America,\nand China at the GEOS-FP meteorology native resolution (0.25x0.3125)\n(latxlon) for June-August 2016-2017.\n\nInput options to process the data include the region, the horizontal\nresolution, and model simulation years.\n\n.. code-block:: bash\n\n usage: ut_no2_gc_test.py [-h] [--gc_dir GC_DIR] [--out_dir OUT_DIR]\n [--resolution RESOLUTION] [--region REGION]\n [--strat_filter_threshold STRAT_FILTER_THRESHOLD]\n [--start_date START_DATE]\n [--end_date END_DATE] [-p PLOT]\n [--do_temp_correct DO_TEMP_CORRECT]\n [--apply_cld_frac_filter APPLY_CLD_FRAC_FILTER]\n [--do_cld_hght_test DO_CLD_HGHT_TEST]\n\n optional arguments:\n -h, --help show this help message and exit\n --gc_dir GC_DIR\n --out_dir OUT_DIR\n --resolution RESOLUTION\n Can be 8x10, 4x5, 2x25 or 1x1\n --region REGION Can be EU, NA, or CH\n --strat_filter_threshold STRAT_FILTER_THRESHOLD\n --start_date START_DATE\n --end_date END_DATE\n -p PLOT, --plot PLOT\n --do_temp_correct DO_TEMP_CORRECT\n --apply_cld_frac_filter APPLY_CLD_FRAC_FILTER\n --do_cld_hght_test DO_CLD_HGHT_TEST\n\n'''\n\n# Note for the future; most of this can probably be replaced with a modification of the GridAggregator class from\n# tropomi_ut_no2\n\n# Import relevant packages:\nimport numpy as np\nfrom netCDF4 import Dataset\nfrom scipy import stats\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.basemap import Basemap\nimport argparse\nfrom sklearn.linear_model import LinearRegression\nimport sys\nimport os\nimport datetime as dt\nfrom dateutil import rrule as rr\n\n# Import hack\nsys.path.append(\n os.path.join(\n os.path.dirname(os.path.abspath(__file__)),\n '..'))\n\nfrom uptrop.date_file_utils import get_gc_file_list\nfrom uptrop.constants import AVOGADRO\nfrom uptrop.constants import G\nfrom uptrop.constants import MW_AIR\nfrom uptrop.bootstrap import rma\nfrom uptrop.cloud_slice_no2 import cldslice, CLOUD_SLICE_ERROR_ENUM\nfrom uptrop.height_pressure_converter import alt2pres, pres2alt\n\n\n# Turn off warnings:\nnp.warnings.filterwarnings('ignore')\n\n\n# Define pressure range:\n# These are fixed, so can be constants, as opposed to inputs.\nP_MIN=180 \nP_MAX=450 \n\n\nclass ProcessingException(Exception):\n pass\n\n\nclass CloudSliceException(Exception):\n pass\n\n\nclass InvalidRegionException(Exception):\n pass\n\n\nclass InvalidResolutionException(Exception):\n pass\n\n\nclass DomainIssueException(Exception):\n pass\n\n\nclass ProcessedData:\n \"\"\"A class for comparing geoschem and tropomi data\"\"\"\n # Note for anyone reading this; this performs very similar functions to the GridAggregator class, but in a different\n # way. I prefer the method in GridAggregator, but this is fine for now. -John Roberts\n def __init__(self, region, str_res, strat_thld, do_temperature_correction=False, do_cld_frac_filter=False, do_cld_hght_test=False):\n \"\"\"Creates and returns an instance of ProcessedData for a given region\n\n This class aggregates geoschem data over a grid defined by the :ref:`define_grid method`.\n\n :param region: The region to aggregate geoschem over; can be NA, EU or CH.\n :type region: str\n :param str_res: The resolution of the grid around teh region to analyse; can be 8x10, 4x5, 2x25 or 1x1\n :type str_res: str\n :param do_temperature_correction: Whether to perform the temperature correction step\n :type do_temperature_correction: bool\n :param do_cld_frac_filter: Whether to perform fractional filtering of clouds\n :type do_cld_frac_filter: bool\n\n :returns: A ProcessedData isntance ready to recieve data\n :rtype: ProcessedData\n \"\"\"\n\n self.temperature_correction = do_temperature_correction\n self.cld_frac_filter = do_cld_frac_filter\n self.cloud_height_test = do_cld_hght_test\n \n # Filtering threshold for stratosphere:\n self.strat_filt = strat_thld\n\n self.define_grid(region, str_res)\n grid_shape = self.X.shape\n\n # Define output arrays:\n self.g_no2_vcd = np.zeros(grid_shape)\n self.g_no2_vmr = np.zeros(grid_shape)\n self.g_cld_fr = np.zeros(grid_shape)\n self.g_cld_p = np.zeros(grid_shape)\n self.g_slope_err = np.zeros(grid_shape)\n self.g_gaus_wgt = np.zeros(grid_shape)\n self.true_o3 = np.zeros(grid_shape) # ozone mixing ratio coincident with cloud-sliced ut self\n self.true_no2 = np.zeros(grid_shape) # \"true\" cloudy UT NO2\n self.g_askut_no2 = np.zeros(grid_shape) # \"true\" all-sky UT NO2\n self.g_ask_gaus_wgt = np.zeros(grid_shape) # \"true\" all-sky UT NO2 weights\n self.g_as_cnt = np.zeros(grid_shape) # Count all-sky\n self.g_cnt = np.zeros(grid_shape)\n\n # Type of data loss in the cloud-slicing retrieval:\n self.loss_count = {\n \"too_few_points\": 0,\n \"low_cloud_height_range\": 0,\n \"low_cloud_height_std\": 0,\n \"large_error\": 0,\n \"sig_diff_from_zero\": 0,\n \"no2_outlier\": 0,\n \"non_uni_strat\": 0,\n }\n\n # Initialize:\n self.cloud_slice_count = 0\n self.maxcnt = 0\n self.grad_retain = 0\n self.grad_remove = 0\n # Print out min and max cloud-sliced UT NO2 error size:\n self.minerr = 1 # Set to maximum possible error (100%)\n self.maxerr = 0\n\n # Define string to represent the layer range:\n self.prange = str(P_MIN) + '-' + str(P_MAX)\n\n # Define factor to convert slope of NO2 mixing ratio versus pressure\n # to VMR:\n self.den2mr = np.divide((np.multiply(G, MW_AIR)), AVOGADRO)\n\n def define_grid(self, region, str_res):\n \"\"\"Defines a grid based on a set of regional bounding boxes and a resolution\n\n :param region: The region to aggregate geoschem over; can be NA, EU or CH.\n :type region: str\n :param str_res: The resolution of the grid around the region to analyse; can be 8x10, 4x5, 2x25 or 1x1\n :type str_res: str\n \"\"\"\n # Define target grid:\n if region == 'NA':\n self.minlat = 2.\n self.maxlat = 62.\n self.minlon = -140.\n self.maxlon = -55.\n elif region == 'EU':\n self.minlat = 26.\n self.maxlat = 66.\n self.minlon = -25.\n self.maxlon = 45.\n elif region == 'CH':\n self.minlat = 6.\n self.maxlat = 62.\n self.minlon = 60.\n self.maxlon = 140.\n else:\n print(\"Invalid region; valid regions are 'NA','EU','CH'.\")\n raise InvalidRegionException\n # NOTE FOR LATER: This snippet turns up in fresco_cld_err; a candidate for the library.\n # Define grid information:\n if str_res == '8x10':\n self.dellat, self.dellon = 8, 10\n elif str_res == '4x5':\n self.dellat, self.dellon = 4, 5\n elif str_res == '2x25':\n self.dellat, self.dellon = 2, 2.5\n elif str_res == '1x1':\n self.dellat, self.dellon = 1, 1\n else:\n print(\"Invalid resolution: valid resolutions are 8x10, 4x5, 2x25 (two pt 5) and 1x1\")\n raise InvalidResolutionException\n self.out_lon = np.arange(self.minlon, self.maxlon + self.dellon, self.dellon)\n self.out_lat = np.arange(self.minlat, self.maxlat + self.dellat, self.dellat)\n # Convert output lats and long to 2D:\n self.X, self.Y = np.meshgrid(self.out_lon, self.out_lat, indexing='ij')\n # Dimensions of output data:\n self.xdim = len(self.out_lon)\n self.ydim = len(self.out_lat)\n # Get maximum possible number of native resolution model gridsquares\n # in the coarser grid (to use in process_grid_square to check that \n # don't exceed this):\n self.max_limit=(self.dellon/0.3125)*(self.dellat/0.25)\n\n\n # ----Processing methods----\n def process_geoschem_day(self, file_path):\n \"\"\"Aggregates geoschem data into the processing grid for a file on a given day.\n\n Calls :ref:`regrid_and_process` for each pixel in the geoschem file, then calls\n :ref:`process_grid_square` for each square of the grid\n\n :param file_path: Path to the geoschem file to load into the processing grid\n :type file_path: str\"\"\"\n # Define output data for this day:\n out_shape = (self.xdim, self.ydim) # This feel gross. A 3-d list of appendable lists.\n self.g_no2 = [[[] for n in range(self.ydim)] for m in range(self.xdim)]\n self.g_grad = [[[] for n in range(self.ydim)] for m in range(self.xdim)]\n self.g_o3 = [[[] for n in range(self.ydim)] for m in range(self.xdim)]\n self.all_cld_fr = [[[] for n in range(self.ydim)] for m in range(self.xdim)]\n self.strat_no2 = [[[] for n in range(self.ydim)] for m in range(self.xdim)]\n self.all_cld_p = [[[] for n in range(self.ydim)] for m in range(self.xdim)]\n self.g_true_no2 = [[[] for n in range(self.ydim)] for m in range(self.xdim)]\n\n this_geoschem_day = GeosChemDay(file_path,\n temperature_correction=self.temperature_correction,\n cloud_height_test=self.cloud_height_test)\n # Get column values:\n for y in range(len(this_geoschem_day.t_lat)):\n for x in range(len(this_geoschem_day.t_lon)):\n this_geoschem_day.prepare_no2_pixel(x, y)\n self.regrid_and_process(x, y, this_geoschem_day)\n for i in range(self.xdim):\n for j in range(self.ydim):\n if any(value != 0 for value in self.g_no2[i][j]):\n self.process_grid_square(i, j)\n\n def regrid_and_process(self, x, y, gc_data):\n \"\"\"Inserts data from pixel x,y from geoschem data into the appropriate grid cell\n\n :param x: X index of geoschem grid cell\n :type x: int\n :param y: Y index of geoschem grid cell\n :type y: int\n :param gc_data: An instance of GeosChemDay data\n :type gc_data: GeosChemDay\n \"\"\"\n # If no valid data, skip:\n if ( len(gc_data.askind) == 0):\n return\n\n # Find nearest gridsquare in output grid:\n lon = int(np.argmin(abs(self.out_lon - gc_data.t_lon[x])))\n lat = int(np.argmin(abs(self.out_lat - gc_data.t_lat[y])))\n\n self.g_ask_gaus_wgt[lon, lat] += np.sum(gc_data.twgt)\n\n self.g_askut_no2[lon, lat] += np.sum(gc_data.t_gc_no2[gc_data.askind, y, x] * gc_data.twgt * 1e3)\n self.g_as_cnt[lon, lat] += 1.0\n\n # Add relevant data to array if there are clouds at 450-180 hPa:\n if (gc_data.lcld < gc_data.level_min) or (gc_data.lcld > gc_data.level_max):\n # Check for clouds between min and max pressure. If none, move to next pixel.\n #print(\"Cloud top outside pressure range in pixel {},{}\".format(x,y))\n return\n\n # Find where cloud fraction in UT exceeds 0.7 after calculating\n # true all-sky NO2:\n # (Keep for testing effect of thick clouds on cloud-sliced UT NO2):\n if ( self.cld_frac_filter ):\n if np.sum(gc_data.t_cld_fr[gc_data.level_min:gc_data.level_max + 1, y, x]) < 0.7:\n return\n\n self.g_no2[lon][lat].append(gc_data.no2_2d)\n self.g_grad[lon][lat].append(gc_data.grad)\n self.strat_no2[lon][lat].append(gc_data.strat_col)\n self.all_cld_p[lon][lat].append(gc_data.t_cld_hgt[y, x])\n self.g_o3[lon][lat].append(\n np.mean(gc_data.t_gc_o3[gc_data.level_min:gc_data.level_max + 1, y, x]))\n self.g_true_no2[lon][lat].append(\n np.mean(gc_data.t_gc_no2[gc_data.level_min:gc_data.level_max + 1, y, x]))\n self.all_cld_fr[lon][lat].append(\n np.sum(gc_data.t_cld_fr[gc_data.level_min:gc_data.level_max + 1, y, x]))\n pass\n\n def process_grid_square(self, i, j):\n\n # Define vectors of relevant data:\n # These should all have the same length\n t_col_no2 = np.asarray(self.g_no2[i][j],dtype=np.float)\n t_strat_no2 = np.asarray(self.strat_no2[i][j],dtype=np.float)\n t_fr_c = np.asarray(self.all_cld_fr[i][j],dtype=np.float)\n t_cld = np.asarray(self.all_cld_p[i][j],dtype=np.float)\n t_mr_no2 = np.asarray(self.g_true_no2[i][j],dtype=np.float)\n t_o3 = np.asarray(self.g_o3[i][j],dtype=np.float)\n t_grad_no2 = np.asarray(self.g_grad[i][j],dtype=np.float)\n\n # Skip if fewer than 10 points:\n if len(t_col_no2) < 10:\n #print(\"Grid square {}, {} failed with condition too_few_points\".format(i, j))\n self.loss_count[\"too_few_points\"] += 1\n return\n\n # Remove non-uniform stratosphere:\n if (np.std(t_strat_no2) / np.mean(t_strat_no2)) > self.strat_filt:\n self.loss_count[\"non_uni_strat\"] += 1\n return # continue\n\n # Get number of points:\n n_pnts = len(t_cld)\n if n_pnts > self.maxcnt:\n self.maxcnt = n_pnts\n print('Max no. of points in a cluster: ', self.maxcnt, flush=True)\n\n # Check if number of gridsquares exceeds max possible\n # (indicates error in coarser grid domain):\n if ( self.maxcnt > self.max_limit ):\n print('No. of model grids exceeds max possible')\n raise DomainIssueException\n\n # Use cloud_slice_ut_no2 function to get cloud-sliced UT NO2.\n # Treat data differently depending on whether there are 10-99 points:\n if n_pnts >= 10 and n_pnts <100:\n self.add_slice(i,j,t_cld,t_col_no2, t_mr_no2, t_fr_c, t_grad_no2, t_o3)\n # Or at least 100 points:\n elif n_pnts >= 100:\n num_slices = 40\n stride = round(n_pnts / num_slices)\n nloop = list(range(stride))\n for w in nloop:\n subset_t_col_no2 = t_col_no2[w::stride]\n subset_t_cld = t_cld[w::stride]\n subset_t_mr_no2 = t_mr_no2[w::stride]\n subset_t_fr_c = t_fr_c[w::stride]\n subset_t_grad_no2 = t_grad_no2[w::stride]\n subset_t_o3 = t_o3[w::stride]\n self.add_slice(i, j, subset_t_cld, subset_t_col_no2, subset_t_mr_no2, subset_t_fr_c, subset_t_grad_no2, subset_t_o3)\n\n def add_slice(self, i, j, t_cld, t_col_no2, t_mr_no2, t_fr_c, t_grad_no2, t_o3):\n \"\"\"Extracts the upper troposphere gc_data, gc_data error, ozone data, ozone error,\n and mean cloud pressure for grid square [i,j]\n\n This method uses the cloud-slicing function :ref:`uptrop.cloud_slice_ut_no2.cldslice`\n Once calculated, the a weighting is derived from cloud pressure.\n The weighted upper tropospheric gc_data and error is added to the rolling total for this season.\n If the cloud slicing fails, then the reason is added to loss_count for the end report.\n\n :param i: X-index of grid square\n :type i: int\n :param j: Y-index of grid square\n :type j: int\n :param t_cld: Tropospheric cloud\n :type t_cld: float\n :param t_col_no2: Total (stratosphere+troposphere) column no2\n :type t_col_no2: float\n :param t_mr_no2: NO2 mixing ratio between pmax and pmin\n :type t_mr_no2: float\n :param t_fr_c: Cloud fraction between pmax and pmin\n :type t_fr_c: float\n :param t_grad_no2: NO2 gradient between pmax and pmin in pptv/hPa\n :type t_grad_no2: float\n :param t_o3: O3 mixing ratio to test influence from stratosphere\n :type t_o3: float\n \"\"\"\n utmrno2, utmrno2err, stage_reached, mean_cld_pres = cldslice(t_col_no2, t_cld,140)\n \n # Skip if approach didn't work (i.e. cloud-sliced UT NO2 is NaN):\n # Drop out after the reason for data loss is added to loss_count.\n if np.isnan(utmrno2) or np.isnan(utmrno2err):\n # Cloud-slicing led to nan, but due to rma regression rather\n # than data filtering (these are rare):\n if ( stage_reached==0 ):\n print(\"Cloud-sliced NO2 NAN for pixel i:{} j:{}\".format(i, j))\n return\n self.loss_count[CLOUD_SLICE_ERROR_ENUM[stage_reached]] += 1\n # Track non-uniform NO2 removed:\n grad_ind=np.where(np.abs(t_grad_no2) >= 0.33)[0]\n self.grad_remove += len(grad_ind)\n #print(\"Cloud-slice exception {} in pixel i:{} j:{}\".format(\n # CLOUD_SLICE_ERROR_ENUM[stage_reached], i, j))\n else:\n # Calculate weights:\n #err_wgt = 1.0 / (utmrno2err ** 2) # not use, but preserve anyway\n gaus_wgt = np.exp((-(mean_cld_pres - 315) ** 2) / (2 * 135 ** 2))\n \n # Get and track error range:\n nerr = utmrno2err / utmrno2\n if nerr > self.maxerr:\n self.maxerr = nerr\n print('Max rel. cloud-sliced NO2 error: ', self.maxerr, flush=True)\n if nerr < self.minerr:\n self.minerr = nerr\n print('Min rel. cloud-sliced NO2 error: ', self.minerr, flush=True)\n \n # Track non-uniform NO2 retained:\n grad_ind=np.where(np.abs(t_grad_no2) >= 0.33)[0]\n self.grad_retain += len(grad_ind)\n \n # Weighted mean for each pass of cldslice:\n weight_mean = np.mean(t_mr_no2 * 1e3) * gaus_wgt \n self.true_no2[i, j] += weight_mean\n self.true_o3[i, j] += (np.mean(t_o3) * gaus_wgt)\n self.g_no2_vmr[i, j] += utmrno2 * gaus_wgt\n self.g_slope_err[i, j] += utmrno2err * gaus_wgt\n self.g_gaus_wgt[i, j] += gaus_wgt\n self.g_cnt[i, j] += 1\n self.g_cld_fr[i, j] += np.mean(t_fr_c)\n self.cloud_slice_count += 1\n\n def get_weighted_mean(self):\n \"\"\"Applies weighting to the aggregated means.\n \"\"\"\n # Mean physical parameters:\n self.g_no2_vmr = np.divide(self.g_no2_vmr, self.g_gaus_wgt, where=self.g_cnt != 0)\n self.g_cld_fr = np.divide(self.g_cld_fr, self.g_cnt, where=self.g_cnt != 0)\n self.true_no2 = np.divide(self.true_no2, self.g_gaus_wgt, where=self.g_cnt != 0)\n self.g_cld_p = np.divide(self.g_cld_p, self.g_cnt, where=self.g_cnt != 0)\n self.true_o3 = np.divide(self.true_o3, self.g_gaus_wgt, where=self.g_cnt != 0)\n self.g_askut_no2 = np.divide(self.g_askut_no2, self.g_ask_gaus_wgt, where=self.g_as_cnt != 0)\n # Mean cloud-sliced UT NO2 error:\n self.g_slope_err = np.divide(self.g_slope_err, self.g_gaus_wgt, where=self.g_cnt != 0)\n # Mean weights:\n self.g_gaus_wgt = np.divide(self.g_gaus_wgt, self.g_cnt, where=self.g_cnt != 0)\n # No data (nan):\n self.true_no2[self.g_cnt == 0] = np.nan\n self.true_o3[self.g_cnt == 0] = np.nan\n self.g_slope_err[self.g_cnt == 0] = np.nan\n self.g_gaus_wgt[self.g_cnt == 0] = np.nan\n self.g_askut_no2[self.g_as_cnt == 0] = np.nan\n self.g_no2_vmr[self.g_cnt == 0] = np.nan\n self.g_cld_fr[self.g_cnt == 0] = np.nan\n self.g_cld_p[self.g_cnt == 0] = np.nan\n\n # ----Reporting and saving methods----\n def print_data_report(self):\n \"\"\"Prints a set of reasons for missing data\n \"\"\"\n # Output code diagnostics:\n # No. of data points:\n # print('No. of valid data points: ',cloud_slice_count,flush=True)\n print('Max no. of data points in a gridsquare: ', np.amax(self.g_cnt), flush=True)\n # Track reasons for data loss:\n print('(1) Too few points: ', self.loss_count[\"too_few_points\"], flush=True)\n print('(2) Low cloud height range: ', self.loss_count[\"low_cloud_height_range\"], flush=True)\n print('(3) Low cloud height std dev: ', self.loss_count[\"low_cloud_height_std\"], flush=True)\n print('(4) Large error: ', self.loss_count[\"large_error\"], flush=True)\n print('(5) Significantly less than zero: ', self.loss_count[\"sig_diff_from_zero\"], flush=True)\n print('(6) Outlier (NO2 > 200 pptv): ', self.loss_count[\"no2_outlier\"], flush=True)\n print('(7) Non-uniform stratosphere: ', self.loss_count[\"non_uni_strat\"], flush=True)\n print('(8) Successful retrievals: ', self.cloud_slice_count, flush=True)\n print('(9) Total possible points: ', (sum(self.loss_count.values()) + self.cloud_slice_count), flush=True)\n print('Non-uniform NO2 retained = ', self.grad_retain)\n print('Non-uniform NO2 removed = ', self.grad_remove)\n print('Error range of cloud-sliced UT NO2: ', np.nanmin(self.g_slope_err), np.nanmax(self.g_slope_err))\n\n def plot_data(self):\n \"\"\"Plots the present state of the gridded data\n \"\"\"\n # ===> FUTURE UPDATE : change from basemap to cartopy <===\n # Plot the data:\n m = Basemap(resolution='l', projection='merc',\n lat_0=0, lon_0=0, llcrnrlon=self.minlon,\n llcrnrlat=self.minlat, urcrnrlon=self.maxlon, urcrnrlat=self.maxlat)\n xi, yi = m(self.X, self.Y)\n plt.subplot(2, 3, 1)\n cs = m.pcolor(xi, yi, np.squeeze(self.g_no2_vmr), vmin=0, vmax=80, cmap='jet')\n m.drawparallels(np.arange(-80., 81., 45.), labels=[1, 0, 0, 0], fontsize=8)\n m.drawmeridians(np.arange(-180., 181., 45.), labels=[0, 0, 0, 1], fontsize=8)\n m.drawcoastlines()\n m.drawcountries()\n cbar = m.colorbar(cs, location='bottom', pad=\"10%\")\n plt.title('Cloud-sliced NO2 VMRs')\n plt.subplot(2, 3, 2)\n cs = m.pcolor(xi, yi, np.squeeze(self.true_no2), vmin=0.0, vmax=80, cmap='jet')\n m.drawparallels(np.arange(-80., 81., 45.), labels=[1, 0, 0, 0], fontsize=8)\n m.drawmeridians(np.arange(-180., 181., 45.), labels=[0, 0, 0, 1], fontsize=8)\n m.drawcoastlines()\n m.drawcountries()\n cbar = m.colorbar(cs, location='bottom', pad=\"10%\")\n plt.title('True cloudy NO2')\n plt.subplot(2, 3, 3)\n cs = m.pcolor(xi, yi, np.squeeze(self.g_askut_no2), vmin=0, vmax=80, cmap='jet')\n m.drawparallels(np.arange(-80., 81., 45.), labels=[1, 0, 0, 0], fontsize=8)\n m.drawmeridians(np.arange(-180., 181., 45.), labels=[0, 0, 0, 1], fontsize=8)\n m.drawcoastlines()\n m.drawcountries()\n cbar = m.colorbar(cs, location='bottom', pad=\"10%\")\n plt.title('True NO2 VMRs under all-sky conditions')\n plt.subplot(2, 3, 4)\n plt.plot(self.true_no2, self.g_no2_vmr, 'o', color='black', markersize=6)\n r = stats.pearsonr(self.true_no2[~np.isnan(self.g_no2_vmr)],\n self.g_no2_vmr[~np.isnan(self.g_no2_vmr)])\n # print('Correlation = ', r[0])\n result = rma(self.true_no2[~np.isnan(self.g_no2_vmr)], self.g_no2_vmr[~np.isnan(self.g_no2_vmr)],\n len(self.true_no2[~np.isnan(self.g_no2_vmr)]), 1000)\n print(result, flush=True)\n xvals = np.arange(0, 100, 5)\n yvals = result[1] + xvals * result[0]\n plt.plot(xvals, yvals, '-')\n plt.xlim(-4, 80)\n plt.ylim(-4, 80)\n plt.xlabel('True NO2 (cloudy)')\n plt.ylabel('Cloud-sliced NO2')\n print('===== True (cloudy) vs cloud-sliced UT NO2 ====')\n print('R = ', r[0], flush=True)\n print('Slope = ', result[0])\n print('Slope Err = ', result[2], flush=True)\n print('Intercept = ', result[1], flush=True)\n print('Intercept Err = ', result[3], flush=True)\n add2plt = (\"y = {a:6.2f}x + {b:6.3f}\".format(a=result[0], b=result[1]))\n plt.text(2, 75, add2plt, fontsize=8,\n ha='left', va='center') # , transform=ax.transAxes)\n add2plt = (\"R = {a:6.2f}\".format(a=r[0]))\n plt.text(2, 65, add2plt, fontsize=8,\n ha='left', va='center') # , transform=ax.transAxes)\n plt.subplot(2, 3, 5)\n plt.plot(self.g_askut_no2, self.g_no2_vmr, 'o', color='black', markersize=6)\n r = stats.pearsonr(self.g_askut_no2[(~np.isnan(self.g_no2_vmr)) & (~np.isnan(self.g_askut_no2))],\n self.g_no2_vmr[(~np.isnan(self.g_no2_vmr)) & (~np.isnan(self.g_askut_no2))])\n result = rma(self.g_askut_no2[(~np.isnan(self.g_no2_vmr)) & (~np.isnan(self.g_askut_no2))],\n self.g_no2_vmr[(~np.isnan(self.g_no2_vmr)) & (~np.isnan(self.g_askut_no2))],\n len(self.g_askut_no2[(~np.isnan(self.g_no2_vmr)) & (~np.isnan(self.g_askut_no2))]),\n 1000)\n xvals = np.arange(0, 100, 5)\n yvals = result[1] + xvals * result[0]\n plt.plot(xvals, yvals, '-')\n plt.xlim(-4, 80)\n plt.ylim(-4, 80)\n plt.xlabel('True NO2 (all-sky)')\n plt.ylabel('Cloud-sliced NO2')\n add2plt = (\"y = {a:6.2f}x + {b:6.3f}\". \\\n format(a=result[0], b=result[1]))\n plt.text(2, 75, add2plt, fontsize=8, \\\n ha='left', va='center') # , transform=ax.transAxes)\n add2plt = (\"R = {a:6.2f}\".format(a=r[0]))\n plt.text(2, 65, add2plt, fontsize=8, \\\n ha='left', va='center') # , transform=ax.transAxes)\n plt.subplot(2, 3, 6)\n plt.plot(self.g_askut_no2, self.true_no2, 'o', color='black', markersize=6)\n r = stats.pearsonr(self.g_askut_no2[(~np.isnan(self.true_no2)) & (~np.isnan(self.g_askut_no2))],\n self.true_no2[(~np.isnan(self.true_no2)) & (~np.isnan(self.g_askut_no2))])\n result = rma(self.g_askut_no2[(~np.isnan(self.true_no2)) & (~np.isnan(self.g_askut_no2))],\n self.true_no2[(~np.isnan(self.true_no2)) & (~np.isnan(self.g_askut_no2))],\n len(self.g_askut_no2[(~np.isnan(self.true_no2)) & (~np.isnan(self.g_askut_no2))]),\n 1000)\n xvals = np.arange(0, 100, 5)\n yvals = result[1] + xvals * result[0]\n plt.plot(xvals, yvals, '-')\n plt.xlim(-4, 80)\n plt.ylim(-4, 80)\n plt.xlabel('True NO2 (all-sky)')\n plt.ylabel('True NO2 (cloudy)')\n add2plt = (\"y = {a:6.2f}x + {b:6.3f}\".format(a=result[0], b=result[1]))\n plt.text(2, 75, add2plt, fontsize=8, ha='left', va='center')\n add2plt = (\"R = {a:6.2f}\".format(a=r[0]))\n plt.text(2, 65, add2plt, fontsize=8, ha='left', va='center')\n plt.show()\n\n def save_to_netcdf(self, out_path):\n \"\"\"Saves the present state of the grid to a netCDF4 file\n\n :param out_path: Path to the output file\n :type out_path: str\n \"\"\"\n # Save the data to NetCDF:\n ncout = Dataset(out_path, mode='w', format='NETCDF4')\n # Create data dimensions:\n ncout.createDimension('lat', self.ydim)\n ncout.createDimension('lon', self.xdim)\n # create lon axis:\n lon = ncout.createVariable('lon', np.float32, ('lon',))\n lon.units = 'degrees_east'\n lon.long_name = 'longitude'\n lon[:] = self.out_lon\n # create lat axis:\n lat = ncout.createVariable('lat', np.float32, ('lat',))\n lat.units = 'degrees_north'\n lat.long_name = 'latgitude'\n lat[:] = self.out_lat\n # create data axes:\n # (1) Cloud-sliced NO2:\n csutno2 = ncout.createVariable('csutno2', np.float32, ('lon', 'lat'))\n csutno2.units = 'pptv'\n csutno2.long_name = 'UT NO2 mixing ratio (180-450 hPa) obtained using cloud-slicing'\n csutno2[:] = self.g_no2_vmr\n # (2a) Double-weighting error:\n utdblerr = ncout.createVariable('utdblerr', np.float32, ('lon', 'lat'))\n utdblerr.units = 'pptv'\n utdblerr.long_name = 'Standard error of the NO2 mixing ratios in the UT (180-450 hPa) obtained using cloud-slicing'\n utdblerr[:] = self.g_slope_err\n # (2b) Gaussian-weighting error:\n utgauserr = ncout.createVariable('utgauserr', np.float32, ('lon', 'lat'))\n utgauserr.units = 'pptv'\n utgauserr.long_name = 'Standard error of the NO2 mixing ratios in the UT (180-450 hPa) obtained using cloud-slicing'\n utgauserr[:] = self.g_gaus_wgt\n # (3) Number of observations in each gridsquare:\n nobs = ncout.createVariable('nobs', np.float32, ('lon', 'lat'))\n nobs.units = 'unitless'\n nobs.long_name = 'Number of observations in each gridsquare used to obtain cloud-sliced UT NO2 mixing ratios'\n nobs[:] = self.g_cnt\n # (4) Mean cloud pressure for season between 450-180 hPa:\n utcld = ncout.createVariable('utcld', np.float32, ('lon', 'lat'))\n utcld.units = 'hPa'\n utcld.long_name = 'Mean cloud pressure between 450 and 180 hPa'\n utcld[:] = self.g_cld_p\n # (5) Mean NO2 mixing ratio at 450-180 hPa for scenes with clouds:\n cldutno2 = ncout.createVariable('cldutno2', np.float32, ('lon', 'lat'))\n cldutno2.units = 'pptv'\n cldutno2.long_name = 'UT NO2 mixing ratio (180-450 hPa) obtained if clouds are present'\n cldutno2[:] = self.true_no2\n # (6) Mean NO2 mixing ratio at 450-180 hPa under all conditions (all-sky):\n askutno2 = ncout.createVariable('askutno2', np.float32, ('lon', 'lat'))\n askutno2.units = 'pptv'\n askutno2.long_name = 'UT NO2 mixing ratio (180-450 hPa) obtained under all conditions (all-sky)'\n askutno2[:] = self.g_askut_no2\n # (7) Cloud fraction:\n utcldfrc = ncout.createVariable('utcldfrc', np.float32, ('lon', 'lat'))\n utcldfrc.units = 'unitless'\n utcldfrc.long_name = 'GEOS-FP cloud fraction obtained as sum of 3D cloud fractions across range of interest (180-450 hPa)'\n utcldfrc[:] = self.g_cld_fr\n # (8) O3 sampled coincident with cloud-slicing retrieval:\n uto3 = ncout.createVariable('uto3', np.float32, ('lon', 'lat'))\n uto3.units = 'ppbv'\n uto3.long_name = 'GEOS-Chem ozone obtained coincident with cloud-sliced NO2'\n uto3[:] = self.true_o3\n # Close the file:\n ncout.close()\n\n\nclass GeosChemDay:\n \"\"\"A class for reading, preprocessing and accessing Geoschem data on a given day\n \"\"\"\n def __init__(self, file_path, temperature_correction=False, cloud_height_test=False):\n \"\"\"Reads the data at file_path and returns a GeosChemDay object containing that data\n\n :param file_path: Path to the netcdf4 file containing the GeosChem data\n :type file_path: str\n :param temperature_correction: Whether to apply temperature correction\n :type temperature_correction: bool\n :param cloud_height_test: Whether to test effect of systematic underestimate in cloud height\n :type cloud_height_test: bool\n\n :returns: A GeosChemDay class\n :rtype: GeosChemDay\n \"\"\"\n print('File path: ',file_path, flush=True)\n\n self.temperature_correction = temperature_correction\n self.cloud_height_test = cloud_height_test\n\n # Read dataset:\n fh = Dataset(file_path, mode='r')\n # Extract data of interest:\n tlon, tlat, tgcno2, tcldfr, tcldhgt, tadn, tbxhgt, tpedge, tpause, tgco3, tdegk = \\\n fh.variables['LON'], fh.variables['LAT'], \\\n fh.variables['IJ-AVG-S__NO2'], fh.variables['TIME-SER__CF'], \\\n fh.variables['TIME-SER__CThgt'], fh.variables['TIME-SER__AIRDEN'], \\\n fh.variables['BXHGHT-S__BXHEIGHT'], fh.variables['PEDGE-S__PSURF'], \\\n fh.variables['TR-PAUSE__TP-PRESS'], fh.variables['IJ-AVG-S__O3'], \\\n fh.variables['DAO-3D-S__TMPU']\n self.t_lon = tlon[:]\n self.t_lat = tlat[:]\n self.t_gc_no2 = tgcno2[:]\n self.t_cld_fr = tcldfr[:]\n self.t_cld_hgt = tcldhgt[0, :, :]\n self.t_adn = tadn[:] # in molec/cm3\n self.t_bx_hgt = tbxhgt[:]\n self.t_p_edge = tpedge[:]\n self.t_pause = tpause[0, :, :]\n self.t_gc_o3 = tgco3[:]\n self.t_deg_k = tdegk[:]\n # Convert box height from m to cm:\n self.t_bx_hgt = self.t_bx_hgt * 1e2\n\n if self.cloud_height_test:\n # Lower cloud heights by 1 km to roughly mimic lower altitude\n # clouds retrieved for TROPOMI assuming clouds are reflective\n # boundaries with uniform reflectivity:\n # Calculate cloud top height in m:\n t_cld_hgt = pres2alt(self.t_cld_hgt*1e2)\n # Lower the clouds by 1 km (1000 m) (this won't work for low-altitude\n # clouds):\n t_cld_hgt = t_cld_hgt - 1e3\n # Convert back to Pa and convert that to hPa:\n self.t_cld_hgt = alt2pres(t_cld_hgt)*1e-2\n\n #Get outputs ready here for tidyness:\n self.no2_2d = None\n self.trop_col = None\n self.strat_col = None\n self.gcutno2 = None\n self.gascnt = None\n self.grad = None\n\n self.level_min = None\n self.level_max = None\n self.askind = None\n\n def prepare_no2_pixel(self, x, y):\n \"\"\"Extracts preprocesed no2 from the geoschem pixel at x,y\n\n :param x: The x index of the pixel\n :type x: int\n :param y: The y index of the pixel\n :type y: int\n \"\"\"\n # Calculate corresponding mid-pressure values:\n tp_mid = np.zeros(len(self.t_p_edge[:, y, x]))\n # Get mid-pressure values, except for highest layer:\n for k in range(len(self.t_p_edge[:, y, x]) - 1):\n tp_mid[k] = np.multiply(0.5, (self.t_p_edge[k, y, x] + self.t_p_edge[k + 1, y, x]))\n # Estimate mid-pressure for highest value (doesn't need to\n # be accurate, as surpassing the range of interset):\n # Data output from the model includes 47 vertical layers. This means that only 46 pressure centres can be calculated as the calculation requires pressure edges.\n tp_mid[46] = np.multiply(0.5, (self.t_p_edge[46, y, x] + (self.t_p_edge[46, y, x] - 0.1)))\n # Get model layer of tropopause:\n tppind = np.argmin(abs(tp_mid - self.t_pause[y, x]))\n # Get indices that fall between 450 and 180 hPa for estimating\n # \"true' all-sky UT NO2 and partial columns:\n lind = np.where((tp_mid >= P_MIN) & (tp_mid <= P_MAX))[0]\n # Get UT NO2 under \"true\" all-sky conditions:\n # Make sure this is below the tropopause:\n # If below tropopause, use full extent (180-450 hPa):\n if lind[len(lind) - 1] <= tppind:\n self.askind = lind\n # If above tropopause, trim to tropopause-450 hPa:\n if lind[len(lind) - 1] > tppind:\n self.askind = lind[np.where(lind <= tppind)[0]]\n # If tropopause below 450 hPa, skip entirely:\n if self.t_pause[y, x] > P_MAX:\n #print(\"Tropopause less than P_MAX in geoschem pixel x:{}, y:{}\".format(x,y))\n return # continue\n\n # Get Guassian weights that allocate higher weights to points\n # closest to the pressure centre (315 hPa):\n # Equation is:\n # w = exp(-(p-315)^2/2*135^2 ) where 315 hPa is the centre and\n # 135 hPa is the standard deviation.\n self.twgt = np.exp((-(tp_mid[self.askind] - 315) ** 2) / (2 * 135 ** 2))\n\n # Get model level of cloud top height closest to lowest\n # pressure-altitude of interest (P_MIN):\n self.lcld = np.argmin(abs(self.t_cld_hgt[y, x] - tp_mid))\n # Skip if cloud top height ouside pressure range of interest:\n self.level_min, self.level_max = np.amin(lind), np.amax(lind)\n\n if (self.temperature_correction):\n\n # Equation is from the TROPOMI product ATBD (p. 32, Eqn 18)\n # (product document abbrevation: S5P-KNMI-L2-0005-RP)\n self.temp_corr = 1 - (3.16e-3 * (self.t_deg_k[self.level_min:, y, x] - 220.)) + \\\n (3.39e-6 * ((self.t_deg_k[self.level_min:, y, x] - 220) ** 2))\n else:\n # Set to 1 so that no scaling is applied:\n # (might be a more eloquent way to do this)\n self.temp_corr = np.ones(len(self.t_gc_no2[self.level_min:, y, x]))\n\n # Calculate NO2 gradient:\n regr = LinearRegression() \n # Pressure (hPa)\n x_vals=tp_mid[self.level_min:self.level_max].reshape(-1,1)\n # NO2 (ppbv)\n y_vals=self.t_gc_no2[self.level_min:self.level_max, y, x].reshape(-1,1)\n # NO2 (pptv)\n y_vals=y_vals*1e3\n # Perform regression:\n regr.fit(x_vals,y_vals)\n # Define gradient from regression slope (pptv/hPa):\n self.grad = regr.coef_\n\n # Get partial NO2 column in molec/m2 from cloud top height\n # to highest model level (output up to level 47):\n # print(t_gc_no2[self.level_min:tppind,y,x])\n # print(t_gc_no2[self.level_min:tppind,y,x]*1.5)\n self.no2_2d = np.sum(self.t_gc_no2[self.level_min:, y, x]\n * 1e-5\n * self.temp_corr\n * self.t_adn[self.level_min:, y, x]\n * self.t_bx_hgt[self.level_min:, y, x])\n # Get stratospheric column from 180 hPa aloft:\n # Previous approach (remove when model simulations done):\n # tppind=np.where(tpmid<180.)[0]\n self.strat_col = np.sum(self.t_gc_no2[tppind:, y, x]\n * 1e-5 * self.t_adn[tppind:, y, x]\n * self.t_bx_hgt[tppind:, y, x])\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n # Shorten directory name to up to \"GC/\", then define the subdirectory\n # as 'geosfp' + dirreg + 'iccw/' in get_file_list.\n # This is now done in get_gc_file_list\n parser.add_argument(\"--gc_dir\")\n parser.add_argument(\"--out_dir\")\n parser.add_argument(\"--resolution\", default=\"4x5\", help=\"Can be 8x10, 4x5, 2x25 or 1x1\")\n parser.add_argument(\"--region\", default=\"EU\", help=\"Can be EU, NA, or CH\")\n parser.add_argument(\"--strat_filter_threshold\", default=\"002\", help=\"\")\n #parser.add_argument(\"--start_date\", default=\"2016-06-01\")\n #parser.add_argument(\"--end_date\", default=\"2017-08-31\")\n parser.add_argument(\"-p\", \"--plot\", type=bool, default=False)\n parser.add_argument(\"--do_temp_correct\", type=bool)\n parser.add_argument(\"--apply_cld_frac_filter\", type=bool)\n parser.add_argument(\"--do_cld_hght_test\", type=bool)\n args = parser.parse_args()\n\n # Get files:\n gc_dir = args.gc_dir\n STR_RES = args.resolution\n REGION = args.region\n \n # Hard code for GEOS-Chem synthetic experiment:\n yrrange = '2016-2017'\n\n # Define output file depending on input arguments:\n out_file = os.path.join(args.out_dir, 'gc-v12-1-0-ut-no2'\n + '-' + args.region\n + '-' + args.resolution\n + '-jja-' + yrrange\n + '-' + \"gaus-wgt\" )\n\n if args.do_cld_hght_test:\n out_file += \"-cldtop\"\n if args.strat_filter_threshold != \"002\":\n out_file += '-' + args.strat_filter_threshold +'strat'\n if args.do_temp_correct:\n out_file += \"-temp-corr\"\n if args.apply_cld_frac_filter:\n out_file += \"-cld-filt\"\n \n out_file += \"-v1.nc\"\n\n strat_filter_threshold = float(args.strat_filter_threshold)/100\n files = get_gc_file_list(gc_dir, args.region)\n print('Number of files:', len(files), flush=True)\n\n rolling_total = ProcessedData(REGION, STR_RES, strat_filter_threshold,\n do_temperature_correction=args.do_temp_correct,\n do_cld_frac_filter=args.apply_cld_frac_filter,\n do_cld_hght_test=args.do_cld_hght_test)\n\n for file_path in files:\n rolling_total.process_geoschem_day(file_path)\n\n rolling_total.get_weighted_mean()\n rolling_total.print_data_report()\n if args.plot==True: rolling_total.plot_data()\n rolling_total.save_to_netcdf(out_file)\n\n\n", "meta": {"hexsha": "be33e00de44ea186cbd66076d5a3c284b72f2848", "size": 40381, "ext": "py", "lang": "Python", "max_stars_repo_path": "uptrop/cloud_slice_model_no2.py", "max_stars_repo_name": "zxdawn/erc-uptrop", "max_stars_repo_head_hexsha": "58111cb80285a0f959ef140c7177195e823b5289", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "uptrop/cloud_slice_model_no2.py", "max_issues_repo_name": "zxdawn/erc-uptrop", "max_issues_repo_head_hexsha": "58111cb80285a0f959ef140c7177195e823b5289", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "uptrop/cloud_slice_model_no2.py", "max_forks_repo_name": "zxdawn/erc-uptrop", "max_forks_repo_head_hexsha": "58111cb80285a0f959ef140c7177195e823b5289", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.0444697834, "max_line_length": 168, "alphanum_fraction": 0.609643149, "include": true, "reason": "import numpy,from scipy", "num_tokens": 11143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.2782568056728001, "lm_q1q2_score": 0.14889477947017576}} {"text": "#-*- coding: utf-8 -*-\nfrom __future__ import division\nimport os\nimport math\nimport time\nimport tensorflow as tf\nimport numpy as np\nfrom tensorflow.python.ops import math_ops\nfrom ops import *\nfrom utils import *\nfrom GRUI import mygru_cell\n\n\"\"\"\nD输入标准化, 不要m 填充0\nG输入去掉m,只有delta\ng 没有每次累加z\n\"\"\"\nclass WGAN(object):\n model_name = \"WGAN_no_mask\" # name for checkpoint\n\n def __init__(self, sess, args, datasets):\n self.sess = sess\n self.isbatch_normal=args.isBatch_normal\n self.isNormal=args.isNormal\n self.checkpoint_dir = args.checkpoint_dir\n self.result_dir = args.result_dir\n self.log_dir = args.log_dir\n self.dataset_name=args.dataset_name\n self.run_type=args.run_type\n self.lr = args.lr\n self.epoch = args.epoch\n self.batch_size = args.batch_size\n self.n_inputs = args.n_inputs # MNIST data input (img shape: 28*28)\n self.n_steps = datasets.maxLength # time steps\n self.n_hidden_units = args.n_hidden_units # neurons in hidden layer\n self.n_classes = args.n_classes # MNIST classes (0-9 digits)\n self.gpus=args.gpus\n self.run_type=args.run_type\n self.result_path=args.result_path\n self.model_path=args.model_path\n self.pretrain_epoch=args.pretrain_epoch\n self.impute_iter=args.impute_iter\n self.isSlicing=args.isSlicing\n self.g_loss_lambda=args.g_loss_lambda\n\n self.datasets=datasets\n self.z_dim = args.z_dim # dimension of noise-vector\n self.gen_length=args.gen_length\n\n # WGAN_GP parameter\n self.lambd = 0.25 # The higher value, the more stable, but the slower convergence\n self.disc_iters = args.disc_iters # The number of critic iterations for one-step of generator\n\n # train\n self.learning_rate = args.lr\n self.beta1 = args.beta1\n if \"1.5\" in tf.__version__ or \"1.7\" in tf.__version__ :\n self.grud_cell_d = mygru_cell.MyGRUCell15(self.n_hidden_units)\n self.grud_cell_g = mygru_cell.MyGRUCell15(self.n_hidden_units)\n elif \"1.4\" in tf.__version__:\n self.grud_cell_d = mygru_cell.MyGRUCell4(self.n_hidden_units)\n self.grud_cell_g = mygru_cell.MyGRUCell4(self.n_hidden_units)\n elif \"1.2\" in tf.__version__:\n self.grud_cell_d = mygru_cell.MyGRUCell2(self.n_hidden_units)\n self.grud_cell_g = mygru_cell.MyGRUCell2(self.n_hidden_units)\n # test\n self.sample_num = 64 # number of generated images to be saved\n\n self.num_batches = len(datasets.x) // self.batch_size\n\n\n def pretrainG(self, X, M, Delta, Mean, Lastvalues, X_lengths, Keep_prob, is_training=True, reuse=False):\n\n with tf.variable_scope(\"g_enerator\", reuse=reuse):\n\n \"\"\"\n the rnn cell's variable scope is defined by tensorflow,\n if we want to update rnn cell's weights, the variable scope must contains 'g_' or 'd_'\n \n \"\"\"\n\n wr_h=tf.get_variable(\"g_wr_h\",shape=[self.n_inputs,self.n_hidden_units],initializer=tf.random_normal_initializer())\n w_out= tf.get_variable(\"g_w_out\",shape=[self.n_hidden_units, self.n_inputs],initializer=tf.random_normal_initializer())\n\n br_h= tf.get_variable(\"g_br_h\",shape=[self.n_hidden_units, ],initializer=tf.constant_initializer(0.001))\n b_out= tf.get_variable(\"g_b_out\",shape=[self.n_inputs, ],initializer=tf.constant_initializer(0.001))\n w_z=tf.get_variable(\"g_w_z\",shape=[self.z_dim,self.n_inputs],initializer=tf.random_normal_initializer())\n b_z=tf.get_variable(\"g_b_z\",shape=[self.n_inputs, ],initializer=tf.constant_initializer(0.001))\n\n\n X = tf.reshape(X, [-1, self.n_inputs])\n Delta=tf.reshape(Delta,[-1,self.n_inputs])\n\n rth= tf.matmul(Delta, wr_h)+br_h\n rth=math_ops.exp(-tf.maximum(0.0,rth))\n\n X=tf.concat([X,rth],1)\n\n X_in = tf.reshape(X, [-1, self.n_steps, self.n_inputs+self.n_hidden_units])\n\n init_state = self.grud_cell_g.zero_state(self.batch_size, dtype=tf.float32) # 初始化全零 state\n outputs, final_state = tf.nn.dynamic_rnn(self.grud_cell_g, X_in, \\\n initial_state=init_state,\\\n sequence_length=X_lengths,\n time_major=False)\n #outputs: batch_size*n_steps*n_hiddensize\n outputs=tf.reshape(outputs,[-1,self.n_hidden_units])\n out_predict=tf.matmul(tf.nn.dropout(outputs,Keep_prob), w_out) + b_out\n out_predict=tf.reshape(out_predict,[-1,self.n_steps,self.n_inputs])\n return out_predict\n\n\n def discriminator(self, X, M, DeltaPre, Lastvalues ,DeltaSub ,SubValues , Mean, X_lengths,Keep_prob, is_training=True, reuse=False, isTdata=True):\n # Network Architecture is exactly same as in infoGAN (https://arxiv.org/abs/1606.03657)\n # Architecture : (64)4c2s-(128)4c2s_BL-FC1024_BL-FC1_S\n with tf.variable_scope(\"d_iscriminator\", reuse=reuse):\n\n wr_h=tf.get_variable(\"d_wr_h\",shape=[self.n_inputs,self.n_hidden_units],initializer=tf.random_normal_initializer())\n w_out= tf.get_variable(\"d_w_out\",shape=[self.n_hidden_units, 1],initializer=tf.random_normal_initializer())\n br_h= tf.get_variable(\"d_br_h\",shape=[self.n_hidden_units, ],initializer=tf.constant_initializer(0.001))\n b_out= tf.get_variable(\"d_b_out\",shape=[1, ],initializer=tf.constant_initializer(0.001))\n\n\n M=tf.reshape(M,[-1,self.n_inputs])\n X = tf.reshape(X, [-1, self.n_inputs])\n DeltaPre=tf.reshape(DeltaPre,[-1,self.n_inputs])\n\n\n rth= tf.matmul(DeltaPre, wr_h)+br_h\n rth=math_ops.exp(-tf.maximum(0.0,rth))\n # add noise\n #X=X+np.random.standard_normal(size=(self.batch_size*self.n_steps, self.n_inputs))/100\n X=tf.concat([X,rth],1)\n\n X_in = tf.reshape(X, [self.batch_size, self.n_steps , self.n_inputs+self.n_hidden_units])\n\n init_state = self.grud_cell_d.zero_state(self.batch_size, dtype=tf.float32) # 初始化全零 state\n outputs, final_state = tf.nn.dynamic_rnn(self.grud_cell_d, X_in, \\\n initial_state=init_state,\\\n sequence_length=X_lengths,\n time_major=False)\n\n # final_state:batch_size*n_hiddensize\n # 不能用最后一个,应该用第length个 之前用了最后一个,所以输出无论如何都是b_out\n out_logit=tf.matmul(tf.nn.dropout(final_state,Keep_prob), w_out) + b_out\n out =tf.nn.sigmoid(out_logit) #选取最后一个 output\n return out,out_logit\n\n def generator(self, z, Keep_prob, is_training=True, reuse=False):\n # x,delta,n_steps\n # z :[self.batch_size, self.z_dim]\n # first feed noize in rnn, then feed the previous output into next input\n # or we can feed noize and previous output into next input in future version\n with tf.variable_scope(\"g_enerator\", reuse=reuse):\n #gennerate\n\n wr_h=tf.get_variable(\"g_wr_h\",shape=[self.n_inputs,self.n_hidden_units],initializer=tf.random_normal_initializer())\n w_out= tf.get_variable(\"g_w_out\",shape=[self.n_hidden_units, self.n_inputs],initializer=tf.random_normal_initializer())\n br_h= tf.get_variable(\"g_br_h\",shape=[self.n_hidden_units, ],initializer=tf.constant_initializer(0.001))\n b_out= tf.get_variable(\"g_b_out\",shape=[self.n_inputs, ],initializer=tf.constant_initializer(0.001))\n w_z=tf.get_variable(\"g_w_z\",shape=[self.z_dim,self.n_inputs],initializer=tf.random_normal_initializer())\n b_z=tf.get_variable(\"g_b_z\",shape=[self.n_inputs, ],initializer=tf.constant_initializer(0.001))\n\n #self.times=tf.reshape(self.times,[self.batch_size,self.n_steps,self.n_inputs])\n #change z's dimension\n # batch_size*z_dim-->batch_size*n_inputs\n x=tf.matmul(z,w_z)+b_z\n x=tf.reshape(x,[-1,self.n_inputs])\n delta_zero=tf.constant(0.0,shape=[self.batch_size,self.n_inputs])\n #delta_normal=tf.constant(48.0*60.0/self.gen_length,shape=[self.batch_size,self.n_inputs])\n #delta:[batch_size,1,n_inputs]\n\n\n # combine X_in\n rth= tf.matmul(delta_zero, wr_h)+br_h\n rth=math_ops.exp(-tf.maximum(0.0,rth))\n x=tf.concat([x,rth],1)\n\n X_in = tf.reshape(x, [-1, 1, self.n_inputs+self.n_hidden_units])\n\n init_state = self.grud_cell_g.zero_state(self.batch_size, dtype=tf.float32) # 初始化全零 state\n #z=tf.reshape(z,[self.batch_size,1,self.z_dim])\n seq_len=tf.constant(1,shape=[self.batch_size])\n\n outputs, final_state = tf.nn.dynamic_rnn(self.grud_cell_g, X_in, \\\n initial_state=init_state,\\\n sequence_length=seq_len,\n time_major=False)\n init_state=final_state\n #outputs: batch_size*1*n_hidden\n outputs=tf.reshape(outputs,[-1,self.n_hidden_units])\n # full connect\n out_predict=tf.matmul(tf.nn.dropout(outputs,Keep_prob), w_out) + b_out\n out_predict=tf.reshape(out_predict,[-1,1,self.n_inputs])\n\n total_result=tf.multiply(out_predict,1.0)\n\n for i in range(1,self.n_steps):\n out_predict=tf.reshape(out_predict,[self.batch_size,self.n_inputs])\n #输出加上noise z\n #out_predict=out_predict+tf.matmul(z,w_z)+b_z\n #\n delta_normal=tf.reshape(self.imputed_deltapre[:,i:(i+1),:],[self.batch_size,self.n_inputs])\n rth= tf.matmul(delta_normal, wr_h)+br_h\n rth=math_ops.exp(-tf.maximum(0.0,rth))\n x=tf.concat([out_predict,rth],1)\n X_in = tf.reshape(x, [-1, 1, self.n_inputs+self.n_hidden_units])\n\n outputs, final_state = tf.nn.dynamic_rnn(self.grud_cell_g, X_in, \\\n initial_state=init_state,\\\n sequence_length=seq_len,\n time_major=False)\n init_state=final_state\n outputs=tf.reshape(outputs,[-1,self.n_hidden_units])\n out_predict=tf.matmul(tf.nn.dropout(outputs,Keep_prob), w_out) + b_out\n out_predict=tf.reshape(out_predict,[-1,1,self.n_inputs])\n total_result=tf.concat([total_result,out_predict],1)\n\n #delta:[batch_size,,n_inputs]\n\n if self.isbatch_normal:\n with tf.variable_scope(\"g_bn\", reuse=tf.AUTO_REUSE):\n total_result=bn(total_result,is_training=is_training, scope=\"g_bn_imple\")\n\n\n last_values=tf.multiply(total_result,1)\n sub_values=tf.multiply(total_result,1)\n\n return total_result,self.imputed_deltapre,self.imputed_deltasub,self.imputed_m,self.x_lengths,last_values,sub_values\n\n def impute(self):\n with tf.variable_scope(\"impute\", reuse=tf.AUTO_REUSE):\n z_need_tune=tf.get_variable(\"z_needtune\",shape=[self.batch_size,self.z_dim],initializer=tf.random_normal_initializer(mean=0,stddev=0.1) )\n return z_need_tune\n\n def build_model(self):\n\n self.keep_prob = tf.placeholder(tf.float32)\n self.x = tf.placeholder(tf.float32, [None, self.n_steps, self.n_inputs])\n self.y = tf.placeholder(tf.float32, [None, self.n_classes])\n self.m = tf.placeholder(tf.float32, [None, self.n_steps, self.n_inputs])\n self.mean = tf.placeholder(tf.float32, [self.n_inputs,])\n self.deltaPre = tf.placeholder(tf.float32, [None, self.n_steps, self.n_inputs])\n self.lastvalues = tf.placeholder(tf.float32, [None, self.n_steps, self.n_inputs])\n self.deltaSub = tf.placeholder(tf.float32, [None, self.n_steps, self.n_inputs])\n self.subvalues = tf.placeholder(tf.float32, [None, self.n_steps, self.n_inputs])\n self.x_lengths = tf.placeholder(tf.int32, shape=[self.batch_size,])\n self.imputed_deltapre=tf.placeholder(tf.float32, shape=[self.batch_size,self.n_steps,self.n_inputs])\n self.imputed_deltasub=tf.placeholder(tf.float32, shape=[self.batch_size,self.n_steps,self.n_inputs])\n self.imputed_m = tf.placeholder(tf.float32, [None, self.n_steps, self.n_inputs])\n self.z = tf.placeholder(tf.float32, [self.batch_size, self.z_dim], name='z')\n\n\n\n\n \"\"\" Loss Function \"\"\"\n\n Pre_out=self.pretrainG(self.x, self.m, self.deltaPre, self.mean,\\\n self.lastvalues, self.x_lengths,self.keep_prob, \\\n is_training=True, reuse=False)\n\n self.pretrain_loss=tf.reduce_sum(tf.square(tf.multiply(Pre_out,self.m)-self.x)) / tf.cast(tf.reduce_sum(self.x_lengths),tf.float32)\n\n #discriminator( X, M, DeltaPre, Lastvalues ,DeltaSub ,SubValues , Mean, X_lengths,Keep_prob, is_training=True, reuse=False, isTdata=True):\n\n D_real, D_real_logits = self.discriminator(self.x, self.m, self.deltaPre,self.lastvalues,\\\n self.deltaSub,self.subvalues, self.mean,\\\n self.x_lengths,self.keep_prob, \\\n is_training=True, reuse=False,isTdata=True)\n\n #G return total_result,self.imputed_deltapre,self.imputed_deltasub,self.imputed_m,self.x_lengths,last_values,sub_values\n g_x,g_deltapre,g_deltasub,g_m,G_x_lengths,g_last_values,g_sub_values = self.generator(self.z,self.keep_prob, is_training=True, reuse=True)\n\n D_fake, D_fake_logits = self.discriminator(g_x,g_m,g_deltapre,g_last_values,\\\n g_deltasub,g_sub_values,self.mean,\\\n G_x_lengths,self.keep_prob,\n is_training=True, reuse=True ,isTdata=False)\n\n \"\"\"\n impute loss\n \"\"\"\n self.z_need_tune=self.impute()\n\n impute_out,impute_deltapre,impute_deltasub,impute_m,impute_x_lengths,impute_last_values,impute_sub_values=self.generator(self.z_need_tune,self.keep_prob, is_training=False, reuse=True)\n\n\n impute_fake, impute_fake_logits = self.discriminator(impute_out,impute_m,impute_deltapre,impute_last_values,\\\n impute_deltasub,impute_sub_values,self.mean,\\\n impute_x_lengths,self.keep_prob,\n is_training=False, reuse=True ,isTdata=False)\n\n # loss for imputation\n\n self.impute_loss=tf.reduce_mean(tf.square(tf.multiply(impute_out,self.m)-self.x))-self.g_loss_lambda*tf.reduce_mean(impute_fake_logits)\n #self.impute_loss=tf.reduce_mean(tf.square(tf.multiply(impute_out,self.m)-self.x))\n\n self.impute_out=impute_out\n\n #the imputed results\n self.imputed=tf.multiply((1-self.m),self.impute_out)+self.x\n # get loss for discriminator\n d_loss_real = - tf.reduce_mean(D_real_logits)\n d_loss_fake = tf.reduce_mean(D_fake_logits)\n\n\n self.d_loss = d_loss_real + d_loss_fake\n\n # get loss for generator\n self.g_loss = - d_loss_fake\n\n\n \"\"\" Training \"\"\"\n # divide trainable variables into a group for D and a group for G\n t_vars = tf.trainable_variables()\n d_vars = [var for var in t_vars if 'd_' in var.name]\n g_vars = [var for var in t_vars if 'g_' in var.name]\n z_vars = [self.z_need_tune]\n '''\n print(\"d vars:\")\n for v in d_vars:\n print(v.name)\n print(\"g vars:\")\n for v in g_vars:\n print(v.name)\n print(\"z vars:\")\n for v in z_vars:\n print(v.name)\n '''\n\n #don't need normalization because we have adopted the dropout\n\n ld = 0.0\n for w in d_vars:\n ld += tf.contrib.layers.l2_regularizer(1e-4)(w)\n lg = 0.0\n for w in g_vars:\n lg += tf.contrib.layers.l2_regularizer(1e-4)(w)\n\n self.d_loss+=ld\n self.g_loss+=lg\n\n\n # optimizers\n with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):\n # this code have used batch normalization, so the upside line should be executed\n self.d_optim = tf.train.AdamOptimizer(self.learning_rate, beta1=self.beta1) \\\n .minimize(self.d_loss, var_list=d_vars)\n #self.d_optim=self.optim(self.learning_rate, self.beta1,self.d_loss,d_vars)\n self.g_optim = tf.train.AdamOptimizer(self.learning_rate*self.disc_iters, beta1=self.beta1) \\\n .minimize(self.g_loss, var_list=g_vars)\n #self.g_optim=self.optim(self.learning_rate, self.beta1,self.g_loss,g_vars)\n self.g_pre_optim=tf.train.AdamOptimizer(self.learning_rate*2,beta1=self.beta1) \\\n .minimize(self.pretrain_loss,var_list=g_vars)\n self.impute_optim=tf.train.AdamOptimizer(self.learning_rate*7,beta1=self.beta1) \\\n .minimize(self.impute_loss,var_list=z_vars)\n\n\n\n\n #clip weight\n # self.clip_all_vals = [p.assign(tf.clip_by_value(p, -0.99, 0.99)) for p in t_vars]\n # self.clip_D = [p.assign(tf.clip_by_value(p, -0.99, 0.99)) for p in d_vars]\n # self.clip_G = [p.assign(tf.clip_by_value(p, -0.99, 0.99)) for p in g_vars]\n\n self.clip_all_vals = [p.assign(tf.clip_by_value(p, -0.75, 0.75)) for p\n in t_vars]\n self.clip_D = [p.assign(tf.clip_by_value(p, -0.75, 0.75)) for p in\n d_vars]\n self.clip_G = [p.assign(tf.clip_by_value(p, -0.75, 0.75)) for p in\n g_vars]\n\n \"\"\"\" Testing \"\"\"\n # for test\n self.fake_x,self.fake_delta,_,_,_,_,_ = self.generator(self.z, self.keep_prob, is_training=False, reuse=True)\n\n \"\"\" Summary \"\"\"\n d_loss_real_sum = tf.summary.scalar(\"d_loss_real\", d_loss_real)\n d_loss_fake_sum = tf.summary.scalar(\"d_loss_fake\", d_loss_fake)\n d_loss_sum = tf.summary.scalar(\"d_loss\", self.d_loss)\n g_loss_sum = tf.summary.scalar(\"g_loss\", self.g_loss)\n g_pretrain_loss_sum=tf.summary.scalar(\"g_pretrain_loss\", self.pretrain_loss)\n # final summary operations\n self.impute_sum=tf.summary.scalar(\"impute_loss\", self.impute_loss)\n self.g_sum = g_loss_sum\n self.g_pretrain_sum=tf.summary.merge([g_pretrain_loss_sum])\n self.d_sum = tf.summary.merge([d_loss_real_sum,d_loss_fake_sum, d_loss_sum])\n\n def optim(self,learning_rate,beta,loss,var):\n optimizer = tf.train.AdamOptimizer(learning_rate, beta1=beta)\n grads = optimizer.compute_gradients(loss,var_list=var)\n for i, (g, v) in enumerate(grads):\n if g is not None:\n grads[i] = (tf.clip_by_norm(g, 5), v) # clip gradients\n train_op = optimizer.apply_gradients(grads)\n return train_op\n def pretrain(self, start_epoch,counter,start_time):\n\n if start_epoch < self.pretrain_epoch:\n #todo\n for epoch in range(start_epoch, self.pretrain_epoch):\n # get batch data\n self.datasets.shuffle(self.batch_size,True)\n idx=0\n #x,y,mean,m,deltaPre,x_lengths,lastvalues,files,imputed_deltapre,imputed_m,deltaSub,subvalues,imputed_deltasub\n for data_x,data_y,data_mean,data_m,data_deltaPre,data_x_lengths,data_lastvalues,_,imputed_deltapre,imputed_m,deltaSub,subvalues,imputed_deltasub in self.datasets.nextBatch():\n\n # pretrain\n _, summary_str, p_loss = self.sess.run([self.g_pre_optim, self.g_pretrain_sum, self.pretrain_loss],\n feed_dict={self.x: data_x,\n self.m: data_m,\n self.deltaPre: data_deltaPre,\n self.mean: data_mean,\n self.x_lengths: data_x_lengths,\n self.lastvalues: data_lastvalues,\n self.deltaSub:deltaSub,\n self.subvalues:subvalues,\n self.imputed_m:imputed_m,\n self.imputed_deltapre:imputed_deltapre,\n self.imputed_deltasub:imputed_deltasub,\n self.keep_prob: 0.5})\n self.writer.add_summary(summary_str, counter)\n\n\n counter += 1\n\n # display training status\n print(\"Epoch: [%2d] [%4d/%4d] time: %4.4f, pretrain_loss: %.8f\" \\\n % (epoch, idx, self.num_batches, time.time() - start_time, p_loss))\n idx+=1\n # After an epoch, start_batch_id is set to zero\n # non-zero value is only for the first epoch after loading pre-trained model\n start_batch_id = 0\n\n # save model\n #调好之后再保存\n #if epoch%10==0:\n # self.save(self.checkpoint_dir, counter)\n\n\n def train(self):\n\n # graph inputs for visualize training results\n self.sample_z = np.random.standard_normal(size=(self.batch_size , self.z_dim))\n\n # saver to save model\n self.saver = tf.train.Saver()\n\n # summary writer\n self.writer = tf.summary.FileWriter(self.log_dir + '/' + self.model_name+'/'+self.model_dir)\n\n # restore check-point if it exits\n could_load, checkpoint_counter = self.load(self.checkpoint_dir)\n if could_load:\n start_epoch = (int)(checkpoint_counter / self.num_batches)\n #start_batch_id = checkpoint_counter - start_epoch * self.num_batches\n start_batch_id=0\n #counter = checkpoint_counter\n counter=start_epoch*self.num_batches\n print(\" [*] Load SUCCESS\")\n return\n else:\n # initialize all variables\n tf.global_variables_initializer().run()\n start_epoch = 0\n start_batch_id = 0\n counter = 1\n print(\" [!] Load failed...\")\n\n # loop for epoch\n start_time = time.time()\n\n self.pretrain(start_epoch,counter,start_time)\n if start_epoch < self.pretrain_epoch:\n start_epoch=self.pretrain_epoch\n\n for epoch in range(start_epoch, self.epoch):\n\n # get batch data\n self.datasets.shuffle(self.batch_size,True)\n idx=0\n for data_x,data_y,data_mean,data_m,data_deltaPre,data_x_lengths,data_lastvalues,_,imputed_deltapre,imputed_m,deltaSub,subvalues,imputed_deltasub in self.datasets.nextBatch():\n\n batch_z = np.random.standard_normal(size=(self.batch_size, self.z_dim))\n\n # print(\"batch_z: \" + str(batch_z))\n # print(\"data_x: \" + str(data_x))\n # print(\"data_m: \" + str(data_m))\n # print(\"data_deltaPre: \" + str(data_deltaPre))\n # print(\"data_mean: \" + str(data_mean))\n # print(\"max data_x_lengths: \" + str(max(data_x_lengths)))\n # print(\"data_lastvalues: \" + str(data_lastvalues))\n # print(\"deltaSub: \" + str(deltaSub))\n # print(\"subvalues: \" + str(subvalues))\n # print(\"imputed_m: \" + str(imputed_m))\n # print(\"imputed_deltapre: \" + str(imputed_deltapre))\n # print(\"imputed_deltasub: \" + str(imputed_deltasub))\n\n\n #_ = self.sess.run(self.clip_D)\n _ = self.sess.run(self.clip_all_vals)\n _, summary_str, d_loss = self.sess.run([self.d_optim, self.d_sum, self.d_loss],\n feed_dict={self.z: batch_z,\n self.x: data_x,\n self.m: data_m,\n self.deltaPre: data_deltaPre,\n self.mean: data_mean,\n self.x_lengths: data_x_lengths,\n self.lastvalues: data_lastvalues,\n self.deltaSub:deltaSub,\n self.subvalues:subvalues,\n self.imputed_m:imputed_m,\n self.imputed_deltapre:imputed_deltapre,\n self.imputed_deltasub:imputed_deltasub,\n self.keep_prob: 0.5})\n self.writer.add_summary(summary_str, counter)\n\n # update G network\n if counter%self.disc_iters==0:\n #batch_z = np.random.normal(0, 1, [self.batch_size, self.z_dim]).astype(np.float32)\n _, summary_str, g_loss = self.sess.run([self.g_optim, self.g_sum, self.g_loss],\n feed_dict={self.z: batch_z,\n self.keep_prob: 0.5,\n self.deltaPre: data_deltaPre,\n self.mean: data_mean,\n self.x_lengths: data_x_lengths,\n self.lastvalues: data_lastvalues,\n self.deltaSub:deltaSub,\n self.subvalues:subvalues,\n self.imputed_m:imputed_m,\n self.imputed_deltapre:imputed_deltapre,\n self.imputed_deltasub:imputed_deltasub,\n self.mean: data_mean})\n self.writer.add_summary(summary_str, counter)\n print(\"Epoch: [%2d] [%4d/%4d] time: %4.4f, d_loss: %.8f, g_loss: %.8f,counter:%4d\" \\\n % (epoch, idx, self.num_batches, time.time() - start_time, d_loss, g_loss,counter))\n #debug\n\n counter += 1\n\n # display training status\n print(\"Epoch: [%2d] [%4d/%4d] time: %4.4f, d_loss: %.8f, counter:%4d\" \\\n % (epoch, idx, self.num_batches, time.time() - start_time, d_loss, counter))\n\n # save training results for every 300 steps\n if np.mod(counter, 300) == 0 :\n fake_x,fake_delta = self.sess.run([self.fake_x,self.fake_delta],\n feed_dict={self.z: batch_z,\n self.deltaPre: data_deltaPre,\n self.mean: data_mean,\n self.x_lengths: data_x_lengths,\n self.lastvalues: data_lastvalues,\n self.deltaSub:deltaSub,\n self.subvalues:subvalues,\n self.imputed_m:imputed_m,\n self.imputed_deltapre:imputed_deltapre,\n self.imputed_deltasub:imputed_deltasub,\n self.mean: data_mean,\n self.keep_prob: 0.5})\n if self.run_type==\"train\":\n self.writeG_Samples(\"G_sample_x\",counter,fake_x)\n self.writeG_Samples(\"G_sample_delta\",counter,fake_delta)\n\n idx+=1\n # After an epoch, start_batch_id is set to zero\n # non-zero value is only for the first epoch after loading pre-trained model\n start_batch_id = 0\n\n\n self.save(self.checkpoint_dir, counter)\n\n def imputation(self,dataset,isTrain):\n self.datasets=dataset\n self.datasets.shuffle(self.batch_size,True)\n tf.variables_initializer([self.z_need_tune]).run()\n #是否shuffle无所谓,填充之后存起来,测试的时候用填充之后的数据再shuffle即可\n #训练数据集不能被batch_size整除剩下的部分,扔掉\n start_time = time.time()\n batchid=1\n impute_tune_time=1\n counter=1\n for data_x,data_y,data_mean,data_m,data_deltaPre,data_x_lengths,data_lastvalues,_,imputed_deltapre,imputed_m,deltaSub,subvalues,imputed_deltasub in self.datasets.nextBatch():\n #self.z_need_tune=tf.assign(self.z_need_tune,tf.random_normal([self.batch_size,self.z_dim]))\n tf.variables_initializer([self.z_need_tune]).run()\n for i in range(0,self.impute_iter):\n _, impute_out, summary_str, impute_loss, imputed = self.sess.run([self.impute_optim, self.impute_out, self.impute_sum, self.impute_loss, self.imputed], \\\n feed_dict={self.x: data_x,\n self.m: data_m,\n self.deltaPre: data_deltaPre,\n self.mean: data_mean,\n self.x_lengths: data_x_lengths,\n self.lastvalues: data_lastvalues,\n self.deltaSub:deltaSub,\n self.subvalues:subvalues,\n self.imputed_m:imputed_m,\n self.imputed_deltapre:imputed_deltapre,\n self.imputed_deltasub:imputed_deltasub,\n self.keep_prob: 1.0})\n impute_tune_time+=1\n counter+=1\n if counter%10==0:\n print(\"Batchid: [%2d] [%4d/%4d] time: %4.4f, impute_loss: %.8f\" \\\n % (batchid, impute_tune_time, self.impute_iter, time.time() - start_time, impute_loss))\n self.writer.add_summary(summary_str, counter/10)\n #imputed=tf.multiply((1-self.m),impute_out)+data_x\n self.save_imputation(imputed,batchid,data_x_lengths,data_deltaPre,data_y,isTrain)\n batchid+=1\n impute_tune_time=1\n @property\n def model_dir(self):\n return \"{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}\".format(\n self.epoch,self.disc_iters,\n self.batch_size, self.z_dim,\n self.lr,self.impute_iter,\n self.isNormal,self.isbatch_normal,\n self.isSlicing,self.g_loss_lambda,\n self.beta1\n )\n\n\n def save_imputation(self,impute_out,batchid,data_x_lengths,data_times,data_y,isTrain):\n #填充后的数据全是n_steps长度!,但只有data_x_lengths才是可用的\n if isTrain:\n imputation_dir=\"imputation_train_results\"\n else:\n imputation_dir=\"imputation_test_results\"\n\n if not os.path.exists(os.path.join(imputation_dir,\\\n self.model_name,\\\n self.model_dir)):\n os.makedirs(os.path.join(imputation_dir,\\\n self.model_name,\\\n self.model_dir))\n\n #write imputed data\n resultFile=open(os.path.join(imputation_dir,\\\n self.model_name,\\\n self.model_dir,\\\n \"batch\"+str(batchid)+\"x\"),'w')\n for length in data_x_lengths:\n resultFile.writelines(str(length)+\",\")\n resultFile.writelines(\"\\r\\n\")\n # impute_out:ndarray\n for oneSeries in impute_out:\n resultFile.writelines(\"begin\\r\\n\")\n for oneClass in oneSeries:\n for i in oneClass.flat:\n resultFile.writelines(str(i)+\",\")\n resultFile.writelines(\"\\r\\n\")\n resultFile.writelines(\"end\\r\\n\")\n resultFile.close()\n\n #write data_times data_times:list\n resultFile=open(os.path.join(imputation_dir,\\\n self.model_name,\\\n self.model_dir,\\\n \"batch\"+str(batchid)+\"delta\"),'w')\n for oneSeries in data_times:\n resultFile.writelines(\"begin\\r\\n\")\n for oneClass in oneSeries:\n for i in oneClass:\n resultFile.writelines(str(i)+\",\")\n resultFile.writelines(\"\\r\\n\")\n resultFile.writelines(\"end\\r\\n\")\n resultFile.close()\n\n #write y\n resultFile=open(os.path.join(imputation_dir,\\\n self.model_name,\\\n self.model_dir,\\\n \"batch\"+str(batchid)+\"y\"),'w')\n for oneSeries in data_y:\n #resultFile.writelines(\"begin\\r\\n\")\n for oneClass in oneSeries:\n resultFile.writelines(str(oneClass)+\",\")\n resultFile.writelines(\"\\r\\n\")\n #resultFile.writelines(\"end\\r\\n\")\n resultFile.close()\n\n def writeG_Samples(self,filename,step,o):\n if not os.path.exists(os.path.join(\"G_results\",\\\n self.model_name,\\\n self.model_dir)):\n os.makedirs(os.path.join(\"G_results\",\\\n self.model_name,\\\n self.model_dir))\n resultFile=open(os.path.join(\"G_results\",\\\n self.model_name,\\\n self.model_dir,\\\n filename+str(step)),'w')\n for oneSeries in o:\n resultFile.writelines(\"begin\\r\\n\")\n for oneClass in oneSeries:\n for i in oneClass.flat:\n resultFile.writelines(str(i)+\",\")\n resultFile.writelines(\"\\r\\n\")\n resultFile.writelines(\"end\\r\\n\")\n resultFile.close()\n\n def save(self, checkpoint_dir, step):\n checkpoint_dir = os.path.join(checkpoint_dir, self.model_name, self.model_dir )\n\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n\n self.saver.save(self.sess,os.path.join(checkpoint_dir, self.model_name+'.model'), global_step=step)\n\n def load(self, checkpoint_dir):\n import re\n print(\" [*] Reading checkpoints...\")\n checkpoint_dir = os.path.join(checkpoint_dir, self.model_name, self.model_dir)\n\n ckpt = tf.train.get_checkpoint_state(checkpoint_dir)\n if ckpt and ckpt.model_checkpoint_path:\n ckpt_name = os.path.basename(ckpt.model_checkpoint_path)\n self.saver.restore(self.sess, os.path.join(checkpoint_dir, ckpt_name))\n counter = int(next(re.finditer(\"(\\d+)(?!.*\\d)\",ckpt_name)).group(0))\n print(\" [*] Success to read {}\".format(ckpt_name))\n return True, counter\n else:\n print(\" [*] Failed to find a checkpoint\")\n return False, 0\n", "meta": {"hexsha": "cd1c41d65a0744e63a1addc0362da363042c323e", "size": 36623, "ext": "py", "lang": "Python", "max_stars_repo_path": "deprecated/Imputation/Gan_Imputation/WGAN_GRUI.py", "max_stars_repo_name": "srinivasans/DeepSepsis", "max_stars_repo_head_hexsha": "8647a2ec93ad5a937638acfc279a756bbfa04f7f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-22T07:41:23.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-23T02:45:06.000Z", "max_issues_repo_path": "deprecated/Imputation/Gan_Imputation/WGAN_GRUI.py", "max_issues_repo_name": "srinivasans/DeepSepsis", "max_issues_repo_head_hexsha": "8647a2ec93ad5a937638acfc279a756bbfa04f7f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deprecated/Imputation/Gan_Imputation/WGAN_GRUI.py", "max_forks_repo_name": "srinivasans/DeepSepsis", "max_forks_repo_head_hexsha": "8647a2ec93ad5a937638acfc279a756bbfa04f7f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.7243767313, "max_line_length": 192, "alphanum_fraction": 0.5511017666, "include": true, "reason": "import numpy", "num_tokens": 7849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.2782567877172032, "lm_q1q2_score": 0.14889476986216404}} {"text": "\"\"\"\nExecutes the parallelization of Stochastic DiNT through MPI4Py\n\"\"\"\n\nimport os\nimport os.path\nimport sys\nimport math\nimport numpy as np\n\n#take the current main() function/subroutine and move that code \n# into a main_run_DiNT() function/subroutine that main() now calls. \n#Then, one can create a libDiNT.a library that a new lightweight MPI code \n# could link in where each MPI rank spawned would call main_run_DiNT() \n# to launch its own instance of a DiNT calculation. \n#Making sure each instance of DiNT had unique input and output is the \n# next step, and then it’s a matter of optimizing performance, \n# which in this case is usually turning off all unnecessary writing of \n# output and/or refactoring how output gets written so that it’s \n# efficient when 100,000s of DiNTs are all running (e.g. could capture \n# important output in memory and write single output file in parallel).\n\nfrom mpi4py import MPI\n#from libDiNT.a import dint\n#or use f2py?\nimport stoch_driver.collisions as collisions\nimport stoch_driver.zonz as zonz\nimport stoch_driver.constants as constants\n\n\nclass Trajectory:\n \"\"\"\n A representation of a stochastic trajectory.\n =========================== ================================================\n Attribute Description\n =========================== ================================================\n `rank` MPI process rank assigned to this trajectory\n `A` A list of the reactants present in the system\n `X` A list of the reactive collider species in the system\n `M` A list of the nonreactive collider species in the system\n `natoms` An array of the number of atoms in associated A species\n `temp` Temperature of the system in Kelvin\n `xA` Number of molar equivalents of each A species\n `xX` Number of molar equivalents of each X species\n `xM` Number of molar equivalents of each M species\n `steps` Maximum number of Monte Carlo steps the simulation should take\n `Ei_list` A list of the initial energies for each step in the trajectory\n `Ef_list` A list of the final energies for each step in the trajectory\n `Ji_list` A list of the initial J for each step in the trajectory\n `Jf_list` A list of the final J for each step in the trajectory\n --------------------------- ----------------------------------------------------\n `xAn` Normalized mole fraction of A species\n `xXn` Normalized mole fraction of A species\n `xMn` Normalized mole fraction of A species\n =========================== ================================================\n \"\"\"\n def __init__(self, label, A, X, M, natomsA, natomsX, natomsM, \n xA, xX, xM, temperature, steps):\n self.label = label\n self.A = A\n self.X = X\n self.M = M\n self.natomsA = natomsA\n self.natomsX = natomsX\n self.natomsM = natomsM\n self.temperature = temperature\n self.xA = xA\n self.xX = xX\n self.xM = xM\n self.steps = steps\n\n self.outputDirectory = join(os.path.abspath(outputDirectory),\"b\",rank)\n\n self.Ei_list = []\n self.Ji_list = []\n self.Ef_list = []\n self.Jf_list = []\n\n# def species(self): \n\n #for i in range(len(A)):\n # self.A[i] = A[i]\n #for i in range(len(X)):\n # self.X[i] = X[i]\n #for i in range(len(M)):\n # self.M[i] = M[i]\n \n# return A, X, M\n\n# def moleFracs(self):\n\n #for i in range(len(xA)):\n # self.xA[i] = xA[i]\n #for i in range(len(xA)):\n # self.xX[i] = xX[i]\n #for i in range(len(xA)):\n # self.xM[i] = xM[i]\n\n# return xA, xX, xM\n\n def initEJ(self, ei, ji):\n self.Ei_list.append(ei)\n self.Ji_list.append(ji)\n\n def updateEJ(self, ef, jf):\n self.Ef_list.append(ef)\n self.Jf_list.append(jf)\n\n def executeStochasticDynamics(self, rates):\n # Set path\n DRIVE_PATH = os.getcwd()\n\n xA = self.xA\n xX = self.xX\n xM = self.xM\n zhsA = rates.zhsA\n zhsX = rates.zhsX\n zhsM = rates.zhsM\n zljA = rates.zljA\n zljX = rates.zljX\n zljM = rates.zljM\n bmaxA = rates.bmaxA\n bmaxX = rates.bmaxX\n bmaxM = rates.bmaxM\n\n # Initialize trajectory objects\n collisions.normMoleFracs(xA, xX, xM, zhsA, zhsX, zhsM, \n zljA, zljX, zljM, bmaxA, bmaxX, bmaxM)\n\n # Initialize E, J values \n zonz.pEJ(temp)\n\n ef = ee*constants.cmtokcalmol + 4.5*constants.evtokcalmol\n self.initEJ(ei = ef, ji = jf)\n self.Ei_list.append(ei)\n self.Ji_list.append(ji)\n\n # Continue stochastic dynamics until reaction occurs or max steps reached:\n while nn[0] < maxsteps:\n x = random.randrange(0,1)\n it = 0\n test = pp/ps\n while (x > test):\n it += 1\n test += pp[it]/ps\n nn[it] += 1\n\n if (it == 0): # Counter\n # print to specific traj file\n print(nn[0],ji,ei,jf,ef)\n elif (it == 1): # A + M\n collisions.prepAMTraj(ef,jf,temp) # creates new input file for A+M\n print(\"Run dint-alkT here\")\n# dint.dint-alkT ### call appropriate dint exe\n elif (it == 2): # A + X\n collisions.prepAXTraj(nmodes,ef,jf,temp,bmax) # creates new input file for A+X\n print(\"Run dint-ch4hALL here\")\n# dint.dint-ch4hALL ### call appropriate dint exe\n else:\n print(\"Error: Iteration not found\")\n break\n\n with open('fort.31') as f:\n for line in f:\n pass # grab last line from fort.31\n f31 = split(line)\n\n ji = f31[12]\n ei = (f31[13]+f31[14]+f31[15])*constants.eVtokcalmol\n jf = f31[24]\n ef = (f31[25]+f31[26]+f31[27])*constants.eVtokcalmol\n\n self.updateEJ(ef = ef, jf = jf)\n self.Ef_list.append(ef)\n self.Jf_list.append(jf)\n\n# print(\"Traj b\",i,\": Timestep \",nn[0],\" , M collision \",nn[it],\" ( \",ji,\" , \",ei,\" ) --> ( \",jf,\" , \",ef\" )\")\n\nclass Reactants:\n def __init__(self, A, natomsA, xA, B):\n self.A = A\n self.natomsA = natomsA\n self.xA = xA\n self.B = B\n\nclass xColliders:\n def __init__(self, X, natomsX, xX):\n self.X = X\n self.natomsX = natomsX\n self.xX = xX\n\nclass mColliders:\n def __init__(self, M, natomsM, xM):\n self.M = M\n self.natomsM = natomsM\n self.xM = xM", "meta": {"hexsha": "af9d98d65d116f82b69274b768920ffc9209966d", "size": 7043, "ext": "py", "lang": "Python", "max_stars_repo_path": "stoch_driver/main.py", "max_stars_repo_name": "mobergd/StochasticDiNT", "max_stars_repo_head_hexsha": "a1d59ff5c21bdf4bb99d87363f3ef3cb745e6251", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stoch_driver/main.py", "max_issues_repo_name": "mobergd/StochasticDiNT", "max_issues_repo_head_hexsha": "a1d59ff5c21bdf4bb99d87363f3ef3cb745e6251", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stoch_driver/main.py", "max_forks_repo_name": "mobergd/StochasticDiNT", "max_forks_repo_head_hexsha": "a1d59ff5c21bdf4bb99d87363f3ef3cb745e6251", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9336734694, "max_line_length": 121, "alphanum_fraction": 0.5223626296, "include": true, "reason": "import numpy", "num_tokens": 1838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.26284182582255894, "lm_q1q2_score": 0.14877334908872003}} {"text": "# -*- coding: utf-8 -*-\n# vim: tabstop=4 shiftwidth=4 softtabstop=4\n#\n# Copyright (C) 2012-2016 GEM Foundation\n#\n# OpenQuake is free software: you can redistribute it and/or modify it\n# under the terms of the GNU Affero General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# OpenQuake is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with OpenQuake. If not, see .\n\n\"\"\"\nModule :mod:`openquake.hazardlib.geo.mesh` defines classes :class:`Mesh` and\nits subclass :class:`RectangularMesh`.\n\"\"\"\nimport numpy\nimport shapely.geometry\nimport shapely.ops\n\nfrom openquake.hazardlib.geo.point import Point\nfrom openquake.hazardlib.geo import geodetic\nfrom openquake.hazardlib.geo import utils as geo_utils\n\nmesh_dt = numpy.dtype([('lon', float), ('lat', float), ('depth', float)])\n\n\ndef build_array(lons_lats_depths):\n \"\"\"\n Convert a list of n triples into a composite numpy array with fields\n lon, lat, depth and shape (n,) + lons.shape.\n \"\"\"\n shape = (len(lons_lats_depths),) + lons_lats_depths[0][0].shape\n arr = numpy.zeros(shape, mesh_dt)\n for i, (lons, lats, depths) in enumerate(lons_lats_depths):\n arr['lon'][i] = lons\n arr['lat'][i] = lats\n arr['depth'][i] = depths\n return arr\n\n\nclass Mesh(object):\n \"\"\"\n Mesh object represent a collection of points and provides the most\n efficient way of keeping those collections in memory.\n\n :param lons:\n A numpy array of longitude values of points. Array may be\n of arbitrary shape.\n :param lats:\n Numpy array of latitude values. The array must be of the same\n shape as ``lons``.\n :param depths:\n Either ``None``, which means that all points the mesh consists\n of are lying on the earth surface (have zero depth) or numpy\n array of the same shape as previous two.\n\n Mesh object can also be created from a collection of points, see\n :meth:`from_points_list`.\n \"\"\"\n #: Tolerance level to be used in various spatial operations when\n #: approximation is required -- set to 5 meters.\n DIST_TOLERANCE = 0.005\n\n def __init__(self, lons, lats, depths=None):\n assert (isinstance(lons, numpy.ndarray) and\n isinstance(lats, numpy.ndarray) and\n (depths is None or isinstance(depths, numpy.ndarray))\n ), (type(lons), type(lats), type(depths))\n assert ((lons.shape == lats.shape) and\n (depths is None or depths.shape == lats.shape)\n ), (lons.shape, lats.shape)\n assert lons.size > 0\n self.lons = lons\n self.lats = lats\n self.depths = depths\n\n @classmethod\n def from_points_list(cls, points):\n \"\"\"\n Create a mesh object from a collection of points.\n\n :param point:\n List of :class:`~openquake.hazardlib.geo.point.Point` objects.\n :returns:\n An instance of :class:`Mesh` with one-dimensional arrays\n of coordinates from ``points``.\n \"\"\"\n lons = numpy.zeros(len(points), dtype=float)\n lats = lons.copy()\n depths = lons.copy()\n for i in range(len(points)):\n lons[i] = points[i].longitude\n lats[i] = points[i].latitude\n depths[i] = points[i].depth\n if not depths.any():\n # all points have zero depth, no need to waste memory\n depths = None\n return cls(lons, lats, depths)\n\n @property\n def shape(self):\n \"\"\"\n Return the shape of this mesh.\n\n :returns tuple:\n The shape of this mesh as (rows, columns)\n \"\"\"\n return self.lons.shape\n\n def __iter__(self):\n \"\"\"\n Generate :class:`~openquake.hazardlib.geo.point.Point` objects the mesh\n is composed of.\n\n Coordinates arrays are processed sequentially (as if they were\n flattened).\n \"\"\"\n lons = self.lons.flat\n lats = self.lats.flat\n if self.depths is not None:\n depths = self.depths.flat\n for i in range(self.lons.size):\n yield Point(lons[i], lats[i], depths[i])\n else:\n for i in range(self.lons.size):\n yield Point(lons[i], lats[i])\n\n def __getitem__(self, item):\n \"\"\"\n Get a submesh of this mesh.\n\n :param item:\n Indexing is only supported by slices. Those slices are used\n to cut the portion of coordinates (and depths if it is available)\n arrays. These arrays are then used for creating a new mesh.\n :returns:\n A new object of the same type that borrows a portion of geometry\n from this mesh (doesn't copy the array, just references it).\n \"\"\"\n if isinstance(item, int):\n raise ValueError('You must pass a slice, not an index: %s' % item)\n lons = self.lons[item]\n lats = self.lats[item]\n depths = None\n if self.depths is not None:\n depths = self.depths[item]\n return type(self)(lons, lats, depths)\n\n def __len__(self):\n \"\"\"\n Return the number of points in the mesh.\n \"\"\"\n return self.lons.size\n\n def __eq__(self, mesh, tol=1.0E-7):\n \"\"\"\n Compares the mesh with another returning True if all elements are\n equal to within the specific tolerance, False otherwise\n\n :param mesh:\n Mesh for comparison as instance of :class:\n openquake.hazardlib.geo.mesh.Mesh\n\n :param float tol:\n Numerical precision for equality\n \"\"\"\n if self.depths is not None:\n if mesh.depths is not None:\n # Both meshes have depth values - compare equality\n return numpy.allclose(self.lons, mesh.lons, atol=tol) and\\\n numpy.allclose(self.lats, mesh.lats, atol=tol) and\\\n numpy.allclose(self.depths, mesh.depths, atol=tol)\n else:\n # Second mesh missing depths - not equal\n return False\n else:\n if mesh.depths is None:\n return False\n else:\n return numpy.allclose(self.lons, mesh.lons, atol=tol) and\\\n numpy.allclose(self.lats, mesh.lats, atol=tol)\n\n def get_min_distance(self, mesh):\n \"\"\"\n Compute and return the minimum distance from the mesh to each point\n in another mesh.\n\n :returns:\n numpy array of distances in km of the same shape as ``mesh``.\n\n Method doesn't make any assumptions on arrangement of the points\n in either mesh and instead calculates the distance from each point of\n this mesh to each point of the target mesh and returns the lowest found\n for each.\n \"\"\"\n return self._min_idx_dst(mesh)[1]\n\n def get_closest_points(self, mesh):\n \"\"\"\n Find closest point of this mesh for each one in ``mesh``.\n\n :returns:\n :class:`Mesh` object of the same shape as ``mesh`` with closest\n points from this one at respective indices.\n \"\"\"\n min_idx, min_dst = self._min_idx_dst(mesh)\n lons = self.lons.take(min_idx)\n lats = self.lats.take(min_idx)\n if self.depths is None:\n depths = None\n else:\n depths = self.depths.take(min_idx)\n return Mesh(lons, lats, depths)\n\n def _min_idx_dst(self, mesh):\n if self.depths is None:\n depths1 = numpy.zeros_like(self.lons)\n else:\n depths1 = self.depths\n if mesh.depths is None:\n depths2 = numpy.zeros_like(mesh.lons)\n else:\n depths2 = mesh.depths\n return geodetic.min_idx_dst(\n self.lons, self.lats, depths1, mesh.lons, mesh.lats, depths2)\n\n def get_distance_matrix(self):\n \"\"\"\n Compute and return distances between each pairs of points in the mesh.\n\n This method requires that all the points lie on Earth surface (have\n zero depth) and coordinate arrays are one-dimensional.\n\n .. warning::\n Because of its quadratic space and time complexity this method\n is safe to use for meshes of up to several thousand points. For\n mesh of 10k points it needs ~800 Mb for just the resulting matrix\n and four times that much for intermediate storage.\n\n :returns:\n Two-dimensional numpy array, square matrix of distances. The matrix\n has zeros on main diagonal and positive distances in kilometers\n on all other cells. That is, value in cell (3, 5) is the distance\n between mesh's points 3 and 5 in km, and it is equal to value\n in cell (5, 3).\n\n Uses :func:`openquake.hazardlib.geo.geodetic.geodetic_distance`.\n \"\"\"\n assert self.lons.ndim == 1\n assert self.depths is None or (self.depths == 0).all()\n distances = geodetic.geodetic_distance(\n self.lons.reshape(self.lons.shape + (1, )),\n self.lats.reshape(self.lats.shape + (1, )),\n self.lons,\n self.lats\n )\n return numpy.matrix(distances, copy=False)\n\n def _get_proj_convex_hull(self):\n \"\"\"\n Create a projection centered in the center of this mesh and define\n a convex polygon in that projection, enveloping all the points\n of the mesh.\n\n :returns:\n Tuple of two items: projection function and shapely 2d polygon.\n Note that the result geometry can be line or point depending\n on number of points in the mesh and their arrangement.\n \"\"\"\n # create a projection centered in the center of points collection\n proj = geo_utils.get_orthographic_projection(\n *geo_utils.get_spherical_bounding_box(self.lons, self.lats)\n )\n # project all the points and create a shapely multipoint object.\n # need to copy an array because otherwise shapely misinterprets it\n coords = numpy.transpose(proj(self.lons.flatten(),\n self.lats.flatten())).copy()\n multipoint = shapely.geometry.MultiPoint(coords)\n # create a 2d polygon from a convex hull around that multipoint.\n polygon2d = multipoint.convex_hull\n return proj, polygon2d\n\n def _get_proj_enclosing_polygon(self):\n \"\"\"\n Create a projection centered in the center of this mesh and define\n a minimum polygon in that projection, enveloping all the points\n of the mesh.\n\n In :class:`Mesh` this is equivalent to :meth:`_get_proj_convex_hull`.\n \"\"\"\n return self._get_proj_convex_hull()\n\n def get_convex_hull(self):\n \"\"\"\n Get a convex polygon object that contains projections of all the points\n of the mesh.\n\n :returns:\n Instance of :class:`openquake.hazardlib.geo.polygon.Polygon` that\n is a convex hull around all the points in this mesh. If the\n original mesh had only one point, the resulting polygon has a\n square shape with a side length of 10 meters. If there were only\n two points, resulting polygon is a stripe 10 meters wide.\n \"\"\"\n proj, polygon2d = self._get_proj_convex_hull()\n # if mesh had only one point, the convex hull is a point. if there\n # were two, it is a line string. we need to return a convex polygon\n # object, so extend that area-less geometries by some arbitrarily\n # small distance.\n if isinstance(polygon2d, (shapely.geometry.LineString,\n shapely.geometry.Point)):\n polygon2d = polygon2d.buffer(self.DIST_TOLERANCE, 1)\n\n # avoid circular imports\n from openquake.hazardlib.geo.polygon import Polygon\n return Polygon._from_2d(polygon2d, proj)\n\n\nclass RectangularMesh(Mesh):\n \"\"\"\n A specification of :class:`Mesh` that requires coordinate numpy-arrays\n to be two-dimensional.\n\n Rectangular mesh is meant to represent not just an unordered collection\n of points but rather a sort of table of points, where index of the point\n in a mesh is related to it's position with respect to neighbouring points.\n \"\"\"\n def __init__(self, lons, lats, depths=None):\n super(RectangularMesh, self).__init__(lons, lats, depths)\n assert lons.ndim == 2\n\n @classmethod\n def from_points_list(cls, points):\n \"\"\"\n Create a rectangular mesh object from a list of lists of points.\n Lists in a list are supposed to have the same length.\n\n :param point:\n List of lists of :class:`~openquake.hazardlib.geo.point.Point`\n objects.\n \"\"\"\n assert points is not None and len(points) > 0 and len(points[0]) > 0, \\\n 'list of at least one non-empty list of points is required'\n lons = numpy.zeros((len(points), len(points[0])), dtype=float)\n lats = lons.copy()\n depths = lons.copy()\n num_cols = len(points[0])\n for i, row in enumerate(points):\n assert len(row) == num_cols, \\\n 'lists of points are not of uniform length'\n for j, point in enumerate(row):\n lons[i][j] = point.longitude\n lats[i][j] = point.latitude\n depths[i][j] = point.depth\n if not depths.any():\n depths = None\n return cls(lons, lats, depths)\n\n def get_joyner_boore_distance(self, mesh):\n \"\"\"\n Compute and return Joyner-Boore distance to each point of ``mesh``.\n Point's depth is ignored.\n\n See\n :meth:`openquake.hazardlib.geo.surface.base.BaseQuadrilateralSurface.get_joyner_boore_distance`\n for definition of this distance.\n\n :returns:\n numpy array of distances in km of the same shape as ``mesh``.\n Distance value is considered to be zero if a point\n lies inside the polygon enveloping the projection of the mesh\n or on one of its edges.\n \"\"\"\n # we perform a hybrid calculation (geodetic mesh-to-mesh distance\n # and distance on the projection plane for close points). first,\n # we find the closest geodetic distance for each point of target\n # mesh to this one. in general that distance is greater than\n # the exact distance to enclosing polygon of this mesh and it\n # depends on mesh spacing. but the difference can be neglected\n # if calculated geodetic distance is over some threshold.\n # get the highest slice from the 3D mesh\n distances = geodetic.min_geodetic_distance(\n self.lons, self.lats, mesh.lons, mesh.lats)\n # here we find the points for which calculated mesh-to-mesh\n # distance is below a threshold. this threshold is arbitrary:\n # lower values increase the maximum possible error, higher\n # values reduce the efficiency of that filtering. the maximum\n # error is equal to the maximum difference between a distance\n # from site to two adjacent points of the mesh and distance\n # from site to the line connecting them. thus the error is\n # a function of distance threshold and mesh spacing. the error\n # is maximum when the site lies on a perpendicular to the line\n # connecting points of the mesh and that passes the middle\n # point between them. the error then can be calculated as\n # ``err = trsh - d = trsh - \\sqrt(trsh^2 - (ms/2)^2)``, where\n # ``trsh`` and ``d`` are distance to mesh points (the one\n # we found on the previous step) and distance to the line\n # connecting them (the actual distance) and ``ms`` is mesh\n # spacing. the threshold of 40 km gives maximum error of 314\n # meters for meshes with spacing of 10 km and 5.36 km for\n # meshes with spacing of 40 km. if mesh spacing is over\n # ``(trsh / \\sqrt(2)) * 2`` then points lying in the middle\n # of mesh cells (that is inside the polygon) will be filtered\n # out by the threshold and have positive distance instead of 0.\n # so for threshold of 40 km mesh spacing should not be more\n # than 56 km (typical values are 5 to 10 km).\n\n [idxs] = (distances < 40).nonzero()\n if not len(idxs):\n # no point is close enough, return distances as they are\n return distances\n\n # for all the points that are closer than the threshold we need\n # to recalculate the distance and set it to zero, if point falls\n # inside the enclosing polygon of the mesh. for doing that we\n # project both this mesh and the points of the second mesh--selected\n # by distance threshold--to the same Cartesian space, define\n # minimum shapely polygon enclosing the mesh and calculate point\n # to polygon distance, which gives the most accurate value\n # of distance in km (and that value is zero for points inside\n # the polygon).\n proj, polygon = self._get_proj_enclosing_polygon()\n if not isinstance(polygon, shapely.geometry.Polygon):\n # either line or point is our enclosing polygon. draw\n # a square with side of 10 m around in order to have\n # a proper polygon instead.\n polygon = polygon.buffer(self.DIST_TOLERANCE, 1)\n mesh_xx, mesh_yy = proj(mesh.lons[idxs], mesh.lats[idxs])\n # replace geodetic distance values for points-closer-than-the-threshold\n # by more accurate point-to-polygon distance values.\n distances[idxs] = geo_utils.point_to_polygon_distance(\n polygon, mesh_xx, mesh_yy)\n\n return distances\n\n def _get_proj_enclosing_polygon(self):\n \"\"\"\n See :meth:`Mesh._get_proj_enclosing_polygon`.\n\n :class:`RectangularMesh` contains an information about relative\n positions of points, so it allows to define the minimum polygon,\n containing the projection of the mesh, which doesn't necessarily\n have to be convex (in contrast to :class:`Mesh` implementation).\n\n :returns:\n Same structure as :meth:`Mesh._get_proj_convex_hull`.\n \"\"\"\n if self.lons.size < 4:\n # the mesh doesn't contain even a single cell, use :class:`Mesh`\n # method implementation (which would dilate the point or the line)\n return super(RectangularMesh, self)._get_proj_enclosing_polygon()\n\n proj = geo_utils.get_orthographic_projection(\n *geo_utils.get_spherical_bounding_box(self.lons.flatten(),\n self.lats.flatten())\n )\n mesh2d = numpy.array(proj(self.lons.transpose(),\n self.lats.transpose())).transpose()\n lines = iter(mesh2d)\n # we iterate over horizontal stripes, keeping the \"previous\"\n # line of points. we keep it reversed, such that together\n # with the current line they define the sequence of points\n # around the stripe.\n prev_line = next(lines)[::-1]\n polygons = []\n for i, line in enumerate(lines):\n coords = numpy.concatenate((prev_line, line, prev_line[0:1]))\n # create the shapely polygon object from the stripe\n # coordinates and simplify it (remove redundant points,\n # if there are any lying on the straight line).\n stripe = shapely.geometry.LineString(coords) \\\n .simplify(self.DIST_TOLERANCE) \\\n .buffer(self.DIST_TOLERANCE, 2)\n polygons.append(shapely.geometry.Polygon(stripe.exterior))\n prev_line = line[::-1]\n try:\n # create a final polygon as the union of all the stripe ones\n polygon = shapely.ops.cascaded_union(polygons) \\\n .simplify(self.DIST_TOLERANCE)\n except ValueError:\n # NOTE(larsbutler): In some rare cases, we've observed ValueErrors\n # (\"No Shapely geometry can be created from null value\") with very\n # specific sets of polygons such that there are two unique\n # and many duplicates of one.\n # This bug is very difficult to reproduce consistently (except on\n # specific platforms) so the work around here is to remove the\n # duplicate polygons. In fact, we only observed this error on our\n # CI/build machine. None of our dev environments or production\n # machines has encountered this error, at least consistently. >:(\n polygons = [shapely.wkt.loads(x) for x in\n list(set(p.wkt for p in polygons))]\n polygon = shapely.ops.cascaded_union(polygons) \\\n .simplify(self.DIST_TOLERANCE)\n return proj, polygon\n\n def get_middle_point(self):\n \"\"\"\n Return the middle point of the mesh.\n\n :returns:\n An instance of :class:`~openquake.hazardlib.geo.point.Point`.\n\n The middle point is taken from the middle row and a middle column\n of the mesh if there are odd number of both. Otherwise the geometric\n mean point of two or four middle points.\n \"\"\"\n num_rows, num_cols = self.lons.shape\n mid_row = num_rows // 2\n depth = 0\n if num_rows & 1 == 1:\n # there are odd number of rows\n mid_col = num_cols // 2\n if num_cols & 1 == 1:\n # odd number of columns, we can easily take\n # the middle point\n if self.depths is not None:\n depth = self.depths[mid_row][mid_col]\n return Point(self.lons[mid_row][mid_col],\n self.lats[mid_row][mid_col], depth)\n else:\n # even number of columns, need to take two middle\n # points on the middle row\n lon1, lon2 = self.lons[mid_row][mid_col - 1: mid_col + 1]\n lat1, lat2 = self.lats[mid_row][mid_col - 1: mid_col + 1]\n if self.depths is not None:\n depth1 = self.depths[mid_row][mid_col - 1]\n depth2 = self.depths[mid_row][mid_col]\n else:\n # there are even number of rows. take the row just above\n # and the one just below the middle and find middle point\n # of each\n submesh1 = self[mid_row - 1: mid_row]\n submesh2 = self[mid_row: mid_row + 1]\n p1, p2 = submesh1.get_middle_point(), submesh2.get_middle_point()\n lon1, lat1, depth1 = p1.longitude, p1.latitude, p1.depth\n lon2, lat2, depth2 = p2.longitude, p2.latitude, p2.depth\n\n # we need to find the middle between two points\n if self.depths is not None:\n depth = (depth1 + depth2) / 2.0\n lon, lat = geo_utils.get_middle_point(lon1, lat1, lon2, lat2)\n return Point(lon, lat, depth)\n\n def get_mean_inclination_and_azimuth(self):\n \"\"\"\n Calculate weighted average inclination and azimuth of the mesh surface.\n\n :returns:\n Tuple of two float numbers: inclination angle in a range [0, 90]\n and azimuth in range [0, 360) (in decimal degrees).\n\n The mesh is triangulated, the inclination and azimuth for each triangle\n is computed and average values weighted on each triangle's area\n are calculated. Azimuth is always defined in a way that inclination\n angle doesn't exceed 90 degree.\n \"\"\"\n assert 1 not in self.lons.shape, (\n \"inclination and azimuth are only defined for mesh of more than \"\n \"one row and more than one column of points\"\n )\n\n if self.depths is not None:\n assert ((self.depths[1:] - self.depths[:-1]) >= 0).all(), (\n \"get_mean_inclination_and_azimuth() requires next mesh row \"\n \"to be not shallower than the previous one\"\n )\n\n points, along_azimuth, updip, diag = self.triangulate()\n\n # define planes that are perpendicular to each point's vector\n # as normals to those planes\n earth_surface_tangent_normal = geo_utils.normalized(points)\n\n # calculating triangles' area and normals for top-left triangles\n e1 = along_azimuth[:-1]\n e2 = updip[:, :-1]\n tl_area = geo_utils.triangle_area(e1, e2, diag)\n tl_normal = geo_utils.normalized(numpy.cross(e1, e2))\n # ... and bottom-right triangles\n e1 = along_azimuth[1:]\n e2 = updip[:, 1:]\n br_area = geo_utils.triangle_area(e1, e2, diag)\n br_normal = geo_utils.normalized(numpy.cross(e1, e2))\n\n if self.depths is None:\n # mesh is on earth surface, inclination is zero\n inclination = 0\n else:\n # inclination calculation\n # top-left triangles\n en = earth_surface_tangent_normal[:-1, :-1]\n # cosine of inclination of the triangle is scalar product\n # of vector normal to triangle plane and (normalized) vector\n # pointing to top left corner of a triangle from earth center\n incl_cos = numpy.sum(en * tl_normal, axis=-1).clip(-1.0, 1.0)\n # we calculate average angle using mean of circular quantities\n # formula: define 2d vector for each triangle where length\n # of the vector corresponds to triangle's weight (we use triangle\n # area) and angle is equal to inclination angle. then we calculate\n # the angle of vector sum of all those vectors and that angle\n # is the weighted average.\n xx = numpy.sum(tl_area * incl_cos)\n # express sine via cosine using Pythagorean trigonometric identity,\n # this is a bit faster than sin(arccos(incl_cos))\n yy = numpy.sum(tl_area * numpy.sqrt(1 - incl_cos * incl_cos))\n\n # bottom-right triangles\n en = earth_surface_tangent_normal[1:, 1:]\n # we need to clip scalar product values because in some cases\n # they might exceed range where arccos is defined ([-1, 1])\n # because of floating point imprecision\n incl_cos = numpy.sum(en * br_normal, axis=-1).clip(-1.0, 1.0)\n # weighted angle vectors are calculated independently for top-left\n # and bottom-right triangles of each cell in a mesh. here we\n # combine both and finally get the weighted mean angle\n xx += numpy.sum(br_area * incl_cos)\n yy += numpy.sum(br_area * numpy.sqrt(1 - incl_cos * incl_cos))\n inclination = numpy.degrees(numpy.arctan2(yy, xx))\n\n # azimuth calculation is done similar to one for inclination. we also\n # do separate calculations for top-left and bottom-right triangles\n # and also combine results using mean of circular quantities approach\n\n # unit vector along z axis\n z_unit = numpy.array([0.0, 0.0, 1.0])\n\n # unit vectors pointing west from each point of the mesh, they define\n # planes that contain meridian of respective point\n norms_west = geo_utils.normalized(numpy.cross(points + z_unit, points))\n # unit vectors parallel to planes defined by previous ones. they are\n # directed from each point to a point lying on z axis on the same\n # distance from earth center\n norms_north = geo_utils.normalized(numpy.cross(points, norms_west))\n # need to normalize triangles' azimuthal edges because we will project\n # them on other normals and thus calculate an angle in between\n along_azimuth = geo_utils.normalized(along_azimuth)\n\n # process top-left triangles\n # here we identify the sign of direction of the triangles' azimuthal\n # edges: is edge pointing west or east? for finding that we project\n # those edges to vectors directing to west by calculating scalar\n # product and get the sign of resulting value: if it is negative\n # than the resulting azimuth should be negative as top edge is pointing\n # west.\n sign = numpy.sign(numpy.sign(\n numpy.sum(along_azimuth[:-1] * norms_west[:-1, :-1], axis=-1))\n # we run numpy.sign(numpy.sign(...) + 0.1) to make resulting values\n # be only either -1 or 1 with zero values (when edge is pointing\n # strictly north or south) expressed as 1 (which means \"don't\n # change the sign\")\n + 0.1\n )\n # the length of projection of azimuthal edge on norms_north is cosine\n # of edge's azimuth\n az_cos = numpy.sum(along_azimuth[:-1] * norms_north[:-1, :-1], axis=-1)\n # use the same approach for finding the weighted mean\n # as for inclination (see above)\n xx = numpy.sum(tl_area * az_cos)\n # the only difference is that azimuth is defined in a range\n # [0, 360), so we need to have two reference planes and change\n # sign of projection on one normal to sign of projection to another one\n yy = numpy.sum(tl_area * numpy.sqrt(1 - az_cos * az_cos) * sign)\n\n # bottom-right triangles\n sign = numpy.sign(numpy.sign(\n numpy.sum(along_azimuth[1:] * norms_west[1:, 1:], axis=-1))\n + 0.1\n )\n az_cos = numpy.sum(along_azimuth[1:] * norms_north[1:, 1:], axis=-1)\n xx += numpy.sum(br_area * az_cos)\n yy += numpy.sum(br_area * numpy.sqrt(1 - az_cos * az_cos) * sign)\n\n azimuth = numpy.degrees(numpy.arctan2(yy, xx))\n if azimuth < 0:\n azimuth += 360\n\n if inclination > 90:\n # average inclination is over 90 degree, that means that we need\n # to reverse azimuthal direction in order for inclination to be\n # in range [0, 90]\n inclination = 180 - inclination\n azimuth = (azimuth + 180) % 360\n\n return inclination, azimuth\n\n def get_cell_dimensions(self):\n \"\"\"\n Calculate centroid, width, length and area of each mesh cell.\n\n :returns:\n Tuple of four elements, each being 2d numpy array.\n Each array has both dimensions less by one the dimensions\n of the mesh, since they represent cells, not vertices.\n Arrays contain the following cell information:\n\n #. centroids, 3d vectors in a Cartesian space,\n #. length (size along row of points) in km,\n #. width (size along column of points) in km,\n #. area in square km.\n \"\"\"\n points, along_azimuth, updip, diag = self.triangulate()\n top = along_azimuth[:-1]\n left = updip[:, :-1]\n tl_area = geo_utils.triangle_area(top, left, diag)\n top_length = numpy.sqrt(numpy.sum(top * top, axis=-1))\n left_length = numpy.sqrt(numpy.sum(left * left, axis=-1))\n\n bottom = along_azimuth[1:]\n right = updip[:, 1:]\n br_area = geo_utils.triangle_area(bottom, right, diag)\n bottom_length = numpy.sqrt(numpy.sum(bottom * bottom, axis=-1))\n right_length = numpy.sqrt(numpy.sum(right * right, axis=-1))\n\n cell_area = tl_area + br_area\n\n tl_center = (points[:-1, :-1] + points[:-1, 1:] + points[1:, :-1]) / 3\n br_center = (points[:-1, 1:] + points[1:, :-1] + points[1:, 1:]) / 3\n\n cell_center = ((tl_center * tl_area.reshape(tl_area.shape + (1, ))\n + br_center * br_area.reshape(br_area.shape + (1, )))\n / cell_area.reshape(cell_area.shape + (1, )))\n\n cell_length = ((top_length * tl_area + bottom_length * br_area)\n / cell_area)\n cell_width = ((left_length * tl_area + right_length * br_area)\n / cell_area)\n\n return cell_center, cell_length, cell_width, cell_area\n\n def triangulate(self):\n \"\"\"\n Convert mesh points to vectors in Cartesian space.\n\n :returns:\n Tuple of four elements, each being 2d numpy array of 3d vectors\n (the same structure and shape as the mesh itself). Those arrays\n are:\n\n #. points vectors,\n #. vectors directed from each point (excluding the last column)\n to the next one in a same row →,\n #. vectors directed from each point (excluding the first row)\n to the previous one in a same column ↑,\n #. vectors pointing from a bottom left point of each mesh cell\n to top right one ↗.\n\n So the last three arrays of vectors allow to construct triangles\n covering the whole mesh.\n \"\"\"\n points = geo_utils.spherical_to_cartesian(self.lons, self.lats,\n self.depths)\n # triangulate the mesh by defining vectors of triangles edges:\n # →\n along_azimuth = points[:, 1:] - points[:, :-1]\n # ↑\n updip = points[:-1] - points[1:]\n # ↗\n diag = points[:-1, 1:] - points[1:, :-1]\n\n return points, along_azimuth, updip, diag\n\n def get_mean_width(self):\n \"\"\"\n Calculate and return (weighted) mean width (km) of a mesh surface.\n\n The length of each mesh column is computed (summing up the cell widths\n in a same column), and the mean value (weighted by the mean cell\n length in each column) is returned.\n \"\"\"\n assert 1 not in self.lons.shape, (\n \"mean width is only defined for mesh of more than \"\n \"one row and more than one column of points\")\n\n _, cell_length, cell_width, cell_area = self.get_cell_dimensions()\n\n # compute widths along each mesh column\n widths = numpy.sum(cell_width, axis=0)\n\n # compute (weighted) mean cell length along each mesh column\n column_areas = numpy.sum(cell_area, axis=0)\n mean_cell_lengths = numpy.sum(cell_length * cell_area, axis=0) / \\\n column_areas\n\n # compute and return weighted mean\n return numpy.sum(widths * mean_cell_lengths) / \\\n numpy.sum(mean_cell_lengths)\n", "meta": {"hexsha": "18edb07affe393eac4e2beaffefe3389cff436b5", "size": 34624, "ext": "py", "lang": "Python", "max_stars_repo_path": "openquake.hazardlib/openquake/hazardlib/geo/mesh.py", "max_stars_repo_name": "rainzhop/ConvNetQuake", "max_stars_repo_head_hexsha": "a3e6de3f7992eac72f1b9883fec36b8c7fdefd48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "openquake.hazardlib/openquake/hazardlib/geo/mesh.py", "max_issues_repo_name": "rainzhop/ConvNetQuake", "max_issues_repo_head_hexsha": "a3e6de3f7992eac72f1b9883fec36b8c7fdefd48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openquake.hazardlib/openquake/hazardlib/geo/mesh.py", "max_forks_repo_name": "rainzhop/ConvNetQuake", "max_forks_repo_head_hexsha": "a3e6de3f7992eac72f1b9883fec36b8c7fdefd48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.6070528967, "max_line_length": 103, "alphanum_fraction": 0.6121187616, "include": true, "reason": "import numpy", "num_tokens": 7849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.28776780965284365, "lm_q1q2_score": 0.14837881376099607}} {"text": "# coding: utf-8\n# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License.\n\nfrom __future__ import division, unicode_literals\n\nimport logging\nimport numpy as np\nimport itertools\n\nfrom scipy.spatial import ConvexHull\nfrom pymatgen.analysis.pourbaix.entry import MultiEntry, ion_or_solid_comp_object\nfrom pymatgen.core.periodic_table import Element\nfrom pymatgen.core.composition import Composition\nfrom pymatgen.entries.computed_entries import ComputedEntry\nfrom pymatgen.analysis.reaction_calculator import Reaction, ReactionError\nfrom pymatgen.analysis.phase_diagram import PhaseDiagram\n\n\"\"\"\nModule containing analysis classes which compute a pourbaix diagram given a\ntarget compound/element.\n\"\"\"\n\nfrom six.moves import zip\n\n__author__ = \"Sai Jayaraman\"\n__copyright__ = \"Copyright 2012, The Materials Project\"\n__version__ = \"0.0\"\n__maintainer__ = \"Sai Jayaraman\"\n__credits__ = \"Arunima Singh, Joseph Montoya\"\n__email__ = \"sjayaram@mit.edu\"\n__status__ = \"Development\"\n__date__ = \"Nov 1, 2012\"\n\n\nlogger = logging.getLogger(__name__)\n\nPREFAC = 0.0591\nMU_H2O = -2.4583\nelements_HO = {Element('H'), Element('O')}\n# TODO: There's a lot of functionality here that diverges\n# based on whether or not the pbx diagram is multielement\n# or not. Could be a more elegant way to\n# treat the two distinct modes.\n\nclass PourbaixDiagram(object):\n \"\"\"\n Class to create a Pourbaix diagram from entries\n\n Args:\n entries [Entry]: Entries list containing both Solids and Ions\n comp_dict {str: float}: Dictionary of compositions, defaults to\n equal parts of each elements\n conc_dict {str: float}: Dictionary of ion concentrations, defaults\n to 1e-6 for each element\n filter_multielement (bool): applying this filter to a multi-\n element pourbaix diagram makes generates it a bit more\n efficiently by filtering the entries used to generate\n the hull. This breaks some of the functionality of\n the analyzer, though, so use with caution.\n \"\"\"\n def __init__(self, entries, comp_dict=None, conc_dict=None,\n filter_multielement=False):\n # Get non-OH elements\n pbx_elts = set(itertools.chain.from_iterable(\n [entry.composition.elements for entry in entries]))\n pbx_elts = list(pbx_elts - elements_HO)\n\n # Set default conc/comp dicts\n if not comp_dict:\n comp_dict = {elt.symbol : 1. / len(pbx_elts) for elt in pbx_elts}\n if not conc_dict:\n conc_dict = {elt.symbol : 1e-6 for elt in pbx_elts}\n\n self._elt_comp = comp_dict\n self.pourbaix_elements = pbx_elts\n\n solid_entries = [entry for entry in entries\n if entry.phase_type == \"Solid\"]\n ion_entries = [entry for entry in entries\n if entry.phase_type == \"Ion\"]\n\n for entry in ion_entries:\n ion_elts = list(set(entry.composition.elements) - elements_HO)\n if len(ion_elts) != 1:\n raise ValueError(\"Elemental concentration not compatible \"\n \"with multi-element ions\")\n entry.conc = conc_dict[ion_elts[0].symbol]\n\n if not len(solid_entries + ion_entries) == len(entries):\n raise ValueError(\"All supplied entries must have a phase type of \"\n \"either \\\"Solid\\\" or \\\"Ion\\\"\")\n\n self._unprocessed_entries = entries\n\n if len(comp_dict) > 1:\n self._multielement = True\n if filter_multielement:\n # Add two high-energy H/O entries that ensure the hull\n # includes all stable solids.\n entries_HO = [ComputedEntry('H', 10000), ComputedEntry('O', 10000)]\n solid_pd = PhaseDiagram(solid_entries + entries_HO)\n solid_entries = list(set(solid_pd.stable_entries) - set(entries_HO))\n self._processed_entries = self._generate_multielement_entries(\n solid_entries + ion_entries)\n else:\n self._multielement = False\n\n self._processed_entries = solid_entries + ion_entries\n self._make_pourbaix_diagram()\n\n def _create_conv_hull_data(self):\n \"\"\"\n Make data conducive to convex hull generator.\n \"\"\"\n entries_to_process = list()\n for entry in self._processed_entries:\n entry.scale(entry.normalization_factor)\n entry.correction += (- MU_H2O * entry.nH2O + entry.conc_term)\n entries_to_process.append(entry)\n self._qhull_entries = entries_to_process\n return self._process_conv_hull_data(entries_to_process)\n\n def _process_conv_hull_data(self, entries_to_process):\n \"\"\"\n From a sequence of ion+solid entries, generate the necessary data\n for generation of the convex hull.\n \"\"\"\n data = []\n for entry in entries_to_process:\n row = [entry.npH, entry.nPhi, entry.g0]\n data.append(row)\n temp = sorted(zip(data, self._qhull_entries),\n key=lambda x: x[0][2])\n [data, self._qhull_entries] = list(zip(*temp))\n return data\n\n def _generate_multielement_entries(self, entries):\n \"\"\"\n Create entries for multi-element Pourbaix construction.\n\n This works by finding all possible linear combinations\n of entries that can result in the specified composition\n from the initialized comp_dict.\n\n Args:\n entries ([PourbaixEntries]): list of pourbaix entries\n to process into MultiEntries\n \"\"\"\n N = len(self._elt_comp) # No. of elements\n total_comp = Composition(self._elt_comp)\n\n # generate all possible combinations of compounds that have all elts\n entry_combos = [itertools.combinations(entries, j+1) for j in range(N)]\n entry_combos = itertools.chain.from_iterable(entry_combos)\n entry_combos = filter(lambda x: total_comp < MultiEntry(x).total_composition, \n entry_combos)\n\n # Generate and filter entries\n processed_entries = []\n for entry_combo in entry_combos:\n processed_entry = self.process_multientry(entry_combo, total_comp)\n if processed_entry is not None:\n processed_entries.append(processed_entry)\n\n return processed_entries\n\n @staticmethod\n def process_multientry(entry_list, prod_comp):\n \"\"\"\n Static method for finding a multientry based on\n a list of entries and a product composition.\n Essentially checks to see if a valid aqueous\n reaction exists between the entries and the \n product composition and returns a MultiEntry\n with weights according to the coefficients if so.\n\n Args:\n entry_list ([Entry]): list of entries from which to\n create a MultiEntry\n comp (Composition): composition constraint for setting\n weights of MultiEntry\n \"\"\"\n dummy_oh = [Composition(\"H\"), Composition(\"O\")]\n try:\n # Get balanced reaction coeffs, ensuring all < 0 or conc thresh\n # Note that we get reduced compositions for solids and non-reduced \n # compositions for ions because ions aren't normalized due to\n # their charge state.\n entry_comps = [e.composition if e.phase_type=='Ion'\n else e.composition.reduced_composition \n for e in entry_list]\n rxn = Reaction(entry_comps + dummy_oh, [prod_comp])\n thresh = np.array([pe.conc if pe.phase_type == \"Ion\"\n else 1e-3 for pe in entry_list])\n coeffs = -np.array([rxn.get_coeff(comp) for comp in entry_comps])\n if (coeffs > thresh).all():\n weights = coeffs / coeffs[0]\n return MultiEntry(entry_list, weights=weights.tolist())\n else:\n return None\n except ReactionError:\n return None\n\n def _make_pourbaix_diagram(self):\n \"\"\"\n Calculates entries on the convex hull in the dual space.\n \"\"\"\n stable_entries = set()\n self._qhull_data = self._create_conv_hull_data()\n dim = len(self._qhull_data[0])\n if len(self._qhull_data) < dim:\n # TODO: might want to lift this restriction and\n # supply a warning instead, should work even if it's slow.\n raise NotImplementedError(\"Can only do elements with at-least \"\n \"3 entries for now\")\n if len(self._qhull_data) == dim:\n self._facets = [list(range(dim))]\n else:\n facets_hull = np.array(ConvexHull(self._qhull_data).simplices)\n self._facets = np.sort(np.array(facets_hull))\n logger.debug(\"Final facets are\\n{}\".format(self._facets))\n\n logger.debug(\"Removing vertical facets...\")\n vert_facets_removed = list()\n for facet in self._facets:\n facetmatrix = np.zeros((len(facet), len(facet)))\n count = 0\n for vertex in facet:\n facetmatrix[count] = np.array(self._qhull_data[vertex])\n facetmatrix[count, dim - 1] = 1\n count += 1\n if abs(np.linalg.det(facetmatrix)) > 1e-8:\n vert_facets_removed.append(facet)\n else:\n logger.debug(\"Removing vertical facet : {}\".format(facet))\n\n logger.debug(\"Removing UCH facets by eliminating normal.z >0 ...\")\n\n # Find center of hull\n vertices = set()\n for facet in vert_facets_removed:\n for vertex in facet:\n vertices.add(vertex)\n c = [0.0, 0.0, 0.0]\n c[0] = np.average([self._qhull_data[vertex][0]\n for vertex in vertices])\n c[1] = np.average([self._qhull_data[vertex][1]\n for vertex in vertices])\n c[2] = np.average([self._qhull_data[vertex][2]\n for vertex in vertices])\n\n # Shift origin to c\n new_qhull_data = np.array(self._qhull_data)\n for vertex in vertices:\n new_qhull_data[vertex] -= c\n\n # For each facet, find normal n, find dot product with P, and\n # check if this is -ve\n final_facets = list()\n for facet in vert_facets_removed:\n a = new_qhull_data[facet[1]] - new_qhull_data[facet[0]]\n b = new_qhull_data[facet[2]] - new_qhull_data[facet[0]]\n n = np.cross(a, b)\n val = np.dot(n, new_qhull_data[facet[0]])\n if val < 0:\n n = -n\n if n[2] <= 0:\n final_facets.append(facet)\n else:\n logger.debug(\"Removing UCH facet : {}\".format(facet))\n final_facets = np.array(final_facets)\n self._facets = final_facets\n\n stable_vertices = set()\n for facet in self._facets:\n for vertex in facet:\n stable_vertices.add(vertex)\n stable_entries.add(self._qhull_entries[vertex])\n self._stable_entries = stable_entries\n self._vertices = stable_vertices\n\n @property\n def facets(self):\n \"\"\"\n Facets of the convex hull in the form of [[1,2,3],[4,5,6]...]\n \"\"\"\n return self._facets\n\n @property\n def qhull_data(self):\n \"\"\"\n Data used in the convex hull operation. This is essentially a matrix of\n composition data and energy per atom values created from qhull_entries.\n \"\"\"\n return self._qhull_data\n\n @property\n def qhull_entries(self):\n \"\"\"\n Return qhull entries\n \"\"\"\n return self._qhull_entries\n\n @property\n def stable_entries(self):\n \"\"\"\n Returns the stable entries in the Pourbaix diagram.\n \"\"\"\n return list(self._stable_entries)\n \n @property\n def unstable_entries(self):\n \"\"\"\n Returns all unstable entries in the Pourbaix diagram\n \"\"\"\n return [e for e in self.qhull_entries if e not in self.stable_entries]\n\n @property\n def all_entries(self):\n \"\"\"\n Return all entries used to generate the pourbaix diagram\n \"\"\"\n return self._processed_entries\n\n @property\n def vertices(self):\n \"\"\"\n Return vertices of the convex hull\n \"\"\"\n return self._vertices\n\n @property\n def unprocessed_entries(self):\n \"\"\"\n Return unprocessed entries\n \"\"\"\n return self._unprocessed_entries\n", "meta": {"hexsha": "97ed85db4c8476f7b3e9a71151fc4f062e52e784", "size": 12869, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymatgen/analysis/pourbaix/maker.py", "max_stars_repo_name": "frssp/pymatgen", "max_stars_repo_head_hexsha": "bdd977f065b66191557c7398b31a1571bc541fdb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-11T20:57:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T05:00:42.000Z", "max_issues_repo_path": "pymatgen/analysis/pourbaix/maker.py", "max_issues_repo_name": "frssp/pymatgen", "max_issues_repo_head_hexsha": "bdd977f065b66191557c7398b31a1571bc541fdb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pymatgen/analysis/pourbaix/maker.py", "max_forks_repo_name": "frssp/pymatgen", "max_forks_repo_head_hexsha": "bdd977f065b66191557c7398b31a1571bc541fdb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-14T19:47:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-02T08:10:45.000Z", "avg_line_length": 37.9616519174, "max_line_length": 86, "alphanum_fraction": 0.6022223949, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.14837881262662073}} {"text": "import numpy as np\nimport os,xml.etree.ElementTree as ET\nimport cv2\nimport matplotlib.pyplot as plt\nfrom glob import glob\nfrom concurrent.futures import ThreadPoolExecutor\nimport tensorflow as tf\nfrom PIL import Image,ImageDraw\nfrom math import *\nanchor_scale = 16\n#\nIOU_NEGATIVE = 0.3\nIOU_POSITIVE = 0.7\nIOU_SELECT = 0.7\n\nRPN_POSITIVE_NUM = 150\nRPN_TOTAL_NUM = 300\n\n# bgr can find from here https://github.com/fchollet/deep-learning-models/blob/master/imagenet_utils.py\nIMAGE_MEAN = [123.68, 116.779, 103.939]\n\nDEBUG = True\ndef rotate(img_path,degree=90):\n\n img=cv2.imread(img_path)\n height, width = img.shape[:2]\n\n # 旋转后的尺寸\n heightNew = int(width * fabs(sin(radians(degree))) + height * fabs(cos(radians(degree)))) # 这个公式参考之前内容\n widthNew = int(height * fabs(sin(radians(degree))) + width * fabs(cos(radians(degree))))\n\n matRotation = cv2.getRotationMatrix2D((width / 2, height / 2), degree, 1)\n\n matRotation[0, 2] += (widthNew - width) / 2 # 因为旋转之后,坐标系原点是新图像的左上角,所以需要根据原图做转化\n matRotation[1, 2] += (heightNew - height) / 2\n\n imgRotation = cv2.warpAffine(img, matRotation, (widthNew, heightNew), borderValue=(255, 255, 255))\n\n return Image.fromarray(imgRotation)\n\ndef drawRect(gtboxes,img):\n draw=ImageDraw.Draw(img)\n for i in gtboxes:\n draw.rectangle((i[0],i[1],i[2],i[3]),outline='red')\n img.show()\n\ndef readxml(path):\n gtboxes=[]\n tree=ET.parse(path)\n root=tree.getroot()\n image_name = tree.find('filename').text\n for obj in root.iter('object'):\n try:\n bnd=obj.find('bndbox')\n xmin=int(bnd.find('xmin').text)\n ymin=int(bnd.find('ymin').text)\n xmax=int(bnd.find('xmax').text)\n ymax=int(bnd.find('ymax').text)\n gtboxes.append((xmin,ymin,xmax,ymax))\n except Exception as e:\n raise Exception(e+\" when {} loading xml file, there are errors\".format(path))\n return np.array(gtboxes),image_name\n\n\ndef gen_anchor(featuresize, scale):\n \"\"\"\n gen base anchor from feature map [HXW][10][4]\n reshape [HXW][10][4] to [HXWX10][4]\n 生成的锚框是相对于原图的,即原图中每16像素就有10个锚框\n \"\"\"\n\n heights = [11, 16, 23, 33, 48, 68, 97, 139, 198, 283]\n widths = [16, 16, 16, 16, 16, 16, 16, 16, 16, 16]\n\n # gen k=9 anchor size (h,w)\n heights = np.array(heights).reshape(len(heights), 1)\n widths = np.array(widths).reshape(len(widths), 1)\n\n # 锚框大小为16像素\n base_anchor = np.array([0, 0, 15, 15])\n # center x,y\n xt = (base_anchor[0] + base_anchor[2]) * 0.5\n yt = (base_anchor[1] + base_anchor[3]) * 0.5\n\n # x1 y1 x2 y2\n x1 = xt - widths * 0.5\n y1 = yt - heights * 0.5\n x2 = xt + widths * 0.5\n y2 = yt + heights * 0.5\n\n # 一组十个锚框\n base_anchor = np.hstack((x1, y1, x2, y2))\n\n h, w = featuresize\n shift_x = np.arange(0, w) * scale\n shift_y = np.arange(0, h) * scale\n # apply shift\n anchor = []\n for i in shift_y:\n for j in shift_x:\n anchor.append(base_anchor + [j, i, j, i])\n return np.array(anchor).reshape((-1, 4))\n\n\ndef cal_iou(box1, box1_area, boxes2, boxes2_area):\n \"\"\"\n box1 [x1,y1,x2,y2]\n boxes2 [Msample,x1,y1,x2,y2]\n \"\"\"\n x1 = np.maximum(box1[0], boxes2[:, 0])\n x2 = np.minimum(box1[2], boxes2[:, 2])\n y1 = np.maximum(box1[1], boxes2[:, 1])\n y2 = np.minimum(box1[3], boxes2[:, 3])\n\n intersection = np.maximum(x2 - x1, 0) * np.maximum(y2 - y1, 0)\n iou = intersection / (box1_area + boxes2_area[:] - intersection[:])\n return iou\n\n\ndef cal_overlaps(boxes1, boxes2):\n \"\"\"\n boxes1 [Nsample,x1,y1,x2,y2] anchor\n boxes2 [Msample,x1,y1,x2,y2] grouth-box\n\n \"\"\"\n area1 = (boxes1[:, 0] - boxes1[:, 2]) * (boxes1[:, 1] - boxes1[:, 3]) # (Nsample, 1)\n area2 = (boxes2[:, 0] - boxes2[:, 2]) * (boxes2[:, 1] - boxes2[:, 3]) # (Msample, 1)\n\n overlaps = np.zeros((boxes1.shape[0], boxes2.shape[0])) # (Nsample, Msample)\n\n # calculate the intersection of boxes1(anchor) and boxes2(GT box)\n for i in range(boxes1.shape[0]):\n overlaps[i][:] = cal_iou(boxes1[i], area1[i], boxes2, area2)\n\n return overlaps\n\n\ndef bbox_transfrom(anchors, gtboxes):\n \"\"\"\n anchors: (Nsample, 4)\n gtboxes: (Nsample, 4)\n compute relative predicted vertical coordinates Vc ,Vh\n with respect to the bounding box location of an anchor\n \"\"\"\n Cy = (gtboxes[:, 1] + gtboxes[:, 3]) * 0.5 # (Nsample, )\n Cya = (anchors[:, 1] + anchors[:, 3]) * 0.5 # (Nsample, )\n h = gtboxes[:, 3] - gtboxes[:, 1] + 1.0 # (Nsample, )\n ha = anchors[:, 3] - anchors[:, 1] + 1.0 # (Nsample, )\n\n Vc = (Cy - Cya) / ha # (Nsample, )\n Vh = np.log(h / ha) # (Nsample, )\n\n ret = np.vstack((Vc, Vh))\n\n return ret.transpose() # (Nsample, 2)\n\n\ndef bbox_transfor_inv(anchor, regr):\n \"\"\"\n anchor: (NSample, 4)\n regr: (NSample, 2)\n 根据锚框和偏移量反向得到GTBox\n \"\"\"\n\n Cya = (anchor[:, 1] + anchor[:, 3]) * 0.5 # 锚框y中心点\n ha = anchor[:, 3] - anchor[:, 1] + 1\n\n Vcx = regr[..., 0] # y中心点偏移\n Vhx = regr[..., 1] # 高度偏移\n\n Cyx = Vcx * ha + Cya # GTBox y中心点\n hx = np.exp(Vhx) * ha # GTBox 高\n xt = (anchor[:, 0] + anchor[:, 2]) * 0.5 # 锚框x中心点\n\n x1 = xt - 16 * 0.5\n y1 = Cyx - hx * 0.5\n x2 = xt + 16 * 0.5\n y2 = Cyx + hx * 0.5\n bbox = np.vstack((x1, y1, x2, y2)).transpose()\n\n return bbox\n\n\ndef clip_box(bbox, im_shape):\n # x1 >= 0\n bbox[:, 0] = np.maximum(np.minimum(bbox[:, 0], im_shape[1] - 1), 0)\n # y1 >= 0\n bbox[:, 1] = np.maximum(np.minimum(bbox[:, 1], im_shape[0] - 1), 0)\n # x2 < im_shape[1]\n bbox[:, 2] = np.maximum(np.minimum(bbox[:, 2], im_shape[1] - 1), 0)\n # y2 < im_shape[0]\n bbox[:, 3] = np.maximum(np.minimum(bbox[:, 3], im_shape[0] - 1), 0)\n\n return bbox\n\n\ndef filter_bbox(bbox, minsize):\n ws = bbox[:, 2] - bbox[:, 0] + 1\n hs = bbox[:, 3] - bbox[:, 1] + 1\n keep = np.where((ws >= minsize) & (hs >= minsize))[0]\n return keep\n\n\ndef cal_rpn(imgsize, featuresize, scale, gtboxes):\n \"\"\"\n gtboxes: (Msample, 4)\n \"\"\"\n imgh, imgw = imgsize\n\n # gen base anchor\n base_anchor = gen_anchor(featuresize, scale) # (Nsample, 4)\n\n # calculate iou\n overlaps = cal_overlaps(base_anchor, gtboxes) # (Nsample, Msample)\n\n # init labels -1 don't care 0 is negative 1 is positive\n labels = np.empty(base_anchor.shape[0])\n labels.fill(-1) # (Nsample,)\n\n # for each GT box corresponds to an anchor which has highest IOU\n gt_argmax_overlaps = overlaps.argmax(axis=0) # (Msample, )\n\n # the anchor with the highest IOU overlap with a GT box\n anchor_argmax_overlaps = overlaps.argmax(axis=1) # (Nsample, )\n anchor_max_overlaps = overlaps[range(overlaps.shape[0]), anchor_argmax_overlaps] # (Nsample, )\n print('anchor max overlaps')\n for i in anchor_max_overlaps:\n if i>IOU_POSITIVE:\n print(i)\n\n # IOU > IOU_POSITIVE\n labels[anchor_max_overlaps > IOU_POSITIVE] = 1\n # IOU = imgw) |\n (base_anchor[:, 3] >= imgh)\n )[0]\n labels[outside_anchor] = -1\n\n # 剔除掉多余的正负样例\n # subsample positive labels ,if greater than RPN_POSITIVE_NUM(default 128)\n fg_index = np.where(labels == 1)[0]\n if (len(fg_index) > RPN_POSITIVE_NUM):\n labels[np.random.choice(fg_index, len(fg_index) - RPN_POSITIVE_NUM, replace=False)] = -1\n\n # subsample negative labels\n bg_index = np.where(labels == 0)[0]\n num_bg = RPN_TOTAL_NUM - np.sum(labels == 1)\n if (len(bg_index) > num_bg):\n # print('bgindex:',len(bg_index),'num_bg',num_bg)\n labels[np.random.choice(bg_index, len(bg_index) - num_bg, replace=False)] = -1\n\n # calculate bbox targets\n # debug here\n bbox_targets = bbox_transfrom(base_anchor, gtboxes[anchor_argmax_overlaps, :])\n # bbox_targets=[]\n\n return [labels, bbox_targets], base_anchor\n\n\ndef get_session(gpu_fraction=0.6):\n '''''Assume that you have 6GB of GPU memory and want to allocate ~2GB'''\n\n num_threads = os.environ.get('OMP_NUM_THREADS')\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_fraction)\n\n if num_threads:\n return tf.Session(config=tf.ConfigProto(\n gpu_options=gpu_options, intra_op_parallelism_threads=num_threads, allow_soft_placement=True))\n else:\n return tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, allow_soft_placement=True))\n\n\nclass random_uniform_num():\n \"\"\"\n uniform random\n \"\"\"\n\n def __init__(self, total, start=0):\n self.total = total\n self.range = [i for i in range(total)]\n np.random.shuffle(self.range)\n self.index = start\n\n def get(self, batch_size):\n ret = []\n if self.index + batch_size > self.total:\n piece1 = self.range[self.index:]\n np.random.shuffle(self.range)\n self.index = (self.index + batch_size) - self.total\n piece2 = self.range[0:self.index]\n ret.extend(piece1)\n ret.extend(piece2)\n else:\n ret = self.range[self.index:self.index + batch_size]\n self.index = self.index + batch_size\n return ret\n\n\ndef nms(dets, thresh):\n x1 = dets[:, 0]\n y1 = dets[:, 1]\n x2 = dets[:, 2]\n y2 = dets[:, 3]\n scores = dets[:, 4]\n\n areas = (x2 - x1 + 1) * (y2 - y1 + 1)\n order = scores.argsort()[::-1] # Sort from high to low\n\n keep = []\n while order.size > 0:\n i = order[0]\n keep.append(i)\n xx1 = np.maximum(x1[i], x1[order[1:]])\n yy1 = np.maximum(y1[i], y1[order[1:]])\n xx2 = np.minimum(x2[i], x2[order[1:]])\n yy2 = np.minimum(y2[i], y2[order[1:]])\n\n w = np.maximum(0.0, xx2 - xx1 + 1)\n h = np.maximum(0.0, yy2 - yy1 + 1)\n inter = w * h\n ovr = inter / (areas[i] + areas[order[1:]] - inter)\n\n inds = np.where(ovr <= thresh)[0]\n order = order[inds + 1]\n return keep\n\n\ndef gen_sample(xmlpath, imgpath, batchsize=1):\n \"\"\"\n 由于图像大小不定,批处理大小只能为1\n \"\"\"\n\n # list xml\n xmlfiles = glob(xmlpath + '/*.xml')\n rd = random_uniform_num(len(xmlfiles))\n xmlfiles = np.array(xmlfiles)\n\n while True:\n shuf = xmlfiles[rd.get(1)]\n gtbox, imgfile = readxml(shuf[0])\n img = cv2.imread(imgpath + \"\\\\\" + imgfile)\n h, w, c = img.shape\n\n # clip image\n if np.random.randint(0, 100) > 50:\n img = img[:, ::-1, :]\n newx1 = w - gtbox[:, 2] - 1\n newx2 = w - gtbox[:, 0] - 1\n gtbox[:, 0] = newx1\n gtbox[:, 2] = newx2\n\n [cls, regr], _ = cal_rpn((h, w), (int(h / 16), int(w / 16)), 16, gtbox)\n # zero-center by mean pixel\n m_img = img - IMAGE_MEAN\n m_img = np.expand_dims(m_img, axis=0)\n\n regr = np.hstack([cls.reshape(cls.shape[0], 1), regr])\n\n #\n cls = np.expand_dims(cls, axis=0)\n cls = np.expand_dims(cls, axis=1)\n # regr = np.expand_dims(regr,axis=1)\n regr = np.expand_dims(regr, axis=0)\n\n yield m_img, {'rpn_class_reshape': cls, 'rpn_regress_reshape': regr}\n\n\ndef rpn_test():\n xmlpath = 'G:\\data\\VOCdevkit\\VOC2007\\Annotations\\img_4375.xml'\n imgpath = 'G:\\data\\VOCdevkit\\VOC2007\\JPEGImages\\img_4375.jpg'\n gtbox, _ = readxml(xmlpath)\n img = cv2.imread(imgpath)\n h, w, c = img.shape\n [cls, regr], base_anchor = cal_rpn((h, w), (int(h / 16), int(w / 16)), 16, gtbox)\n print(cls.shape)\n print(regr.shape)\n\n regr = np.expand_dims(regr, axis=0)\n inv_anchor = bbox_transfor_inv(base_anchor, regr)\n anchors = inv_anchor[cls == 1]\n anchors = anchors.astype(int)\n for i in anchors:\n cv2.rectangle(img, (i[0], i[1]), (i[2], i[3]), (255, 0, 0), 3)\n plt.imshow(img)\n\n\ndef threshold(coords, min_, max_):\n return np.maximum(np.minimum(coords, max_), min_)\n\ndef clip_boxes(boxes, im_shape):\n \"\"\"\n Clip boxes to image boundaries.\n \"\"\"\n boxes[:, 0::2]=threshold(boxes[:, 0::2], 0, im_shape[1]-1)\n boxes[:, 1::2]=threshold(boxes[:, 1::2], 0, im_shape[0]-1)\n return boxes\n\n\nclass Graph:\n def __init__(self, graph):\n self.graph=graph\n\n def sub_graphs_connected(self):\n sub_graphs=[]\n for index in range(self.graph.shape[0]):\n if not self.graph[:, index].any() and self.graph[index, :].any():\n v=index\n sub_graphs.append([v])\n while self.graph[v, :].any():\n v=np.where(self.graph[v, :])[0][0]\n sub_graphs[-1].append(v)\n return sub_graphs\nclass TextLineCfg:\n SCALE=600\n MAX_SCALE=1200\n TEXT_PROPOSALS_WIDTH=16\n MIN_NUM_PROPOSALS = 2\n MIN_RATIO=0.5\n LINE_MIN_SCORE=0.9\n MAX_HORIZONTAL_GAP=60\n TEXT_PROPOSALS_MIN_SCORE=0.7\n TEXT_PROPOSALS_NMS_THRESH=0.3\n MIN_V_OVERLAPS=0.6\n MIN_SIZE_SIM=0.6\n\nclass TextProposalGraphBuilder:\n \"\"\"\n Build Text proposals into a graph.\n \"\"\"\n def get_successions(self, index):\n box=self.text_proposals[index]\n results=[]\n for left in range(int(box[0])+1, min(int(box[0])+TextLineCfg.MAX_HORIZONTAL_GAP+1, self.im_size[1])):\n adj_box_indices=self.boxes_table[left]\n for adj_box_index in adj_box_indices:\n if self.meet_v_iou(adj_box_index, index):\n results.append(adj_box_index)\n if len(results)!=0:\n return results\n return results\n\n def get_precursors(self, index):\n box=self.text_proposals[index]\n results=[]\n for left in range(int(box[0])-1, max(int(box[0]-TextLineCfg.MAX_HORIZONTAL_GAP), 0)-1, -1):\n adj_box_indices=self.boxes_table[left]\n for adj_box_index in adj_box_indices:\n if self.meet_v_iou(adj_box_index, index):\n results.append(adj_box_index)\n if len(results)!=0:\n return results\n return results\n\n def is_succession_node(self, index, succession_index):\n precursors=self.get_precursors(succession_index)\n if self.scores[index]>=np.max(self.scores[precursors]):\n return True\n return False\n\n def meet_v_iou(self, index1, index2):\n def overlaps_v(index1, index2):\n h1=self.heights[index1]\n h2=self.heights[index2]\n y0=max(self.text_proposals[index2][1], self.text_proposals[index1][1])\n y1=min(self.text_proposals[index2][3], self.text_proposals[index1][3])\n return max(0, y1-y0+1)/min(h1, h2)\n\n def size_similarity(index1, index2):\n h1=self.heights[index1]\n h2=self.heights[index2]\n return min(h1, h2)/max(h1, h2)\n\n return overlaps_v(index1, index2)>=TextLineCfg.MIN_V_OVERLAPS and \\\n size_similarity(index1, index2)>=TextLineCfg.MIN_SIZE_SIM\n\n def build_graph(self, text_proposals, scores, im_size):\n self.text_proposals=text_proposals\n self.scores=scores\n self.im_size=im_size\n self.heights=text_proposals[:, 3]-text_proposals[:, 1]+1\n\n boxes_table=[[] for _ in range(self.im_size[1])]\n for index, box in enumerate(text_proposals):\n boxes_table[int(box[0])].append(index)\n self.boxes_table=boxes_table\n\n graph=np.zeros((text_proposals.shape[0], text_proposals.shape[0]), np.bool)\n\n for index, box in enumerate(text_proposals):\n successions=self.get_successions(index)\n if len(successions)==0:\n continue\n succession_index=successions[np.argmax(scores[successions])]\n if self.is_succession_node(index, succession_index):\n # NOTE: a box can have multiple successions(precursors) if multiple successions(precursors)\n # have equal scores.\n graph[index, succession_index]=True\n return Graph(graph)\nclass TextProposalConnector:\n def __init__(self):\n self.graph_builder=TextProposalGraphBuilder()\n\n def group_text_proposals(self, text_proposals, scores, im_size):\n graph=self.graph_builder.build_graph(text_proposals, scores, im_size)\n return graph.sub_graphs_connected()\n\n def fit_y(self, X, Y, x1, x2):\n len(X)!=0\n # if X only include one point, the function will get line y=Y[0]\n if np.sum(X==X[0])==len(X):\n return Y[0], Y[0]\n p=np.poly1d(np.polyfit(X, Y, 1))\n return p(x1), p(x2)\n\n def get_text_lines(self, text_proposals, scores, im_size):\n # tp=text proposal\n tp_groups=self.group_text_proposals(text_proposals, scores, im_size)\n text_lines=np.zeros((len(tp_groups), 5), np.float32)\n\n for index, tp_indices in enumerate(tp_groups):\n text_line_boxes=text_proposals[list(tp_indices)]\n\n x0=np.min(text_line_boxes[:, 0])\n x1=np.max(text_line_boxes[:, 2])\n\n offset=(text_line_boxes[0, 2]-text_line_boxes[0, 0])*0.5\n\n lt_y, rt_y=self.fit_y(text_line_boxes[:, 0], text_line_boxes[:, 1], x0+offset, x1-offset)\n lb_y, rb_y=self.fit_y(text_line_boxes[:, 0], text_line_boxes[:, 3], x0+offset, x1-offset)\n\n # the score of a text line is the average score of the scores\n # of all text proposals contained in the text line\n score=scores[list(tp_indices)].sum()/float(len(tp_indices))\n\n text_lines[index, 0]=x0\n text_lines[index, 1]=min(lt_y, rt_y)\n text_lines[index, 2]=x1\n text_lines[index, 3]=max(lb_y, rb_y)\n text_lines[index, 4]=score\n\n text_lines=clip_boxes(text_lines, im_size)\n\n text_recs = np.zeros((len(text_lines), 9), np.float)\n index = 0\n for line in text_lines:\n xmin,ymin,xmax,ymax=line[0],line[1],line[2],line[3]\n text_recs[index, 0] = xmin\n text_recs[index, 1] = ymin\n text_recs[index, 2] = xmax\n text_recs[index, 3] = ymin\n text_recs[index, 4] = xmin\n text_recs[index, 5] = ymax\n text_recs[index, 6] = xmax\n text_recs[index, 7] = ymax\n text_recs[index, 8] = line[4]\n index = index + 1\n\n return text_recs\n\n\nclass TextProposalConnectorOriented:\n \"\"\"\n Connect text proposals into text lines\n \"\"\"\n\n def __init__(self):\n self.graph_builder = TextProposalGraphBuilder()\n\n def group_text_proposals(self, text_proposals, scores, im_size):\n graph = self.graph_builder.build_graph(text_proposals, scores, im_size)\n return graph.sub_graphs_connected()\n\n def fit_y(self, X, Y, x1, x2):\n len(X) != 0\n # if X only include one point, the function will get line y=Y[0]\n if np.sum(X == X[0]) == len(X):\n return Y[0], Y[0]\n p = np.poly1d(np.polyfit(X, Y, 1))\n return p(x1), p(x2)\n\n def get_text_lines(self, text_proposals, scores, im_size):\n \"\"\"\n text_proposals:boxes\n\n \"\"\"\n # tp=text proposal\n tp_groups = self.group_text_proposals(text_proposals, scores, im_size) # 首先还是建图,获取到文本行由哪几个小框构成\n\n text_lines = np.zeros((len(tp_groups), 8), np.float32)\n\n for index, tp_indices in enumerate(tp_groups):\n text_line_boxes = text_proposals[list(tp_indices)] # 每个文本行的全部小框\n X = (text_line_boxes[:, 0] + text_line_boxes[:, 2]) / 2 # 求每一个小框的中心x,y坐标\n Y = (text_line_boxes[:, 1] + text_line_boxes[:, 3]) / 2\n\n z1 = np.polyfit(X, Y, 1) # 多项式拟合,根据之前求的中心店拟合一条直线(最小二乘)\n\n x0 = np.min(text_line_boxes[:, 0]) # 文本行x坐标最小值\n x1 = np.max(text_line_boxes[:, 2]) # 文本行x坐标最大值\n\n offset = (text_line_boxes[0, 2] - text_line_boxes[0, 0]) * 0.5 # 小框宽度的一半\n\n # 以全部小框的左上角这个点去拟合一条直线,然后计算一下文本行x坐标的极左极右对应的y坐标\n lt_y, rt_y = self.fit_y(text_line_boxes[:, 0], text_line_boxes[:, 1], x0 + offset, x1 - offset)\n # 以全部小框的左下角这个点去拟合一条直线,然后计算一下文本行x坐标的极左极右对应的y坐标\n lb_y, rb_y = self.fit_y(text_line_boxes[:, 0], text_line_boxes[:, 3], x0 + offset, x1 - offset)\n\n score = scores[list(tp_indices)].sum() / float(len(tp_indices)) # 求全部小框得分的均值作为文本行的均值\n\n text_lines[index, 0] = x0\n text_lines[index, 1] = min(lt_y, rt_y) # 文本行上端 线段 的y坐标的小值\n text_lines[index, 2] = x1\n text_lines[index, 3] = max(lb_y, rb_y) # 文本行下端 线段 的y坐标的大值\n text_lines[index, 4] = score # 文本行得分\n text_lines[index, 5] = z1[0] # 根据中心点拟合的直线的k,b\n text_lines[index, 6] = z1[1]\n height = np.mean((text_line_boxes[:, 3] - text_line_boxes[:, 1])) # 小框平均高度\n text_lines[index, 7] = height + 2.5\n\n text_recs = np.zeros((len(text_lines), 9), np.float)\n index = 0\n for line in text_lines:\n b1 = line[6] - line[7] / 2 # 根据高度和文本行中心线,求取文本行上下两条线的b值\n b2 = line[6] + line[7] / 2\n x1 = line[0]\n y1 = line[5] * line[0] + b1 # 左上\n x2 = line[2]\n y2 = line[5] * line[2] + b1 # 右上\n x3 = line[0]\n y3 = line[5] * line[0] + b2 # 左下\n x4 = line[2]\n y4 = line[5] * line[2] + b2 # 右下\n disX = x2 - x1\n disY = y2 - y1\n width = np.sqrt(disX * disX + disY * disY) # 文本行宽度\n\n fTmp0 = y3 - y1 # 文本行高度\n fTmp1 = fTmp0 * disY / width\n x = np.fabs(fTmp1 * disX / width) # 做补偿\n y = np.fabs(fTmp1 * disY / width)\n if line[5] < 0:\n x1 -= x\n y1 += y\n x4 += x\n y4 -= y\n else:\n x2 += x\n y2 += y\n x3 -= x\n y3 -= y\n text_recs[index, 0] = x1\n text_recs[index, 1] = y1\n text_recs[index, 2] = x2\n text_recs[index, 3] = y2\n text_recs[index, 4] = x3\n text_recs[index, 5] = y3\n text_recs[index, 6] = x4\n text_recs[index, 7] = y4\n text_recs[index, 8] = line[4]\n index = index + 1\n\n return text_recs\n\nif __name__=='__main__':\n xmlpath = 'D:\\py_projects\\data_new\\data_new\\data\\\\annotation\\\\img_calligraphy_00003_bg.xml'\n imgpath = 'D:\\py_projects\\data_new\\data_new\\data\\\\train_img\\\\img_calligraphy_00003_bg.jpg'\n gtboxes, _ = readxml(xmlpath)\n img = rotate(imgpath,90)\n print(gtboxes)\n ow,oh=img.size\n newbox = []\n for i in gtboxes:\n newbox.append([i[1], ow - i[2], i[3], ow - i[0]])\n gtboxes = np.array(newbox)\n image_shape = (512,256)\n x_scale = image_shape[0] / ow\n y_scale = image_shape[1] / oh\n newbox = []\n for i in range(len(gtboxes)):\n newbox.append(\n [gtboxes[i][0] * x_scale, gtboxes[i][1] * y_scale, gtboxes[i][2] * x_scale,\n gtboxes[i][3] * y_scale]\n )\n img = img.resize(image_shape, Image.ANTIALIAS)\n gtboxes = np.array(newbox)\n print(gtboxes)\n [cls,regr],base_anchor=cal_rpn((256,512),(256//16,512//16),16,gtboxes)\n print(cls)\n regr=np.expand_dims(regr,axis=0)\n anchor=bbox_transfor_inv(base_anchor,regr)\n anchor=anchor[cls==1]\n anchor=anchor.astype(int)\n print(anchor)\n drawRect(anchor,img)\n\n\n", "meta": {"hexsha": "08c2bf308868a5f804f163977df1f5c3dfefc086", "size": 23532, "ext": "py", "lang": "Python", "max_stars_repo_path": "Detection/CTPN_vertical/CP.py", "max_stars_repo_name": "TomHacker/VTD", "max_stars_repo_head_hexsha": "3009fd53cec8a86493b5f1960e8879e5a0c7345c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-01T14:38:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-01T14:38:44.000Z", "max_issues_repo_path": "Detection/CTPN_vertical/CP.py", "max_issues_repo_name": "TomHacker/VTD", "max_issues_repo_head_hexsha": "3009fd53cec8a86493b5f1960e8879e5a0c7345c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Detection/CTPN_vertical/CP.py", "max_forks_repo_name": "TomHacker/VTD", "max_forks_repo_head_hexsha": "3009fd53cec8a86493b5f1960e8879e5a0c7345c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-07T12:04:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-07T12:04:33.000Z", "avg_line_length": 33.2372881356, "max_line_length": 113, "alphanum_fraction": 0.5836308006, "include": true, "reason": "import numpy", "num_tokens": 7525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.27512972382317524, "lm_q1q2_score": 0.14829030465312804}} {"text": "from __future__ import division\nfrom build.cioverlap import *\nfrom qm.dftbplus.dftbplus import DFTBplus\nfrom qm.dftbplus.dftbpar import spin_w, spin_w_lc, onsite_uu, onsite_ud, max_l\nfrom misc import data, eps, eV_to_au, call_name\nimport os, shutil, re, textwrap\nimport numpy as np\n\nclass DFTB(DFTBplus):\n \"\"\" Class for (TD)DFTB method of DFTB+\n\n :param object molecule: Molecule object\n :param boolean l_scc: Include self-consistent charge (SCC) scheme\n :param double scc_tol: Stopping criteria for the SCC iterations\n :param integer scc_max_iter: Maximum number of SCC iterations\n :param boolean l_onsite: Include onsite correction to SCC term\n :param boolean l_range_sep: Include long-range corrected functional\n :param string lc_method: Algorithms for LC-DFTB\n :param boolean l_spin_pol: Include spin-polarisation scheme\n :param double unpaired_elec: Number of unpaired electrons\n :param string guess: Initial guess method for SCC scheme\n :param string guess_file: Initial guess file for charges\n :param double elec_temp: Electronic temperature in Fermi-Dirac scheme\n :param string mixer: Charge mixing method used in DFTB\n :param string ex_symmetry: Symmetry of excited state in TDDFTB\n :param double e_window: Energy window for TDDFTB. Increases efficiency of NACME calculation.\n :param integer,list k_point: Number of k-point samplings\n :param boolean l_periodic: Use periodicity in the calculations\n :param double,list cell_length: The lattice vectors of periodic unit cell\n :param string sk_path: Path for Slater-Koster files\n :param string install_path: Path for DFTB+ install directory\n :param boolean mpi: Use MPI parallelization\n :param string mpi_path: Path for MPI binary\n :param integer nthreads: Number of threads in the calculations\n :param string version: Version of DFTB+\n \"\"\"\n def __init__(self, molecule, l_scc=True, scc_tol=1E-6, scc_max_iter=100, l_onsite=False, \\\n l_range_sep=False, lc_method=\"MatrixBased\", l_spin_pol=False, unpaired_elec=0., guess=\"h0\", \\\n guess_file=\"./charges.bin\", elec_temp=0., mixer=\"Broyden\", ex_symmetry=\"singlet\", e_window=0., \\\n k_point=[1, 1, 1], l_periodic=False, cell_length=[0., 0., 0., 0., 0., 0., 0., 0., 0.,], \\\n sk_path=\"./\", install_path=\"./\", mpi=False, mpi_path=\"./\", nthreads=1, version=\"20.1\"):\n # Initialize DFTB+ common variables\n super(DFTB, self).__init__(molecule, sk_path, install_path, nthreads, version)\n\n # Initialize DFTB+ DFTB variables\n self.l_scc = l_scc\n self.scc_tol = scc_tol\n self.scc_max_iter = scc_max_iter\n\n self.l_onsite = l_onsite\n\n self.l_range_sep = l_range_sep\n self.lc_method = lc_method.lower()\n\n self.l_spin_pol = l_spin_pol\n self.unpaired_elec = unpaired_elec\n\n # Set initial guess for SCC term\n self.guess = guess.lower()\n self.guess_file = guess_file\n if not (self.guess in [\"h0\", \"read\"]):\n error_message = \"Invalid initial guess for DFTB!\"\n error_vars = f\"guess = {self.guess}\"\n raise ValueError (f\"( {self.qm_method}.{call_name()} ) {error_message} ( {error_vars} )\")\n\n self.elec_temp = elec_temp\n self.mixer = mixer.lower()\n\n self.ex_symmetry = ex_symmetry.lower()\n self.e_window = e_window\n\n self.k_point = k_point\n self.l_periodic = l_periodic\n self.a_axis = np.copy(cell_length[0:3])\n self.b_axis = np.copy(cell_length[3:6])\n self.c_axis = np.copy(cell_length[6:9])\n\n # Check excitation symmetry in TDDFTB\n # TODO : Currently, allows only singlet excited states with TDDFTB\n# if not (self.ex_symmetry in [\"singlet\", \"triplet\"]):\n if (not self.ex_symmetry == \"singlet\"):\n error_message = \"Invalid symmetry of excited states for TDDFTB given!\"\n error_vars = f\"ex_symmetry = {self.ex_symmetry}\"\n raise ValueError (f\"( {self.qm_method}.{call_name()} ) {error_message} ( {error_vars} )\")\n\n self.mpi = mpi\n self.mpi_path = mpi_path\n\n # Set 'l_nacme' and 're_calc' with respect to the computational method\n # TDDFTB do not produce NACs, so we should get NACME from CIoverlap\n # TDDFTB cannot compute the gradient of several states simultaneously.\n molecule.l_nacme = True\n self.re_calc = True\n\n # Calculate number of basis for current system\n # Set new variable to decide the position of basis functions in terms of atoms\n # DFTB method considers only valence electrons, so core electrons should be removed\n core_elec = 0.\n self.nbasis = 0\n self.check_atom = [0]\n for iat in range(molecule.nat_qm):\n # Check number of basis functions with respect to maximum angular momentum\n max_ang = max_l[molecule.symbols[iat]]\n if (max_ang == 's'):\n self.nbasis += 1\n elif (max_ang == 'p'):\n self.nbasis += 4\n elif (max_ang == 'd'):\n self.nbasis += 9\n else:\n error_message = \"Number of basis for f orbital not implemented, see '$PYUNIXMDHOME/src/qm/dftbplus/dftb.py'!\"\n error_vars = f\"current atom = {molecule.symbols[iat]}, max_ang = {max_ang}\"\n raise NotImplementedError (f\"( {self.qm_method}.{call_name()} ) {error_message} ( {error_vars} )\")\n self.check_atom.append(self.nbasis)\n # Check number of core electrons with respect to atomic number\n sym_index = list(data.keys()).index(molecule.symbols[iat])\n if (sym_index > 0 and sym_index <= 2):\n core_elec += 0.\n elif (sym_index > 2 and sym_index <= 10):\n core_elec += 2.\n elif (sym_index > 10 and sym_index <= 18):\n core_elec += 10.\n elif (sym_index > 18 and sym_index <= 36):\n core_elec += 18.\n elif (sym_index > 36 and sym_index <= 54):\n core_elec += 36.\n else:\n error_message = \"Core electrons for current element not implemented, see '$PYUNIXMDHOME/src/qm/dftbplus/dftb.py'!\"\n error_vars = f\"current atom = {molecule.symbols[iat]}, sym_index = {sym_index}\"\n raise NotImplementedError (f\"( {self.qm_method}.{call_name()} ) {error_message} ( {error_vars} )\")\n\n # Set new variable to decide the position of atoms in terms of basis functions\n self.check_basis = []\n for ibasis in range(self.nbasis):\n for iat in range(molecule.nat_qm):\n ind_a = self.check_atom[iat] + 1\n ind_b = self.check_atom[iat + 1]\n if (ibasis + 1 >= ind_a and ibasis + 1 <= ind_b):\n self.check_basis.append(iat + 1)\n\n # Initialize NACME variables\n # There is no core orbitals in TDDFTB (fixed occupations)\n # nocc is number of occupied orbitals and nvirt is number of virtual orbitals\n self.norb = self.nbasis\n self.nocc = int(int(molecule.nelec - core_elec) / 2)\n self.nvirt = self.norb - self.nocc\n \n # Replace norb by arrays containing the limits of the for loops.\n # For energy window calculations loops will not go from (0 to nocc/nvirt) or (0 to norb)\n # but from (nocc_min to nocc/0 to nvirt_max) or (nocc_min to norb).\n self.orb_ini = np.zeros(1, dtype=np.int32)\n self.orb_final = np.zeros(1, dtype=np.int32)\n self.orb_final[0] = self.norb\n\n if (self.e_window > eps):\n # Swap minimal/maximal values to replace them in reading of SPX.DAT by the minimal/maximal values.\n self.orb_ini[0] = self.norb\n self.orb_final[0] = 0\n\n self.ao_overlap = np.zeros((self.nbasis, self.nbasis))\n self.mo_coef_old = np.zeros((self.norb, self.nbasis))\n self.mo_coef_new = np.zeros((self.norb, self.nbasis))\n self.ci_coef_old = np.zeros((molecule.nst, self.nocc, self.nvirt))\n self.ci_coef_new = np.zeros((molecule.nst, self.nocc, self.nvirt))\n\n def get_data(self, molecule, base_dir, bo_list, dt, istep, calc_force_only):\n \"\"\" Extract energy, gradient and nonadiabatic couplings from (TD)DFTB method\n\n :param object molecule: Molecule object\n :param string base_dir: Base directory\n :param integer,list bo_list: List of BO states for BO calculation\n :param double dt: Time interval\n :param integer istep: Current MD step\n :param boolean calc_force_only: Logical to decide whether calculate force only\n \"\"\"\n self.copy_files(molecule, istep, calc_force_only)\n super().get_data(base_dir, calc_force_only)\n self.write_xyz(molecule)\n self.get_input(molecule, istep, bo_list, calc_force_only)\n self.run_QM(molecule, base_dir, istep, bo_list, calc_force_only)\n self.extract_QM(molecule, base_dir, istep, bo_list, dt, calc_force_only)\n self.move_dir(base_dir)\n\n def copy_files(self, molecule, istep, calc_force_only):\n \"\"\" Copy necessary scratch files in previous step\n\n :param object molecule: Molecule object\n :param integer istep: Current MD step\n :param boolean calc_force_only: Logical to decide whether calculate force only\n \"\"\"\n # Copy required files for NACME\n if (self.calc_coupling and not calc_force_only and istep >= 0 and molecule.nst > 1):\n # After T = 0.0 s\n shutil.copy(os.path.join(self.scr_qm_dir, \"geometry.xyz\"), \\\n os.path.join(self.scr_qm_dir, \"../geometry.xyz.pre\"))\n if (istep == 0):\n shutil.copy(os.path.join(self.scr_qm_dir, \"eigenvec.bin\"), \\\n os.path.join(self.scr_qm_dir, \"../eigenvec.bin.pre\"))\n shutil.copy(os.path.join(self.scr_qm_dir, \"SPX.DAT\"), \\\n os.path.join(self.scr_qm_dir, \"../SPX.DAT.pre\"))\n shutil.copy(os.path.join(self.scr_qm_dir, \"XplusY.DAT\"), \\\n os.path.join(self.scr_qm_dir, \"../XplusY.DAT.pre\"))\n\n # Copy required files to read initial guess\n if (self.guess == \"read\" and istep >= 0):\n # After T = 0.0 s\n shutil.copy(os.path.join(self.scr_qm_dir, \"charges.bin\"), \\\n os.path.join(self.scr_qm_dir, \"../charges.bin.pre\"))\n\n def get_input(self, molecule, istep, bo_list, calc_force_only):\n \"\"\" Generate DFTB+ input files: geometry.gen, dftb_in.hsd\n\n :param object molecule: Molecule object\n :param integer istep: Current MD step\n :param integer,list bo_list: List of BO states for BO calculation\n :param boolean calc_force_only: Logical to decide whether calculate force only\n \"\"\"\n # Make 'geometry.gen' file\n os.system(\"xyz2gen geometry.xyz\")\n if (self.l_periodic):\n # Substitute C to S in first line\n file_be = open('geometry.gen', 'r')\n file_af = open('tmp.gen', 'w')\n first_row = True\n for row in file_be:\n if (first_row):\n row = f'{molecule.nat_qm} S\\n'\n first_row = False\n file_af.write(row)\n # Add gamma-point and cell lattice information\n geom_periodic = textwrap.dedent(f\"\"\"\\\n {0.0:15.8f} {0.0:15.8f} {0.0:15.8f}\n {self.a_axis[0]:15.8f} {self.a_axis[1]:15.8f} {self.a_axis[2]:15.8f}\n {self.b_axis[0]:15.8f} {self.b_axis[1]:15.8f} {self.b_axis[2]:15.8f}\n {self.c_axis[0]:15.8f} {self.c_axis[1]:15.8f} {self.c_axis[2]:15.8f}\n \"\"\")\n file_af.write(geom_periodic)\n file_be.close()\n file_af.close()\n os.rename('tmp.gen', 'geometry.gen')\n\n # Make 'double.gen' file for CIoverlap in TDDFTB\n # In this case, we do not need to consider periodicity\n if (self.calc_coupling and not calc_force_only and istep >= 0 and molecule.nst > 1):\n # Move previous files to currect directory\n os.rename('../geometry.xyz.pre', './geometry.xyz.pre')\n if (istep == 0):\n os.rename('../eigenvec.bin.pre', './eigenvec.bin.pre')\n os.rename('../SPX.DAT.pre', './SPX.DAT.pre')\n os.rename('../XplusY.DAT.pre', './XplusY.DAT.pre')\n # Open 'geometry.xyz.pre'\n file_af = open('double.xyz', 'w')\n file_be = open('geometry.xyz.pre', 'r')\n first_row = True\n for row in file_be:\n if (first_row):\n row = f'{molecule.nat_qm * 2}\\n'\n first_row = False\n file_af.write(row)\n file_be.close()\n # Open 'geometry.xyz'\n file_be = open('geometry.xyz', 'r')\n iline = 1\n for row in file_be:\n if (iline > 2):\n file_af.write(row)\n iline += 1\n file_be.close()\n file_af.close()\n os.system(\"xyz2gen double.xyz\")\n\n # Make 'dftb_in.hsd' file\n input_dftb = \"\"\n\n # Geometry Block\n input_geom = textwrap.dedent(f\"\"\"\\\n Geometry = GenFormat{{\n <<< 'geometry.gen'\n }}\n \"\"\")\n input_dftb += input_geom\n\n # Hamiltonian Block\n input_ham_init = textwrap.dedent(f\"\"\"\\\n Hamiltonian = DFTB{{\n \"\"\")\n input_dftb += input_ham_init\n\n # SCC-DFTB option\n if (self.l_scc):\n input_ham_scc = textwrap.indent(textwrap.dedent(f\"\"\"\\\n SCC = Yes\n SCCTolerance = {self.scc_tol}\n MaxSCCIterations = {self.scc_max_iter}\n Mixer = {self.mixer}{{}}\n \"\"\"), \" \")\n input_dftb += input_ham_scc\n\n # Onsite-corrected DFTB (OC-DFTB) option\n if (self.l_onsite):\n onsite_const_uu = (\"\\n\" + \" \" * 18).join([f\" {itype}uu = {{ {onsite_uu[f'{itype}']} }}\" for itype in self.atom_type])\n onsite_const_ud = (\"\\n\" + \" \" * 18).join([f\" {itype}ud = {{ {onsite_ud[f'{itype}']} }}\" for itype in self.atom_type])\n input_ham_oc = textwrap.indent(textwrap.dedent(f\"\"\"\\\n OnsiteCorrection = {{\n {onsite_const_uu}\n {onsite_const_ud}\n }}\n \"\"\"), \" \")\n input_dftb += input_ham_oc\n\n # Long-range corrected DFTB (LC-DFTB) option\n if (self.l_range_sep):\n input_ham_lc = textwrap.indent(textwrap.dedent(f\"\"\"\\\n RangeSeparated = LC{{\n Screening = {self.lc_method}{{}}\n }}\n \"\"\"), \" \")\n input_dftb += input_ham_lc\n\n # Spin-polarized DFTB option\n if (self.l_spin_pol and molecule.nst == 1):\n input_ham_spin = textwrap.dedent(f\"\"\"\\\n SpinPolarisation = Colinear{{\n UnpairedElectrons = {self.unpaired_elec}\n }}\n \"\"\")\n input_dftb += input_ham_spin\n\n # Read atomic spin constants used in spin-polarized DFTB or TDDFTB\n # TODO : Currently, allows only singlet excited states with TDDFTB\n# if (self.l_spin_pol or self.ex_symmetry == \"triplet\"):\n if (self.l_spin_pol and molecule.nst == 1):\n if (self.l_range_sep):\n spin_constant = (\"\\n\" + \" \" * 18).join([f\" {itype} = {{ {spin_w_lc[f'{itype}']} }}\" for itype in self.atom_type])\n else:\n spin_constant = (\"\\n\" + \" \" * 18).join([f\" {itype} = {{ {spin_w[f'{itype}']} }}\" for itype in self.atom_type])\n input_ham_spin_w = textwrap.indent(textwrap.dedent(f\"\"\"\\\n SpinConstants = {{\n ShellResolvedSpin = Yes\n {spin_constant}\n }}\n \"\"\"), \" \")\n input_dftb += input_ham_spin_w\n\n # Read 'charges.bin' from previous step\n if (self.guess == \"read\"):\n if (istep == -1):\n if (os.path.isfile(self.guess_file)):\n # Copy guess file to currect directory\n shutil.copy(self.guess_file, os.path.join(self.scr_qm_dir, \"charges.bin\"))\n restart = \"Yes\"\n else:\n restart = \"No\"\n elif (istep >= 0):\n # Move previous file to currect directory\n os.rename(\"../charges.bin.pre\", \"./charges.bin\")\n restart = \"Yes\"\n elif (self.guess == \"h0\"):\n restart = \"No\"\n\n # Read 'charges.bin' for surface hopping dynamics when hop occurs\n if (calc_force_only):\n restart = \"Yes\"\n\n input_ham_restart = textwrap.indent(textwrap.dedent(f\"\"\"\\\n ReadInitialCharges = {restart}\n \"\"\"), \" \")\n input_dftb += input_ham_restart\n\n # TODO: for QM/MM, point_charge??\n\n if (self.l_periodic):\n num_k_point = np.sum(self.k_point)\n if (num_k_point == 3):\n # gamma-point sampling\n input_ham_periodic = textwrap.indent(textwrap.dedent(f\"\"\"\\\n KPointsAndWeights = {{\n 0.0 0.0 0.0 1.0\n }}\n \"\"\"), \" \")\n else:\n # K-point sampling\n shift_vector = [0.5 if (ik % 2 == 0) else 0 for ik in self.k_point]\n input_ham_periodic = textwrap.indent(textwrap.dedent(f\"\"\"\\\n KPointsAndWeights = SupercellFolding{{\n {self.k_point[0]} 0.0 0.0\n 0.0 {self.k_point[1]} 0.0\n 0.0 0.0 {self.k_point[2]}\n {shift_vector[0]} {shift_vector[1]} {shift_vector[2]}\n }}\n \"\"\"), \" \")\n input_dftb += input_ham_periodic\n\n angular_momentum = (\"\\n\" + \" \" * 10).join([f\" {itype} = '{max_l[f'{itype}']}'\" for itype in self.atom_type])\n input_ham_basic = textwrap.dedent(f\"\"\"\\\n Charge = {molecule.charge}\n Filling = Fermi{{\n Temperature[K] = {self.elec_temp}\n }}\n MaxAngularMomentum = {{\n {angular_momentum}\n }}\n SlaterKosterFiles = Type2FileNames{{\n Prefix = '{self.sk_path}'\n Separator = '-'\n Suffix = '.skf'\n LowerCaseTypeName = No\n }}\n }}\n \"\"\")\n input_dftb += input_ham_basic\n\n # Analysis Block\n input_analysis = textwrap.dedent(f\"\"\"\\\n Analysis = {{\n CalculateForces = Yes\n WriteBandOut = Yes\n WriteEigenvectors = Yes\n MullikenAnalysis = Yes\n }}\n \"\"\")\n input_dftb += input_analysis\n\n # Options Block\n input_options = textwrap.dedent(f\"\"\"\\\n Options = {{\n WriteDetailedXml = Yes\n WriteDetailedOut = Yes\n TimingVerbosity = -1\n }}\n \"\"\")\n input_dftb += input_options\n\n # ExcitedState Block\n if (molecule.nst > 1):\n # Calculate excited state force for target state\n if (bo_list[0] > 0):\n ex_force = \"Yes\"\n rst = bo_list[0]\n else:\n ex_force = \"No\"\n rst = bo_list[0] + 1\n\n # Set number of excitations in TDDFTB\n # This part can be modified by users\n if (molecule.nat_qm <= 5):\n num_ex = molecule.nst + 2\n elif (molecule.nat_qm > 5 and molecule.nat_qm <= 15):\n num_ex = 2 * molecule.nst + 2\n else:\n num_ex = 3 * molecule.nst + 2\n\n # Write XplusY data?\n if (self.calc_coupling):\n xpy = \"Yes\"\n else:\n xpy = \"No\"\n\n input_excited = textwrap.dedent(f\"\"\"\\\n ExcitedState = Casida{{\n NrOfExcitations = {num_ex}\n StateOfInterest = {rst}\n Symmetry = {self.ex_symmetry}\n WriteTransitions = Yes\n WriteSPTransitions = {xpy}\n WriteMulliken = Yes\n WriteXplusY = {xpy}\n EnergyWindow [eV] = {self.e_window}\n ExcitedStateForces = {ex_force}\n }}\n \"\"\")\n\n input_dftb += input_excited\n\n # ParserOptions Block\n if (self.version == \"19.1\"):\n parser_version = 7\n elif (self.version == \"20.1\"):\n parser_version = 8\n\n input_parseroptions = textwrap.dedent(f\"\"\"\\\n ParserOptions = {{\n ParserVersion = {parser_version}\n }}\n \"\"\")\n input_dftb += input_parseroptions\n\n # Parallel Block\n if (self.mpi):\n if (self.l_spin_pol and self.nthreads > 1):\n groups = 2\n else:\n groups = 1\n input_parallel = textwrap.dedent(f\"\"\"\\\n Parallel = {{\n Groups = {groups}\n UseOmpThreads = No\n Blacs = BlockSize {{ 32 }}\n }}\n \"\"\")\n input_dftb += input_parallel\n\n # Write 'dftb_in.hsd.geom' file\n file_name = f\"dftb_in.hsd.geom.{bo_list[0]}\"\n with open(file_name, \"w\") as f:\n f.write(input_dftb)\n\n # Write 'dftb_in.hsd.double' file\n if (self.calc_coupling and not calc_force_only and istep >= 0 and molecule.nst > 1):\n # New input for dftb\n input_dftb = \"\"\n\n # Geometry Block\n input_geom = textwrap.dedent(f\"\"\"\\\n Geometry = GenFormat{{\n <<< 'double.gen'\n }}\n \"\"\")\n input_dftb += input_geom\n input_dftb += input_ham_init\n input_dftb += input_ham_basic\n\n # Options Block\n input_options = textwrap.dedent(f\"\"\"\\\n Options = {{\n WriteDetailedXml = Yes\n WriteDetailedOut = Yes\n WriteHS = Yes\n TimingVerbosity = -1\n }}\n \"\"\")\n input_dftb += input_options\n\n file_name = \"dftb_in.hsd.double\"\n with open(file_name, \"w\") as f:\n f.write(input_dftb)\n\n def run_QM(self, molecule, base_dir, istep, bo_list, calc_force_only):\n \"\"\" Run (TD)DFTB calculation and save the output files to qm_log directory\n\n :param object molecule: Molecule object\n :param string base_dir: Base directory\n :param integer istep: Current MD step\n :param integer,list bo_list: List of BO states for BO calculation\n :param boolean calc_force_only: Logical to decide whether calculate force only\n \"\"\"\n # Set run command\n qm_command = os.path.join(self.qm_path, \"dftb+\")\n if (self.mpi):\n # MPI setting\n os.environ[\"OMP_NUM_THREADS\"] = \"1\"\n mpi_command = os.path.join(self.mpi_path, \"mpirun\")\n command = f\"{mpi_command} -np {self.nthreads} {qm_command} > log\"\n else:\n # OpenMP setting\n os.environ[\"OMP_NUM_THREADS\"] = f\"{self.nthreads}\"\n command = f\"{qm_command} > log\"\n\n # Run DFTB+ for calculation of overlap matrix\n if (self.calc_coupling and not calc_force_only and istep >= 0 and molecule.nst > 1):\n shutil.copy(\"dftb_in.hsd.double\", \"dftb_in.hsd\")\n os.system(command)\n\n # Copy dftb_in.hsd for target state\n file_name = f\"dftb_in.hsd.geom.{bo_list[0]}\"\n shutil.copy(file_name, \"dftb_in.hsd\")\n\n # Run DFTB+ method for molecular dynamics\n os.system(command)\n\n # Copy detailed.out for target state\n file_name = f\"detailed.out.{bo_list[0]}\"\n shutil.copy(\"detailed.out\", file_name)\n\n # Copy the output file to 'qm_log' directory\n tmp_dir = os.path.join(base_dir, \"qm_log\")\n if (os.path.exists(tmp_dir)):\n detailed_out_step = f\"detailed.out.{istep + 1}.{bo_list[0]}\"\n shutil.copy(\"detailed.out\", os.path.join(tmp_dir, detailed_out_step))\n log_step = f\"log.{istep + 1}.{bo_list[0]}\"\n shutil.copy(\"log\", os.path.join(tmp_dir, log_step))\n\n def extract_QM(self, molecule, base_dir, istep, bo_list, dt, calc_force_only):\n \"\"\" Read the output files to get BO information\n\n :param object molecule: Molecule object\n :param string base_dir: Base directory\n :param integer istep: Current MD step\n :param integer,list bo_list: List of BO states for BO calculation\n :param double dt: Time interval\n :param boolean calc_force_only: Logical to decide whether calculate force only\n \"\"\"\n # Read 'detailed.out' file\n # TODO: the qmmm information is written in this file\n file_name = f\"detailed.out.{bo_list[0]}\"\n with open(file_name, \"r\") as f:\n detailed_out = f.read()\n\n # Read 'EXC.DAT' file\n if (molecule.nst > 1):\n file_name = \"EXC.DAT\"\n with open(file_name, \"r\") as f:\n exc_out = f.read()\n\n # Energy\n if (not calc_force_only):\n energy = re.findall('Total energy:\\s+([-]\\S+) H', detailed_out)\n energy = np.array(energy[0], dtype=np.float64)\n molecule.states[0].energy = energy\n\n if (molecule.nst > 1):\n tmp_e = f'[=]+\\n' + ('\\s+([-]*\\S+)\\s+\\S+\\s+\\d+\\s+->\\s+\\d+\\s+\\S+\\s+\\S+\\s+[ST]') * molecule.nst\n energy = re.findall(tmp_e, exc_out)\n energy = np.array(energy[0], dtype=np.float64)\n energy *= eV_to_au\n for ist in range(1, molecule.nst):\n molecule.states[ist].energy = molecule.states[0].energy + energy[ist - 1]\n\n # Force\n tmp_f = 'Total Forces' + '\\n\\s+\\d*\\s+([-]*\\S+)\\s+([-]*\\S+)\\s+([-]*\\S+)' * molecule.nat_qm\n force = re.findall(tmp_f, detailed_out)\n force = np.array(force[0], dtype=np.float64)\n force = force.reshape(molecule.nat_qm, 3, order='C')\n molecule.states[bo_list[0]].force = np.copy(force)\n\n # NACME\n if (self.calc_coupling and not calc_force_only):\n if (istep >= 0):\n self.CI_overlap(molecule, istep, dt)\n\n def CI_overlap(self, molecule, istep, dt):\n \"\"\" Read the necessary files and calculate NACME from tdnac.c routine,\n note that only reading of several files is required in this method\n\n :param object molecule: Molecule object\n :param integer istep: Current MD step\n :param double dt: Time interval\n \"\"\"\n # Read upper right block of 'oversqr.dat' file (< t | t+dt >)\n file_name_in = \"oversqr.dat\"\n\n self.ao_overlap = np.zeros((self.nbasis, self.nbasis))\n with open(file_name_in, \"r\") as f_in:\n lines = f_in.readlines()\n row = 0\n iline = 0\n for line in lines:\n # Skip first five lines and read upper block\n if (iline in range(5, 5 + self.nbasis)):\n col = 0\n count = False\n field = line.split()\n for element in field:\n # Read right block\n if (count):\n ind_a = self.check_basis[row]\n ind_b = self.check_basis[col]\n if (ind_a == ind_b):\n # Choose onsite (same-atom) block\n # Sometimes NaN or too large values appear in the onsite block due to the slater-koster file\n # The values set to 1 or 0 regardless of original elements\n if (row == col):\n # Diagonal element in onsite block\n new_val = 1.\n else:\n # Off-diagonal element in onsite block\n new_val = 0.\n else:\n # Choose offsite (different-atom) block\n new_val = float(element)\n # Set overlap matrix element\n self.ao_overlap[row, col] = new_val\n col += 1\n # Read right block\n if (col > self.nbasis - 1):\n col -= self.nbasis\n count = True\n row += 1\n iline += 1\n# np.savetxt(\"test-over\", self.ao_overlap, fmt=f\"%6.3f\")\n\n # Read 'eigenvec.bin.pre' file at time t\n if (istep == 0):\n file_name_in = \"eigenvec.bin.pre\"\n\n self.mo_coef_old = np.zeros((self.norb, self.nbasis))\n with open(file_name_in, \"rb\") as f_in:\n dummy = np.fromfile(f_in, dtype=np.int32, count=1)\n for iorb in range(self.norb):\n dummy = np.fromfile(f_in, dtype=np.int32, count=1)\n data = np.fromfile(f_in, dtype=np.float64, count=self.nbasis)\n self.mo_coef_old[iorb] = data\n# np.savetxt(\"test-mo1\", self.mo_coef_old, fmt=f\"%12.6f\")\n\n # Read 'eigenvec.bin' file at time t + dt\n file_name_in = \"eigenvec.bin\"\n\n self.mo_coef_new = np.zeros((self.norb, self.nbasis))\n with open(file_name_in, \"rb\") as f_in:\n dummy = np.fromfile(f_in, dtype=np.int32, count=1)\n for iorb in range(self.norb):\n dummy = np.fromfile(f_in, dtype=np.int32, count=1)\n data = np.fromfile(f_in, dtype=np.float64, count=self.nbasis)\n self.mo_coef_new[iorb] = data\n# np.savetxt(\"test-mo2\", self.mo_coef_new, fmt=f\"%12.6f\")\n\n # The CI coefficients are arranged in order of single-particle excitations\n # Read 'SPX.DAT.pre' file at time t\n if (istep == 0):\n file_name_in = \"SPX.DAT.pre\"\n\n with open(file_name_in, \"r\") as f_in:\n lines = f_in.readlines()\n # Dimension for CI coefficients (number of excitations)\n ndim_old = int(lines[-2].strip().split()[0])\n get_wij_ind_old = np.zeros((ndim_old, 2), dtype=np.int32)\n iline = 0\n for line in lines:\n # Skip first five lines\n if (iline in range(5, 5 + ndim_old)):\n # Column information: 1st = index, 4th = occ(i), 6th = virt(a)\n field = line.split()\n # Determine new limits for for-loops\n if (int(field[5]) > self.orb_final[0]):\n self.orb_final[0] = int(field[5])\n if (int(field[3]) < self.orb_ini[0] + 1):\n self.orb_ini[0] = int(field[3]) - 1\n get_wij_ind_old[int(field[0]) - 1] = [int(field[3]), int(field[5])]\n iline += 1\n\n # Read 'SPX.DAT' file at time t + dt\n file_name_in = \"SPX.DAT\"\n\n with open(file_name_in, \"r\") as f_in:\n lines = f_in.readlines()\n # Dimension for CI coefficients (number of excitations)\n ndim = int(lines[-2].strip().split()[0])\n get_wij_ind_new = np.zeros((ndim, 2), dtype=np.int32)\n iline = 0\n for line in lines:\n # Skip first five lines\n if (iline in range(5, 5 + ndim)):\n # Column information: 1st = index, 4th = occ(i), 6th = virt(a)\n field = line.split()\n if (int(field[5]) > self.orb_final[0]):\n self.orb_final[0] = int(field[5])\n if (int(field[3]) < self.orb_ini[0] + 1):\n self.orb_ini[0] = int(field[3]) - 1\n get_wij_ind_new[int(field[0]) - 1] = [int(field[3]), int(field[5])]\n iline += 1\n\n # Read 'XplusY.DAT.pre' file at time t\n if (istep == 0):\n file_name_in = \"XplusY.DAT.pre\"\n\n self.ci_coef_old = np.zeros((molecule.nst, self.nocc, self.nvirt))\n with open(file_name_in, \"r\") as f_in:\n lines = f_in.readlines()\n iline = 0\n for line in lines:\n if (iline == 0):\n field = line.split()\n assert (int(field[0]) == ndim_old)\n assert (int(field[1]) >= molecule.nst - 1)\n # nxply is number of lines for each excited state in 'XplusY.dat'\n nxply = int(ndim_old / 6) + 1\n if (ndim_old % 6 != 0):\n nxply += 1\n else:\n field = line.split()\n if (iline % nxply == 1):\n ind = 0\n ist = int(field[0]) - 1\n # In general, TDDFTB calculate the excited states more than molecule.nst,\n # so we do not need to read all data for 'XplusY.DAT'\n if (ist == molecule.nst - 1):\n break\n else:\n # Currently, elements for CI coefficients for S0 state are zero (not used values)\n for element in field:\n ind_occ = get_wij_ind_old[ind, 0] - 1\n ind_virt = get_wij_ind_old[ind, 1] - self.nocc - 1\n self.ci_coef_old[ist + 1, ind_occ, ind_virt] = float(element)\n ind += 1\n iline += 1\n# np.savetxt(\"test-ci1\", self.ci_coef_old[1], fmt=f\"%12.6f\")\n\n # Read 'XplusY.DAT' file at time t + dt\n file_name_in = \"XplusY.DAT\"\n\n self.ci_coef_new = np.zeros((molecule.nst, self.nocc, self.nvirt))\n with open(file_name_in, \"r\") as f_in:\n lines = f_in.readlines()\n iline = 0\n for line in lines:\n if (iline == 0):\n field = line.split()\n assert (int(field[0]) == ndim)\n assert (int(field[1]) >= molecule.nst - 1)\n # nxply is number of lines for each excited state in 'XplusY.dat'\n nxply = int(ndim / 6) + 1\n if (ndim % 6 != 0):\n nxply += 1\n else:\n field = line.split()\n if (iline % nxply == 1):\n ind = 0\n ist = int(field[0]) - 1\n # In general, TDDFTB calculate the excited states more than molecule.nst,\n # so we do not need to read all data for 'XplusY.DAT'\n if (ist == molecule.nst - 1):\n break\n else:\n # Currently, elements for CI coefficients for S0 state are zero (not used values)\n for element in field:\n ind_occ = get_wij_ind_new[ind, 0] - 1\n ind_virt = get_wij_ind_new[ind, 1] - self.nocc - 1\n self.ci_coef_new[ist + 1, ind_occ, ind_virt] = float(element)\n ind += 1\n iline += 1\n# np.savetxt(\"test-ci2\", self.ci_coef_new[1], fmt=f\"%12.6f\")\n\n # Calculate wavefunction overlap with orbital scheme\n # Reference: J. Phys. Chem. Lett. 2015, 6, 4200-4203\n wf_overlap(self, molecule, istep, dt)\n\n\n", "meta": {"hexsha": "67ebd544b086de6619df7b3cfcd119a329a1fbde", "size": 36233, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/qm/dftbplus/dftb.py", "max_stars_repo_name": "jkha-unist/unixmd", "max_stars_repo_head_hexsha": "164eabc9969acb285096513119af6caea485748c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/qm/dftbplus/dftb.py", "max_issues_repo_name": "jkha-unist/unixmd", "max_issues_repo_head_hexsha": "164eabc9969acb285096513119af6caea485748c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/qm/dftbplus/dftb.py", "max_forks_repo_name": "jkha-unist/unixmd", "max_forks_repo_head_hexsha": "164eabc9969acb285096513119af6caea485748c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.7596618357, "max_line_length": 134, "alphanum_fraction": 0.5255430133, "include": true, "reason": "import numpy", "num_tokens": 8947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.27512972382317524, "lm_q1q2_score": 0.14829030465312804}} {"text": "# -*- coding: UTF-8 -*-\n# \\file solvate_maths.py\n# \\brief This file provides the specific computations functionality for other parts of solvate.\n#\n# Copyright by the Authors and individual contributors. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n# 1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n# 2) 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.\n# 3) Neither the name of Michal Tykac nor the names of this code's contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n#\n# This software is provided by the copyright holder and contributors \"as is\" and any express or implied warranties, including, but not limitted to, the implied warranties of merchantibility and fitness for a particular purpose are disclaimed. In no event shall the copyright owner or the contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limitted to, procurement of substitute goods or services, loss of use, data or profits, or business interuption) 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.\n#\n# \\author Michal Tykac\n# \\author Lada Biedermannová\n# \\author Jiří Černý\n# \\version 0.1.0\n# \\date DEC 2020\n######################################################\n\n######################################################\n# Imports\n\nimport numpy ### Maths\nimport solvate.solvate_log as solvate_log ### For writing the log\n\n######################################################\n# residueToResFragmentDistance_backbone ()\ndef residueToResFragmentDistance_backbone ( res, resFrag, settings ):\n \"\"\"\n This function computes the procrustes optimal overlay of the backbone atoms of the input residue and\n hydrated residue fragment and then proceeds to obtain the RMSD of these backbone atoms.\n\n Parameters\n ----------\n list : res\n A list containing the positions and names of the compared residue atoms.\n \n list : resFrag\n A list containing the positions and names of the hydrated residue frament atoms.\n \n solvate_globals.globalSettings : settings\n Instance of the settings class contaning all the options and values.\n\n Returns\n -------\n list : dist, tForm\n First element: The RMSD distance between the supplied residues's side-chain atoms\n Second element: The dictionary of procrustes transformations.\n\n \"\"\"\n ### Reduce residue to N, Ca, C and O (backbone) atoms\n resAts = []\n resAtsNames = []\n for rIt in range( 0, len( res[1] ) ):\n if ( res[1][rIt][0] == \"C\" ) or ( res[1][rIt][0] == \"CA\" ) or ( res[1][rIt][0] == \"O\" ) or ( res[1][rIt][0] == \"N\" ):\n resAts.append ( [ res[1][rIt][1], res[1][rIt][2], res[1][rIt][3] ] )\n resAtsNames.append ( res[1][rIt][0] )\n\n ### Sanity check\n if len( resAts ) != 4:\n solvate_log.writeLog ( \"!!! ERROR !!! Could not find all backbone atoms (C, CA, N and O) in the residue described by \" + str( res ), settings, 0 )\n \n # Terminate\n solvate_log.endLog ( settings )\n \n ### Reduce hydrated residue fragment to N, Ca, C and O (backbone) atoms\n fraAts = []\n for fIt in range( 0, len( resFrag ) ):\n for rIt in range ( 0, len( resAtsNames ) ):\n if resFrag[fIt][0] == resAtsNames[rIt]:\n fraAts.append ( [ resFrag[fIt][1], resFrag[fIt][2], resFrag[fIt][3] ] )\n \n ### Sanity check\n if len( fraAts ) != 4:\n solvate_log.writeLog ( \"!!! ERROR !!! Could not find all backbone atoms (C, CA, N and O) in the supplied hydrated fragment \" + str ( resFrag ), settings, 0 )\n \n # Terminate\n solvate_log.endLog ( settings )\n \n ### Convert to numpy arrays\n resNumpy = numpy.array ( [ numpy.array ( xi ) for xi in resAts ] )\n fraNumpy = numpy.array ( [ numpy.array ( xi ) for xi in fraAts ] )\n \n ### Compute procrustes analysis\n ( dist, z, t ) = procrustes ( resNumpy, fraNumpy )\n \n ### Get RMSD\n rmsdDist = getRMSD ( resAts, z )\n \n ### Report log\n solvate_log.writeLog ( \"Found residue to hydrated residue fragment distance of \" + str( rmsdDist ), settings, 5 )\n \n ### Done\n return ( rmsdDist, t )\n \n######################################################\n# residueToResFragmentDistance_rotamer ()\ndef residueToResFragmentDistance_rotamer ( res, resFrag, settings ):\n \"\"\"\n This function computes the procrustes optimal overlay of the side-chain atoms of the input residue and\n hydrated residue fragment and then proceeds to obtain the RMSD of these side-chain atoms.\n\n Parameters\n ----------\n list : res\n A list containing the positions and names of the compared residue atoms.\n \n list : resFrag\n A list containing the positions and names of the hydrated residue frament atoms.\n \n solvate_globals.globalSettings : settings\n Instance of the settings class contaning all the options and values.\n\n Returns\n -------\n list : dist, tForm\n First element: The RMSD distance between the supplied residues's side-chain atoms\n Second element: The dictionary of procrustes transformations.\n\n \"\"\"\n ### Initialise variables\n resAts = []\n resAtsNames = []\n fraAts = []\n \n ### Parse out the side-chain atoms for the residue\n for rIt in range( 0, len( res[1] ) ):\n \n # Deal with various atom names and lengths for different amino acids\n if ( ( ( res[0] == \"VAL\" ) or ( res[0] == \"ILE\" ) ) and ( ( res[1][rIt][0] == \"C\" ) or ( res[1][rIt][0] == \"CA\" ) or ( res[1][rIt][0] == \"CB\" ) or ( res[1][rIt][0] == \"CG1\" ) ) ) or \\\n ( ( ( res[0] == \"THR\" ) ) and ( ( res[1][rIt][0] == \"C\" ) or ( res[1][rIt][0] == \"CA\" ) or ( res[1][rIt][0] == \"CB\" ) or ( res[1][rIt][0] == \"OG1\" ) ) ) or \\\n ( ( ( res[0] == \"SER\" ) ) and ( ( res[1][rIt][0] == \"C\" ) or ( res[1][rIt][0] == \"CA\" ) or ( res[1][rIt][0] == \"CB\" ) or ( res[1][rIt][0] == \"OG\" ) ) ) or \\\n ( ( ( res[0] == \"CYS\" ) ) and ( ( res[1][rIt][0] == \"C\" ) or ( res[1][rIt][0] == \"CA\" ) or ( res[1][rIt][0] == \"CB\" ) or ( res[1][rIt][0] == \"SG\" ) ) ) or \\\n ( ( ( res[0] == \"ARG\" ) or ( res[0] == \"ASN\" ) or ( res[0] == \"ASP\" ) or ( res[0] == \"GLN\" ) or ( res[0] == \"GLU\" ) or ( res[0] == \"HIS\" ) or ( res[0] == \"LEU\" ) or \\\n ( res[0] == \"LYS\" ) or ( res[0] == \"MET\" ) or ( res[0] == \"PHE\" ) or ( res[0] == \"PRO\" ) or ( res[0] == \"TRP\" ) or ( res[0] == \"TYR\" ) \\\n ) and ( ( res[1][rIt][0] == \"C\" ) or ( res[1][rIt][0] == \"CA\" ) or ( res[1][rIt][0] == \"CB\" ) or ( res[1][rIt][0] == \"CG\" ) ) ):\n \n # Save\n resAts.append ( [ res[1][rIt][1], res[1][rIt][2], res[1][rIt][3] ] )\n resAtsNames.append ( res[1][rIt][0] )\n\n ### Sanity check\n if len ( resAts ) != 4:\n solvate_log.writeLog ( \"!!! ERROR !!! Could not find all side-chain atoms (C, CA, CB and ?) in the supplied residue \" + str ( res ), settings, 0 )\n \n # Terminate\n solvate_log.endLog ( )\n\n \n ### Reduce fragment to N, Ca, Cb and X (as above) atoms\n for rIt in range( 0, len( resAtsNames ) ):\n \n # For each fragment atom\n for fIt in range( 0, len( resFrag ) ):\n \n # Get only the same atoms\n if resAtsNames[rIt] == resFrag[fIt][0]:\n \n # Save\n fraAts.append ( [ resFrag[fIt][1], resFrag[fIt][2], resFrag[fIt][3] ] )\n \n ### Sanity check\n if len ( fraAts ) != 4:\n solvate_log.writeLog ( \"!!! ERROR !!! Could not find all side-chain atoms (C, CA, CB and ?) in the supplied hydrated residue fragment \" + str ( resFrag ), settings, 0 )\n \n # Terminate\n solvate_log.endLog ( )\n \n ### Convert to numpy arrays\n resNumpy = numpy.array ( [ numpy.array ( xi ) for xi in resAts ] )\n fraNumpy = numpy.array ( [ numpy.array ( xi ) for xi in fraAts ] )\n \n ### Compute procrustes analysis\n ( dist, z, t ) = procrustes ( resNumpy, fraNumpy )\n \n ### Get RMSD\n rmsdDist = getRMSD ( resAts, z )\n \n ### Report log\n solvate_log.writeLog ( \"Found residue to hydrated residue fragment distance of \" + str( rmsdDist ), settings, 4 )\n \n ### Done\n return ( rmsdDist, t )\n\n######################################################\n# residueToResFragmentDistance_direct ()\ndef residueToResFragmentDistance_direct ( res, fragInfo, settings ):\n \"\"\"\n This function computes the procrustes optimal overlay of all available atoms\n and then proceeds to obtain the RMSD of these atoms.\n\n Parameters\n ----------\n list : res\n A list containing the positions and names of the compared residue atoms.\n \n list : fragInfo\n A list containing the positions and names of the hydrated frament atoms.\n \n solvate_globals.globalSettings : settings\n Instance of the settings class contaning all the options and values.\n\n Returns\n -------\n list : dist, tForm\n First element: The RMSD distance between the supplied residues's side-chain atoms\n Second element: The dictionary of procrustes transformations.\n\n \"\"\"\n ### Initialise variables\n resAtoms = []\n fragAtoms = []\n\n ### Get residue positions in same order as fragment\n for fIt in range ( 0, len ( fragInfo ) ):\n \n # For each residue atom name\n for atIt in range ( 0, len ( res[1] ) ):\n \n # Compare the atom names\n if res[1][atIt][0] == fragInfo[fIt][0]:\n \n # Save atoms in same order\n resAtoms.append ( [ res[1][atIt][1], res[1][atIt][2], res[1][atIt][3] ] )\n fragAtoms.append ( [ fragInfo[fIt][1], fragInfo[fIt][2], fragInfo[fIt][3] ] )\n \n ### Check for missing atoms\n if len ( fragInfo ) != len ( resAtoms ):\n solvate_log.writeLog ( \"!!! ERROR !!! Failed to match the fragment atoms of fragment \" + str ( fragInfo ) + \" to residue \" + str( res ), settings, 0 )\n \n # Terminate\n solvate_log.endLog ( )\n \n\n ### Convert to numpy arrays\n resNumpy = numpy.array ( [ numpy.array ( xi ) for xi in resAtoms ] )\n fraNumpy = numpy.array ( [ numpy.array ( xi ) for xi in fragAtoms ] )\n \n ### Compute procrustes analysis\n ( dist, z, t ) = procrustes ( resNumpy, fraNumpy )\n \n ### Get RMSD\n rmsdDist = getRMSD ( resAtoms, z )\n \n ### Report log\n solvate_log.writeLog ( \"Found residue to hydrated fragment distance of \" + str( rmsdDist ), settings, 5 )\n \n ### Done\n return ( rmsdDist, t )\n\n######################################################\n# procrustes ()\ndef procrustes ( X, Y ):\n \"\"\"\n A port of MATLAB's \"procrustes\" function to Numpy.\n \n Procrustes analysis determines a linear transformation (translation,\n reflection, orthogonal rotation and scaling) of the points in Y to best\n conform them to the points in matrix X, using the sum of squared errors\n as the goodness of fit criterion.\n \n d, Z, [tform] = procrustes ( X, Y )\n \n In this particular code, scaling has been disabled (in protein comparisons,\n scale plays a role) as was the reflections ( mirror immage of a molecule is\n a different molecule ).\n \n Parameters\n ----------\n numpy.ndarray : X, Y\n Matrices of target and input coordinates. They must have equal\n numbers of points (rows), but Y may have fewer dimensions\n (columns) than X.\n \n Returns\n -------\n float : d\n The residual sum of squared errors, normalized according to a\n measure of the scale of X, ( ( X - X.mean(0))^2 ).sum( )\n \n matrix : Z\n The matrix of transformed Y-values\n \n dictionary : tform\n A dict specifying the rotation, translation and scaling that\n maps X --> Y\n \n \"\"\"\n \n ### Find the dimensions of the input matrices\n nx , mx = X.shape\n ny , my = Y.shape\n \n ### Find the column means of the input matrices\n muX = X.mean(0)\n muY = Y.mean(0)\n \n ### Find the x - mean values of the input matrices\n X0 = X - muX\n Y0 = Y - muY\n \n ### Sum the squares of the x - mean values of the input matrices\n ssX = ( numpy.power ( X0, 2.0 ) ).sum()\n ssY = ( numpy.power ( Y0, 2.0 ) ).sum()\n \n ### Compute the centred Frobenius norm of the input matrices (i.e. square root of sum of x - mean squared)\n normX = numpy.sqrt ( ssX )\n normY = numpy.sqrt ( ssY )\n \n ### Scale x - mean to equal (unit) norm\n X0 /= normX\n Y0 /= normY\n \n ### If second matrix has more rows than the first, shorten it ( this should really be error... )\n if my < mx:\n Y0 = numpy.concatenate ( ( Y0, numpy.zeros ( nx, mx - my ) ), 0 )\n \n ### Find the optimal rotation matrix of Y using least squares\n A = numpy.dot ( X0.T, Y0 )\n U,s,Vt = numpy.linalg.svd ( A, full_matrices=False )\n V = Vt.T\n T = numpy.dot(V, U.T)\n \n ### Does the current solution use a reflection?\n have_reflection = numpy.linalg.det(T) < 0\n \n ### If that's the case, force the other reflection (i.e. solution with no reflections)\n if have_reflection != False:\n V[:,-1] *= -1\n s[-1] *= -1\n T = numpy.dot(V, U.T)\n \n ### Find the trace of singular values\n traceTA = s.sum()\n \n ### With no scaling\n b = 1\n d = 1 + ssY/ssX - 2 * traceTA * normY / normX\n Z = normY * numpy.dot ( Y0, T ) + muX\n \n ### If second matrix has more rows than the first, shorten it ( this should really be error... )\n if my < mx:\n T = T[:my,:]\n \n ### Compute the translation vector\n c = muX - b * numpy.dot ( muY, T )\n \n ### Save all to transformation list\n tform = {'rotation':T, 'scale':b, 'translation':c}\n \n ### Done\n return d, Z, tform\n\n######################################################\n# getRMSD ()\ndef getRMSD ( coo1, coo2 ):\n \"\"\"\n This is a simple function for computing RMSD given two matrices with equal dimmensions (n rows and\n exactly 3 columns) of (presumably atomic) co-ordinates.\n \n Parameters\n ----------\n matrix : coo1, coo2\n matrices of target and input coordinates. They must have equal\n numbers of points (rows) and equal number of dimensions (columns\n = 3)\n \n Returns\n -------\n float : dist\n The RMSD distance value between the two matrices.\n \n \"\"\"\n ### Initialise sum\n sum = 0.0\n \n ### For each row\n for iter in range ( 0, len ( coo1 ) ):\n sum += ( numpy.power ( coo1[iter][0] - coo2[iter][0], 2.0 ) +\n numpy.power ( coo1[iter][1] - coo2[iter][1], 2.0 ) +\n numpy.power ( coo1[iter][2] - coo2[iter][2], 2.0 ) )\n \n ### Done\n return ( numpy.sqrt ( sum / float ( len ( coo1 ) ) ) )\n \n\n######################################################\n# findSmallestDistance ()\ndef findSmallestDistance ( distances, threshold ):\n \"\"\"\n This function takes a list of distances and a threshold and returns the index of the\n smallest distance or -1 if no distances is below the threshold.\n\n Parameters\n ----------\n list : distances\n The list of the distances to be searched.\n \n float : threshold\n The threshold below which any passing distance needs to be.\n\n Returns\n -------\n int : index\n The index of the smallest distance or -1 if no distance is below the threshold.\n\n \"\"\"\n ### Find lowest RMSD and check if it is larger than the threshold\n minVal = numpy.Inf\n minInd = -1\n indCtr = 0\n \n ### Find the best match (lowest distance)\n for val in distances:\n if ( val[0] < minVal ) and ( val[0] < threshold ):\n minVal = val[0]\n minInd = indCtr\n indCtr += 1\n \n ### Return the index\n return ( minInd )\n\n######################################################\n# findPassingDistances ()\ndef findPassingDistances ( distances, threshold ):\n \"\"\"\n This function takes a list of distances and a threshold and returns all indices of\n distances which pass the threshold, or -1 if no distances is below the threshold.\n\n Parameters\n ----------\n list : distances\n The list of the distances to be searched.\n \n float : threshold\n The threshold below which any passing distance needs to be.\n\n Returns\n -------\n list : indices\n The indices of all passing distances or -1 if no distance is below the threshold.\n\n \"\"\"\n ### Initialise variables\n minInd = []\n indCtr = 0\n \n ### Find all passing distances\n for val in distances:\n if val[0] < threshold:\n minInd.append ( indCtr )\n indCtr += 1\n \n ### Check for at least one\n if len( minInd ) == 0:\n minInd = -1\n \n ### Return the index\n return ( minInd )\n\n######################################################\n# findPassingDistances ()\ndef rotateAndTranslateAtom ( atom, transform ):\n \"\"\"\n This function takes a numpy.array of atom positions (X, Y, Z) and proceeds to\n apply the transform rotation and then transform translation to this position.\n It then returns the new position.\n \n Warning: Note that rotation is done before translation, if this is not the\n correct order of transformations, then please do not use the function!\n\n Parameters\n ----------\n numpy.array : atom\n Array with three numbers signifying the current atom position.\n \n dictionary : transform\n Dictionary containing the \"rotation\" key with the optimal rotation matrix and\n a \"translation\" key with the optimal translation. It should be the result of\n the procrustes analysis.\n\n Returns\n -------\n numpy.array : res\n Array containing the new position resulting from rotating and translation the\n input position.\n\n \"\"\"\n ### Apply rotation\n atomPos = numpy.matmul ( atom, transform[\"rotation\"] )\n \n ### Apply translation\n atomPos = atomPos + transform[\"translation\"]\n \n ### Return the index\n return ( atomPos )\n\n######################################################\n# getWaterClusterCOM ()\ndef getWaterClusterCOM ( clusterIndex, clusteredWaters ):\n \"\"\"\n This function takes the index of a cluster, the list of all water molecules and the\n appropriate labels list and proceeds to compute the occupancy weighted COM position\n for the cluster, which it then returns.\n\n Parameters\n ----------\n int : clusterIndex\n The index of the cluster for which the computation is to be made.\n \n list : clusteredWaters\n A list of cluster labels, cluster count, water positions and molecule occupancies and B factors for\n each structure type available in the noClashWaters input variable.\n \n list : watersNoClash\n List containing a list of water molecules which have no clashes (as defined by the settings)\n to the various versions of the input structure. The versions are: full structure, no hydrogens,\n no waters, no ligands. If some of the versions were not requested, the list for that version will\n be empty.\n\n Returns\n -------\n list : COM\n This list contains the COM position weighted by the occupancy of the contributing water molecules and the\n average occupancy and B factor as well.\n\n \"\"\"\n ### Find all member indices\n members = numpy.where ( clusteredWaters[0] == clusterIndex )[0]\n \n ### Initialise variables\n COM = numpy.zeros ( 5 )\n occSum = 0.0\n bFacSum = 0.0\n \n ### For each member, find sum of positions weighted by occupancy\n for mem in members:\n\n ### Get occupancy weighted COM and occupancy sum\n COM[0] += ( clusteredWaters[2][mem][0] * clusteredWaters[3][mem] )\n COM[1] += ( clusteredWaters[2][mem][1] * clusteredWaters[3][mem] )\n COM[2] += ( clusteredWaters[2][mem][2] * clusteredWaters[3][mem] )\n occSum += clusteredWaters[3][mem]\n bFacSum += clusteredWaters[4][mem]\n \n ### Average by occupancy sum\n COM[0] /= occSum\n COM[1] /= occSum\n COM[2] /= occSum\n COM[3] = occSum / float ( len ( members ) )\n COM[4] = bFacSum / float ( len ( members ) )\n \n ### Done\n return ( COM )\n", "meta": {"hexsha": "e7757809ae64b571d0a0bbed90d1536502f22451", "size": 25266, "ext": "py", "lang": "Python", "max_stars_repo_path": "solvate/solvate_maths.py", "max_stars_repo_name": "michaltykac/SolvateAminoAcids", "max_stars_repo_head_hexsha": "cde6364a1ab9f4188975e1e4ea7296d6655cc6a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-08T16:24:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-08T16:24:33.000Z", "max_issues_repo_path": "solvate/solvate_maths.py", "max_issues_repo_name": "michaltykac/SolvateAminoAcids", "max_issues_repo_head_hexsha": "cde6364a1ab9f4188975e1e4ea7296d6655cc6a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solvate/solvate_maths.py", "max_forks_repo_name": "michaltykac/SolvateAminoAcids", "max_forks_repo_head_hexsha": "cde6364a1ab9f4188975e1e4ea7296d6655cc6a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.4424460432, "max_line_length": 760, "alphanum_fraction": 0.4854745508, "include": true, "reason": "import numpy", "num_tokens": 5589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.2751297238231752, "lm_q1q2_score": 0.148290304653128}} {"text": "#!/usr/bin/python3\n\nimport cobra as cb\nimport pandas as pd\nimport re\nimport sys\nimport getopt\nimport os.path\nimport copy\nimport csv\nimport math\nimport cobra.flux_analysis.variability\nimport subprocess\nimport shutil, errno\nimport statistics\nfrom cobra import Reaction\nimport cometspy as c\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.rcParams.update({'figure.max_open_warning': 0})\n################################################################\n\n\ndef model_modifications(glu1, ac1, o21, glu2, ac2, o22):\n # Single GEMs parameter modifications\n # ===================================\n\n # 1.1.- [COBRApy] Establish modifications in model 1\n model1=c.model('/home/ana/FLYCOP/Scripts/iJO1366.cmd')\n model1.change_bounds('GLCtex_copy2', 0, 0)\n model1.change_bounds('PFK_3', 0, 0)\n model1.change_bounds('EX_o2_e',-1000,1000)\n model1.change_bounds('EX_glc__D_e',-1000,1000)\n model1.change_bounds('GLCtex_copy1', 0, -glu1)\n model1.change_bounds('O2tex', 0,-o21)\n if ac1<=0:\n model1.change_bounds('ACtex',-1000,-ac1)\n model1.change_bounds('EX_ac_e', ac1, 1000)\n else:\n model1.change_bounds('ACtex', -ac1,1000)\n model1.change_bounds('EX_ac_e',-1000,ac1)\n model1.id='ecoli_1_tmp'\n model1.write_comets_model()\n del(model1)\n\n # 1.2.- [COBRApy] Establish modifications in model 2\n model2=c.model(\"/home/ana/FLYCOP/Scripts/iJO1366.cmd\")\n model2.change_bounds('GLCtex_copy2', 0, 0)\n model2.change_bounds('PFK_3', 0, 0)\n model2.change_bounds('EX_o2_e',-1000,1000)\n model2.change_bounds('EX_glc__D_e',-1000,1000)\n model2.change_bounds('GLCtex_copy1',0,-glu2)\n model2.change_bounds('O2tex',0,-o22)\n if(ac2<=0):\n model2.change_bounds('ACtex',-1000,-ac2)\n model2.change_bounds('EX_ac_e',ac2,1000)\n\n else:\n model2.change_bounds('ACtex',-ac2,1000)\n model2.change_bounds('EX_ac_e',-1000,ac2)\n model2.id='ecoli_2_tmp'\n model2.write_comets_model()\n del(model2)\n return (print('Modifications of the model done!'))\n\ndef initialize_layout(file):\n #The layout is a file with the stablished format\n layout=c.layout(file)\n return layout\n\ndef initialize_params(package, globall):\n \"\"\"Function to initialize the comets' params class\n it can be initialize by submitting two files, one for the package parameters\n and one for the global ones.\n If you don't submit a file, the params class will be initialize with the values stated below\n which have been tested in this simulation\"\"\"\n\n if package or globall is not None:\n params = c.params(global_params = globall, package_params= package)\n else:\n params = c.params()\n params.all_params['maxCycles']=240\n params.all_params['timeStep']=0.1\n params.all_params['spaceWidth']=0.05\n params.all_params['allowCellOverlap']= True\n params.all_params['deathRate']= 0.01\n params.all_params['numRunThreads']= 4\n params.all_params['maxSpaceBiomass']= 10\n params.all_params['defaultVmax']=20\n params.all_params['showCycleTime']=True\n params.all_params['writeTotalBiomassLog']=True\n params.all_params['writeMediaLog']=True\n params.all_params['writeFluxLog']=True\n params.all_params['useLogNameTimeStamp']=False\n params.all_params['FluxLogRate']=1\n params.all_params['MediaLogRate']=1\n\n return params\n\ndef make_graph(comets, met, met22):\n\n '''This function creates a figure and saves it to pdf format.\n It also creates the file biomass_vs_met.txt which contais the quantity\n of each strain and metabolite and has the following columns:\n time(h), strain1 ... strainX, met1 ... metX.'''\n\n df =comets.media\n df=df.drop(columns=['x', 'y'])\n met2 =df[df['metabolite'] == str(met22)]\n met1 =df[df['metabolite'] == str(met)]\n met1 =met1.reset_index()\n met1=met1.drop(columns=['index', 'metabolite'])\n\n i = 45\n while i < 242:\n met1.loc[i] = [i+2, 0]\n i +=1\n\n met1=met1.drop(columns='cycle')\n\n\n\n met2=met2.reset_index()\n met2=met2.drop(columns=['metabolite', 'index'])\n\n j=46\n\n while j < 240:\n met2.loc[j] = [j+2, 0]\n j=j+1\n met2.loc[-1] = [1, 0]\n met2 =met2.sort_values(by=['cycle'])\n met2=met2.drop(columns='cycle')\n met2=met2.reset_index()\n met2=met2.drop(columns='index')\n df2=comets.total_biomass\n\n df2[str(met)]=met1\n df2[str(met22)]=met2\n\n df2.columns=['time(h)','Ecoli1', 'Ecoli2', str(met), str(met22)]\n np.savetxt(r'biomass_vs_glc_D_e_ac_e_template.txt', df2.values, fmt='%s',delimiter='\\t')\n\n #reading the biomass file as a dataframe and adding it the metabolite concentrations\n plt.ioff()\n fig, ax = plt.subplots()\n ax.axis(ymax=1.6)\n ax.set_xlabel('time (h)')\n ax.set_ylabel('biomass (g/L)')\n l1,=ax.plot(df2['time(h)']*0.1, df2['Ecoli1'], label='Ecoli1', color='k')\n l2,=ax.plot(df2['time(h)']*0.1, df2['Ecoli2'], linestyle='--', label='Ecoli2', color='k')\n ax2 = ax.twinx()\n ax2.set_ylabel('metabolite conc (mM)')\n ax2.axis(ymin=0, ymax=10)\n l3,=ax2.plot(df2['time(h)']*0.1, df2[str(met)], label=str(met), color='b')\n l4,=ax2.plot(df2['time(h)']*0.1, df2[str(met22)], label=str(met22), color='r')\n fig.tight_layout()\n plt.legend([l1, l2, l3, l4],[\"Ecoli1\", \"Ecoli2\", str(met), str(met22)])\n\n #Saving the graph as a pdf\n plt.savefig('biomass_vs_glc_D_e_ac_e_template_plot1.pdf')\n return df2\n #df2.drop(df2.index, inplace=True)\n\ndef end_simulation_cycle(ac1, ac2, df2, met):\n #function that stablishes the endCyle after a certain stop condition\n\n iniBiomass=float(df2.at[0,'Ecoli1'])+float(df2.at[0, 'Ecoli2'])\n totGlc=float(df2.at[0,'glc__D_e'])\n endGlcCycle=0\n for row in df2.iterrows():\n endCycle=int(row[1][0])\n glcConc=float(row[1][3])\n acConc=float(row[1][4])\n if endGlcCycle==0 and glcConc==0.0:\n endGlcCycle=endCycle\n if glcConc==0.0 and acConc==0.0:\n break\n if glcConc==0.0 and ac1>=0 and ac2>=0:\n break\n\n\n return iniBiomass, endCycle, totGlc\n\ndef biomass_yield(df2,endCycle):\n # Function that compute final biomass as the maximum biomass of each strain\n\n finalBiomass1=0\n finalBiomass2=0\n count=0\n for row in df2.iterrows():\n if float(row[1][1])>finalBiomass1:\n finalBiomass1=float(row[1][1])\n if float(row[1][2])>finalBiomass2:\n finalBiomass2=float(row[1][2])\n if count > endCycle:\n break\n count+=1\n finalBiomass=finalBiomass1+finalBiomass2\n return finalBiomass\n\ndef compute_fitness(biomassYieldNew, MaximumYield, finalBiomass, iniBiomass):\n #Function that computes the fitness according to the fitness function 'yield'\n fitness=(biomassYieldNew/MaximumYield) # Normalizing Yield\n if(float(finalBiomass-iniBiomass) > 1.03): # Given that with both strains with WT, total biomass=1.028\n fitness=0\n return fitness\n\ndef uptakeMetabolite(comets,layout):\n #Function that calculates the uptake of the metabolite 'ac_e'\n #Changing the metabolite needs changing numRxnMet; the position of the reaction 'Ex_metName' in the model\n flux = comets.fluxes\n numRxnMet=88\n uptakeMet=[]\n i=0\n while i < len(layout.models)+1:\n uptakeMet.append(float(flux.iat[i+2,numRxnMet+3]))\n i+=1\n return uptakeMet\n\ndef ecoliLongTermFLYCOP_oneConf(glu1,ac1,o21,glu2,ac2,o22, fitFunc='MaxYield_MinTime', dirPlot='',repeat=10, params_package=None, params_global=None, layout_file='/home/ana/FLYCOP/Scripts/Nuevo_layout.txt',met='glc__D_e', met2='ac_e'):\n \"\"\"Primarily function of the simulation\"\"\"\n\n print(\"Fitness function:\"+fitFunc)\n\n if not(os.path.exists('/home/ana/FLYCOP/Scripts/ecoli_1_tmp.cmd')):\n model_modifications(glu1, ac1, o21, glu2, ac2, o22)\n\n layout=initialize_layout(layout_file)\n\n params =initialize_params(params_package, params_global)\n\n #establish comets class\n comets = c.comets(layout, params)\n\n \"\"\"You may need to adjust the comets.set_classpath object if your programs aren't in the default comets location\"\"\"\n\n\n\n if not(os.path.exists('IndividualRunsResults')):\n os.makedirs('IndividualRunsResults')\n totfitness=0\n sumTotBiomass=0\n sumTotYield=0\n fitnessList=[]\n\n # To repeat X times, due to random behaviour in COMETS:\n for i in range(repeat):\n\t\n comets.run(delete_files=True)\n\t\n #obtaining the results and writing them to csv\n comets.total_biomass.to_csv('Total_biomass_log_template.txt',sep='\\t',index=False)\n comets.fluxes.to_csv('Flux_log_template.txt',sep='\\t', index=False)\n comets.media.to_csv('Media_log_template.txt',sep='\\t', index=False)\n\n #graphic part\n df2 =make_graph(comets, met, met2)\n\n # 7.- Compute fitness (measure to optimize):\n print('computing fitness...')\n\n # 7.1.- Determine endCycle: when glucose and acetate are exhausted\n iniBiomass, endCycle, totGlc = end_simulation_cycle(ac1, ac2, df2, met)\n\n # 7.2.- Compute first element fitness: maximize biomass yield\n finalBiomass = biomass_yield(df2,endCycle)\n\n biomassYieldNew=float((finalBiomass-iniBiomass)/(totGlc*0.1801559)) # molecular weigth of met1 per mmol\n\n # For normalizing yield\n MaximumYield=0.6\n\n # 7.3.- Compute second element fitnes: minimize time\n fitTime=1-(float(endCycle)/float(240))\n\n # 7.4.- Compute joint fitness, as a 50% each element.\n fitness= compute_fitness(biomassYieldNew, MaximumYield, finalBiomass, iniBiomass)\n\n # 7.5.- Calculate the uptake of ac_e\n uptakeMet = uptakeMetabolite(comets,layout)\n\n print(\" Total biomass: \"+str(round(finalBiomass,6))+\" in cycle \"+str(endCycle)+\". Biomass yield=\"+str(round(biomassYieldNew,6)))\n totfitness=totfitness+fitness\n fitnessList.append(fitness)\n sumTotBiomass=sumTotBiomass+finalBiomass\n sumTotYield=sumTotYield+biomassYieldNew\n\n # Copy individual solution\n file='IndividualRunsResults/'+'biomass_vs_glc_D_ac_run'+str(i)+'_'+str(fitness)+'_'+str(endCycle)+'.pdf'\n shutil.move('biomass_vs_glc_D_e_ac_e_template_plot1.pdf',file)\n if(dirPlot != ''):\n file2=dirPlot+'biomass_vs_glc_D_ac_'+str(glu1)+'_'+str(ac1)+'_'+str(o21)+'_'+str(glu2)+'_'+str(ac2)+'_'+str(o22)+'_'+str(round(uptakeMet[0],1))+'_'+str(round(uptakeMet[1],1))+'_run'+str(i)+'_'+str(fitness)+'_'+str(endCycle)+'.pdf'\n shutil.copy(file,file2)\n\n\n\n file='IndividualRunsResults/'+'total_biomass_log_run'+str(i)+'.txt'\n shutil.move('Total_biomass_log_template.txt',file)\n file='IndividualRunsResults/'+'media_log_run'+str(i)+'.txt'\n shutil.move('Media_log_template.txt',file)\n file='IndividualRunsResults/'+'flux_log_run'+str(i)+'.txt'\n shutil.move('Flux_log_template.txt',file)\n\n avgfitness=totfitness/repeat\n sdfitness=statistics.stdev(fitnessList)\n avgBiomass=sumTotBiomass/repeat\n avgYield=sumTotYield/repeat\n print(\"Fitness_function\\tconfiguration\\tfitness\\tsd\\tavg.Biomass\\tavg.Yield\\tendCycle\")\n print(fitFunc+\"\\t\"+str(glu1)+','+str(ac1)+','+str(o21)+','+str(glu2)+','+str(ac2)+','+str(o22)+','+str(round(uptakeMet[0],1))+','+str(round(uptakeMet[1],1))+\"\\t\"+str(round(avgfitness,6))+\"\\t\"+str(sdfitness)+\"\\t\"+str(round(avgBiomass,6))+\"\\t\"+str(round(avgYield,6))+\"\\t\"+str(endCycle))\n with open(dirPlot+\"configurationsResults\"+fitFunc+\".txt\", \"a\") as myfile:\n myfile.write(\"Fitness_function\\tconfiguration\\tfitness\\tsd\\tavg.Biomass\\tavg.Yield\\tendCycle\\n\")\n myfile.write(fitFunc+\"\\t\"+str(glu1)+','+str(ac1)+','+str(o21)+','+str(glu2)+','+str(ac2)+','+str(o22)+','+str(round(uptakeMet[0],1))+','+str(round(uptakeMet[1],1))+\"\\t\"+str(round(avgfitness,6))+\"\\t\"+str(sdfitness)+\"\\t\"+str(round(avgBiomass,6))+\"\\t\"+str(round(avgYield,6))+\"\\t\"+str(endCycle)+\"\\n\")\n print(\"Avg.fitness(sd):\\t\"+str(avgfitness)+\"\\t\"+str(sdfitness)+\"\\n\")\n if(sdfitness>0.1):\n avgfitness=0.0\n try:\n os.remove('/home/ana/FLYCOP/Scripts/ecoli_1_tmp.cmd')\n except FileNotFoundError:\n pass\n try:\n os.remove('/home/ana/FLYCOP/Scripts/ecoli_2_tmp.cmd')\n except FileNotFoundError:\n pass\n return avgfitness,sdfitness\n", "meta": {"hexsha": "cf37a2401f9b65c13bd144596b3baf9cd0d30729", "size": 12321, "ext": "py", "lang": "Python", "max_stars_repo_path": "Scripts/ecoliLongTermFLYCOP.py", "max_stars_repo_name": "SBGlab/FLYCOP", "max_stars_repo_head_hexsha": "901b64a6e316eaadfdd03728c410dcdad853b829", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Scripts/ecoliLongTermFLYCOP.py", "max_issues_repo_name": "SBGlab/FLYCOP", "max_issues_repo_head_hexsha": "901b64a6e316eaadfdd03728c410dcdad853b829", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Scripts/ecoliLongTermFLYCOP.py", "max_forks_repo_name": "SBGlab/FLYCOP", "max_forks_repo_head_hexsha": "901b64a6e316eaadfdd03728c410dcdad853b829", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7944785276, "max_line_length": 304, "alphanum_fraction": 0.6642317994, "include": true, "reason": "import numpy", "num_tokens": 3729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.27512972382317524, "lm_q1q2_score": 0.14829030057829712}} {"text": "\"\"\"Contains code for data set creation as well as live environments.\"\"\"\n\nimport argparse\nimport pickle\nimport imageio\nimport numpy as np\nimport scipy as sc\nimport multiprocessing as mp\nfrom tqdm import tqdm\n\nfrom spriteworld import renderers as spriteworld_renderers\nfrom spriteworld.sprite import Sprite\n\n\ndef norm(x):\n \"\"\"Overloading numpys default behaviour for norm().\"\"\"\n if len(x.shape) == 1:\n _norm = np.linalg.norm(x)\n else:\n _norm = np.linalg.norm(x, axis=1).reshape(-1, 1)\n return _norm\n\n\nclass Task():\n \"\"\"Defines a task for interactive environments.\n\n For all tasks defined here, actions correspond to direct movements of the\n controlled balls. Rewards are defined by the derived classes.\n \"\"\"\n\n angular = 1. / np.sqrt(2)\n action_selection = [\n np.array([0., 0.]),\n np.array([1., 0.]),\n np.array([0., 1.]),\n np.array([angular, angular]),\n np.array([-1., 0.]),\n np.array([0., -1.]),\n np.array([-angular, -angular]),\n np.array([-angular, angular]),\n np.array([angular, -angular])]\n\n def __init__(self, env, num_stacked=4, greyscale=False, action_force=.3):\n \"\"\"Initialise task.\n\n Args:\n env (Environment): Tasks have environments as attribute.\n num_stacked (int): Create a frame buffer of num_stacked images.\n greyscale (bool): Convert rgb images to 'greyscale'.\n action_force (float): Distance moved per applied action.\n \"\"\"\n self.env = env\n\n # make controlled ball quasi-static\n self.env.m[0] = 10000\n\n if greyscale:\n self.frame_buffer = np.zeros(\n (*env.get_obs_shape()[:2], num_stacked))\n self.conversion = lambda x: np.sum(\n x * [[[0.3, 0.59, 0.11]]], 2, keepdims=True)\n else:\n sh = env.get_obs_shape()\n self.frame_buffer = np.zeros((*sh[:2], sh[2] * num_stacked))\n self.conversion = lambda x: x\n\n self.frame_channels = 3 if not greyscale else 1\n self.action_force = action_force\n\n def get_action_space(self):\n \"\"\"Return number of available actions.\"\"\"\n return len(self.action_selection)\n\n def get_framebuffer_shape(self):\n \"\"\"Return shape of frame buffer.\"\"\"\n return self.frame_buffer.shape\n\n def calculate_reward(self, state, action, env):\n \"\"\"Abstract method. To be overwritten by derived classes.\"\"\"\n raise NotImplementedError\n\n def resolve_action(self, _action, env=None):\n \"\"\"Implement the effects of an action. Change this to change action.\"\"\"\n action = self.action_selection[_action]\n action = action * self.action_force\n return action\n\n def step(self, _action):\n \"\"\"Propagate env to next step.\"\"\"\n action = self.resolve_action(_action)\n img, state, done = self.env.step(action)\n r = self.calculate_reward()\n return img, state, r, done\n\n def step_frame_buffer(self, _action=None):\n \"\"\"Step environment with frame buffer.\"\"\"\n action = self.resolve_action(_action)\n img, state, done = self.env.step(action)\n r = self.calculate_reward()\n\n img = self.conversion(img)\n c = self.frame_channels\n self.frame_buffer[:, :, :-c] = self.frame_buffer[:, :, c:]\n self.frame_buffer[:, :, -c:] = img\n\n return self.frame_buffer, state, r, done\n\n\nclass AvoidanceTask(Task):\n \"\"\"Derived Task: Avoidance Task.\"\"\"\n\n def calculate_reward(self,):\n \"\"\"Negative sparse reward of -1 is given in case of collisions.\"\"\"\n return -self.env.collisions\n\nclass MaxDistanceTask(Task):\n \"\"\"Derived Task: Maximal Distance Task.\"\"\"\n\n def calculate_reward(self):\n \"\"\"Continuous reward is given.\n\n Negative reward is given in dependence of the minimal distance of the\n controlled ball to any other ball.\n \"\"\"\n scaling = 2\n r = 0\n for i in range(1, self.env.n):\n current_norm = norm(self.env.x[i, 0:2] - self.env.x[0, 0:2])\\\n - 2 * self.env.r[0]\n current_exp = -np.clip(np.exp(-current_norm * scaling), 0, 1)\n r = min(r, current_exp)\n return r\n\n\nclass MinDistanceTask(Task):\n \"\"\"Derived Task: Minimal Distance Task.\"\"\"\n\n def calculate_reward(self, state, action, env):\n \"\"\"Continuous reward is given.\n\n Controlled ball is incentivised to follow any of the other balls.\n Reward is always negative, unless the controlled ball touches any of the\n other balls. Negative reward is given for the distance to the nearest\n ball to the controlled ball.\n \"\"\"\n # initialize r to very small reward (~ -inf)\n r = - ((100 * env.hw) ** 2)\n for i in range(1, env.n):\n r = max(r,\n -(norm(state[i, 0:2] - state[0, 0:2]) - 2 * env.r[0]) ** 2)\n return r\n\n\nclass PhysicsEnv:\n \"\"\"Base class for the physics environments.\"\"\"\n\n def __init__(self, n=3, r=1., m=1., hw=10, granularity=5, res=32, t=1.,\n init_v_factor=None, friction_coefficient=0., seed=None,\n sprites=False, use_colors=None):\n \"\"\"Initialize a physics env with some general parameters.\n\n Args:\n n (int): Optional, number of objects in the scene.\n r (float)/list(float): Optional, radius of objects in the scene.\n m (float)/list(float): Optional, mass of the objects in the scene.\n hw (float): Optional, coordinate limits of the environment.\n eps (float): Optional, internal simulation granularity as the\n fraction of one time step. Does not change speed of simulation.\n res (int): Optional, pixel resolution of the images.\n t (float): Optional, dt of the step() method. Speeds up or slows\n down the simulation.\n init_v_factor (float): Scaling factor for inital velocity. Used only\n in Gravity Environment.\n friction_coefficient (float): Friction slows down balls.\n seed (int): Set random seed for reproducibility.\n sprites (bool): Render selection of sprites using spriteworld\n instead of balls.\n\n \"\"\"\n np.random.seed(seed)\n\n self.n = n\n self.r = np.array([[r]] * n) if np.isscalar(r) else r\n self.m = np.array([[m]] * n) if np.isscalar(m) else m\n self.hw = hw\n self.internal_steps = granularity\n self.eps = 1 / granularity\n self.res = res\n self.t = t\n\n self.x = self.init_x()\n self.v = self.init_v(init_v_factor)\n self.a = np.zeros_like(self.v)\n\n self.fric_coeff = friction_coefficient\n self.v_rotation_angle = 2 * np.pi * 0.05\n\n if use_colors is None:\n if n < 3:\n self.use_colors = False\n else:\n self.use_colors = True\n else:\n self.use_colors = use_colors\n\n if sprites:\n self.renderer = spriteworld_renderers.PILRenderer(\n image_size=(self.res, self.res),\n anti_aliasing=10,\n )\n\n shapes = ['triangle', 'square', 'circle', 'star_4']\n\n if not np.isscalar(r):\n print(\"Scale elements according to radius of first element.\")\n\n # empirical scaling rule, works for r = 1.2 and 2\n self.scale = self.r[0] / self.hw / 0.6\n self.shapes = np.random.choice(shapes, 3)\n self.draw_image = self.draw_sprites\n\n else:\n self.draw_image = self.draw_balls\n\n def init_v(self, init_v_factor=None):\n \"\"\"Randomly initialise velocities.\"\"\"\n v = np.random.normal(size=(self.n, 2))\n v = v / np.sqrt((v ** 2).sum()) * .5\n\n if init_v_factor is not None:\n v = v * np.random.uniform(1/init_v_factor, init_v_factor)\n\n return v\n\n def init_x(self):\n \"\"\"Initialize ojbject positions without overlap and in bounds.\"\"\"\n good_config = False\n while not good_config:\n x = np.random.rand(self.n, 2) * self.hw / 2 + self.hw / 4\n good_config = True\n for i in range(self.n):\n for z in range(2):\n if x[i][z] - self.r[i] < 0:\n good_config = False\n if x[i][z] + self.r[i] > self.hw:\n good_config = False\n\n for i in range(self.n):\n for j in range(i):\n if norm(x[i] - x[j]) < self.r[i] + self.r[j]:\n good_config = False\n return x\n\n def simulate_physics(self, actions):\n \"\"\"Calculates physics for a single time step.\n\n What \"physics\" means is defined by the respective derived classes.\n\n Args:\n action (np.Array(float)): A 2D-float giving an x,y force to\n enact upon the first object.\n\n Returns:\n d_vs (np.Array(float)): Velocity updates for the simulation.\n\n \"\"\"\n raise NotImplementedError\n\n def step(self, action=None, mass_center_obs=False):\n \"\"\"Full step for the environment.\"\"\"\n if action is not None:\n # Actions are implemented as hardly affecting the first object's v.\n self.v[0] = action * self.t\n actions = True\n\n else:\n actions = False\n\n for _ in range(self.internal_steps):\n self.x += self.t * self.eps * self.v\n\n if mass_center_obs:\n # Do simulation in center of mass system.\n c_body = np.sum(self.m * self.x, 0) / np.sum(self.m)\n self.x += self.hw / 2 - c_body\n\n self.v -= self.fric_coeff * self.m * self.v * self.t * self.eps\n self.v = self.simulate_physics(actions)\n\n img = self.draw_image()\n state = np.concatenate([self.x, self.v], axis=1)\n done = False\n\n return img, state, done\n\n def get_obs_shape(self):\n \"\"\"Return image dimensions.\"\"\"\n return (self.res, self.res, 3)\n\n def get_state_shape(self):\n \"\"\"Get shape of state array.\"\"\"\n state = np.concatenate([self.x, self.v], axis=1)\n return state.shape\n\n @staticmethod\n def ar(x, y, z):\n \"\"\"Offset array function.\"\"\"\n return z / 2 + np.arange(x, y, z, dtype='float')\n\n def draw_balls(self):\n \"\"\"Render balls on canvas.\"\"\"\n if self.n > 6:\n raise ValueError(\n 'Max self.n implemented currently is 6.')\n\n img = np.zeros((self.res, self.res, 3), dtype='float')\n [I, J] = np.meshgrid(self.ar(0, 1, 1. / self.res) * self.hw,\n self.ar(0, 1, 1. / self.res) * self.hw)\n\n colors = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1],\n [1, 1, 0], [1, 0, 1], [0, 1, 1]])\n\n for i in range(self.n):\n factor = np.exp(- (((I - self.x[i, 0]) ** 2 +\n (J - self.x[i, 1]) ** 2) /\n (self.r[i] ** 2)) ** 4)\n\n if self.use_colors:\n img[:, :, 0] += colors[i, 0] * factor\n img[:, :, 1] += colors[i, 1] * factor\n img[:, :, 2] += colors[i, 2] * factor\n\n else:\n idx = i % 3\n img[:, :, idx] += factor\n\n img[img > 1] = 1\n\n return img\n\n def draw_sprites(self):\n \"\"\"Render sprites on the current locations.\"\"\"\n\n s1 = Sprite(self.x[0, 0] / self.hw, 1 - self.x[0, 1] / self.hw,\n self.shapes[0],\n c0=255, c1=0, c2=0, scale=self.scale)\n s2 = Sprite(self.x[1, 0] / self.hw, 1 - self.x[1, 1] / self.hw,\n self.shapes[1],\n c0=0, c1=255, c2=0, scale=self.scale)\n s3 = Sprite(self.x[2, 0] / self.hw, 1 - self.x[2, 1] / self.hw,\n self.shapes[2],\n c0=0, c1=0, c2=255, scale=self.scale)\n\n sprites = [s1, s2, s3]\n img = self.renderer.render(sprites)\n\n return img / 255.\n\n def reset(self, init_v_factor=None):\n \"\"\"Resets the environment to a new configuration.\"\"\"\n self.v = self.init_v(init_v_factor)\n self.a = np.zeros_like(self.v)\n self.x = self.init_x()\n\n\nclass BillardsEnv(PhysicsEnv):\n \"\"\"Billiards or Bouncing Balls environment.\"\"\"\n\n def __init__(self, n=3, r=1., m=1., hw=10, granularity=5, res=32, t=1.,\n init_v_factor=None, friction_coefficient=0., seed=None,\n sprites=False, use_colors=None, drift=False):\n \"\"\"Initialise arguments of parent class.\"\"\"\n super().__init__(n, r, m, hw, granularity, res, t, init_v_factor,\n friction_coefficient, seed, sprites, use_colors)\n\n # collisions is updated in step to measure the collisions of the balls\n self.collisions = 0\n\n # no collisions between objects!\n self.drift = drift\n\n def simulate_physics(self, actions):\n # F = ma = m dv/dt ---> dv = a * dt = F/m * dt\n v = self.v.copy()\n\n # check for collisions with wall\n for i in range(self.n):\n for z in range(2):\n next_pos = self.x[i, z] + (v[i, z] * self.eps * self.t)\n # collision at 0 wall\n if next_pos < self.r[i]:\n self.x[i, z] = self.r[i]\n v[i, z] = - v[i, z]\n # collision at hw wall\n elif next_pos > (self.hw - self.r[i]):\n self.x[i, z] = self.hw - self.r[i]\n v[i, z] = - v[i, z]\n\n if self.drift:\n return v\n\n # check for collisions with objects\n for i in range(self.n):\n for j in range(i):\n\n dist = norm((self.x[i] + v[i] * self.t * self.eps)\n - (self.x[j] + v[j] * self.t * self.eps))\n\n if dist < (self.r[i] + self.r[j]):\n if actions and j == 0:\n self.collisions = 1\n\n w = self.x[i] - self.x[j]\n w = w / norm(w)\n\n v_i = np.dot(w.transpose(), v[i])\n v_j = np.dot(w.transpose(), v[j])\n\n if actions and j == 0:\n v_j = 0\n\n new_v_i, new_v_j = self.new_speeds(\n self.m[i], self.m[j], v_i, v_j)\n\n v[i] += w * (new_v_i - v_i)\n v[j] += w * (new_v_j - v_j)\n\n if actions and j == 0:\n v[j] = 0\n\n return v\n\n def new_speeds(self, m1, m2, v1, v2):\n \"\"\"Implement elastic collision between two objects.\"\"\"\n new_v2 = (2 * m1 * v1 + v2 * (m2 - m1)) / (m1 + m2)\n new_v1 = new_v2 + (v2 - v1)\n return new_v1, new_v2\n\n def step(self, action=None):\n \"\"\"Overwrite step functino to ensure collisions are zeroed beforehand.\"\"\"\n self.collisions = 0\n return super().step(action)\n\n\nclass GravityEnv(PhysicsEnv):\n \"\"\"Derived Task: Minimal Distance Task.\"\"\"\n\n def __init__(self, n=3, r=1., m=1., hw=10, granularity=5, res=32, t=1,\n init_v_factor=0.18, friction_coefficient=0, seed=None,\n sprites=False, use_colors=False, drift=False):\n \"\"\"Initialise arguments of parent class.\"\"\"\n\n super().__init__(\n n, r, m, hw, granularity, res, t, init_v_factor,\n friction_coefficient, seed, sprites, use_colors)\n\n self.G = 0.5\n self.K1 = self.G\n self.K2 = 1\n\n def init_x(self):\n \"\"\"Initialize object positions without overlap and in bounds.\n\n To achieve a stable gravity configuration, default init is overwritten.\n Here, objects are initialised with more padding.\n \"\"\"\n good_config = False\n counter = 0\n while not good_config and counter < 1000:\n x = sc.rand(self.n, 2) * 0.9 * self.hw / 2 + self.hw / 2\n good_config = True\n for i in range(self.n):\n for j in range(i):\n good_config = good_config and norm(\n x[i] - x[j]) > self.hw / 3\n counter += 1\n return x\n\n def init_v(self, factor):\n \"\"\"Initialize a stable velocity configuration.\n\n Velocities are initialised as orthogonal to the object's position vector\n as measured from the center.\n \"\"\"\n x_middle = np.sum(self.x, 0) / self.n\n pref = np.random.choice([-1, 1])\n full_v = np.zeros((self.n, 2))\n\n for i in range(self.n):\n v = - (x_middle - self.x[i])\n v = v / norm(v)\n # make noise component wise\n full_v[i] = np.array([pref * v[1] * (factor + 0.13 * sc.randn()),\n -pref * v[0] * (factor + 0.13 * sc.randn())])\n return full_v\n\n def step(self, action=None):\n \"\"\"Set actions to false by default.\"\"\"\n return super().step(action, True)\n\n def simulate_physics(self, actions):\n \"\"\"Simulate gravitational physics.\n\n Additional attractive force towards the center is applied for stability.\n Forces are clipped to avoid slingshotting effects.\n \"\"\"\n x_middle = np.array([self.hw/2, self.hw/2])\n v = np.zeros_like(self.v)\n\n for i in range(self.n):\n F_tot = np.array([0., 0.])\n\n for j in range(self.n):\n if i != j:\n r = np.linalg.norm(self.x[j] - self.x[i])\n F_tot -= self.G * self.m[j] * self.m[i] * (\n self.x[i] - self.x[j]) / ((r + 1e-5) ** 3)\n\n r = (x_middle - self.x[i])\n F_tot += 0.001 * (r ** 3) / norm(r)\n F_tot = np.clip(F_tot, -1, 1)\n v[i] = self.v[i] + (F_tot / self.m[i]) * self.t * self.eps\n\n return v\n\n\nclass ActionPolicy:\n \"\"\"Abstract base class for action policy.\n\n An action policy specifies a series of actions.\n \"\"\"\n\n def __init__(self, action_space):\n \"\"\"Initialise action policy.\n\n Args:\n action_space (int): Number of available actions.\n \"\"\"\n self.action_space = action_space\n\n def next(self):\n raise NotImplementedError(\"ABC does not implement methods.\")\n\n\nclass RandomActionPolicy(ActionPolicy):\n \"\"\"Random action policy.\"\"\"\n\n def __init__(self, action_space=9):\n \"\"\"Initialise random action policy.\"\"\"\n super().__init__(action_space)\n\n def next(self):\n \"\"\"Next action is given completely independent of history.\"\"\"\n return np.random.randint(self.action_space)\n\n\nclass MonteCarloActionPolicy(ActionPolicy):\n \"\"\"Monte carlo action policy.\n\n First action is chosen randomly. After, action is only changed with\n prob_change probability.\n \"\"\"\n\n def __init__(self, action_space=9, prob_change=0.1):\n \"\"\"Initialise monte carlo action policy.\n\n Args:\n prob_change (float): Probability of changing action from t to t+1.\n\n \"\"\"\n super().__init__(action_space)\n self.p = prob_change\n self.action_arr = range(self.action_space)\n self.current_state = np.random.randint(self.action_space)\n\n def next(self):\n \"\"\"Get next action given current.\"\"\"\n action_space = self.action_space\n current_weights = self.p / (action_space - 1) * np.ones(action_space)\n current_weights[self.current_state] = 1 - self.p\n # assert current_weights.sum() == 1\n\n self.current_state = np.random.choice(self.action_arr,\n p=current_weights)\n return self.current_state\n\n\ndef generate_fitting_run(env_class, run_len=100, run_num=1000, max_tries=10000,\n res=50, n=2, r=1., dt=0.01, granularity=10, fc=0.3,\n hw=10, m=1., seed=None,\n init_v_factor=None, check_overlap=False, sprites=False,\n use_colors=None, drift=False):\n \"\"\"Generate runs for environments.\n\n Integrated error checks. Parameters as passed to environments.\n \"\"\"\n good_counter = 0\n bad_counter = 0\n good_imgs = []\n good_states = []\n\n for _try in tqdm(range(max_tries)):\n # init_v is ignored for BillardsEnv\n env = env_class(\n n=n, r=r, m=m, hw=hw, granularity=granularity, res=res, t=dt,\n init_v_factor=init_v_factor, friction_coefficient=fc, seed=seed,\n sprites=sprites, use_colors=use_colors, drift=drift)\n\n run_value = 0\n\n all_imgs = np.zeros((run_len, *env.get_obs_shape()))\n all_states = np.zeros((run_len, env.n, 4))\n\n run_value = 0\n for t in tqdm(range(run_len)):\n\n img, state, _ = env.step()\n all_imgs[t] = img\n all_states[t] = state\n\n run_value += np.sum(np.logical_and(\n state[:, :2] > 0, state[:, :2] < env.hw)) / (env.n * 2)\n\n if check_overlap:\n\n overlap = 0\n for i in range(n):\n other = list(set(range(n)) - {i, })\n # allow small overlaps\n overlap += np.any(norm(state[i, :2] - state[other, :2])\n < 0.9 * (env.r[i] + env.r[other]))\n\n if overlap > 0:\n run_value -= 1\n\n if run_value > (run_len - run_len / 100):\n good_imgs.append(all_imgs)\n good_states.append(all_states)\n good_counter += 1\n else:\n bad_counter += 1\n\n if good_counter >= run_num:\n break\n\n good_imgs = np.stack(good_imgs, 0)\n good_states = np.stack(good_states, 0)\n\n print(\n 'Generation of {} runs finished, total amount of bad runs: {}. '.format(\n run_num, bad_counter))\n\n return good_imgs, good_states\n\n\ndef generate_data(save=True, test_gen=False, name='billiards', env=BillardsEnv,\n config=None, num_runs=None):\n \"\"\"Generate data for billiards or gravity environment.\"\"\"\n if num_runs is None or test_gen:\n num_runs = [1000, 300] if (save and not test_gen) else [2, 5]\n\n for run_types, run_num in zip(['train', 'test'], num_runs):\n\n # generate runs\n X, y = generate_fitting_run(\n env, run_len=100, run_num=run_num, max_tries=10000, **config)\n\n # save data\n data = dict()\n data['X'] = X\n data['y'] = y\n data.update(config)\n data['coord_lim'] = config['hw']\n\n if save:\n path = './data/{}_{}.pkl'.format(name, run_types)\n f = open(path, \"wb\")\n pickle.dump(data, f, protocol=4)\n f.close()\n\n # also generate gif of data\n first_seq = (255 * X[:20].reshape(\n (-1, config['res'], config['res'], 3))).astype(np.uint8)\n imageio.mimsave('./data/{}.gif'.format(name), first_seq, fps=24)\n\n\ndef generate_billiards_w_actions(ChosenTask=AvoidanceTask, save=True,\n config=None, test_gen=False):\n \"\"\"Generate action conditioned billiards data.\"\"\"\n run_len = 100\n action_space = 9\n action_force = 0.6\n\n num_runs = [1000, 300] if (save and not test_gen) else [2, 10]\n\n for run_types, run_num in zip(['train', 'test'], num_runs):\n\n all_imgs = np.zeros(\n (run_num, run_len, config['res'], config['res'], 3))\n all_states = np.zeros((run_num, run_len, config['n'], 4))\n all_actions = np.zeros((run_num, run_len, 9))\n all_rewards = np.zeros((run_num, run_len, 1))\n all_dones = np.zeros((run_num, run_len, 1))\n\n # number of sequences\n for run in tqdm(range(run_num)):\n env = ChosenTask(BillardsEnv(**config),\n 4, greyscale=False, action_force=action_force)\n\n assert action_space == env.get_action_space()\n p = np.random.uniform(0.2, 0.3)\n ap = MonteCarloActionPolicy(action_space=action_space,\n prob_change=p)\n\n # number of steps per sequence\n for t in tqdm(range(run_len)):\n action = ap.next()\n img, state, reward, done = env.step(action)\n all_imgs[run, t] = img\n all_states[run, t] = state\n\n tmp = np.zeros(action_space)\n tmp[action] = 1\n all_actions[run, t - 1] = tmp\n all_rewards[run, t] = reward\n all_dones[run, t] = done\n\n # save results\n data = dict()\n data['X'] = all_imgs\n data['y'] = all_states\n data['action'] = all_actions\n data['reward'] = all_rewards\n data['done'] = all_dones\n # still a bit hacky, need to implement __str__\n if ChosenTask is not AvoidanceTask:\n raise ValueError\n data['type'] = 'AvoidanceTask'\n data['action_force'] = action_force\n\n data.update({'action_space': action_space})\n data.update(config)\n data['coord_lim'] = config['hw']\n\n if save:\n path = 'data/avoidance_{}.pkl'.format(run_types)\n f = open(path, \"wb\")\n pickle.dump(data, f, protocol=4)\n f.close()\n\n # example sequences as gif\n res = config['res']\n first_seq = (255 * all_imgs[:20].reshape((-1, res, res, 3)))\n first_seq = first_seq.astype(np.uint8)\n imageio.mimsave('data/avoidance.gif'.format(save), first_seq, fps=24)\n\n\ndef parse_wrapper(script_args):\n \"\"\"DRY wrapper around parse.\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--test-gen', dest='test_gen', action='store_true')\n parser.add_argument('--no-save', dest='save', action='store_false')\n args = parser.parse_args(script_args)\n return args\n\n\ndef multi_billiards(script_args):\n \"\"\"Create billiards with 6 balls.\"\"\"\n args = parse_wrapper(script_args)\n\n config = {\n 'res': 50, 'hw': 10, 'n': 6, 'dt': 1, 'm': 1., 'fc': 0,\n 'granularity': 10, 'r': 1, 'check_overlap': False, 'use_colors': False}\n\n generate_data(\n save=args.save, test_gen=args.test_gen, name='multibilliards',\n env=BillardsEnv, config=config)\n\n\ndef billiards_energy(script_args):\n \"\"\"Create billiards with varying total energy.\"\"\"\n args = parse_wrapper(script_args)\n\n config = {\n 'res': 32, 'hw': 10, 'n': 3, 'dt': 1, 'm': 1., 'fc': 0,\n 'granularity': 10, 'r': 1.2, 'check_overlap': False,\n 'init_v_factor': args.init_v}\n\n name = 'billiards_energy_{:.1f}'.format(args.init_v)\n\n generate_data(\n save=args.save, test_gen=args.test_gen, name=name,\n env=BillardsEnv, config=config)\n\n\ndef drift_runs(script_args):\n \"\"\"Create billiards with varying total energy.\"\"\"\n args = parse_wrapper(script_args)\n\n config = {\n 'res': 32, 'hw': 10, 'n': 3, 'dt': 1, 'm': 1., 'fc': 0,\n 'granularity': 10, 'r': 1.2, 'check_overlap': False, 'drift': True}\n\n name = 'billiards_drift'\n\n generate_data(\n save=args.save, test_gen=args.test_gen, name=name,\n env=BillardsEnv, config=config)\n\n\ndef billiards_smooth(script_args):\n \"\"\"Create billiards with varying total energy.\"\"\"\n args = parse_wrapper(script_args)\n\n config = {\n 'res': 32, 'hw': 10, 'n': 3, 'dt': 1, 'm': 1., 'fc': 0,\n 'granularity': 10, 'r': 1.2, 'check_overlap': False, 'drift': False,}\n\n name = 'billiards_smooth'\n\n generate_data(\n save=args.save, test_gen=args.test_gen, name=name,\n env=BillardsEnv, config=config)\n\ndef main(script_args):\n \"\"\"Create standard collection of data sets.\"\"\"\n args = parse_wrapper(script_args)\n\n config = {\n 'res': 32, 'hw': 10, 'n': 3, 'dt': 1, 'm': 1., 'fc': 0,\n 'granularity': 10, 'r': 1.2, 'check_overlap': False}\n\n generate_data(\n save=args.save, test_gen=args.test_gen, name='billiards',\n env=BillardsEnv, config=config)\n\n # config.update({'sprites': True})\n # generate_data(\n # test_gen=args.test_gen, name='billards_sprites', env=BillardsEnv, config=config)\n\n config = {\n 'res': 50, 'hw': 30, 'n': 3, 'dt': 1, 'm': 4., 'fc': 0,\n 'init_v_factor': 0.55, 'granularity': 50, 'r': 2,\n 'check_overlap': True}\n\n generate_data(\n save=args.save, test_gen=args.test_gen, name='gravity',\n env=GravityEnv, config=config)\n\n # config.update({'sprites': True})\n # generate_data(\n # test_gen=args.test_gen, name='gravity_sprites', env=GravityEnv, config=config)\n\n config = {\n 'res': 32, 'hw': 10, 'n': 3, 't': 1., 'm': 1.,\n 'granularity': 50, 'r': 1, 'friction_coefficient': 0}\n\n generate_billiards_w_actions(\n config=config, save=args.save, test_gen=args.test_gen)\n", "meta": {"hexsha": "0af3d12952374cf52746ee046c82c6ed43e0a829", "size": 28906, "ext": "py", "lang": "Python", "max_stars_repo_path": "model/envs/envs.py", "max_stars_repo_name": "jlko/STOVE", "max_stars_repo_head_hexsha": "8cbb7da856c18c6eb75d86030dbbf42b067ab559", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T19:19:14.000Z", "max_issues_repo_path": "model/envs/envs.py", "max_issues_repo_name": "jlko/STOVE", "max_issues_repo_head_hexsha": "8cbb7da856c18c6eb75d86030dbbf42b067ab559", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-05-08T11:01:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-24T07:50:10.000Z", "max_forks_repo_path": "model/envs/envs.py", "max_forks_repo_name": "jlko/STOVE", "max_forks_repo_head_hexsha": "8cbb7da856c18c6eb75d86030dbbf42b067ab559", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2020-01-13T11:25:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-10T06:04:08.000Z", "avg_line_length": 33.611627907, "max_line_length": 90, "alphanum_fraction": 0.5473950045, "include": true, "reason": "import numpy,import scipy", "num_tokens": 7236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.2782568056728001, "lm_q1q2_score": 0.1478126233784312}} {"text": "# Copyright (C) 2011 Atsushi Togo\n# All rights reserved.\n#\n# This file is part of phonopy.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in\n# the documentation and/or other materials provided with the\n# distribution.\n#\n# * Neither the name of the phonopy project nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport sys\nimport numpy as np\nimport phonopy.structure.spglib as spg\nfrom phonopy.structure.cells import (get_primitive, get_supercell,\n compute_all_sg_permutations)\nfrom phonopy.structure.atoms import PhonopyAtoms as Atoms\nfrom phonopy.harmonic.force_constants import similarity_transformation\n\nclass Symmetry(object):\n def __init__(self, cell, symprec=1e-5, is_symmetry=True):\n self._cell = cell\n self._symprec = symprec\n\n self._symmetry_operations = None\n self._international_table = None\n self._dataset = None\n self._wyckoff_letters = None\n self._map_atoms = None\n self._atomic_permutations = None\n\n magmom = cell.get_magnetic_moments()\n if type(magmom) is np.ndarray:\n if (magmom < symprec).all():\n magmom = None\n\n if not is_symmetry:\n self._set_nosym()\n elif magmom is None:\n self._set_symmetry_dataset()\n else:\n self._set_symmetry_operations_with_magmoms()\n\n self._pointgroup_operations = None\n self._pointgroup = None\n self._set_pointgroup_operations()\n\n self._independent_atoms = None\n self._set_independent_atoms()\n self._map_operations = None\n\n def get_symmetry_operations(self):\n return self._symmetry_operations\n\n def get_symmetry_operation(self, operation_number):\n operation = self._symmetry_operations\n return {'rotations': operation['rotations'][operation_number],\n 'translations': operation['translations'][operation_number]}\n\n def get_pointgroup_operations(self):\n return self._pointgroup_operations\n\n def get_pointgroup(self):\n return self._pointgroup\n\n def get_international_table(self):\n return self._international_table\n\n def get_Wyckoff_letters(self):\n return self._wyckoff_letters\n\n def get_dataset(self):\n return self._dataset\n\n def get_independent_atoms(self):\n return self._independent_atoms\n\n def get_map_atoms(self):\n return self._map_atoms\n\n def get_map_operations(self):\n if self._map_operations is None:\n self._set_map_operations()\n return self._map_operations\n\n def get_site_symmetry(self, atom_number):\n positions = self._cell.get_scaled_positions()\n lattice = self._cell.get_cell()\n rotations = self._symmetry_operations['rotations']\n translations = self._symmetry_operations['translations']\n\n return self._get_site_symmetry(atom_number,\n lattice,\n positions,\n rotations,\n translations,\n self._symprec)\n\n def get_symmetry_tolerance(self):\n return self._symprec\n\n def get_reciprocal_operations(self):\n \"\"\"\n Definition of operation:\n q' = Rq\n\n This is transpose of that shown in ITA (q' = qR).\n \"\"\"\n return self._reciprocal_operations\n\n def get_atomic_permutations(self):\n if self._atomic_permutations is None:\n positions = self._cell.get_scaled_positions()\n lattice = np.array(self._cell.get_cell().T,\n dtype='double', order='C')\n rotations = self._symmetry_operations['rotations']\n translations = self._symmetry_operations['translations']\n self._atomic_permutations = compute_all_sg_permutations(\n positions, # scaled positions\n rotations, # scaled\n translations, # scaled\n lattice, # column vectors\n self._symprec)\n\n return self._atomic_permutations\n\n def _get_pointgroup_operations(self, rotations):\n ptg_ops = []\n for rot in rotations:\n is_same = False\n for tmp_rot in ptg_ops:\n if (tmp_rot == rot).all():\n is_same = True\n break\n if not is_same:\n ptg_ops.append(rot)\n\n return ptg_ops\n\n def _get_site_symmetry(self,\n atom_number,\n lattice,\n positions,\n rotations,\n translations,\n symprec):\n pos = positions[atom_number]\n site_symmetries = []\n\n for r, t in zip(rotations, translations):\n rot_pos = np.dot(pos, r.T) + t\n diff = pos - rot_pos\n diff -= np.rint(diff)\n diff = np.dot(diff, lattice)\n if np.linalg.norm(diff) < symprec:\n site_symmetries.append(r)\n\n return np.array(site_symmetries, dtype='intc')\n\n def _set_symmetry_dataset(self):\n self._dataset = spg.get_symmetry_dataset(self._cell, self._symprec)\n self._symmetry_operations = {\n 'rotations': self._dataset['rotations'],\n 'translations': self._dataset['translations']}\n self._international_table = \"%s (%d)\" % (self._dataset['international'],\n self._dataset['number'])\n self._wyckoff_letters = self._dataset['wyckoffs']\n\n self._map_atoms = self._dataset['equivalent_atoms']\n\n def _set_symmetry_operations_with_magmoms(self):\n cell = (self._cell.get_cell(),\n self._cell.get_scaled_positions(),\n self._cell.get_atomic_numbers(),\n self._cell.get_magnetic_moments())\n self._symmetry_operations = spg.get_symmetry(cell,\n symprec=self._symprec)\n self._map_atoms = self._symmetry_operations['equivalent_atoms']\n self._set_map_atoms()\n\n def _set_map_atoms(self):\n rotations = self._symmetry_operations['rotations']\n translations = self._symmetry_operations['translations']\n positions = self._cell.get_scaled_positions()\n lattice = self._cell.get_cell()\n map_atoms = np.arange(self._cell.get_number_of_atoms())\n for i, p in enumerate(positions):\n is_found = False\n for j in range(i):\n for r, t in zip(rotations, translations):\n diff = np.dot(p, r.T) + t - positions[j]\n diff -= np.rint(diff)\n dist = np.linalg.norm(np.dot(diff, lattice))\n if dist < self._symprec:\n map_atoms[i] = j\n is_found = True\n break\n if is_found:\n break\n self._map_atoms = np.array(map_atoms, dtype='intc')\n\n def _set_independent_atoms(self):\n indep_atoms = []\n for i, atom_map in enumerate(self._map_atoms):\n if i == atom_map:\n indep_atoms.append(i)\n self._independent_atoms = np.array(indep_atoms, dtype='intc')\n\n def _set_pointgroup_operations(self):\n rotations = self._symmetry_operations['rotations']\n ptg_ops = self._get_pointgroup_operations(rotations)\n reciprocal_rotations = [rot.T for rot in ptg_ops]\n exist_r_inv = False\n for rot in ptg_ops:\n if (rot + np.eye(3, dtype='intc') == 0).all():\n exist_r_inv = True\n break\n if not exist_r_inv:\n reciprocal_rotations += [-rot.T for rot in ptg_ops]\n\n self._pointgroup_operations = np.array(ptg_ops, dtype='intc')\n self._pointgroup = get_pointgroup(self._pointgroup_operations)[0]\n self._reciprocal_operations = np.array(reciprocal_rotations,\n dtype='intc')\n\n def _set_map_operations(self):\n ops = self._symmetry_operations\n pos = self._cell.get_scaled_positions()\n lattice = self._cell.get_cell()\n map_operations = np.zeros(len(pos), dtype='intc')\n\n for i, eq_atom in enumerate(self._map_atoms):\n for j, (r, t) in enumerate(\n zip(ops['rotations'], ops['translations'])):\n\n diff = np.dot(pos[i], r.T) + t - pos[eq_atom]\n diff -= np.rint(diff)\n dist = np.linalg.norm(np.dot(diff, lattice))\n if dist < self._symprec:\n map_operations[i] = j\n break\n self._map_operations = map_operations\n\n def _set_nosym(self):\n translations = []\n rotations = []\n\n if 'get_supercell_to_unitcell_map' in dir(self._cell):\n s2u_map = self._cell.get_supercell_to_unitcell_map()\n positions = self._cell.get_scaled_positions()\n\n for i, j in enumerate(s2u_map):\n if j==0:\n ipos0 = i\n break\n\n for i, p in zip(s2u_map, positions):\n if i==0:\n trans = p - positions[ipos0]\n trans -= np.floor(trans)\n translations.append(trans)\n rotations.append(np.eye(3, dtype='intc'))\n\n self._map_atoms = s2u_map\n else:\n rotations.append(np.eye(3, dtype='intc'))\n translations.append(np.zeros(3, dtype='double'))\n self._map_atoms = range(self._cell.get_number_of_atoms())\n\n self._symmetry_operations = {\n 'rotations': np.array(rotations, dtype='intc'),\n 'translations': np.array(translations, dtype='double')}\n self._international_table = 'P1 (1)'\n self._wyckoff_letters = ['a'] * self._cell.get_number_of_atoms()\n\n\ndef find_primitive(cell, symprec=1e-5):\n \"\"\"\n A primitive cell is searched in the input cell. When a primitive\n cell is found, an object of Atoms class of the primitive cell is\n returned. When not, None is returned.\n \"\"\"\n lattice, positions, numbers = spg.find_primitive(cell, symprec)\n if lattice is None:\n return None\n else:\n return Atoms(numbers=numbers,\n scaled_positions=positions,\n cell=lattice,\n pbc=True)\n\ndef get_pointgroup(rotations):\n ptg = spg.get_pointgroup(rotations)\n return ptg[0].strip(), ptg[2]\n\ndef get_lattice_vector_equivalence(point_symmetry):\n \"\"\"Return (b==c, c==a, a==b)\"\"\"\n # primitive_vectors: column vectors\n\n equivalence = [False, False, False]\n for r in point_symmetry:\n if (np.abs(r[:, 0]) == [0, 1, 0]).all():\n equivalence[2] = True\n if (np.abs(r[:, 0]) == [0, 0, 1]).all():\n equivalence[1] = True\n if (np.abs(r[:, 1]) == [1, 0, 0]).all():\n equivalence[2] = True\n if (np.abs(r[:, 1]) == [0, 0, 1]).all():\n equivalence[0] = True\n if (np.abs(r[:, 2]) == [1, 0, 0]).all():\n equivalence[1] = True\n if (np.abs(r[:, 2]) == [0, 1, 0]).all():\n equivalence[0] = True\n\n return equivalence\n\ndef elaborate_borns_and_epsilon(ucell,\n borns,\n epsilon,\n primitive_matrix=None,\n supercell_matrix=None,\n is_symmetry=True,\n symmetrize_tensors=False,\n symprec=1e-5):\n \"\"\"Symmetrize Born effective charges and dielectric constants and\n extract Born effective charges of symmetrically independent atoms\n for primitive cell.\n\n\n Args:\n ucell (Atoms): Unit cell structure\n borns (np.array): Born effective charges of ucell\n epsilon (np.array): Dielectric constant tensor\n\n Returns:\n (np.array) Born effective charges of symmetrically independent atoms\n in primitive cell\n (np.array) Dielectric constant\n (np.array) Atomic index mapping table from supercell to primitive cell\n of independent atoms\n\n Raises:\n AssertionError: Inconsistency of number of atoms or Born effective\n charges.\n\n Warning:\n Broken symmetry of Born effective charges\n\n \"\"\"\n\n assert len(borns) == ucell.get_number_of_atoms(), \\\n \"num_atom %d != len(borns) %d\" % (ucell.get_number_of_atoms(),\n len(borns))\n\n if symmetrize_tensors:\n borns_, epsilon_ = symmetrize_borns_and_epsilon(borns,\n epsilon,\n ucell,\n symprec=symprec,\n is_symmetry=is_symmetry)\n\n if (abs(borns - borns_) > 0.1).any():\n lines = [\"Born effective charge symmetry is largely broken. \"\n \"Largest different among elements: \"\n \"%s\" % np.amax(abs(borns - borns_))]\n import warnings\n warnings.warn(\"\\n\".join(lines))\n\n borns = borns_\n epsilon = epsilon_\n\n borns, s_indep_atoms = _extract_independent_borns(\n borns,\n ucell,\n primitive_matrix=primitive_matrix,\n supercell_matrix=supercell_matrix,\n is_symmetry=is_symmetry,\n symprec=symprec)\n\n return borns, epsilon, s_indep_atoms\n\ndef symmetrize_borns_and_epsilon(borns,\n epsilon,\n ucell,\n symprec=1e-5,\n is_symmetry=True):\n lattice = ucell.get_cell()\n positions = ucell.get_scaled_positions()\n u_sym = Symmetry(ucell, is_symmetry=is_symmetry, symprec=symprec)\n rotations = u_sym.get_symmetry_operations()['rotations']\n translations = u_sym.get_symmetry_operations()['translations']\n ptg_ops = u_sym.get_pointgroup_operations()\n epsilon_ = _symmetrize_2nd_rank_tensor(epsilon, ptg_ops, lattice)\n\n for i, Z in enumerate(borns):\n site_sym = u_sym.get_site_symmetry(i)\n Z = _symmetrize_2nd_rank_tensor(Z, site_sym, lattice)\n\n borns_ = np.zeros_like(borns)\n for i in range(len(borns)):\n count = 0\n for r, t in zip(rotations, translations):\n count += 1\n diff = np.dot(positions, r.T) + t - positions[i]\n diff -= np.rint(diff)\n dist = np.sqrt(np.sum(np.dot(diff, lattice) ** 2, axis=1))\n j = np.nonzero(dist < symprec)[0][0]\n r_cart = similarity_transformation(lattice.T, r)\n borns_[i] += similarity_transformation(r_cart, borns[j])\n borns_[i] /= count\n\n sum_born = borns_.sum(axis=0) / len(borns_)\n borns_ -= sum_born\n\n return borns_, epsilon_\n\ndef _symmetrize_2nd_rank_tensor(tensor, symmetry_operations, lattice):\n sym_cart = [similarity_transformation(lattice.T, r)\n for r in symmetry_operations]\n sum_tensor = np.zeros_like(tensor)\n for sym in sym_cart:\n sum_tensor += similarity_transformation(sym, tensor)\n return sum_tensor / len(symmetry_operations)\n\ndef _extract_independent_borns(borns,\n ucell,\n primitive_matrix=None,\n supercell_matrix=None,\n is_symmetry=True,\n symprec=1e-5):\n if primitive_matrix is None:\n pmat = np.eye(3)\n else:\n pmat = primitive_matrix\n if supercell_matrix is None:\n smat = np.eye(3, dtype='intc')\n else:\n smat = supercell_matrix\n\n inv_smat = np.linalg.inv(smat)\n scell = get_supercell(ucell, smat, symprec=symprec)\n pcell = get_primitive(scell, np.dot(inv_smat, pmat), symprec=symprec)\n p2s = np.array(pcell.get_primitive_to_supercell_map(), dtype='intc')\n p_sym = Symmetry(pcell, is_symmetry=is_symmetry, symprec=symprec)\n\n s_indep_atoms = p2s[p_sym.get_independent_atoms()]\n u2u = scell.get_unitcell_to_unitcell_map()\n u_indep_atoms = [u2u[x] for x in s_indep_atoms]\n reduced_borns = borns[u_indep_atoms].copy()\n\n return reduced_borns, s_indep_atoms\n", "meta": {"hexsha": "76e057b1e082d6c0377e29ce83d7f9879ce49f47", "size": 17769, "ext": "py", "lang": "Python", "max_stars_repo_path": "phonopy/structure/symmetry.py", "max_stars_repo_name": "caseynbrock/phonopy", "max_stars_repo_head_hexsha": "d31a7c99f12094b8cf0f9fcc82904eae2956ebf6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "phonopy/structure/symmetry.py", "max_issues_repo_name": "caseynbrock/phonopy", "max_issues_repo_head_hexsha": "d31a7c99f12094b8cf0f9fcc82904eae2956ebf6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phonopy/structure/symmetry.py", "max_forks_repo_name": "caseynbrock/phonopy", "max_forks_repo_head_hexsha": "d31a7c99f12094b8cf0f9fcc82904eae2956ebf6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4084210526, "max_line_length": 80, "alphanum_fraction": 0.588046598, "include": true, "reason": "import numpy", "num_tokens": 3906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.2720245569956929, "lm_q1q2_score": 0.1476721441142281}} {"text": "from __future__ import print_function\nfrom itertools import islice, product\nimport logging\nimport MDAnalysis as md\nimport math\nimport random\nimport numpy as np\nimport pandas as pd\nimport plotly\nimport plotly.graph_objs as go\nimport subprocess\nimport scipy\nimport scipy.stats\nimport string\nimport time\n\nimport settings\n\n\nclass Atom(object):\n\n def __init__(self, identifier, **kwargs):\n self.id = identifier\n self.type = kwargs.get('type', None)\n self.element = kwargs.get('element', None)\n self.xyz = kwargs.get('xyz', None)\n self.stress = kwargs.get('stress', None)\n self.normal = kwargs.get('normal', False)\n self.distance = None\n self.sin_theta = None\n self.cos_theta = None\n self.sin_phi = None\n self.cos_phi = None\n self.spherical_stress = None\n self.voro_volume = 0\n\n def calc_spherical_stress(self):\n \"\"\"\n Calculate spherical stress tensor from cartesian one\n ref: http://www.brown.edu/Departments/Engineering/Courses/En221/Notes/Polar_Coords/Polar_Coords.htm\n \"\"\"\n xx, yy, zz, xy, xz, yz = self.stress\n cart = np.array( [ [xx, xy, xz], [xy, yy, yz], [xz, yz, zz] ] )\n\n # 1 for theta, the angle between xyz and z axis, 2 for phi, \n # angle between x axis and the projection on xy-plane\n sin1 = self.sin_theta\n cos1 = self.cos_theta\n sin2 = self.sin_phi\n cos2 = self.cos_phi\n\n conv = np.array( [ [sin1*cos2, cos1*cos2, -sin2],\n [sin1*sin2, cos1*sin2, -cos2],\n [cos1, -sin1, 0], ] )\n\n sphe = np.dot( conv, cart.dot( np.transpose(conv) ) )\n\n # Of format [ [rr, rTheta, rPhi], [rTheta, thetaTheta, thetaPhi], [rPhi, thetaPhi, phiPhi] ]\n self.spherical_stress = sphe\n\n\nclass Box(object):\n\n PI = 3.1415926\n\n def __init__(self, timestep=0, radius=None, use_atomic_volume=True, average_on_atom=False, **kwargs):\n # Current timestep.\n self.timestep = timestep\n # Maximum bubble radius in box.\n self.radius = radius\n self.count = 0\n # XYZ boundaries.\n self.bx = kwargs.get('bx', None)\n self.by = kwargs.get('by', None)\n self.bz = kwargs.get('bz', None)\n # Bubble center coordinates.\n self._center = kwargs.get('center', None)\n # All atoms.\n self.atoms = []\n # Container of atoms for each element.\n self._elements = {}\n # Container of shell stress for each element.\n self._shell_stress = {}\n self._shell_stress_r = {}\n self._shell_stress_theta = {}\n self._shell_stress_phi = { }\n # Container of shell atom count for each element.\n self.nbins = None\n self._shell_atoms = {}\n self._shell_atom_objs = []\n self._shell_volumes = {}\n # Indicator of stats status.\n self._stats_finished = False\n self._measured = False\n # Dump atom coordinates to calculate voro tessellation volume\n self.voro_file_name = 'atom_coors'\n self.use_atomic_volume = use_atomic_volume\n self.average_on_atom = average_on_atom\n\n @property\n def measured(self):\n \"\"\"Returns true if all atoms have a distance (to bubble center).\"\"\"\n if all([x.distance for x in self.atoms]):\n self._measured = True\n else:\n self._measured = False\n return self._measured\n\n @property\n def center(self):\n return self._center\n\n @center.setter\n def center(self, coor):\n self._center = coor\n self._measured = False\n self._stats_finished = False\n\n def combine_water_atoms(self):\n \"\"\"\n Combine H and O together into a new particle\n stress = S_h + S_o\n coor = center of mass\n The sequency of H and O atoms are O H H\n \"\"\"\n self._old_atoms = self.atoms\n self.atoms = []\n\n self._old_atoms.sort( key=lambda x: x.id )\n water = []\n for atom in self._old_atoms:\n if atom.element not in ['H', 'O']:\n self.atoms.append( atom )\n else:\n water.append(atom)\n if len( water ) == 3:\n # need to combine the 3 atoms into 1 now\n assert [ _ele.element for _ele in water ] == ['O', 'H', 'H']\n new_stress = [a+b+c for a, b, c in zip(water[0].stress, water[1].stress, water[2].stress)]\n new_volume = sum( _ele.voro_volume for _ele in water )\n masses = [ 16 if _ele.element == 'O' else 1 for _ele in water ]\n xs = [ _ele.xyz[0] for _ele in water]\n ys = [ _ele.xyz[ 1 ] for _ele in water ]\n zs = [ _ele.xyz[ 2 ] for _ele in water ]\n\n cx = sum( m*x for m,x in zip(masses, xs) ) / sum(masses)\n cy = sum( m * y for m, y in zip( masses, ys ) ) / sum( masses )\n cz = sum( m * z for m, z in zip( masses, zs ) ) / sum( masses )\n new_xyz = (cx, cy, cz)\n\n new_id = water[0].id\n normal = water[0].normal\n\n self.atoms.append( Atom(new_id, type=3, element='H', xyz=new_xyz, stress=new_stress, normal=normal) )\n\n water = []\n\n def dump_atoms_for_voro( self, length=None ):\n '''\n Dump atom coordinates so we can calculate Voronoi tessellation using Voro++\n from http://math.lbl.gov/voro++/\n The input file format for voro++ is\n \n and output file format is \n \n '''\n logging.info( 'Dump atom coordinates to {}'.format( self.voro_file_name ) )\n fmt = '{} {} {} {}\\n'\n if length:\n xmin, xmax = self.center[0] - length, self.center[0] + length\n ymin, ymax = self.center[1] - length, self.center[1] + length\n zmin, zmax = self.center[2] - length, self.center[2] + length\n\n with open( self.voro_file_name, 'w' ) as output:\n for atom in self.atoms:\n x, y, z = atom.xyz\n if length:\n if xmin <= x <= xmax and ymin<= y <= ymax and zmin <= z <= zmax:\n output.write( fmt.format( atom.id, x, y, z ) )\n else:\n output.write( fmt.format( atom.id, x, y, z ) )\n\n def voro_cmd( self, gnuplot=False, length=None ):\n '''\n CMD to run voro++ in bash\n gnuplot=True will also export gnu plot file. Be careful when system is large as\n this file will be extremely large\n default to use -o to preserve the atom order. This has small memory and performance\n impact as the documentation says.\n '''\n\n # when have length -o will not work\n cmd = 'voro++' if length else 'voro++ -o'\n fmt = cmd + ' {opts} {{xmin}} {{xmax}} {{ymin}} {{ymax}} {{zmin}} {{zmax}} {{infile}}'\n opts = '-g' if gnuplot else ''\n\n fmt = fmt.format( opts=opts )\n\n if length:\n xmin, xmax = self.center[0] - length, self.center[0] + length\n ymin, ymax = self.center[1] - length, self.center[1] + length\n zmin, zmax = self.center[2] - length, self.center[2] + length\n else:\n xmin, xmax = self.bx\n ymin, ymax = self.by\n zmin, zmax = self.bz\n\n return fmt.format( xmin=xmin, xmax=xmax,\n ymin=ymin, ymax=ymax,\n zmin=zmin, zmax=zmax,\n infile=self.voro_file_name)\n\n def run_voro_cmd( self, gnuplot=False, length=None ):\n logging.info( 'Calculating voro volumes for atoms' )\n cmd = self.voro_cmd( gnuplot=gnuplot, length=length )\n\n logging.info( \"Running: {}\".format( cmd ))\n\n sp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n out, err = sp.communicate()\n if err:\n raise Exception(err)\n\n logging.info( \"Finished: {}\".format( cmd ) )\n\n def read_voro_volumes( self ):\n voro_out = self.voro_file_name + '.vol'\n logging.info( 'Reading voro volumes from {}'.format( voro_out ) )\n with open( voro_out, 'r' ) as volumes:\n idx = 0\n for line in volumes:\n atom_id, x, y, z, vol = [ float(ele) for ele in line.split() ]\n atom_id = int( atom_id )\n atom = self.atoms[ idx ]\n try:\n assert( atom.id == atom_id )\n except Exception as e:\n print( atom.id, atom_id )\n raise e\n atom.voro_volume = vol\n idx += 1\n\n def calc_voro_volumes( self, gnuplot=False, length=None ):\n ''' Calculate voro tessellation volume using voro '''\n self.dump_atoms_for_voro( length=length )\n self.run_voro_cmd( gnuplot=gnuplot, length=length )\n if not length:\n self.read_voro_volumes()\n\n def adjust_water_vol(self, ratio=(0.5, 0.25)):\n \"\"\" Adjust volume of H and O in water. For pure water system only \"\"\"\n satoms = sorted( self.atoms, key= lambda x: x.id)\n assert( len( satoms ) % 3 == 0 )\n assert( ratio[0] + 2 * ratio[1] == 1.0)\n for idx in xrange( len(satoms) / 3):\n o = satoms[ idx * 3 ]\n h1 = satoms[ idx * 3 + 1 ]\n h2 = satoms[ idx * 3 + 2 ]\n\n vsum = sum( ele.voro_volume for ele in [o, h1, h2])\n vo = ratio[0] * vsum\n vh = ratio[1] * vsum\n\n o.adj_vol = vo\n h1.adj_vol = vh\n h2.adj_vol = vh\n\n def set_boundary(self, bx, by, bz):\n \"\"\"Set bx by bz together.\"\"\"\n self.bx = bx\n self.by = by\n self.bz = bz\n\n def add_atom(self, atom):\n self.atoms.append(atom)\n self.count += 1\n # Need to run stats after new atom added.\n self._stats_finished = False\n if atom.element in self._elements:\n self._elements[atom.element].append(atom)\n else:\n self._elements[atom.element] = [atom]\n\n def measure(self):\n \"\"\"Measure distance to bubble center for each atom.\"\"\"\n for atom in self.atoms:\n coor = np.array(atom.xyz)\n atom.distance = np.linalg.norm(coor - self.center)\n\n if atom.normal:\n # Calculate sin cos for theta and phi\n dx = coor[0] - self.center[0]\n dy = coor[1] - self.center[1]\n dz = coor[2] - self.center[2]\n\n xy_square = math.sqrt(dx*dx + dy*dy)\n\n atom.sin_theta = xy_square / atom.distance\n atom.cos_theta = dz / atom.distance\n\n atom.sin_phi = dy / xy_square\n atom.cos_phi = dx / xy_square\n\n self.calc_voro_volumes()\n\n def stats(self, dr, normal):\n \"\"\"\n System stats.\n Generate data for atom stats and stress stats for each element.\n self._shell_atoms = {}\n self._shell_stress = {}\n \"\"\"\n if not self.measured:\n raise AtomUnmeasuredError(\"Some atoms are unmeasuerd\")\n\n self.nbins = int(math.ceil(self.radius / float(dr)))\n self._shell_atom_objs = [ { } for x in range( self.nbins ) ]\n\n for ele, atoms in self._elements.iteritems():\n # Do stats for each element.\n for atom in atoms:\n if atom.distance < self.radius:\n shell_idx = int( atom.distance / dr )\n self._shell_atom_objs[ shell_idx ].setdefault(ele, []).append( atom )\n\n if normal:\n atom.calc_spherical_stress()\n\n self._stats_finished = True\n\n def atom_stats(self, element, dr):\n \"\"\"Atom ratio stats inside bubble.\"\"\"\n if not self._stats_finished:\n self.stats(dr)\n nbins = len(self._shell_atoms[element])\n bubble_atoms = {}\n # Init bubble atoms by copying shell atoms\n for ele, count in self._shell_atoms.iteritems():\n bubble_atoms[ele] = [x for x in count]\n for i in range(1, nbins):\n bubble_atoms[ele][i] += bubble_atoms[ele][i - 1]\n bubble_atoms[ele] = np.array(bubble_atoms[ele])\n\n return bubble_atoms[element] / sum(bubble_atoms.values())\n\n def pressure_stats(self, elements, dr):\n \"\"\"Average pressure stats inside bubble for species in elements.\"\"\"\n if not self._stats_finished:\n self.stats(dr)\n\n nbins = len(self._shell_stress[elements[0]])\n # Calculate stress for all element in elements as whole.\n # Convert numpy.Array to mutable list.\n stress_in = [x for x in sum([self._shell_stress[ele] for ele in elements])]\n stress_out = [x for x in stress_in]\n for i in range(1, nbins):\n # Cumulative stress.\n stress_in[i] += stress_in[i-1]\n stress_out[nbins - 1 - i] += stress_out[nbins - i]\n for i in range(1, nbins):\n # Stress -> pressure.\n stress_in[i] = 0 - stress_in[i] / self.vol_sphere((i+1)*dr) / 3.0\n stress_out[nbins-1-i] = 0 - stress_out[nbins-1-i] / (self.vol_sphere(self.radius) - self.vol_sphere((nbins-i-1)*dr)) / 3\n # Head and tail.\n stress_in[0] = 0 - stress_in[0] / self.vol_sphere(dr) / 3\n stress_out[nbins - 1] = 0 - stress_out[nbins - 1] / (self.vol_sphere(self.radius) - self.vol_sphere((nbins - 1)*dr)) / 3\n return {'in': stress_in, 'out': stress_out}\n\n def shell_pressure_stats(self, elements, dr, normal=False):\n \"\"\"Average pressure of elements inside shell.\"\"\"\n self.stats(dr, normal=normal)\n\n print( \"NNNNNumber of bins: {}\".format(self.nbins) )\n\n if not normal:\n # atom.stress has 3 elements, xx yy zz components\n if self.use_atomic_volume:\n if self.average_on_atom:\n # atomic volume is used, pressure is calculated for each atom and then averaged together\n stress = []\n for idx, shell_atoms in enumerate(self._shell_atom_objs):\n pressure_raw = {}\n for element, atoms in shell_atoms.iteritems():\n if element in elements:\n # P = -(S_xx + S_yy + S_zz)/3/V\n pressure_raw[element] = [ - sum(atom.stress)/atom.voro_volume/3.0 for atom in atoms ]\n # Average pressure = sum(Pressure)/n_atoms\n n_atoms = sum( len(_ele) for _ele in pressure_raw.values() )\n if n_atoms != 0:\n pressure_ave = sum( sum(_ele) for _ele in pressure_raw.values() ) / n_atoms\n else:\n pressure_ave = 0\n stress.append(pressure_ave)\n return stress\n else:\n # pressure is calculated as sum(atom stress in a shell) / sum(atom volume in a shell)\n stress = []\n for idx, shell_atoms in enumerate( self._shell_atom_objs ):\n stress_all = 0\n volume_all = 0\n for element, atoms in shell_atoms.iteritems():\n if element in elements:\n stress_all += sum( sum(atom.stress[:3]) for atom in atoms )\n volume_all += sum( atom.voro_volume for atom in atoms )\n if volume_all != 0:\n pressure_ave = - stress_all / 3.0 / volume_all\n else:\n pressure_ave = 0\n stress.append( pressure_ave )\n return stress\n else:\n # use shell volume\n stress = [ ]\n for idx, shell_atoms in enumerate( self._shell_atom_objs ):\n r_min, r_max = idx * dr, (idx + 1)*dr\n stress_all = 0\n volume_all = self.vol_sphere(r_max) - self.vol_sphere(r_min)\n for element, atoms in shell_atoms.iteritems():\n if element in elements:\n stress_all += sum( sum( atom.stress[:3] ) for atom in atoms )\n pressure_ave = - stress_all / 3.0 / volume_all\n stress.append( pressure_ave )\n return stress\n else:\n # normal pressure, atom.spherical_stress has 6 items: xx, yy, zz, xy, xz, yz.\n stress_r = []\n stress_theta = []\n stress_phi = []\n\n if self.use_atomic_volume:\n\n if self.average_on_atom:\n # Pressure is calculate as average of pressure on each atom\n for idx, shell_atoms in enumerate( self._shell_atom_objs ):\n pressure_r_raw = {}\n pressure_theta_raw = {}\n pressure_phi_raw = {}\n for element, atoms in shell_atoms.iteritems():\n if element in elements:\n pressure_r_raw[element] = [ - atom.spherical_stress[0][0] / atom.voro_volume for atom in atoms ]\n pressure_theta_raw[element] = [ - atom.spherical_stress[1][1] / atom.voro_volume for atom in atoms ]\n pressure_phi_raw[element] = [ - atom.spherical_stress[2][2] / atom.voro_volume for atom in atoms ]\n\n n_atoms = sum( len( _ele ) for _ele in pressure_r_raw.values() )\n if n_atoms != 0:\n pressure_r_ave = sum( sum(_ele) for _ele in pressure_r_raw.values() ) / n_atoms\n pressure_theta_ave = sum( sum(_ele) for _ele in pressure_theta_raw.values() ) / n_atoms\n pressure_phi_ave = sum( sum(_ele) for _ele in pressure_phi_raw.values() ) / n_atoms\n else:\n pressure_r_ave = pressure_theta_ave = pressure_phi_ave = 0\n\n stress_r.append( pressure_r_ave )\n stress_theta.append( pressure_theta_ave )\n stress_phi.append( pressure_phi_ave )\n return { 'r': stress_r, 'theta': stress_theta, 'phi': stress_phi, }\n\n else:\n # Pressure is calculated as sum(stress)/sum(atomic_volume)\n for idx, shell_atoms in enumerate( self._shell_atom_objs ):\n stress_r_all = 0\n stress_theta_all = 0\n stress_phi_all = 0\n volume_all = 0\n\n for element, atoms in shell_atoms.iteritems():\n if element in elements:\n stress_r_all += sum( atom.spherical_stress[0][0] for atom in atoms )\n stress_theta_all += sum( atom.spherical_stress[1][1] for atom in atoms )\n stress_phi_all += sum( atom.spherical_stress[2][2] for atom in atoms )\n volume_all += sum( atom.voro_volume for atom in atoms )\n if volume_all != 0:\n pressure_r_ave = - stress_r_all / volume_all\n pressure_theta_ave = - stress_theta_all / volume_all\n pressure_phi_ave = - stress_phi_all / volume_all\n else:\n pressure_r_ave = pressure_theta_ave = pressure_phi_ave = 0\n\n stress_r.append( pressure_r_ave )\n stress_theta.append( pressure_theta_ave )\n stress_phi.append( pressure_phi_ave )\n return { 'r': stress_r, 'theta': stress_theta, 'phi': stress_phi, }\n else:\n # Use shell volume\n for idx, shell_atoms in enumerate( self._shell_atom_objs ):\n r_min, r_max = idx * dr, (idx+1) * dr\n stress_r_all = 0\n stress_theta_all = 0\n stress_phi_all = 0\n volume_all = self.vol_sphere(r_max) - self.vol_sphere(r_min)\n\n for element, atoms in shell_atoms.iteritems():\n if element in elements:\n stress_r_all += sum( atom.spherical_stress[ 0 ][ 0 ] for atom in atoms )\n stress_theta_all += sum( atom.spherical_stress[ 1 ][ 1 ] for atom in atoms )\n stress_phi_all += sum( atom.spherical_stress[ 2 ][ 2 ] for atom in atoms )\n\n pressure_r_ave = - stress_r_all / volume_all\n pressure_theta_ave = - stress_theta_all / volume_all\n pressure_phi_ave = - stress_phi_all / volume_all\n\n stress_r.append( pressure_r_ave )\n stress_theta.append( pressure_theta_ave )\n stress_phi.append( pressure_phi_ave )\n return { 'r': stress_r, 'theta': stress_theta, 'phi': stress_phi, }\n\n def pressure_between(self, rlow, rhigh):\n \"\"\"Return the average pressure and number of atoms between rlow\n and rhigh.\"\"\"\n stress = 0\n count = 0\n for atom in self.atoms:\n if atom.distance > rlow and atom.distance <= rhigh:\n count += 1\n stress += sum(atom.stress)\n volume = self.vol_sphere(rhigh) - self.vol_sphere(rlow)\n return stress / volume / 3, count \n\n def shell_density(self, elements, mole, dr):\n \"\"\"Shell density for species inside elements.\n mole unit - g/cm^3\n dr unit - angstrom\n \"\"\"\n # Usually density_dr is different from stats_dr.\n self.stats(dr)\n # Avogadro constant. Modified by coefficient used to\n # convert angstrom^3 to cm^3.\n NA = 6.022 / 10\n nbins = len(self._shell_atoms[elements[0]])\n # Calculate atom count for all species in elements as whole.\n # Convert numpy.Array to mutable list.\n count = [x for x in sum([self._shell_atoms[ele] for ele in elements])]\n # Calculate density.\n for i in range(nbins):\n r_low = i * dr\n r_high = r_low + dr\n # Volume unit is Angstrom^3.\n volume = self.vol_sphere(r_high) - self.vol_sphere(r_low)\n count[i] = count[i] / NA / volume\n return count\n\n def bubble_density(self, elements, mole, dr):\n pass\n\n def xyz_density(self, elements, mole, dx):\n \"\"\"Density distribution along x, y, and z inside box.\"\"\"\n # Avogadro constant. Modified by coefficient used to\n # convert angstrom^3 to cm^3.\n NA = 6.022 / 10\n nx = int(math.ceil((self.bx[1] - self.bx[0]) / dx))\n ny = int(math.ceil((self.by[1] - self.by[0]) / dx))\n nz = int(math.ceil((self.bz[1] - self.bz[0]) / dx))\n dist = {}\n dist['x'] = [0 for x in range(nx)]\n dist['y'] = [0 for y in range(ny)]\n dist['z'] = [0 for z in range(nz)]\n\n for ele in elements:\n # Count atoms.\n for atom in self._elements[ele]:\n dist['x'][int(atom.xyz[0] / dx)] += 1\n dist['y'][int(atom.xyz[1] / dx)] += 1\n dist['z'][int(atom.xyz[2] / dx)] += 1\n\n volx = (self.by[1] - self.by[0]) * (self.bz[1] - self.bz[0]) * dx\n voly = (self.bx[1] - self.bx[0]) * (self.bz[1] - self.bz[0]) * dx\n volz = (self.by[1] - self.by[0]) * (self.bx[1] - self.bx[0]) * dx\n\n for i in range(nx):\n # Calculate density.\n dist['x'][i] = dist['x'][i] / NA / volx\n dist['y'][i] = dist['y'][i] / NA / voly\n dist['z'][i] = dist['z'][i] / NA / volz\n return dist\n\n def vol_sphere(self, r):\n \"\"\"Volume of sphere with radius r.\"\"\"\n return 4.0/3 * Box.PI * (r ** 3)\n\n def volume(self):\n \"\"\" Box volume \"\"\"\n return (self.bx[1] - self.bx[0]) * (self.by[1] - self.by[0]) * (self.bz[1] - self.bz[0])\n\n\nclass Trajectory( object ):\n '''Gas molecule trajectory class'''\n def __init__( self, pdbPath, xtcPath ):\n self.universe = md.Universe( pdbPath, xtcPath )\n self.set_density_params()\n\n @property\n def n_frames( self ):\n return self.universe.trajectory.n_frames\n\n @property\n def frame( self ):\n return self.universe.trajectory.frame\n\n def set_density_params(self, low=0.4, high=0.5, length=60 ):\n '''\n Generate grid with length of dnesity_grid_length at x,y,z directions.\n Grids whose density are between low * max_density and high * max_density\n will be used for radius calculation. d\n '''\n self.density_low = low\n self.density_high = high\n self.density_grid_length = length\n\n def set_frame( self, frame ):\n self.universe.trajectory[ frame ]\n\n def radius( self, frame ):\n '''\n Bubble radius at one frame.\n Method:\n 1. Load the snapshot at frame\n 2. Load x, y, z coordinates \n 3. Calculate density grid mesh at grid points\n 4. Filter the shell grids with density between low * max density and high * max density\n 5. Calculate the average radius\n '''\n start = time.clock()\n\n self.set_frame( frame )\n\n # Load x, y, z coordinates\n data = pd.DataFrame( list(self.universe.coord), columns=['x','y','z'])\n x = data[ 'x' ].values\n y = data[ 'y' ].values\n z = data[ 'z' ].values\n\n # Density grid\n xyz = scipy.vstack( [ x, y, z ] )\n kde = scipy.stats.gaussian_kde( xyz )\n xmin, ymin, zmin = x.min(), y.min(), z.min()\n xmax, ymax, zmax = x.max(), y.max(), z.max()\n NI = complex( imag=self.density_grid_length)\n xi, yi, zi = scipy.mgrid[ xmin:xmax:NI, ymin:ymax:NI, zmin:zmax:NI ]\n coords = scipy.vstack([item.ravel() for item in [xi, yi, zi]])\n density = kde(coords).reshape(xi.shape)\n\n # Filter density grid\n density_max = density.max()\n density_low = self.density_low * density_max\n density_high = self.density_high * density_max\n\n xyzs = []\n N = self.density_grid_length\n for idx, idy, idz in product( xrange(N), xrange(N), xrange(N) ):\n if density_low < density[ idx, idy, idz ] <= density_high:\n xyzs.append( [ xi[ idx, idy, idz ], yi[ idx, idy, idz ], zi[ idx, idy, idz ] ] )\n xyzs = np.array( xyzs )\n\n # Average radius\n center = xyzs.mean( axis=0 )\n rs = []\n for xyz_ele in xyzs:\n rs.append( np.linalg.norm( center - xyz_ele ) )\n\n duration = time.clock() - start\n print( \"Radius for frame {} calculated in {:.2f} seconds\".format( frame, duration ) )\n\n return center, scipy.mean( rs )\n\n def radius_for_frames( self, start, end, step=1 ):\n ret = []\n for frame in xrange( start, end, step ):\n center, radius = self.radius( frame )\n ret.append( [ frame, radius ] )\n return ret\n\n def all_radius( self ):\n return self.radius_for_frames( 0, self.n_frames, 1 )\n\n def regression( self, radiusList ):\n ''' Input (frame, radius) lists and do linear regression on the data '''\n ts = [ ele[0] for ele in radiusList ]\n rs = [ ele[1] for ele in radiusList ]\n slope, intercept, r_value, p_value, std_err = scipy.stats.linregress( ts, rs )\n return slope, intercept, r_value, p_value, std_err\n\n def plot_radius( self, rs, notebook=False ):\n ''' plot dots and linear regression results '''\n\n xs = [ ele[0] for ele in rs ]\n ys = [ ele[1] for ele in rs ]\n\n x_min = min( xs )\n x_max = max( xs )\n x_min = x_min - ( x_max - x_min ) * 0.05\n x_max = x_max + ( x_max - x_min ) * 0.05\n\n slope, intercept, r_value, p_value, std_err = self.regression( rs )\n\n xs_line = [ x_min ] + xs + [ x_max ]\n ys_line = [ ele * slope + intercept for ele in xs_line ]\n\n # Scatter plot\n scatter = go.Scatter(\n x = [ele[0] for ele in rs],\n y = [ele[1] for ele in rs],\n mode = 'markers',\n name = 'Radius'\n )\n\n reg_line = go.Scatter(\n x = xs_line, y = ys_line,\n mode='lines', name='y={:.4f}x+{:.4f}, p-value={:.2f}, StdErr={:.3f}'.format(slope, intercept, p_value, std_err)\n )\n\n data = go.Data([scatter, reg_line])\n\n plot = plotly.offline.iplot if notebook else plotly.offline.plot\n\n plot( {\n 'data': data,\n 'layout': go.Layout( title='Radius vs Frame', xaxis={'title':'Frame'}, yaxis={'title':'Radius'} )\n } )\n\n def flux_info( self, start, end, step=1 ):\n '''\n Flux info for frames [start:end:step]. Info are, for each step,\n nframe, center, radius, n atoms inside sphere\n '''\n info = []\n for nframe in xrange( start, end, step ):\n center, radius = self.radius( nframe )\n\n # Selector for AtomGroup in MDAnalysis\n selector = 'point ' + ' '.join( str( ele ) for ele in list( center ) + [ radius ] )\n\n # Explicitly set frame here\n self.set_frame( nframe )\n atoms = self.universe.select_atoms( selector )\n natoms = atoms.n_atoms\n info.append( (nframe, center, radius, natoms) )\n return info\n\n\n#################################################\n################# Exceptions ####################\n#################################################\n\nclass AtomUnmeasuredError(Exception):\n pass\n\n\n################################################\n################## Functions ###################\n################################################\n\ndef next_n_lines(file_opened, N, strip='right'):\n strip_dic = {\n 'right': string.rstrip,\n 'left': string.lstrip,\n 'both': string.strip\n }\n if strip:\n return [strip_dic[strip](x) for x in islice(file_opened, N)]\n else:\n return list(islice(file_opened, N))\n\n\ndef read_stress(stress_file, N=settings.NLINES, normalPressure=False):\n \"\"\"\n Read dump file into a list of atoms, which have type / coordinates /\n stresses info stored as Atom properties.\n Dump file data format:\n atom_id atom_type x y z stress_x stress_y stress_z\n \"\"\"\n atoms = {}\n count = 0\n data = next_n_lines(stress_file, N)[9:]\n while data:\n atoms[count] = []\n for line in data:\n line = line.strip().split()\n identifier = int(line[0])\n atom_type = int(line[1])\n element = settings.ELEMENTS[atom_type]\n xyz = tuple([float(x) for x in line[2:5]])\n if normalPressure:\n # To calculate normal pressure, we need xx, yy, zz, xy, xz, yz\n stress = tuple([float(x) for x in line[5:11]])\n else:\n # To calculate pressure, we need xx, yy, zz\n stress = tuple([float(x) for x in line[5:8]])\n atom = Atom(identifier, type=atom_type, element=element, xyz=xyz, stress=stress, normal=normalPressure)\n atoms[count].append(atom)\n # Process next N lines.\n data = next_n_lines(stress_file, N)[9:]\n count += 1\n return atoms\n\n\ndef read_pdb(filename):\n \"\"\"\n Read pdb file as a list of atoms\n \"\"\"\n logging.info( \"Reading {}\".format(filename) )\n atoms_lines = []\n with open(filename, 'r') as pdbfile:\n for line in pdbfile:\n if line.startswith('CRYST'):\n cryst_line = line\n elif line.startswith('ATOM'):\n atoms_lines.append( line )\n\n x, y, z = [float(ele) for ele in cryst_line.strip().split()[1:4] ]\n\n atoms = []\n for line in atoms_lines:\n data = line.strip().split()\n idx = int(data[1])\n element = data[2][:2]\n coor = [ float(ele) for ele in data[5:8] ]\n atoms.append( Atom(identifier=idx, element=element, xyz=coor) )\n return atoms, (x,y,z)\n\n\ndef combine_water(atoms, remove=True):\n \"\"\"\n Combine water atoms\n \"\"\"\n combined = []\n ne = [ ele for ele in atoms if ele.element == 'Ne' ]\n wat = [ele for ele in atoms if ele.element != 'Ne' ]\n logging.info(\"Before:: {} Ne, {} Water atoms\".format(len(ne), len(wat)))\n idx_wat = len(ne) + 1\n comb_wat = []\n for idx in range( len( wat ) / 3 ):\n coor1 = np.array( wat[ idx * 3 ].xyz )\n coor2 = np.array( wat[ idx * 3 + 1 ].xyz )\n coor3 = np.array( wat[ idx * 3 + 2 ].xyz )\n coor = (coor1 + coor2 + coor3) / 3.\n comb_wat.append(Atom(identifier=idx_wat, element='W', xyz=coor))\n idx_wat += 1\n if remove:\n selected = random.sample(comb_wat, len(comb_wat)/4)\n else:\n selected = comb_wat\n n_ne = len(ne)\n for idx in xrange(len(selected)):\n selected[idx].id = idx + 1 + n_ne\n logging.info(\"After:: {} Ne, {} Water atoms\".format(len(ne), len(selected)))\n return ne + selected\n\n\ndef write_lammps_data(atoms, xyz, filename):\n \"\"\"\n LAMMPS data\n format: atom idx, molecule idx, atom type, x, y, z,\n \"\"\"\n atom_types = {'Ne':1, 'W':2}\n x, y, z = xyz\n header = \"LAMMPS bubble\\n\\n\" \\\n \"{n_atoms} atoms\\n\\n\" \\\n \"{n_types} atom types\\n\" \\\n \"0 bond types\\n\" \\\n \"0 angle types\\n\\n\" \\\n \"0 {x} xlo xhi\\n0 {y} ylo yhi\\n0 {z} zlo zhi\\n\\n\"\\\n \"Atoms\\n\\n\".format(n_atoms=len(atoms), n_types=2,x=x,y=y,z=z)\n print(header)\n\n fmt = \"{idx} {mol} {atype} {charge} {x} {y} {z}\\n\"\n\n for idx, atom in enumerate(atoms):\n header += fmt.format(idx=atom.id, mol=atom.id, atype=atom_types[atom.element], charge=0, x=atom.xyz[0], y=atom.xyz[1], z=atom.xyz[2])\n\n with open(filename, 'w') as output:\n output.write(header)\n\n\ndef average_atom_stress(write=True, step=0, *args):\n \"\"\"Calculates averaged stress from multiple stress files.\n write determines whether to write output or not.\n step determines which timestep to average.\"\"\"\n n_files = float(len(args))\n stress_list = []\n for ele in args:\n stress_list.append(read_stress(ele)[step])\n # Sort atoms by id.\n stress_list[-1].sort(key=lambda x: x.id)\n n_atoms = len(stress_list[0])\n atoms = []\n # Average stress for each atom id.\n for i in range(n_atoms):\n sx = sum([x[i].stress[0] for x in stress_list]) / n_files\n sy = sum([x[i].stress[1] for x in stress_list]) / n_files\n sz = sum([x[i].stress[2] for x in stress_list]) / n_files\n atom = stress_list[0][i]\n atoms.append(\n Atom(atom.id, type=atom.type, element=atom.element, xyz=atom.xyz, stress=(sx, sy, sz))\n )\n # Write averaged stress to file.\n if write:\n out_name = '.'.join(args[0].name.split('.')[:-1]) + '_averaged.dat'\n with open(out_name, 'w') as output:\n # Write header lines to be compatitable with LAMMPS dump files.\n output.write('Header line\\n' * 9)\n for atom in atoms:\n # Do not write element here to be compatitable with \n # LAMMPS dump files.\n output.write(\"{} {} {} {} {} {} {} {}\\n\".format(\n atom.id, atom.type,\n atom.xyz[0], atom.xyz[1], atom.xyz[2],\n atom.stress[0], atom.stress[1], atom.stress[2]))\n print(\"Average Stress saved to {}.\".format(out_name))\n return atoms\n\n\ndef build_box(atoms, timestep, radius, center, use_atomic_volume, average_on_atom, bx, by, bz):\n \"\"\"Build a box from a list of atoms.\"\"\"\n box = Box(timestep, radius=radius, center=center, use_atomic_volume=use_atomic_volume, average_on_atom=average_on_atom)\n for atom in atoms:\n box.add_atom(atom)\n box.set_boundary(bx=bx, by=by, bz=bz)\n box.measure()\n return box\n\n\ndef write_density(density, dr, outname, header):\n \"\"\"Write density (both shell and xyz density) stats to output file.\n One density list at a time.\n \"\"\"\n with open(outname, 'w') as output:\n output.write(header)\n for i, item in enumerate(density):\n low = i * dr\n high = low + dr\n output.write('{l:.3f}\\t{h:.3f}\\t{d:.13f}\\n'.format(l=low, h=high, d=item))\n\n\ndef write_pressure(pressure, dr, outname, header, bubble=False):\n \"\"\"Write pressure (both bubble and shell pressure) stats to output file.\n If bubble is True, r_low is always zero.\n \"\"\"\n logging.info( \"Writing output to {}\".format(outname) )\n if bubble:\n # Bubble pressure has in pressure and out pressure.\n with open(outname, 'w') as output:\n output.write(header)\n nbins = len(pressure['in'])\n for i in range(nbins):\n low = 0\n high = (i + 1) * dr\n if i < nbins - 1:\n output.write('{l:.3f}\\t{h:.3f}\\t{pin:.13f}\\t{pout:.13f}\\n'.format(\n l=low, h=high,\n pin=pressure['in'][i], pout=pressure['out'][i+1]\n ))\n else:\n output.write('{l:.3f}\\t{h:.3f}\\t{pin:.13f}\\t{pout:.13f}\\n'.format(\n l=low, h=high,\n pin=pressure['in'][i], pout=0\n ))\n else:\n # Shell pressure.\n with open(outname, 'w') as output:\n output.write(header)\n for i, item in enumerate(pressure):\n low = i * dr\n high = low + dr\n output.write('{l:.3f}\\t{h:.3f}\\t{p:.13f}\\n'.format(l=low, h=high, p=item))\n\n\ndef write_ratio(ratio, dr, outname, header, bubble=True):\n \"\"\"Write atom ratio stats to output file.\n If bubble is True, r_low is always zero.\n \"\"\"\n with open(outname, 'w') as output:\n output.write(header)\n for i, item in enumerate(ratio):\n low = 0 if bubble else i * dr\n high = (i + 1) * dr\n output.write('{l:.3f}\\t{h:.3f}\\t{r:.13f}\\n'.format(l=low, h=high, r=item))\n\n\ndef bubble_ratio(box, elements, out_fmt, header, dr, time, container, debug=False):\n \"\"\"Calculate bubble ratio stats and write results to disk.\"\"\"\n for eles in elements:\n # Ratio stats for each element.\n e = ''.join(eles)\n print('Bubble ratio stats for {e}'.format(e=e))\n # Calculate ratio.\n ratio = box.atom_stats(eles[0], dr)\n # Write to file.\n outname = out_fmt.format(time=time, ele=e)\n write_ratio(ratio, dr, outname, header, bubble=True)\n\n if debug:\n # For testing.\n with open(container, 'a') as cc:\n cc.write(outname + '\\n')\n\n\ndef shell_ratio(box, elements, out_fmt, header, dr, time, container, debug=False):\n \"\"\"Calculate shell ratio stats and write results to disk.\"\"\"\n pass\n\n\ndef bubble_pressure(box, elements, out_fmt, header, dr, time, container, debug=False):\n \"\"\"Calculate bubble pressure and write results to disk.\"\"\"\n for eles in elements:\n # Bubble pressure stats for each group of specified elements.\n e = ''.join(eles)\n print(\"Bubble pressure stats for {e}\\n\".format(e=e))\n # Calculate bubble pressure.\n bubble_pressure = box.pressure_stats(eles, dr)\n # Write bubble pressure.\n outname = out_fmt.format(time=time, ele=e)\n write_pressure(bubble_pressure, dr, outname, header, bubble=True)\n\n if debug:\n # For testing.\n with open(container, 'a') as cc:\n cc.write(outname + '\\n')\n\n\ndef shell_pressure(box, elements, out_fmt, header, dr, time, container, normal=False, debug=False):\n \"\"\"Calculate shell pressure and write results to disk.\"\"\"\n for eles in elements:\n # Shell pressure stats for each group of specified elements.\n e = ''.join(eles)\n print('Shell pressure stats for {e}\\n'.format(e=e))\n # Shell pressure.\n if not normal:\n shell_pressure = box.shell_pressure_stats(eles, dr, normal=normal)\n # Write to disk.\n outname = out_fmt.format(time=time, ele=e)\n write_pressure(shell_pressure, dr, outname, header, bubble=False)\n if debug:\n # For testing.\n with open(container, 'a') as cc:\n cc.write(outname + '\\n')\n else:\n shell_pressure = box.shell_pressure_stats(eles, dr, normal=normal)\n shell_r, shell_theta, shell_phi = shell_pressure['r'], shell_pressure['theta'], shell_pressure['phi']\n # Write to disk.\n outname1 = out_fmt.format(time=time, ele=e) + '_r'\n outname2 = out_fmt.format(time=time, ele=e) + '_theta'\n outname3 = out_fmt.format( time=time, ele=e ) + '_phi'\n write_pressure(shell_r, dr, outname1, header, bubble=False)\n write_pressure(shell_theta, dr, outname2, header, bubble=False)\n write_pressure( shell_phi, dr, outname3, header, bubble=False )\n\n if debug:\n # For testing.\n with open(container, 'a') as cc:\n cc.write( outname1 + '\\n' )\n cc.write( outname2 + '\\n' )\n cc.write( outname3 + '\\n' )\n\n\ndef bubble_density(box, elements, mole, out_fmt, header, dr, time, container, debug=False):\n \"\"\"Calculate bubble density stats and write results to disk.\"\"\"\n for eles in elements:\n # Bubble density stats for each group of specified elements.\n e = ''.join(eles)\n print('Bubble density stats for {e}\\n'.format(e=e))\n # Bubble density.\n bubble_density = box.bubble_density(eles, mole, dr)\n # Write to disk.\n outname = out_fmt.format(time=time, ele=e)\n write_density(bubble_density, dr, outname, header)\n\n if debug:\n # For testing.\n with open(container, 'a') as cc:\n cc.write(outname + '\\n')\n\n\ndef shell_density(box, elements, mole, out_fmt, header, dr, time, container, debug=False):\n \"\"\"Calculate shell density stats and write results to disk.\"\"\"\n for eles in elements:\n # Shell density stats for each group of specified elements.\n e = ''.join(eles)\n print('Shell density stats for {e}\\n'.format(e=e))\n # Shell density.\n shell_density = box.shell_density(eles, mole, dr)\n # Write to disk.\n outname = out_fmt.format(time=time, ele=e)\n write_density(shell_density, dr, outname, header)\n\n if debug:\n # For testing.\n with open(container, 'a') as cc:\n cc.write(outname + '\\n')\n\n\ndef xyz_density(box, elements, mole, out_fmt, header, dr, time, container, debug=False):\n \"\"\"Calculate xyz density stats and write results to disk.\"\"\"\n for eles in elements:\n # XYZ density stats for each group of specified elements.\n e = ''.join(eles)\n print('XYZ density stats for {e}\\n'.format(e=e))\n # XYZ density.\n xyz_density = box.xyz_density(eles, mole, dr)\n # Write to disk.\n xout = out_fmt.format(time=time, ele=e, xyz='x')\n yout = out_fmt.format(time=time, ele=e, xyz='y')\n zout = out_fmt.format(time=time, ele=e, xyz='z')\n\n write_density(xyz_density['x'], dr, xout, header)\n write_density(xyz_density['y'], dr, yout, header)\n write_density(xyz_density['z'], dr, zout, header)\n\n if debug:\n # For testing.\n with open(container, 'a') as cc:\n out = '\\n'.join([xout, yout, zout, ''])\n cc.write(out)\n\n\ndef get_radius(box, element, dr, n=1, ratio=0.5):\n \"\"\"Get the radius of a bubble.\n Radius is determined to be r with closest value of n_element / n_atoms\n to ratio, i.e. within radius, n_element / n_atoms should be as close to\n ratio as possible.\n n specifies number of radiuses to return, i.e. n radiuses that have\n n_element / n_atoms values closest to ratio.\"\"\"\n bubble_ratio = box.atom_stats(element, dr)\n deltas = [abs(x - ratio) for x in bubble_ratio]\n # Use nanmin to ignore NaNs in ratio vector.\n # Do not select radiuses smaller than 10 angstrom.\n min_index = deltas.index(np.nanmin(deltas))\n n = n / 2\n ret = []\n for i in range(-n, n + 1):\n index = min_index + i\n ret.append((dr * (index + 1), bubble_ratio[index]))\n return ret\n", "meta": {"hexsha": "53ff78b695acab293155638bf1cce25450d125c6", "size": 44991, "ext": "py", "lang": "Python", "max_stars_repo_path": "bubble.py", "max_stars_repo_name": "mikkkee/Bubble", "max_stars_repo_head_hexsha": "f9ac318e64aa3e38f199d191fa63ebe645e58a78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bubble.py", "max_issues_repo_name": "mikkkee/Bubble", "max_issues_repo_head_hexsha": "f9ac318e64aa3e38f199d191fa63ebe645e58a78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bubble.py", "max_forks_repo_name": "mikkkee/Bubble", "max_forks_repo_head_hexsha": "f9ac318e64aa3e38f199d191fa63ebe645e58a78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7446996466, "max_line_length": 141, "alphanum_fraction": 0.5403969683, "include": true, "reason": "import numpy,import scipy", "num_tokens": 11088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.28140561345566495, "lm_q1q2_score": 0.1472934202035343}} {"text": "from __future__ import print_function\nimport numpy as np\nfrom discretize.utils import mkvc\n\n\n########################################################################################\n# DIRECT CURRENT RESISTIVITY AND INDUCED POLARIZATION\n########################################################################################\n\n\ndef read_dcip3d_ubc(file_name, data_type):\n \"\"\"\n Read UBC DCIP3D formatted survey, predicted or observed data files.\n\n This function loads 3D DC or IP data formatted for the UBC DCIP3D\n coding package and outputs a SimPEG data object. The function will\n recognize if the file is a survey, predicted data or observed data file.\n\n Parameters\n ----------\n file_name : str\n The file path to the data file\n data_type: str {'volt', 'apparent_chargeability', 'secondary_potential'}\n Defining the input data type:\n\n - 'volt': DC resistivity data as voltages\n - 'apparent_chargeability': IP data as apparent chargeabilities\n - 'secondary_potential': IP data as secondary potentials\n\n Returns\n -------\n data\n A SimPEG.data.Data object containing:\n\n - The survey\n - Observed/predicted data (if present in the data file)\n - Uncertainties (if present in the data file). Note that predicted DC data\n files contain the apparent resistivities, which are loaded into SimPEG and\n defined as uncertainties.\n\n \"\"\"\n assert data_type.lower() in [\n \"volt\",\n \"apparent_chargeability\",\n \"secondary_potential\",\n ], \"Parameter 'data_type' must be one of {'volt', 'apparent_chargeability', 'secondary_potential'}\"\n\n return _read_dcip_3d_or_octree_ubc(file_name, data_type, \"dcip3d\")\n\n\ndef read_dcipoctree_ubc(file_name, data_type):\n \"\"\"\n Read UBC DCIPoctree formatted survey, predicted or observed data files.\n\n This function loads 3D DC or IP data formatted for the UBC DCIPoctree\n coding package and outputs a SimPEG data object. The function requires\n the user to define whether the data are DC resistivity or IP.\n\n Parameters\n ----------\n file_name : str\n The file path to the data file\n data_type: str {'volt', 'apparent_chargeability'}\n Defining the input data type:\n\n - 'volt': DC resistivity data as voltages\n - 'apparent_chargeability': IP data as apparent chargeabilities\n\n Returns\n -------\n data_object\n A SimPEG.data.Data object containing:\n\n - The survey\n - Observed/predicted data (if present in the data file)\n - Uncertainties (if present in the data file). Note that predicted DC data\n files contain the apparent resistivities, which are loaded into SimPEG and\n defined as uncertainties.\n\n \"\"\"\n\n # Unused for now but it will be when we manage IP types better.\n assert data_type.lower() in [\n \"volt\",\n \"apparent_chargeability\",\n ], \"Parameter 'data_type' must be one of {'volt', 'apparent_chargeability'}\"\n\n return _read_dcip_3d_or_octree_ubc(file_name, data_type, \"dcipoctree\")\n\n\ndef _read_dcip_3d_or_octree_ubc(file_name, data_type, code_type):\n \"\"\"\n Read 3D DC/IP survey, predicted and observation files in UBC-GIF format.\n\n Parameters\n ----------\n\n file_name : str\n The file path to the data file\n code_type : str {'dcip3d', 'dcipoctree'}\n Code type. Choose from {'dcip3d', 'dcipoctree'}\n\n Returns\n -------\n data_object\n A SimPEG.data.Data object containing:\n\n - The survey\n - Observed/predicted data (if present in the data file)\n - Uncertainties (if present in the data file). Note that predicted DC data\n files contain the apparent resistivities, which are loaded into SimPEG and\n defined as uncertainties.\n\n \"\"\"\n assert data_type.lower() in [\n \"volt\",\n \"apparent_chargeability\",\n \"secondary_potential\",\n ], \"Parameter 'data_type' must be one of {'volt', 'apparent_chargeability', 'secondary_potential'}\"\n\n assert code_type.lower() in [\n \"dcip3d\",\n \"dcipoctree\",\n ], \"Parameter 'code_type' must be one of {'dcip3d', 'dcipoctree'}\"\n\n # Prevent circular import\n from ...electromagnetics.static import resistivity as dc\n from ...data import Data\n\n # Load file\n obsfile = np.genfromtxt(file_name, delimiter=\" \\n\", dtype=np.str, comments=\"!\")\n\n # Pre-allocate\n source_list = []\n receiver_list = []\n d = []\n wd = []\n\n # Flag for z value provided\n is_surface = False\n is_pole_tx = False\n is_pole_rx = False\n\n # IP data for dcip3d has a line with a flag we can remove.\n if (code_type == \"dcip3d\") & (data_type != \"volt\"):\n obsfile = obsfile[1:]\n\n # Since SimPEG defines secondary potential from IP as voltage,\n # we must use this type when defining the receivers.\n if data_type.lower() == \"secondary_potential\":\n data_type = \"volt\"\n\n # Countdown for number of obs/tx\n count = 0\n for ii in range(obsfile.shape[0]):\n\n if not obsfile[ii]:\n continue\n\n # Extract transmitter ii and the number of receivers\n if count == 0:\n rx = []\n temp = np.fromstring(obsfile[ii], dtype=float, sep=\" \").T\n count = int(temp[-1])\n\n # Check if z value is provided, if False -> nan\n if len(temp) == 5:\n # check if pole|dipole\n if np.allclose(temp[0:2], temp[2:4]):\n tx = np.r_[temp[0:2], np.nan]\n is_pole_tx = True\n else:\n tx = np.r_[temp[0:2], np.nan, temp[2:4], np.nan]\n is_surface = True\n\n else:\n # check if pole|dipole\n if np.allclose(temp[0:3], temp[3:6]):\n tx = np.r_[temp[0:3]]\n is_pole_tx = True\n else:\n tx = temp[:-1]\n\n continue\n\n # Extract receivers\n temp = np.fromstring(obsfile[ii], dtype=float, sep=\" \")\n\n if is_surface:\n data_column_index = 4 # Since dpred for dc has app_res\n\n # Check if Pole Receiver\n if np.allclose(temp[0:2], temp[2:4]):\n is_pole_rx = True\n rx.append(temp[:2])\n else:\n rx.append(np.r_[temp[0:2], np.nan, temp[2:4], np.nan])\n\n else:\n data_column_index = 6 # Since dpred for dc has app_res\n\n # Check if Pole Receiver\n if np.allclose(temp[0:3], temp[3:6]):\n is_pole_rx = True\n rx.append(temp[:3])\n else:\n rx.append(temp[:6])\n\n # Predicted/observed data\n if len(temp) == data_column_index + 1:\n d.append(temp[data_column_index])\n\n # Observed data or predicted DC data (since app res column)\n elif len(temp) == data_column_index + 2:\n d.append(temp[data_column_index])\n wd.append(temp[data_column_index + 1])\n\n count = count - 1\n\n # Reach the end of transmitter block\n if count == 0:\n rx = np.asarray(rx)\n if is_pole_rx:\n Rx = dc.receivers.Pole(rx[:, :3], data_type=data_type)\n else:\n Rx = dc.receivers.Dipole(rx[:, :3], rx[:, 3:], data_type=data_type)\n if is_pole_tx:\n source_list.append(dc.sources.Pole([Rx], tx[:3]))\n else:\n source_list.append(dc.sources.Dipole([Rx], tx[:3], tx[3:]))\n\n # Define survey type\n if is_pole_tx:\n str1 = \"pole-\"\n else:\n str1 = \"dipole-\"\n\n if is_pole_rx:\n str2 = \"pole\"\n else:\n str2 = \"dipole\"\n\n electrode_configuration = str1 + str2\n survey = dc.survey.Survey(source_list, survey_type=electrode_configuration)\n data_out = Data(survey=survey)\n\n if len(d) > 0:\n data_out.dobs = d\n\n if len(wd) > 0:\n data_out.standard_deviation = wd\n\n return data_out\n\n\ndef write_dcip3d_ubc(\n file_name,\n data_object,\n data_type,\n file_type,\n format_type=\"general\",\n electrode_configuration=None,\n comment_lines=\"\",\n):\n \"\"\"\n Write UBC DCIP3D formatted survey, predicted or observation files.\n\n Parameters\n ----------\n file_name:\n data_object:\n file_type: 'survey', 'dpred', 'dobs'\n format_type: 'general', 'surface', 'simple'\n data_type: 'volt', 'apparent_chargeability', 'secondary_potential'\n electrode_configuration: 'pole-pole', 'pole-dipole', 'dipole-pole', 'dipole-dipole'\n comment_lines:)\n \"\"\"\n\n assert data_type.lower() in [\n \"volt\",\n \"apparent_chargeability\",\n \"secondary_potential\",\n ], \"Parameter 'data_type' must be one of {'volt', 'apparent_chargeability', 'secondary_potential'}\"\n\n assert file_type.lower() in [\n \"survey\",\n \"dpred\",\n \"dobs\",\n ], \"Parameter 'file_type' must be one of {'survey', 'dpred', 'dobs'}\"\n\n _write_dcip_3d_or_octree_ubc(\n file_name,\n data_object,\n data_type,\n file_type,\n format_type=format_type,\n electrode_configuration=electrode_configuration,\n code_type=\"dcip3d\",\n comment_lines=comment_lines,\n )\n\n\ndef write_dcipoctree_ubc(\n file_name,\n data_object,\n data_type,\n file_type,\n format_type=\"general\",\n electrode_configuration=None,\n comment_lines=\"\",\n):\n \"\"\"\n Write UBC DCIPoctree formatted survey, predicted or observation files.\n\n Parameters\n ----------\n file_name:\n data_object:\n file_type: 'survey', 'dpred', 'dobs'\n format_type: 'general', 'surface', 'simple'\n data_type: 0 (DC), 1 (IP), 2 (another IP)\n electrode_configuration: 'pole-pole', 'pole-dipole', 'dipole-pole', 'dipole-dipole'\n comment_lines:)\n \"\"\"\n\n assert data_type.lower() in [\n \"volt\",\n \"apparent_chargeability\",\n ], \"Parameter 'data_type' must be one of {'volt', 'apparent_chargeability'}\"\n\n assert file_type.lower() in [\n \"survey\",\n \"dpred\",\n \"dobs\",\n ], \"Parameter 'file_type' must be one of {'survey', 'dpred', 'dobs'}\"\n\n _write_dcip_3d_or_octree_ubc(\n file_name,\n data_object,\n data_type,\n file_type,\n format_type=\"general\",\n electrode_configuration=electrode_configuration,\n code_type=\"dcipoctree\",\n comment_lines=comment_lines,\n )\n\n\ndef _write_dcip_3d_or_octree_ubc(\n file_name,\n data_object,\n data_type,\n file_type,\n format_type=\"general\",\n electrode_configuration=None,\n code_type=\"dcip3d\",\n comment_lines=None,\n):\n \"\"\"\n Write UBC DCIP3D formatted survey, predicted or observation files.\n\n Parameters\n ----------\n file_name:\n data_object:\n file_type: 'survey', 'dpred', 'dobs'\n format_type: 'general', 'surface', 'simple'\n data_type: {'volt', 'apparent_chargeability', 'secondary_potential'}\n electrode_configuration: 'pole-pole', 'pole-dipole', 'dipole-pole', 'dipole-dipole'\n code_type: 'dcip3d', 'dcipoctree'\n comment_lines:\n \"\"\"\n\n # Prevent circular import\n from ...electromagnetics.static import resistivity as dc\n from ...electromagnetics.static.utils.static_utils import apparent_resistivity\n from ...data import Data\n\n # Validate inputs\n if not isinstance(data_object, Data):\n raise Exception(\n \"A Data instance ({datacls}: <{datapref}.{datacls}>) must be \"\n \"provided as the second input. The provided input is a \"\n \"{providedcls} <{providedpref}.{providedcls}>\".format(\n datacls=Data.__name__,\n datapref=Data.__module__,\n providedcls=data_object.__class__.__name__,\n providedpref=data_object.__module__,\n )\n )\n\n assert data_type.lower() in [\n \"volt\",\n \"apparent_chargeability\",\n \"secondary_potential\",\n ], \"Parameter 'data_type' must be one of {'volt', 'apparent_chargeability', 'secondary_potential'}\"\n\n assert file_type.lower() in [\n \"survey\",\n \"dpred\",\n \"dobs\",\n ], \"Parameter 'file_type' must be one of {'survey', 'dpred', 'dobs'}\"\n\n assert code_type.lower() in [\n \"dcip3d\",\n \"dcipoctree\",\n ], \"Parameter 'code_type' must be one of {'dcip3d', 'dcipoctree'}\"\n\n format_type = format_type.lower()\n if format_type not in [\"surface\", \"general\", \"simple\"]:\n raise Exception(\n \"format_type must be 'surface' | 'general' | 'simple' \"\n \" not {}\".format(format_type)\n )\n\n if electrode_configuration is None:\n electrode_configuration = data_object.survey.survey_type\n\n # Predicted DC data will automatically contain apparent resistivity column.\n # Here we compute the apparent resistivities and treat it like an uncertainties column.\n if (file_type.lower() == \"dpred\") & (data_type == \"volt\"):\n data_object.standard_deviation = apparent_resistivity(data_object)\n file_type = \"dobs\"\n\n # Write comments and IP type (if applicable)\n with open(file_name, \"w\") as fid:\n fid.write(f\"! {format_type} FORMAT\\n\")\n\n if comment_lines is not None and len(comment_lines) > 0:\n # ensure comment_lines ends with a new line character\n if comment_lines[-1] != \"\\n\":\n comment_lines += \"\\n\"\n fid.write(comment_lines)\n\n # DCIP3D will allow user to choose definition of IP data. DC data has no flag.\n # DCIPoctree IP data is always apparent chargeability.\n if (code_type.lower() == \"dcip3d\") & (data_type == \"apparent_chargeability\"):\n fid.write(\"IPTYPE=1\\n\")\n elif (code_type.lower() == \"dcip3d\") & (data_type == \"secondary_potential\"):\n fid.write(\"IPTYPE=2\\n\")\n\n # Index deciding if z locations are written\n if format_type.lower() == \"surface\":\n end_index = 2\n elif format_type.lower() == \"general\":\n end_index = 3\n\n # Loop over all sources\n count = 0\n for src in data_object.survey.source_list:\n\n # Write Source\n nD = src.nD\n\n if electrode_configuration.lower() in [\"pole-dipole\", \"pole-pole\"]:\n tx = np.r_[src.location]\n tx = np.repeat(np.r_[[tx]], 2, axis=0)\n elif electrode_configuration.lower() in [\"dipole-dipole\", \"dipole-pole\"]:\n tx = np.c_[src.location]\n\n fid.writelines(\"%e \" % ii for ii in mkvc(tx[:, 0:end_index].T))\n fid.write(f\"{nD}\\n\")\n\n # Write receivers\n for rx in src.receiver_list:\n\n if electrode_configuration.lower() in [\"pole-dipole\", \"dipole-dipole\"]:\n M = rx.locations[0][0:end_index]\n N = rx.locations[1][0:end_index]\n elif electrode_configuration.lower() in [\"pole-pole\", \"dipole-pole\"]:\n M = rx.locations[0:end_index]\n N = rx.locations[0:end_index]\n\n if file_type.lower() != \"survey\":\n N = np.c_[N, data_object.dobs[count : count + rx.nD]]\n\n if file_type.lower() == \"dobs\":\n N = np.c_[N, data_object.standard_deviation[count : count + rx.nD]]\n\n # Write receivers and locations\n if isinstance(N, np.ndarray):\n np.savetxt(\n fid, np.c_[M, N], fmt=\"%e\",\n )\n else:\n raise Exception(\n \"\"\"Uncertainities SurveyObject.std should be set.\n Either float or nunmpy.ndarray is expected, \"\"\"\n \"not {}\".format(type(data_object.relative_error))\n )\n\n fid.write(\"\\n\")\n\n count += rx.nD\n", "meta": {"hexsha": "8318e5c97abcdd058a69c47d1d205ebdf42c9927", "size": 15865, "ext": "py", "lang": "Python", "max_stars_repo_path": "SimPEG/utils/io_utils/io_utils_electromagnetics.py", "max_stars_repo_name": "JKutt/simpeg", "max_stars_repo_head_hexsha": "a0d9cf88e4551bfbfda3792521f4c85724686103", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SimPEG/utils/io_utils/io_utils_electromagnetics.py", "max_issues_repo_name": "JKutt/simpeg", "max_issues_repo_head_hexsha": "a0d9cf88e4551bfbfda3792521f4c85724686103", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SimPEG/utils/io_utils/io_utils_electromagnetics.py", "max_forks_repo_name": "JKutt/simpeg", "max_forks_repo_head_hexsha": "a0d9cf88e4551bfbfda3792521f4c85724686103", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0505050505, "max_line_length": 103, "alphanum_fraction": 0.5853135834, "include": true, "reason": "import numpy", "num_tokens": 3842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.2877678279774722, "lm_q1q2_score": 0.14725557587572438}} {"text": "import numpy\nimport conf\nimport sys\nimport random \ndef STATS(NEVENT,NGOOD):\n\t# IMPLICIT #real*8 (A-H,O-Z)\n\t# IMPLICIT #integer*8 (I-N) \n\t# COMMON/SETP/TMAX,SMALL,API,ESTART,THETA,PHI,TCFMAX(10),TCFMAX1,RSTART,EFIELD,ETHRM,ECUT,NDELTA,IMIP,IWRITE \n\t# COMMON/IDEXC/NGEXC1,NGEXC2,NGEXC3,NGEXC4,NGEXC5,NGEXC6,IDG1,IDG2,IDG3,IDG4,IDG5,IDG6\n\t# COMMON/PRIM3/MSUM(10000),MCOMP(10000),MRAYL(10000),MPAIR(10000),MPHOT(10000),MVAC(10000)\n\t# COMMON/STTS/XST(150000),YST(150000),ZST(150000),TIME(150000),TTIME(150000),NFGF(150000),NFGPP(150000),NFGBR(150000),NELEC,NEGION,EST1,EST2\n\t# COMMON/STEXC/XSTEXC(150000),YSTEXC(150000),ZSTEXC(150000),TSTEXC(150000),NSTEXC\n\t# COMMON/STEXCNUL/XSTN(150000),YSTN(150000),ZSTN(150000),TSTN(150000),IDNUL(150000),NEXCNUL\n\t# COMMON/CLUS/XAV[100000],YAV[100000],ZAV[100000],TAV[100000],XYAV[100000],XYZAV[100000],DX(100000),DY(100000),DZ[100000],DT(100000),DXY(100000),DXYZ[100000],NCL(100000),FARX1(100000),FARY1(100000),FARZ1(100000),FARXY1(100000),RMAX1(100000),TSUM(100000),XNEG(100000), YNEG(100000),ZNEG(100000),EDELTA[100000],EDELTA2(100000),NCLEXC(100000)\n\t# COMMON/PLOT/NXPL10(31),NYPL10(31),NZPL10(31),NXPL40(31),NYPL40(31),NZPL40(31),NXPL100(31),NYPL100(31),NZPL100(31),NXPL400(31),NYPL400(31),NZPL400(31),NXPL1000(31),NYPL1000(31),NZPL1000(31),NXPL2(31),NYPL2(31),NZPL2(31),NXPL4000(31),NYPL4000(31),NZPL4000(31),NXPL10000(31),NYPL10000(31),NZPL10000(31),NXPL40000(31),NYPL40000(31),NZPL40000(31),NXPL100000(31),NYPL100000(31),NZPL100000(31),NRPL2(31),NRPL10(31),NRPL40(31),NRPL100(31),NRPL400(31),NRPL1000(31),NRPL4000(31),NRPL10000(31),NRPL40000(31),NRPL100000(31),NEPL1(100),NEPL10(100),NEPL100(100),MELEC(1000),MELEC3(1000),MELEC10(1000),MELEC30(1000),MELEC100(1000),MELEC300(1000) \n\t#COMMON/SETP/\n\tglobal TMAX,SMALL,API,ESTART,THETA,PHI,TCFMAX#(10)\n\tglobal TCFMAX1,RSTART,EFIELD,ETHRM,ECUT,NDELTA,IMIP,IWRITE \n\t#COMMON/IDEXC/\n\tglobal NGEXC1,NGEXC2,NGEXC3,NGEXC4,NGEXC5,NGEXC6,IDG1,IDG2,IDG3,IDG4,IDG5,IDG6\n\t#COMMON/PRIM3/\n\tglobal MSUM#(10000)\n\tglobal MCOMP#(10000)\n\tglobal MRAYL#(10000)\n\tglobal MPAIR#(10000)\n\tglobal MPHOT#(10000)\n\tglobal MVAC#(10000)\n\t#COMMON/STTS/\n\tglobal XST#(150000)\n\tglobal YST#(150000)\n\tglobal ZST#(150000)\n\tglobal TIME#(150000)\n\tglobal TTIME#(150000)\n\tglobal NFGF#(150000)\n\tglobal NFGPP#(150000)\n\tglobal NFGBR#(150000)\n\tglobal NELEC,NEGION,EST1,EST2\n\t#COMMON/STEXC/\n\tglobal XSTEXC#(150000)\n\tglobal YSTEXC#(150000)\n\tglobal ZSTEXC#(150000)\n\tglobal TSTEXC#(150000)\n\tglobal NSTEXC\n\t#COMMON/STEXCNUL/\n\tglobal XSTN#(150000)\n\tglobal YSTN#(150000)\n\tglobal ZSTN#(150000)\n\tglobal TSTN#(150000)\n\tglobal IDNUL#(150000)\n\tglobal NEXCNUL\n\t#COMMON/CLUS/\n\tglobal XAV#(100000)\n\tglobal YAV#(100000)\n\tglobal ZAV#(100000)\n\tglobal TAV#(100000)\n\tglobal XYAV#(100000)\n\tglobal XYZAV#(100000)\n\tglobal DX#(100000)\n\tglobal DY#(100000)\n\tglobal DZ#(100000)\n\tglobal DT#(100000)\n\tglobal DXY#(100000)\n\tglobal DXYZ#(100000)\n\tglobal NCL#(100000)\n\tglobal FARX1#(100000)\n\tglobal FARY1#(100000)\n\tglobal FARZ1#(100000)\n\tglobal FARXY1#(100000)\n\tglobal RMAX1#(100000)\n\tglobal TSUM#(100000)\n\tglobal XNEG#(100000)\n\tglobal YNEG#(100000)\n\tglobal ZNEG#(100000)\n\tglobal EDELTA#(100000)\n\tglobal EDELTA2#(100000)\n\tglobal NCLEXC#(100000)\n\t#COMMON/PLOT/\n\tglobal NXPL10#(31)\n\tglobal NYPL10#(31)\n\tglobal NZPL10#(31)\n\tglobal NXPL40#(31)\n\tglobal NYPL40#(31)\n\tglobal NZPL40#(31)\n\tglobal NXPL100#(31)\n\tglobal NYPL100#(31)\n\tglobal NZPL100#(31)\n\tglobal NXPL400#(31)\n\tglobal NYPL400#(31)\n\tglobal NZPL400#(31)\n\tglobal NXPL1000#(31)\n\tglobal NYPL1000#(31)\n\tglobal NZPL1000#(31)\n\tglobal NXPL2#(31)\n\tglobal NYPL2#(31)\n\tglobal NZPL2#(31)\n\tglobal NXPL4000#(31)\n\tglobal NYPL4000#(31)\n\tglobal NZPL4000#(31)\n\tglobal NXPL10000#(31)\n\tglobal NYPL10000#(31)\n\tglobal NZPL10000#(31)\n\tglobal NXPL40000#(31)\n\tglobal NYPL40000#(31)\n\tglobal NZPL40000#(31)\n\tglobal NXPL100000#(31)\n\tglobal NYPL100000#(31)\n\tglobal NZPL100000#(31)\n\tglobal NRPL2#(31)\n\tglobal NRPL10#(31)\n\tglobal NRPL40#(31)\n\tglobal NRPL100#(31)\n\tglobal NRPL400#(31)\n\tglobal NRPL1000#(31)\n\tglobal NRPL4000#(31)\n\tglobal NRPL10000#(31)\n\tglobal NRPL40000#(31)\n\tglobal NRPL100000#(31)\n\tglobal NEPL1#(100)\n\tglobal NEPL10#(100)\n\tglobal NEPL100#(100)\n\tglobal MELEC#(1000)\n\tglobal MELEC3#(1000)\n\tglobal MELEC10#(1000)\n\tglobal MELEC30#(1000)\n\tglobal MELEC100#(1000)\n\tglobal MELEC300#(1000) \n\tdef get_globals():\n\t\tTMAX=conf.TMAX\n\t\tSMALL=conf.SMALL\n\t\tAPI=conf.API\n\t\tESTART=conf.ESTART\n\t\tTHETA=conf.THETA\n\t\tPHI=conf.PHI\n\t\tTCFMAX=conf.TCFMAX\n\t\tTCFMAX1=conf.TCFMAX1\n\t\tRSTART=conf.RSTART\n\t\tEFIELD=conf.EFIELD\n\t\tETHRM=conf.ETHRM\n\t\tECUT=conf.ECUT\n\t\tNDELTA=conf.NDELTA\n\t\tIMIP=conf.IMIP\n\t\tIWRITE =conf.IWRITE \n\t\tNGEXC1=conf.NGEXC1\n\t\tNGEXC2=conf.NGEXC2\n\t\tNGEXC3=conf.NGEXC3\n\t\tNGEXC4=conf.NGEXC4\n\t\tNGEXC5=conf.NGEXC5\n\t\tNGEXC6=conf.NGEXC6\n\t\tIDG1=conf.IDG1\n\t\tIDG2=conf.IDG2\n\t\tIDG3=conf.IDG3\n\t\tIDG4=conf.IDG4\n\t\tIDG5=conf.IDG5\n\t\tIDG6=conf.IDG6\n\t\tMSUM=conf.MSUM\n\t\tMCOMP=conf.MCOMP\n\t\tMRAYL=conf.MRAYL\n\t\tMPAIR=conf.MPAIR\n\t\tMPHOT=conf.MPHOT\n\t\tMVAC=conf.MVAC\n\t\tXST=conf.XST\n\t\tYST=conf.YST\n\t\tZST=conf.ZST\n\t\tTIME=conf.TIME\n\t\tTTIME=conf.TTIME\n\t\tNFGF=conf.NFGF\n\t\tNFGPP=conf.NFGPP\n\t\tNFGBR=conf.NFGBR\n\t\tNELEC=conf.NELEC\n\t\tNEGION=conf.NEGION\n\t\tEST1=conf.EST1\n\t\tEST2=conf.EST2\n\t\tXSTEXC=conf.XSTEXC\n\t\tYSTEXC=conf.YSTEXC\n\t\tZSTEXC=conf.ZSTEXC\n\t\tTSTEXC=conf.TSTEXC\n\t\tNSTEXC=conf.NSTEXC\n\t\tXSTN=conf.XSTN\n\t\tYSTN=conf.YSTN\n\t\tZSTN=conf.ZSTN\n\t\tTSTN=conf.TSTN\n\t\tIDNUL=conf.IDNUL\n\t\tNEXCNUL=conf.NEXCNUL\n\t\tXAV=conf.XAV\n\t\tYAV=conf.YAV\n\t\tZAV=conf.ZAV\n\t\tTAV=conf.TAV\n\t\tXYAV=conf.XYAV\n\t\tXYZAV=conf.XYZAV\n\t\tDX=conf.DX\n\t\tDY=conf.DY\n\t\tDZ=conf.DZ\n\t\tDT=conf.DT\n\t\tDXY=conf.DXY\n\t\tDXYZ=conf.DXYZ\n\t\tNCL=conf.NCL\n\t\tFARX1=conf.FARX1\n\t\tFARY1=conf.FARY1\n\t\tFARZ1=conf.FARZ1\n\t\tFARXY1=conf.FARXY1\n\t\tRMAX1=conf.RMAX1\n\t\tTSUM=conf.TSUM\n\t\tXNEG=conf.XNEG\n\t\tYNEG=conf.YNEG\n\t\tZNEG=conf.ZNEG\n\t\tEDELTA=conf.EDELTA\n\t\tEDELTA2=conf.EDELTA2\n\t\tNCLEXC=conf.NCLEXC\n\t\tNXPL10=conf.NXPL10\n\t\tNYPL10=conf.NYPL10\n\t\tNZPL10=conf.NZPL10\n\t\tNXPL40=conf.NXPL40\n\t\tNYPL40=conf.NYPL40\n\t\tNZPL40=conf.NZPL40\n\t\tNXPL100=conf.NXPL100\n\t\tNYPL100=conf.NYPL100\n\t\tNZPL100=conf.NZPL100\n\t\tNXPL400=conf.NXPL400\n\t\tNYPL400=conf.NYPL400\n\t\tNZPL400=conf.NZPL400\n\t\tNXPL1000=conf.NXPL1000\n\t\tNYPL1000=conf.NYPL1000\n\t\tNZPL1000=conf.NZPL1000\n\t\tNXPL2=conf.NXPL2\n\t\tNYPL2=conf.NYPL2\n\t\tNZPL2=conf.NZPL2\n\t\tNXPL4000=conf.NXPL4000\n\t\tNYPL4000=conf.NYPL4000\n\t\tNZPL4000=conf.NZPL4000\n\t\tNXPL10000=conf.NXPL10000\n\t\tNYPL10000=conf.NYPL10000\n\t\tNZPL10000=conf.NZPL10000\n\t\tNXPL40000=conf.NXPL40000\n\t\tNYPL40000=conf.NYPL40000\n\t\tNZPL40000=conf.NZPL40000\n\t\tNXPL100000=conf.NXPL100000\n\t\tNYPL100000=conf.NYPL100000\n\t\tNZPL100000=conf.NZPL100000\n\t\tNRPL2=conf.NRPL2\n\t\tNRPL10=conf.NRPL10\n\t\tNRPL40=conf.NRPL40\n\t\tNRPL100=conf.NRPL100\n\t\tNRPL400=conf.NRPL400\n\t\tNRPL1000=conf.NRPL1000\n\t\tNRPL4000=conf.NRPL4000\n\t\tNRPL10000=conf.NRPL10000\n\t\tNRPL40000=conf.NRPL40000\n\t\tNRPL100000=conf.NRPL100000\n\t\tNEPL1=conf.NEPL1\n\t\tNEPL10=conf.NEPL10\n\t\tNEPL100=conf.NEPL100\n\t\tMELEC=conf.MELEC\n\t\tMELEC3=conf.MELEC3\n\t\tMELEC10=conf.MELEC10\n\t\tMELEC30=conf.MELEC30\n\t\tMELEC100=conf.MELEC100\n\t\tMELEC300=conf.MELEC300\n\t\tglobals().update(locals())\n\tget_globals()\n\tdef update_globals():\n\t\tconf.TMAX=TMAX\n\t\tconf.SMALL=SMALL\n\t\tconf.API=API\n\t\tconf.ESTART=ESTART\n\t\tconf.THETA=THETA\n\t\tconf.PHI=PHI\n\t\tconf.TCFMAX=TCFMAX\n\t\tconf.TCFMAX1=TCFMAX1\n\t\tconf.RSTART=RSTART\n\t\tconf.EFIELD=EFIELD\n\t\tconf.ETHRM=ETHRM\n\t\tconf.ECUT=ECUT\n\t\tconf.NDELTA=NDELTA\n\t\tconf.IMIP=IMIP\n\t\tconf.IWRITE =IWRITE \n\t\tconf.NGEXC1=NGEXC1\n\t\tconf.NGEXC2=NGEXC2\n\t\tconf.NGEXC3=NGEXC3\n\t\tconf.NGEXC4=NGEXC4\n\t\tconf.NGEXC5=NGEXC5\n\t\tconf.NGEXC6=NGEXC6\n\t\tconf.IDG1=IDG1\n\t\tconf.IDG2=IDG2\n\t\tconf.IDG3=IDG3\n\t\tconf.IDG4=IDG4\n\t\tconf.IDG5=IDG5\n\t\tconf.IDG6=IDG6\n\t\tconf.MSUM=MSUM\n\t\tconf.MCOMP=MCOMP\n\t\tconf.MRAYL=MRAYL\n\t\tconf.MPAIR=MPAIR\n\t\tconf.MPHOT=MPHOT\n\t\tconf.MVAC=MVAC\n\t\tconf.XST=XST\n\t\tconf.YST=YST\n\t\tconf.ZST=ZST\n\t\tconf.TIME=TIME\n\t\tconf.TTIME=TTIME\n\t\tconf.NFGF=NFGF\n\t\tconf.NFGPP=NFGPP\n\t\tconf.NFGBR=NFGBR\n\t\tconf.NELEC=NELEC\n\t\tconf.NEGION=NEGION\n\t\tconf.EST1=EST1\n\t\tconf.EST2=EST2\n\t\tconf.XSTEXC=XSTEXC\n\t\tconf.YSTEXC=YSTEXC\n\t\tconf.ZSTEXC=ZSTEXC\n\t\tconf.TSTEXC=TSTEXC\n\t\tconf.NSTEXC=NSTEXC\n\t\tconf.XSTN=XSTN\n\t\tconf.YSTN=YSTN\n\t\tconf.ZSTN=ZSTN\n\t\tconf.TSTN=TSTN\n\t\tconf.IDNUL=IDNUL\n\t\tconf.NEXCNUL=NEXCNUL\n\t\tconf.XAV=XAV\n\t\tconf.YAV=YAV\n\t\tconf.ZAV=ZAV\n\t\tconf.TAV=TAV\n\t\tconf.XYAV=XYAV\n\t\tconf.XYZAV=XYZAV\n\t\tconf.DX=DX\n\t\tconf.DY=DY\n\t\tconf.DZ=DZ\n\t\tconf.DT=DT\n\t\tconf.DXY=DXY\n\t\tconf.DXYZ=DXYZ\n\t\tconf.NCL=NCL\n\t\tconf.FARX1=FARX1\n\t\tconf.FARY1=FARY1\n\t\tconf.FARZ1=FARZ1\n\t\tconf.FARXY1=FARXY1\n\t\tconf.RMAX1=RMAX1\n\t\tconf.TSUM=TSUM\n\t\tconf.XNEG=XNEG\n\t\tconf.YNEG=YNEG\n\t\tconf.ZNEG=ZNEG\n\t\tconf.EDELTA=EDELTA\n\t\tconf.EDELTA2=EDELTA2\n\t\tconf.NCLEXC=NCLEXC\n\t\tconf.NXPL10=NXPL10\n\t\tconf.NYPL10=NYPL10\n\t\tconf.NZPL10=NZPL10\n\t\tconf.NXPL40=NXPL40\n\t\tconf.NYPL40=NYPL40\n\t\tconf.NZPL40=NZPL40\n\t\tconf.NXPL100=NXPL100\n\t\tconf.NYPL100=NYPL100\n\t\tconf.NZPL100=NZPL100\n\t\tconf.NXPL400=NXPL400\n\t\tconf.NYPL400=NYPL400\n\t\tconf.NZPL400=NZPL400\n\t\tconf.NXPL1000=NXPL1000\n\t\tconf.NYPL1000=NYPL1000\n\t\tconf.NZPL1000=NZPL1000\n\t\tconf.NXPL2=NXPL2\n\t\tconf.NYPL2=NYPL2\n\t\tconf.NZPL2=NZPL2\n\t\tconf.NXPL4000=NXPL4000\n\t\tconf.NYPL4000=NYPL4000\n\t\tconf.NZPL4000=NZPL4000\n\t\tconf.NXPL10000=NXPL10000\n\t\tconf.NYPL10000=NYPL10000\n\t\tconf.NZPL10000=NZPL10000\n\t\tconf.NXPL40000=NXPL40000\n\t\tconf.NYPL40000=NYPL40000\n\t\tconf.NZPL40000=NZPL40000\n\t\tconf.NXPL100000=NXPL100000\n\t\tconf.NYPL100000=NYPL100000\n\t\tconf.NZPL100000=NZPL100000\n\t\tconf.NRPL2=NRPL2\n\t\tconf.NRPL10=NRPL10\n\t\tconf.NRPL40=NRPL40\n\t\tconf.NRPL100=NRPL100\n\t\tconf.NRPL400=NRPL400\n\t\tconf.NRPL1000=NRPL1000\n\t\tconf.NRPL4000=NRPL4000\n\t\tconf.NRPL10000=NRPL10000\n\t\tconf.NRPL40000=NRPL40000\n\t\tconf.NRPL100000=NRPL100000\n\t\tconf.NEPL1=NEPL1\n\t\tconf.NEPL10=NEPL10\n\t\tconf.NEPL100=NEPL100\n\t\tconf.MELEC=MELEC\n\t\tconf.MELEC3=MELEC3\n\t\tconf.MELEC10=MELEC10\n\t\tconf.MELEC30=MELEC30\n\t\tconf.MELEC100=MELEC100\n\t\tconf.MELEC300=MELEC300 \t\n\t#-----------------------------------------------------------------------\n\t# NEVENT IS EVENT EVENT POINTER. NGOOD IS GOOD EVENT POINTER\n\t# FORMS AVERAGES OVER EACH DELTA AND DOES SOME STATISTICS\n\t# LOADS PLOT ARRAYS XPLOT YPLOT AND ZPLOT (SCALED BY 1 10 AND 100)\n\t# OUTPUTS RAW DATA TO FILE IF IWRITE CONTROL GT 0\n\t# OUTPUTS THERMALISED ELECTRON X,Y,Z AND T IF IWRITE EQ 1\n\t# OUTPUTS ALSO X,Y,Z AND T FOR EACH EXCITATION IF \n\t# IWRITE EQ 2 \n\t# ----------------------------------------------------------------------\n\tif(NGOOD <= 0):\n\t\tprint(' IN STATS NEVENT=',NEVENT,' NGOOD=',NGOOD)\n\t# endif\n\tNCLUS=NELEC-NEGION\n\tif(NCLUS > 150000):\n\t\t# GO TO 99\n\t\tpass\n\telse:\n\t\tSUMX=0.00\n\t\tSUMX2=0.00\n\t\tSUMY=0.00\n\t\tSUMY2=0.00\n\t\tSUMZ=0.00\n\t\tSUMZ2=0.00\n\t\tSUMRXY=0.00\n\t\tSUMRXY2=0.00\n\t\tSUMRXYZ=0.00\n\t\tSUMRXYZ2=0.00\n\t\tSUMT=0.00\n\t\tSUMT2=0.00\n\t\tFARX=0.00\n\t\tFARY=0.00\n\t\tFARZ=0.00\n\t\tFARXY=0.00\n\t\tRMAX=0.00\n\t\tSUMTT=0.00\n\t\tNXNEG=0\n\t\tNYNEG=0\n\t\tNZNEG=0\n\t\tESUM=0.0\n\t\tATOTR=0.0\n\t\tATOTC=0.0\n\t\tATOTP=0.0\n\t\tATOTPE=0.0\n\t\t#\n\t\tfor IS in range(1,int(NCLUS)+1):\n\t\t\tXST[IS]=XST[IS]*1.e6\n\t\t\tX=XST[IS]\n\t\t\tif(X < 0.0):\n\t\t\t\tNXNEG=NXNEG+1\n\t\t\t\tI1=int(X/2.0-0.5)\n\t\t\t\tI2=int(X/10.0-0.5)\n\t\t\t\tI3=int(X/40.0-0.5)\n\t\t\t\tI4=int(X/100.0-0.5)\n\t\t\t\tI5=int(X/400.0-0.5)\n\t\t\t\tI6=int(X/1000.0-0.5)\n\t\t\t\tI7=int(X/4000.0-0.5)\n\t\t\t\tI8=int(X/10000.0-0.5)\n\t\t\t\tI9=int(X/40000.0-0.5)\n\t\t\t\tI10=int(X/100000.0-0.5)\n\t\t\telse: \n\t\t\t\tI1=int(X/2.0+0.5)\n\t\t\t\tI2=int(X/10.0+0.5)\n\t\t\t\tI3=int(X/40.0+0.5)\n\t\t\t\tI4=int(X/100.0+0.5)\n\t\t\t\tI5=int(X/400.0+0.5)\n\t\t\t\tI6=int(X/1000.0+0.5)\n\t\t\t\tI7=int(X/4000.0+0.5) \n\t\t\t\tI8=int(X/10000.0+0.5)\n\t\t\t\tI9=int(X/40000.0+0.5)\n\t\t\t\tI10=int(X/100000.0+0.5)\n\t\t\t# endif\n\t\t\tI1=I1+16\n\t\t\tI2=I2+16\n\t\t\tI3=I3+16\n\t\t\tI4=I4+16\n\t\t\tI5=I5+16\n\t\t\tI6=I6+16\n\t\t\tI7=I7+16\n\t\t\tI8=I8+16\n\t\t\tI9=I9+16\n\t\t\tI10=I10+16\n\t\t\tif(I1 < 1):\n\t\t\t\tI1=1\n\t\t\tif(I1 > 31):\n\t\t\t\tI1=31\n\t\t\tif(I2 < 1):\n\t\t\t\tI2=1\n\t\t\tif(I2 > 31):\n\t\t\t\tI2=31\n\t\t\tif(I3 < 1):\n\t\t\t\tI3=1\n\t\t\tif(I3 > 31):\n\t\t\t\tI3=31\n\t\t\tif(I4 < 1):\n\t\t\t\tI4=1\n\t\t\tif(I4 > 31):\n\t\t\t\tI4=31\n\t\t\tif(I5 < 1):\n\t\t\t\tI5=1\n\t\t\tif(I5 > 31):\n\t\t\t\tI5=31\n\t\t\tif(I6 < 1):\n\t\t\t\tI6=1\n\t\t\tif(I6 > 31):\n\t\t\t\tI6=31\n\t\t\tif(I7 < 1):\n\t\t\t\tI7=1\n\t\t\tif(I7 > 31):\n\t\t\t\tI7=31\n\t\t\tif(I8 < 1):\n\t\t\t\tI8=1\n\t\t\tif(I8 > 31):\n\t\t\t\tI8=31\n\t\t\tif(I9 < 1):\n\t\t\t\tI9=1\n\t\t\tif(I9 > 31):\n\t\t\t\tI9=31\n\t\t\tif(I10 < 1):\n\t\t\t\tI10=1\n\t\t\tif(I10 > 31):\n\t\t\t\tI10=31\n\t\t\tNXPL2[I1]=NXPL2[I1]+1\n\t\t\tNXPL10[I2]=NXPL10[I2]+1\n\t\t\tNXPL40[I3]=NXPL40[I3]+1\n\t\t\tNXPL100[I4]=NXPL100[I4]+1\n\t\t\tNXPL400[I5]=NXPL400[I5]+1\n\t\t\tNXPL1000[I6]=NXPL1000[I6]+1\n\t\t\tNXPL4000[I7]=NXPL4000[I7]+1\n\t\t\tNXPL10000[I8]=NXPL10000[I8]+1\n\t\t\tNXPL40000[I9]=NXPL40000[I9]+1\n\t\t\tNXPL100000[I10]=NXPL100000[I10]+1\n\t\t\tX2=X*X\n\t\t\tSUMX=SUMX+X\n\t\t\tSUMX2=SUMX2+X2\n\t\t\tif(abs(X)> abs(FARX)):\n\t\t\t\tFARX=abs(X)\n\t\t\tYST[IS]=YST[IS]*1.e6\n\t\t\tY=YST[IS]\n\t\t\tif(Y < 0.0):\n\t\t\t\tNYNEG=NYNEG+1\n\t\t\t\tI1=int(Y/2.0-0.5)\n\t\t\t\tI2=int(Y/10.0-0.5)\n\t\t\t\tI3=int(Y/40.0-0.5)\n\t\t\t\tI4=int(Y/100.0-0.5)\n\t\t\t\tI5=int(Y/400.0-0.5)\n\t\t\t\tI6=int(Y/1000.0-0.5)\n\t\t\t\tI7=int(Y/4000.0-0.5)\n\t\t\t\tI8=int(Y/10000.0-0.5)\n\t\t\t\tI9=int(Y/40000.0-0.5)\n\t\t\t\tI10=int(Y/100000.0-0.5)\n\t\t\telse: \n\t\t\t\tI1=int(Y/2.0+0.5)\n\t\t\t\tI2=int(Y/10.0+0.5)\n\t\t\t\tI3=int(Y/40.0+0.5)\n\t\t\t\tI4=int(Y/100.0+0.5)\n\t\t\t\tI5=int(Y/400.0+0.5)\n\t\t\t\tI6=int(Y/1000.0+0.5)\n\t\t\t\tI7=int(Y/4000.0+0.5) \n\t\t\t\tI8=int(Y/10000.0+0.5)\n\t\t\t\tI9=int(Y/40000.0+0.5)\n\t\t\t\tI10=int(Y/100000.0+0.5)\n\t\t\t# endif\n\t\t\tI1=I1+16\n\t\t\tI2=I2+16\n\t\t\tI3=I3+16\n\t\t\tI4=I4+16\n\t\t\tI5=I5+16\n\t\t\tI6=I6+16\n\t\t\tI7=I7+16\n\t\t\tI8=I8+16\n\t\t\tI9=I9+16\n\t\t\tI10=I10+16\n\t\t\tif(I1 < 1):\n\t\t\t\tI1=1\n\t\t\tif(I1 > 31):\n\t\t\t\tI1=31\n\t\t\tif(I2 < 1):\n\t\t\t\tI2=1\n\t\t\tif(I2 > 31):\n\t\t\t\tI2=31\n\t\t\tif(I3 < 1):\n\t\t\t\tI3=1\n\t\t\tif(I3 > 31):\n\t\t\t\tI3=31\n\t\t\tif(I4 < 1):\n\t\t\t\tI4=1\n\t\t\tif(I4 > 31):\n\t\t\t\tI4=31\n\t\t\tif(I5 < 1):\n\t\t\t\tI5=1\n\t\t\tif(I5 > 31):\n\t\t\t\tI5=31\n\t\t\tif(I6 < 1):\n\t\t\t\tI6=1\n\t\t\tif(I6 > 31):\n\t\t\t\tI6=31\n\t\t\tif(I7 < 1):\n\t\t\t\tI7=1\n\t\t\tif(I7 > 31):\n\t\t\t\tI7=31\n\t\t\tif(I8 < 1):\n\t\t\t\tI8=1\n\t\t\tif(I8 > 31):\n\t\t\t\tI8=31\n\t\t\tif(I9 < 1):\n\t\t\t\tI9=1\n\t\t\tif(I9 > 31):\n\t\t\t\tI9=31\n\t\t\tif(I10 < 1):\n\t\t\t\tI10=1\n\t\t\tif(I10 > 31):\n\t\t\t\tI10=31\n\t\t\tNYPL2[I1]=NYPL2[I1]+1\n\t\t\tNYPL10[I2]=NYPL10[I2]+1\n\t\t\tNYPL40[I3]=NYPL40[I3]+1\n\t\t\tNYPL100[I4]=NYPL100[I4]+1\n\t\t\tNYPL400[I5]=NYPL400[I5]+1\n\t\t\tNYPL1000[I6]=NYPL1000[I6]+1\n\t\t\tNYPL4000[I7]=NYPL4000[I7]+1\n\t\t\tNYPL10000[I8]=NYPL10000[I8]+1\n\t\t\tNYPL40000[I9]=NYPL40000[I9]+1\n\t\t\tNYPL100000[I10]=NYPL100000[I10]+1\n\t\t\tY2=Y*Y\n\t\t\tSUMY=SUMY+Y\n\t\t\tSUMY2=SUMY2+Y2 \n\t\t\tif(abs(Y)> abs(FARY)):\n\t\t\t\tFARY=abs(Y)\n\t\t\tZST[IS]=ZST[IS]*1.e6\n\t\t\tZ=ZST[IS]\n\t\t\tif(Z < 0.0):\n\t\t\t\tNZNEG=NZNEG+1\n\t\t\t\tI1=int(Z/2.0-0.5)\n\t\t\t\tI2=int(Z/10.0-0.5)\n\t\t\t\tI3=int(Z/40.0-0.5)\n\t\t\t\tI4=int(Z/100.0-0.5)\n\t\t\t\tI5=int(Z/400.0-0.5)\n\t\t\t\tI6=int(Z/1000.0-0.5)\n\t\t\t\tI7=int(Z/4000.0-0.5)\n\t\t\t\tI8=int(Z/10000.0-0.5)\n\t\t\t\tI9=int(Z/40000.0-0.5)\n\t\t\t\tI10=int(Z/100000.0-0.5)\n\t\t\telse: \n\t\t\t\tI1=int(Z/2.0+0.5)\n\t\t\t\tI2=int(Z/10.0+0.5)\n\t\t\t\tI3=int(Z/40.0+0.5)\n\t\t\t\tI4=int(Z/100.0+0.5)\n\t\t\t\tI5=int(Z/400.0+0.5) \n\t\t\t\tI6=int(Z/1000.0+0.5)\n\t\t\t\tI7=int(Z/4000.0+0.5)\n\t\t\t\tI8=int(Z/10000.0+0.5)\n\t\t\t\tI9=int(Z/40000.0+0.5)\n\t\t\t\tI10=int(Z/100000.0+0.5)\n\t\t\t# endif\n\t\t\tI1=I1+16\n\t\t\tI2=I2+16\n\t\t\tI3=I3+16\n\t\t\tI4=I4+16\n\t\t\tI5=I5+16\n\t\t\tI6=I6+16\n\t\t\tI7=I7+16\n\t\t\tI8=I8+16\n\t\t\tI9=I9+16\n\t\t\tI10=I10+16\n\t\t\tif(I1 < 1):\n\t\t\t\tI1=1\n\t\t\tif(I1 > 31):\n\t\t\t\tI1=31\n\t\t\tif(I2 < 1):\n\t\t\t\tI2=1\n\t\t\tif(I2 > 31):\n\t\t\t\tI2=31\n\t\t\tif(I3 < 1):\n\t\t\t\tI3=1\n\t\t\tif(I3 > 31):\n\t\t\t\tI3=31\n\t\t\tif(I4 < 1):\n\t\t\t\tI4=1\n\t\t\tif(I4 > 31):\n\t\t\t\tI4=31\n\t\t\tif(I5 < 1):\n\t\t\t\tI5=1\n\t\t\tif(I5 > 31):\n\t\t\t\tI5=31\n\t\t\tif(I6 < 1):\n\t\t\t\tI6=1\n\t\t\tif(I6 > 31):\n\t\t\t\tI6=31\n\t\t\tif(I7 < 1):\n\t\t\t\tI7=1\n\t\t\tif(I7 > 31):\n\t\t\t\tI7=31\n\t\t\tif(I8 < 1):\n\t\t\t\tI8=1\n\t\t\tif(I8 > 31):\n\t\t\t\tI8=31\n\t\t\tif(I9 < 1):\n\t\t\t\tI9=1\n\t\t\tif(I9 > 31):\n\t\t\t\tI9=31\n\t\t\tif(I10 < 1):\n\t\t\t\tI10=1\n\t\t\tif(I10 > 31):\n\t\t\t\tI10=31\n\t\t\tNZPL2[I1]=NZPL2[I1]+1\n\t\t\tNZPL10[I2]=NZPL10[I2]+1\n\t\t\tNZPL40[I3]=NZPL40[I3]+1\n\t\t\tNZPL100[I4]=NZPL100[I4]+1\n\t\t\tNZPL400[I5]=NZPL400[I5]+1\n\t\t\tNZPL1000[I6]=NZPL1000[I6]+1\n\t\t\tNZPL4000[I7]=NZPL4000[I7]+1\n\t\t\tNZPL10000[I8]=NZPL10000[I8]+1\n\t\t\tNZPL40000[I9]=NZPL40000[I9]+1\n\t\t\tNZPL100000[I10]=NZPL100000[I10]+1\n\t\t\tZ=ZST[IS]\n\t\t\tR=math.sqrt(X*X+Y*Y+Z*Z)\n\t\t\tI1=int(R/2.0+0.5)\n\t\t\tI2=int(R/10.0+0.5)\n\t\t\tI3=int(R/40.0+0.5)\n\t\t\tI4=int(R/100.0+0.5)\n\t\t\tI5=int(R/400.0+0.5) \n\t\t\tI6=int(R/1000.0+0.5)\n\t\t\tI7=int(R/4000.0+0.5)\n\t\t\tI8=int(R/10000.0+0.5)\n\t\t\tI9=int(R/40000.0+0.5)\n\t\t\tI10=int(R/100000.0+0.5)\n\t\t\tI1=I1+16\n\t\t\tI2=I2+16\n\t\t\tI3=I3+16\n\t\t\tI4=I4+16\n\t\t\tI5=I5+16\n\t\t\tI6=I6+16\n\t\t\tI7=I7+16\n\t\t\tI8=I8+16\n\t\t\tI9=I9+16\n\t\t\tI10=I10+16\n\t\t\tif(I1 > 31):\n\t\t\t\tI1=31\n\t\t\tif(I2 > 31):\n\t\t\t\tI2=31\n\t\t\tif(I3 > 31):\n\t\t\t\tI3=31\n\t\t\tif(I4 > 31):\n\t\t\t\tI4=31\n\t\t\tif(I5 > 31):\n\t\t\t\tI5=31\n\t\t\tif(I6 > 31):\n\t\t\t\tI6=31\n\t\t\tif(I7 > 31):\n\t\t\t\tI7=31\n\t\t\tif(I8 > 31):\n\t\t\t\tI8=31\n\t\t\tif(I9 > 31):\n\t\t\t\tI9=31\n\t\t\tif(I10 > 31):\n\t\t\t\tI10=31\n\t\t\tif(I1 < 1):\n\t\t\t\tI1=1\n\t\t\tif(I2 < 1):\n\t\t\t\tI2=1\n\t\t\tif(I3 < 1):\n\t\t\t\tI3=1\n\t\t\tif(I4 < 1):\n\t\t\t\tI4=1\n\t\t\tif(I5 < 1):\n\t\t\t\tI5=1\n\t\t\tif(I6 < 1):\n\t\t\t\tI6=1\n\t\t\tif(I7 < 1):\n\t\t\t\tI7=1\n\t\t\tif(I8 < 1):\n\t\t\t\tI8=1\n\t\t\tif(I9 < 1):\n\t\t\t\tI9=1\n\t\t\tif(I10 < 1):\n\t\t\t\tI10=1\n\t\t\tNRPL2[I1]=NRPL2[I1]+1\n\t\t\tNRPL10[I2]=NRPL10[I2]+1\n\t\t\tNRPL40[I3]=NRPL40[I3]+1\n\t\t\tNRPL100[I4]=NRPL100[I4]+1\n\t\t\tNRPL400[I5]=NRPL400[I5]+1\n\t\t\tNRPL1000[I6]=NRPL1000[I6]+1\n\t\t\tNRPL4000[I7]=NRPL4000[I7]+1\n\t\t\tNRPL10000[I8]=NRPL10000[I8]+1\n\t\t\tNRPL40000[I9]=NRPL40000[I9]+1\n\t\t\tNRPL100000[I10]=NRPL100000[I10]+1\n\t\t\tZ2=Z*Z\n\t\t\tSUMZ=SUMZ+Z\n\t\t\tSUMZ2=SUMZ2+Z2 \n\t\t\tif(abs(Z)> abs(FARZ)):\n\t\t\t\tFARZ=abs(Z)\n\t\t\tRXY=math.sqrt(X2+Y2)\n\t\t\tRXYZ=math.sqrt(X2+Y2+Z2)\n\t\t\tSUMRXY=SUMRXY+RXY\n\t\t\tSUMRXY2=SUMRXY2+RXY*2 \n\t\t\tSUMRXYZ=SUMRXYZ+RXYZ\n\t\t\tSUMRXYZ2=SUMRXYZ2+RXYZ*2\n\t\t\tif(RXY > FARXY):\n\t\t\t\tFARXY=RXY\n\t\t\tif(RXYZ > RMAX):\n\t\t\t\tRMAX=RXYZ \n\t\t\tT=TIME[IS]\n\t\t\tSUMT=SUMT+T \n\t\t\tSUMT2=SUMT2+T*T\n\t\t\tSUMTT=SUMTT+TTIME(IS)\n\t\t\t#\n\t\t\tXSTEXC[IS]=XSTEXC[IS]*1.e6\n\t\t\tYSTEXC[IS]=YSTEXC[IS]*1.e6\n\t\t\tZSTEXC[IS]=ZSTEXC[IS]*1.e6\n\t\t# 400 CONTINUE\n\t\t# OUTPUT THERMAL ELECTRON POSITIONS AND TIME \n\t\tf=open(\"fort.50\",\"w+\")\n\t\tif(IWRITE == 1):\n\t\t\t# ITEST=123456\n\t\t\t# WRITE(50,*) ITEST\n\t\t\t# WRITE(50,*) \n\t\t\tf.write(NGOOD,NCLUS,NSTEXC,NGEXC1,NGEXC2,NGEXC3,NGEXC4,NGEXC5,NGEXC6,MCOMP[NEVENT],MPAIR[NEVENT],NEXCNUL)\n\t\t\t# DO 8876 IPR=1,NCLUS\n\t\t\t# WRITE(50,*) IPR,XST[IPR],YST[IPR],ZST[IPR],TIME[IPR],NFGF[IPR],\n\t\t\t# /NFGPP[IPR],NFGBR[IPR]\n\t\t\t#8876 CONTINUE\n\t\t\t# WRITE(50,*) \n\t\t\tfor IPR in range(1,NCLUS+1):\n\n\t\t\t\tf.write(XST[IPR],YST[IPR],ZST[IPR],TIME[IPR],NFGF[IPR],NFGPP[IPR],NFGBR[IPR])\n\t\t# endif\n\t\t# OUTPUT EXCITATION CLOUD COORDINATES HERE \n\t\tif(IWRITE == 2):\n\t\t\t# ITEST=123456\n\t\t\t# WRITE(50,*) ITEST\n\t\t\t# WRITE(50,*) \n\t\t\tf.write(NGOOD,NCLUS,NSTEXC,NGEXC1,NGEXC2,NGEXC3,NGEXC4,NGEXC5,NGEXC6,MCOMP[NEVENT],MPAIR[NEVENT],NEXCNUL)\n\t\t\t# DO 8877 IPR=1,NCLUS\n\t\t\t# WRITE(50,*) IPR,XST[IPR],YST[IPR],ZST[IPR],TIME[IPR],NFGF[IPR],\n\t\t\t# /NFGPP[IPR],NFGBR[IPR]\n\t\t\t#8877 CONTINUE\n\t\t\t# WRITE(50,*) \n\t\t\tfor IPR in range(1,NCLUS+1):\n\t\t\t\tf.write(XST[IPR],YST[IPR],ZST[IPR],TIME[IPR],NFGF[IPR],NFGPP[IPR],NFGBR[IPR])\n\t\t\t# DO 8878 IPR=1,NSTEXC\n\t\t\t# WRITE(50,*) IPR,XSTEXC[IPR],YSTEXC[IPR],ZSTEXC[IPR],TSTEXC[IPR]\n\t\t\t# 8878 CONTINUE\n\t\t\t# WRITE(50,*) \n\t\t\tfor IPR in range(1,NSTEXC+1):\n\t\t\t\tf.write(XSTEXC[IPR],YSTEXC[IPR],ZSTEXC[IPR],TSTEXC[IPR])\n\t\t\tif(NEXCNUL > 0):\n\t\t\t\t# WRITE(50,*) \n\t\t\t\tfor IPR in range(1,NEXCNUL+1):\n\t\t\t\t\tf.write(XSTN[IPR],YSTN[IPR],ZSTN[IPR],TSTN[IPR],IDNUL[IPR])\n\t\t\telse:\n\t\t\t\t# WRITE BLANK LINE\n\t\t\t\t# WRITE(50,*) \n\t\t\t\tf.write(0.0,0.0,0.0,0.0,0 )\n\t\t\t# endif \n\t\t# endif\n\t\tf.close()\n\t\t#---------------------------------------------------\n\t\tI1=int(EST1+1.0)\n\t\tI2=int(EST1/10.0+1.0)\n\t\tI3=int(EST1/100.0+1.0)\n\t\tif(I1 > 100):\n\t\t\tI1=100\n\t\tif(I2 > 100):\n\t\t\tI2=100\n\t\tif(I3 > 100):\n\t\t\tI3=100\n\t\tNEPL1[I1]=NEPL1[I1]+1\n\t\tNEPL10[I2]=NEPL10[I2]+1\n\t\tNEPL100[I3]=NEPL100[I3]+1\n\t\tKDUM=NELEC\n\t\tKDUM3=1+(NELEC/3)\n\t\tKDUM10=1+(NELEC/10)\n\t\tKDUM30=1+(NELEC/30)\n\t\tKDUM100=1+(NELEC/100)\n\t\tKDUM300=1+(NELEC/300)\n\t\tif(KDUM > 1000):\n\t\t\tKDUM=1000\n\t\tMELEC[int(KDUM)]=MELEC[int(KDUM)]+1\n\t\tif(KDUM3 > 1000):\n\t\t\tKDUM3=1000\n\t\tMELEC3[int(KDUM3)]=MELEC3[int(KDUM3)]+1\n\t\tif(KDUM10 > 1000):\n\t\t\tKDUM10=1000\n\t\tMELEC10[int(KDUM10)]=MELEC10[int(KDUM10)]+1\n\t\tif(KDUM30 > 1000):\n\t\t\tKDUM30=1000\n\t\tMELEC30[int(KDUM30)]=MELEC30[int(KDUM30)]+1\n\t\tif(KDUM100 > 1000):\n\t\t\tKDUM100=1000\n\t\tMELEC100[int(KDUM100)]=MELEC100[int(KDUM100)]+1\n\t\tif(KDUM300 > 1000):\n\t\t\tKDUM300=1000\n\t\tMELEC300[int(KDUM300)]=MELEC300[int(KDUM300)]+1\n\t\t# \n\t\t# STORE AVERAGES AND WIDTHS FOR EACH DELTA\n\t\t#\n\t\tif(NCLUS == 0):\n\t\t\treturn\n\t\tACLUS=float(NCLUS)\n\t\tXAV[NGOOD]=SUMX/ACLUS\n\t\tYAV[NGOOD]=SUMY/ACLUS\n\t\tZAV[NGOOD]=SUMZ/ACLUS\n\t\tTAV[NGOOD]=SUMT/ACLUS\n\t\tXYAV[NGOOD]=SUMRXY/ACLUS\n\t\tXYZAV[NGOOD]=SUMRXYZ/ACLUS\n\t\t# IONISATION CLUSTER SIZE\n\t\tNCL[NGOOD]=NCLUS\n\t\t# EXCITATION CLUSTER SIZE\n\t\tNCLEXC[NGOOD]=NSTEXC\n\t\t#\n\t\tFARX1[NGOOD]=FARX\n\t\tFARY1[NGOOD]=FARY\n\t\tFARZ1[NGOOD]=FARZ\n\t\tFARXY1[NGOOD]=FARXY\n\t\tRMAX1[NGOOD]=RMAX\n\t\tTSUM[NGOOD]=SUMTT\n\t\tXNEG[NGOOD]=float(NXNEG)/ACLUS\n\t\tYNEG[NGOOD]=float(NYNEG)/ACLUS\n\t\tZNEG[NGOOD]=float(NZNEG)/ACLUS\n\t\tEDELTA[NGOOD]=EST1\n\t\tEDELTA2[NGOOD]=EST2\n\t\tif(NCLUS > 1):\n\t\t\tNC2=NCLUS*NCLUS-NCLUS\n\t\t\tANC2=float(NC2)\n\t\t\tDX[NGOOD]=math.sqrt(abs((ACLUS*SUMX2-SUMX*SUMX)/ANC2))\n\t\t\tDY[NGOOD]=math.sqrt(abs((ACLUS*SUMY2-SUMY*SUMY)/ANC2))\n\t\t\tDZ[NGOOD]=math.sqrt(abs((ACLUS*SUMZ2-SUMZ*SUMZ)/ANC2))\n\t\t\tDT[NGOOD]=math.sqrt(abs((ACLUS*SUMT2-SUMT*SUMT)/ANC2))\n\t\t\tDXY[NGOOD]=math.sqrt(abs((ACLUS*SUMRXY2-SUMRXY*SUMRXY)/ANC2))\n\t\t\tDXYZ[NGOOD]=math.sqrt(abs((ACLUS*SUMRXYZ2-SUMRXYZ*SUMRXYZ)/ANC2))\n\t\telse:\n\t\t\tDX[NGOOD]=0.0\n\t\t\tDY[NGOOD]=0.0\n\t\t\tDZ[NGOOD]=0.0\n\t\t\tDZ[NGOOD]=0.0\n\t\t\tDT[NGOOD]=0.0\n\t\t\tDXY[NGOOD]=0.0\n\t\t\tDXYZ[NGOOD]=0.0\n\t\t# endif\n\t\treturn\n\t# 99 WRITE(6,991) NCLUS\n\t# 991 \n\tprint('\\n\\n\\n WARNING OVERFLOW IN ARRAYS IN FUNCTION STATS. NCLUS =',NCLUS,' STOPPED: FUNCTION')\n\tsys.exit()\n\t# end", "meta": {"hexsha": "4e40a4e65922c78927fdd4028d4381b282baf1c3", "size": 20951, "ext": "py", "lang": "Python", "max_stars_repo_path": "Stats.py", "max_stars_repo_name": "fireballpoint1/fortranTOpy", "max_stars_repo_head_hexsha": "55843a62c6f0a2f8e2a777ef70193940d3d2d141", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-26T05:10:56.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-26T05:10:56.000Z", "max_issues_repo_path": "Stats.py", "max_issues_repo_name": "fireballpoint1/fortranTOpy", "max_issues_repo_head_hexsha": "55843a62c6f0a2f8e2a777ef70193940d3d2d141", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Stats.py", "max_forks_repo_name": "fireballpoint1/fortranTOpy", "max_forks_repo_head_hexsha": "55843a62c6f0a2f8e2a777ef70193940d3d2d141", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-06-26T18:06:44.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-26T18:06:44.000Z", "avg_line_length": 22.4314775161, "max_line_length": 650, "alphanum_fraction": 0.6383466183, "include": true, "reason": "import numpy", "num_tokens": 10704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.2598256379609837, "lm_q1q2_score": 0.1470661308092738}} {"text": "\"\"\"Molecular database (MDB) class\n\n * MdbExomol is the MDB for ExoMol\n * MdbHit is the MDB for HITRAN or HITEMP \n \n\"\"\"\nimport numpy as np\nimport jax.numpy as jnp\nimport pathlib\nfrom exojax.spec import hapi, exomolapi, exomol\nfrom exojax.spec.hitran import gamma_natural as gn\nimport pandas as pd\n\n__all__ = ['MdbExomol','MdbHit']\n\nclass MdbExomol(object):\n \"\"\" molecular database of ExoMol\n\n MdbExomol is a class for ExoMol.\n\n Attributes:\n nurange: nu range [min,max] (cm-1)\n nu_lines (nd array): line center (cm-1)\n Sij0 (nd array): line strength at T=Tref (cm)\n dev_nu_lines (jnp array): line center in device (cm-1)\n logsij0 (jnp array): log line strength at T=Tref\n A (jnp array): Einstein A coeeficient\n gamma_natural (jnp array): gamma factor of the natural broadening\n elower (jnp array): the lower state energy (cm-1)\n gpp (jnp array): statistical weight\n jlower (jnp array): J_lower\n jupper (jnp array): J_upper\n n_Tref (jnp array): temperature exponent\n alpha_ref (jnp array): alpha_ref (gamma0)\n n_Tref_def: default temperature exponent in .def file, used for jlower not given in .broad\n alpha_ref_def: default alpha_ref (gamma0) in .def file, used for jlower not given in .broad\n\n \"\"\"\n def __init__(self,path,nurange=[-np.inf,np.inf],margin=1.0,crit=-np.inf, bkgdatm=\"H2\", broadf=True):\n \"\"\"Molecular database for Exomol form\n\n Args: \n path: path for Exomol data directory/tag. For instance, \"/home/CO/12C-16O/Li2015\"\n nurange: wavenumber range list (cm-1) [min,max] or wavenumber grid \n margin: margin for nurange (cm-1)\n crit: line strength lower limit for extraction\n bkgdatm: background atmosphere for broadening. e.g. H2, He, \n broadf: if False, the default broadening parameters in .def file is used\n\n Note:\n The trans/states files can be very large. For the first time to read it, we convert it to the feather-format. After the second-time, we use the feather format instead.\n\n \"\"\"\n explanation=\"Note: Couldn't find the feather format. We convert data to the feather format. After the second time, it will become much faster.\"\n \n self.path = pathlib.Path(path)\n t0=self.path.parents[0].stem \n molec=t0+\"__\"+str(self.path.stem)\n self.bkgdatm=bkgdatm\n print(\"Background atmosphere: \",self.bkgdatm)\n molecbroad=t0+\"__\"+self.bkgdatm\n\n self.crit = crit\n self.margin = margin\n self.nurange=[np.min(nurange),np.max(nurange)]\n self.broadf=broadf\n #Where exomol files are\n self.states_file = self.path/pathlib.Path(molec+\".states.bz2\")\n self.pf_file = self.path/pathlib.Path(molec+\".pf\")\n self.def_file = self.path/pathlib.Path(molec+\".def\")\n self.broad_file = self.path/pathlib.Path(molecbroad+\".broad\")\n\n if not self.def_file.exists():\n self.download(molec,extension=[\".def\"])\n if not self.pf_file.exists():\n self.download(molec,extension=[\".pf\"])\n if not self.states_file.exists():\n self.download(molec,extension=[\".states.bz2\"])\n if not self.broad_file.exists():\n self.download(molec,extension=[\".broad\"])\n \n #load def \n self.n_Texp_def, self.alpha_ref_def, self.molmass, numinf, numtag=exomolapi.read_def(self.def_file)\n # default n_Texp value if not given\n if self.n_Texp_def is None:\n self.n_Texp_def=0.5\n # default alpha_ref value if not given\n if self.alpha_ref_def is None:\n self.alpha_ref_def=0.07\n\n #load states\n if self.states_file.with_suffix(\".feather\").exists():\n states=pd.read_feather(self.states_file.with_suffix(\".feather\"))\n else:\n print(explanation)\n states=exomolapi.read_states(self.states_file)\n states.to_feather(self.states_file.with_suffix(\".feather\"))\n #load pf\n pf=exomolapi.read_pf(self.pf_file)\n self.gQT=jnp.array(pf[\"QT\"].to_numpy()) #grid QT\n self.T_gQT=jnp.array(pf[\"T\"].to_numpy()) #T forgrid QT\n \n #trans file(s)\n print(\"Reading transition file\")\n if numinf is None:\n self.trans_file = self.path/pathlib.Path(molec+\".trans.bz2\")\n if not self.trans_file.exists():\n self.download(molec,[\".trans.bz2\"])\n\n if self.trans_file.with_suffix(\".feather\").exists():\n trans=pd.read_feather(self.trans_file.with_suffix(\".feather\"))\n ndtrans=trans.to_numpy()\n del trans\n else:\n print(explanation)\n trans=exomolapi.read_trans(self.trans_file)\n trans.to_feather(self.trans_file.with_suffix(\".feather\"))\n ndtrans=trans.to_numpy()\n del trans\n #compute gup and elower\n self._A, self.nu_lines, self._elower, self._gpp, self._jlower, self._jupper=exomolapi.pickup_gE(states,ndtrans)\n else:\n imin=np.searchsorted(numinf,self.nurange[0],side=\"right\")-1 #left side\n imax=np.searchsorted(numinf,self.nurange[1],side=\"right\")-1 #left side\n self.trans_file=[]\n for k,i in enumerate(range(imin,imax+1)):\n trans_file = self.path/pathlib.Path(molec+\"__\"+numtag[i]+\".trans.bz2\")\n if not trans_file.exists():\n self.download(molec,extension=[\".trans.bz2\"],numtag=numtag[i])\n if trans_file.with_suffix(\".feather\").exists():\n trans=pd.read_feather(trans_file.with_suffix(\".feather\"))\n ndtrans=trans.to_numpy()\n del trans\n else:\n print(explanation)\n trans=exomolapi.read_trans(trans_file)\n trans.to_feather(trans_file.with_suffix(\".feather\"))\n ndtrans=trans.to_numpy()\n del trans\n self.trans_file.append(trans_file)\n #compute gup and elower \n if k==0:\n self._A, self.nu_lines, self._elower, self._gpp, self._jlower, self._jupper=exomolapi.pickup_gE(states,ndtrans)\n else:\n Ax, nulx, elowerx, gppx, jlowerx, jupperx=exomolapi.pickup_gE(states,ndtrans)\n self._A=np.hstack([self._A,Ax])\n self.nu_lines=np.hstack([self.nu_lines,nulx])\n self._elower=np.hstack([self._elower,elowerx])\n self._gpp=np.hstack([self._gpp,gppx])\n self._jlower=np.hstack([self._jlower,jlowerx])\n self._jupper=np.hstack([self._jupper,jupperx])\n \n\n self.Tref=296.0 \n self.QTref=np.array(self.QT_interp(self.Tref))\n \n ##Line strength: input should be ndarray not jnp array\n self.Sij0=exomol.Sij0(self._A,self._gpp,self.nu_lines,self._elower,self.QTref)\n \n ### MASKING ###\n mask=(self.nu_lines>self.nurange[0]-self.margin)\\\n *(self.nu_linesself.crit)\n \n self.masking(mask)\n \n def masking(self,mask):\n \"\"\"applying mask and (re)generate jnp.arrays\n \n Args:\n mask: mask to be applied. self.mask is updated.\n\n Note:\n We have nd arrays and jnp arrays. We apply the mask to nd arrays and generate jnp array from the corresponding nd array. For instance, self._A is nd array and self.A is jnp array.\n\n \"\"\"\n #numpy float 64 Do not convert them jnp array\n self.nu_lines = self.nu_lines[mask]\n self.Sij0 = self.Sij0[mask]\n self._A=self._A[mask]\n self._elower=self._elower[mask]\n self._gpp=self._gpp[mask]\n self._jlower=self._jlower[mask]\n self._jupper=self._jupper[mask]\n \n #jnp arrays\n self.dev_nu_lines=jnp.array(self.nu_lines)\n self.logsij0=jnp.array(np.log(self.Sij0))\n self.A=jnp.array(self._A)\n self.gamma_natural=gn(self.A)\n self.elower=jnp.array(self._elower)\n self.gpp=jnp.array(self._gpp)\n self.jlower=jnp.array(self._jlower,dtype=int)\n self.jupper=jnp.array(self._jupper,dtype=int)\n ##Broadening parameters \n self.set_broadening()\n\n def set_broadening(self,alpha_ref_def=None,n_Texp_def=None):\n \"\"\"setting broadening parameters\n \n Args:\n alpha_ref: set default alpha_ref and apply it. None=use self.alpha_ref_def\n n_Texp_def: set default n_Texp and apply it. None=use self.n_Texp_def\n \"\"\"\n if alpha_ref_def:\n self.alpha_ref_def = alpha_ref_def\n if n_Texp_def:\n self.n_Texp_def = n_Texp_def\n \n if self.broadf:\n try:\n print(\".broad is used.\")\n bdat=exomolapi.read_broad(self.broad_file)\n codelv=exomolapi.check_bdat(bdat)\n print(\"Broadening code level=\",codelv)\n if codelv==\"a0\":\n j2alpha_ref, j2n_Texp = exomolapi.make_j2b(bdat,\\\n alpha_ref_default=self.alpha_ref_def,\\\n n_Texp_default=self.n_Texp_def,\\\n jlower_max=np.max(self._jlower))\n self.alpha_ref=jnp.array(j2alpha_ref[self._jlower])\n self.n_Texp=jnp.array(j2n_Texp[self._jlower]) \n elif codelv==\"a1\":\n j2alpha_ref, j2n_Texp = exomolapi.make_j2b(bdat,\\\n alpha_ref_default=self.alpha_ref_def,\\\n n_Texp_default=self.n_Texp_def,\\\n jlower_max=np.max(self._jlower)) \n jj2alpha_ref, jj2n_Texp=exomolapi.make_jj2b(bdat,\\\n j2alpha_ref_def=j2alpha_ref,j2n_Texp_def=j2n_Texp,\\\n jupper_max=np.max(self._jupper))\n self.alpha_ref=jnp.array(jj2alpha_ref[self._jlower,self._jupper])\n self.n_Texp=jnp.array(jj2n_Texp[self._jlower,self._jupper]) \n except:\n print(\"Warning: Cannot load .broad. The default broadening parameters are used.\")\n self.alpha_ref=jnp.array(self.alpha_ref_def*np.ones_like(self._jlower))\n self.n_Texp=jnp.array(self.n_Texp_def*np.ones_like(self._jlower))\n \n else:\n print(\"The default broadening parameters are used.\")\n self.alpha_ref=jnp.array(self.alpha_ref_def*np.ones_like(self._jlower))\n self.n_Texp=jnp.array(self.n_Texp_def*np.ones_like(self._jlower))\n\n\n \n \n def QT_interp(self,T):\n \"\"\"interpolated partition function\n\n Args:\n T: temperature\n\n Returns:\n Q(T) interpolated in jnp.array\n\n \"\"\"\n return jnp.interp(T,self.T_gQT,self.gQT)\n \n def qr_interp(self,T):\n \"\"\"interpolated partition function ratio\n\n Args:\n T: temperature\n\n Returns:\n qr(T)=Q(T)/Q(Tref) interpolated in jnp.array\n\n \"\"\"\n return self.QT_interp(T)/self.QT_interp(self.Tref)\n \n \n def download(self,molec,extension,numtag=None):\n \"\"\"Downloading Exomol files\n\n Args: \n molec: like \"12C-16O__Li2015\"\n extension: extension list e.g. [\".pf\",\".def\",\".trans.bz2\",\".states.bz2\",\".broad\"]\n numtag: number tag of transition file if exists. e.g. \"11100-11200\"\n\n Note:\n The download URL is written in exojax.utils.url.\n \n \"\"\"\n import urllib.request\n from exojax.utils.molname import e2s\n import os\n from exojax.utils.url import url_ExoMol\n\n tag=molec.split(\"__\")\n molname_simple=e2s(tag[0])\n \n for ext in extension:\n if ext==\".trans.bz2\" and numtag is not None:\n ext=\"__\"+numtag+ext\n \n if ext==\".broad\":\n pfname_arr=[tag[0]+\"__H2\"+ext,tag[0]+\"__He\"+ext,tag[0]+\"__air\"+ext]\n url = url_ExoMol()+molname_simple+\"/\"+tag[0]+\"/\"\n else:\n pfname_arr=[molec+ext]\n url = url_ExoMol()+molname_simple+\"/\"+tag[0]+\"/\"+tag[1]+\"/\"\n \n for pfname in pfname_arr:\n pfpath=url+pfname\n os.makedirs(str(self.path), exist_ok=True)\n print(\"Downloading \"+pfpath)\n try:\n urllib.request.urlretrieve(pfpath,str(self.path/pfname))\n except:\n print(\"Error: Couldn't download \"+ext+\" file and save.\")\n\n\n\n\nclass MdbHit(object):\n \"\"\" molecular database of ExoMol\n\n MdbExomol is a class for ExoMol.\n\n Attributes:\n nurange: nu range [min,max] (cm-1)\n nu_lines (nd array): line center (cm-1)\n Sij0 (nd array): line strength at T=Tref (cm)\n dev_nu_lines (jnp array): line center in device (cm-1)\n logsij0 (jnp array): log line strength at T=Tref\n A (jnp array): Einstein A coeeficient\n gamma_natural (jnp array): gamma factor of the natural broadening\n gamma_air (jnp array): gamma factor of air pressure broadening\n gamma_self (jnp array): gamma factor of self pressure broadening\n elower (jnp array): the lower state energy (cm-1)\n gpp (jnp array): statistical weight\n n_air (jnp array): air temperature exponent\n\n \"\"\"\n\n def __init__(self,path,nurange=[-np.inf,np.inf],margin=250.0,crit=-np.inf):\n \"\"\"Molecular database for HITRAN/HITEMP form\n\n Args: \n path: path for HITRAN/HITEMP par file\n nurange: wavenumber range list (cm-1) [min,max] or wavenumber grid \n margin: margin for nurange (cm-1)\n crit: line strength lower limit for extraction\n\n \"\"\" \n #downloading\n self.path = pathlib.Path(path)\n molec=str(self.path.stem)\n if not self.path.exists():\n self.download()\n\n #bunzip2 if suffix is .bz2\n if self.path.suffix==\".bz2\":\n import bz2,shutil\n if self.path.with_suffix('').exists():\n import os\n os.remove(self.path.with_suffix(''))\n print(\"bunziping\")\n with bz2.BZ2File(str(self.path)) as fr:\n with open(str(self.path.with_suffix('')),\"wb\") as fw:\n shutil.copyfileobj(fr,fw)\n self.path=self.path.with_suffix('')\n \n molec=str(self.path.stem)\n \n hapi.db_begin(str(self.path.parent)) \n self.Tref=296.0 \n self.molecid = search_molecid(molec)\n self.crit = crit\n self.margin = margin\n self.nurange=[np.min(nurange),np.max(nurange)]\n\n #nd arrays using DRAM (not jnp, not in GPU)\n self.nu_lines = hapi.getColumn(molec, 'nu')\n self.Sij0 = hapi.getColumn(molec, 'sw')\n self.delta_air = hapi.getColumn(molec, 'delta_air')\n self.isoid = hapi.getColumn(molec,'local_iso_id')\n self.uniqiso=np.unique(self.isoid)\n\n self._A=hapi.getColumn(molec, 'a')\n self._n_air = hapi.getColumn(molec, 'n_air')\n self._gamma_air = hapi.getColumn(molec, 'gamma_air')\n self._gamma_self =hapi.getColumn(molec, 'gamma_self')\n self._elower = hapi.getColumn(molec, 'elower')\n self._gpp = hapi.getColumn(molec, 'gpp')\n\n ### MASKING ###\n mask=(self.nu_lines>self.nurange[0]-self.margin)\\\n *(self.nu_linesself.crit)\n \n self.masking(mask)\n \n def masking(self,mask):\n \"\"\"applying mask and (re)generate jnp.arrays\n \n Args:\n mask: mask to be applied\n\n Note:\n We have nd arrays and jnp arrays. We apply the mask to nd arrays and generate jnp array from the corresponding nd array. For instance, self._A is nd array and self.A is jnp array.\n\n \"\"\"\n \n #numpy float 64 Do not convert them jnp array\n self.nu_lines = self.nu_lines[mask]\n self.Sij0 = self.Sij0[mask]\n self.delta_air=self.delta_air[mask]\n self.isoid = self.isoid[mask]\n self.uniqiso=np.unique(self.isoid)\n\n ##numpy float 64 copy source for jnp\n self._A=self._A[mask]\n self._n_air = self._n_air[mask]\n self._gamma_air = self._gamma_air[mask]\n self._gamma_self = self._gamma_self[mask]\n self._elower = self._elower[mask]\n self._gpp = self._gpp[mask]\n\n #jnp.array copy from the copy sources\n self.dev_nu_lines=jnp.array(self.nu_lines)\n self.logsij0=jnp.array(np.log(self.Sij0))\n self.A=jnp.array(self._A)\n self.n_air=jnp.array(self._n_air)\n self.gamma_air = jnp.array(self._gamma_air)\n self.gamma_self = jnp.array(self._gamma_self)\n self.elower=jnp.array(self._elower)\n self.gpp=jnp.array(self._gpp)\n self.gamma_natural=gn(self.A)\n\n \n def download(self):\n \"\"\"Downloading HITRAN/HITEMP par file\n\n Note:\n The download URL is written in exojax.utils.url.\n\n \"\"\"\n import urllib.request\n from exojax.utils.url import url_HITRAN12\n from exojax.utils.url import url_HITEMP\n\n try:\n url = url_HITRAN12()+self.path.name\n urllib.request.urlretrieve(url,str(self.path))\n except:\n print(url)\n print(\"HITRAN download failed\")\n try:\n url = url_HITEMP()+self.path.name\n print(url)\n urllib.request.urlretrieve(url,str(self.path))\n except:\n print(\"HITEMP download failed\")\n\n ####################################\n\n def ExomolQT(self,path):\n \"\"\"use a partition function from ExoMol\n\n Args:\n path: path for Exomol data directory/tag. For instance, \"/home/CO/12C-16O/Li2015\"\n\n \"\"\"\n #load pf\n\n self.empath = pathlib.Path(path)\n t0=self.empath.parents[0].stem \n molec=t0+\"__\"+str(self.empath.stem)\n self.pf_file = self.empath/pathlib.Path(molec+\".pf\")\n if not self.pf_file.exists():\n self.exomol_pf_download(molec)\n\n pf=exomolapi.read_pf(self.pf_file)\n self.gQT=jnp.array(pf[\"QT\"].to_numpy()) #grid QT\n self.T_gQT=jnp.array(pf[\"T\"].to_numpy()) #T forgrid QT\n\n def exomol_pf_download(self,molec):\n \"\"\"Downloading Exomol pf files\n\n Args: \n molec: like \"12C-16O__Li2015\"\n\n Note:\n The download URL is written in exojax.utils.url.\n\n \"\"\"\n import urllib.request\n from exojax.utils.molname import e2s\n import os\n from exojax.utils.url import url_ExoMol\n\n tag=molec.split(\"__\")\n molname_simple=e2s(tag[0]) \n url = url_ExoMol()+molname_simple+\"/\"+tag[0]+\"/\"+tag[1]+\"/\"\n\n ext=\".pf\"\n pfname=molec+ext\n pfpath=url+pfname\n os.makedirs(str(self.empath), exist_ok=True)\n print(\"Downloading \"+pfpath)\n try:\n urllib.request.urlretrieve(pfpath,str(self.empath/pfname))\n except:\n print(\"Error: Couldn't download \"+ext+\" file and save.\")\n\n \n def QT_interp(self,T):\n \"\"\"interpolated partition function\n\n Args:\n T: temperature\n\n Returns:\n Q(T) interpolated in jnp.array\n\n \"\"\"\n return jnp.interp(T,self.T_gQT,self.gQT)\n \n def qr_interp(self,T):\n \"\"\"interpolated partition function ratio\n\n Args:\n T: temperature\n\n Returns:\n qr(T)=Q(T)/Q(Tref) interpolated in jnp.array\n\n \"\"\"\n return self.QT_interp(T)/self.QT_interp(self.Tref)\n \n\n def Qr_HAPI(self,Tarr):\n \"\"\"Partition Function ratio using HAPI partition sum\n\n Args:\n Tarr: temperature array (K)\n \n Returns:\n Qr = partition function ratio array [N_Tarr x N_iso]\n\n Note: \n N_Tarr = len(Tarr), N_iso = len(self.uniqiso)\n\n \"\"\"\n allT=list(np.concatenate([[self.Tref],Tarr]))\n Qrx=[]\n for iso in self.uniqiso:\n Qrx.append(hapi.partitionSum(self.molecid,iso, allT))\n Qrx=np.array(Qrx)\n qr=Qrx[:,1:].T/Qrx[:,0] #Q(T)/Q(Tref)\n return qr\n\n def Qr_line_HAPI(self,T):\n \"\"\"Partition Function ratio using HAPI partition sum\n\n Args:\n T: temperature (K)\n\n Returns:\n Qr_line, partition function ratio array for lines [Nlines]\n\n Note: \n Nlines=len(self.nu_lines)\n\n \"\"\"\n qr_line=np.ones_like(self.isoid,dtype=np.float64)\n qrx=self.Qr_HAPI([T])\n for idx,iso in enumerate(self.uniqiso):\n mask=self.isoid==iso\n qr_line[mask]=qrx[0,idx]\n return qr_line\n\n def Qr_layer_HAPI(self,Tarr):\n \"\"\"Partition Function ratio using HAPI partition sum\n\n Args:\n Tarr: temperature array (K)\n\n Returns:\n Qr_layer, partition function ratio array for lines [N_Tarr x Nlines]\n\n Note: \n Nlines=len(self.nu_lines)\n N_Tarr=len(Tarr)\n\n \"\"\"\n NP=len(Tarr)\n qt=np.zeros((NP,len(self.isoid)))\n qr=self.Qr_HAPI(Tarr)\n for idx,iso in enumerate(self.uniqiso):\n mask=self.isoid==iso\n for ilayer in range(NP):\n qt[ilayer,mask]=qr[ilayer,idx]\n return qt\n \ndef search_molecid(molec):\n \"\"\"molec id from molec (source table name) of HITRAN/HITEMP\n\n Args:\n molec: source table name\n\n Return:\n int: molecid (HITRAN molecular id)\n\n \"\"\"\n try:\n hitf=molec.split(\"_\")\n molecid=int(hitf[0])\n return molecid\n\n except:\n print(\"Warning: Define molecid by yourself.\")\n return None\n\nif __name__ == \"__main__\":\n #mdb=MdbExomol(\"/home/kawahara/exojax/data/CO/12C-16O/Li2015/\") \n #mdb=MdbExomol(\"/home/kawahara/exojax/data/CH4/12C-1H4/YT34to10/\",nurange=[6050.0,6150.0])\n mdb=MdbExomol('.database/H2O/1H2-16O/POKAZATEL',[4310.0,4320.0],crit=1.e-45) \n\n# mask=mdb.A>1.e-42\n# mdb.masking(mask)\n# mdb=MdbExomol(\"/home/kawahara/exojax/data/exomol/NH3/14N-1H3/CoYuTe/\",nurange=[6050.0,6150.0])\n# mdb=MdbExomol(\"/home/kawahara/exojax/data/exomol/H2S/1H2-32S/AYT2/\",nurange=[6050.0,6150.0])\n# mdb=MdbExomol(\"/home/kawahara/exojax/data/exomol/FeH/56Fe-1H/MoLLIST/\",nurange=[6050.0,6150.0])\n# mdb=MdbExomol(\"/home/kawahara/exojax/data/exomol/NO/14N-16O/NOname/14N-16O__NOname\")\n", "meta": {"hexsha": "22456d1efeca850ebd58dee56f9a552017300496", "size": 22835, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/exojax/spec/moldb.py", "max_stars_repo_name": "chonma0ctopus/exojax", "max_stars_repo_head_hexsha": "852fbccebaeaa2ed699237d1d8855aa69eb71867", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/exojax/spec/moldb.py", "max_issues_repo_name": "chonma0ctopus/exojax", "max_issues_repo_head_hexsha": "852fbccebaeaa2ed699237d1d8855aa69eb71867", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/exojax/spec/moldb.py", "max_forks_repo_name": "chonma0ctopus/exojax", "max_forks_repo_head_hexsha": "852fbccebaeaa2ed699237d1d8855aa69eb71867", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4776357827, "max_line_length": 190, "alphanum_fraction": 0.5812130501, "include": true, "reason": "import numpy,import jax", "num_tokens": 5881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.2782567877172032, "lm_q1q2_score": 0.14672940190580183}} {"text": "# Copyright 2021 D-Wave Systems Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nr\"\"\"Contains implementations for applying MPO's to MPS's with subsequent\ncompression.\n\"\"\"\n\n\n\n#####################################\n## Load libraries/packages/modules ##\n#####################################\n\n# For deep copies of objects.\nimport copy\n\n\n\n# For general array handling.\nimport numpy as np\n\n# For calculating the eigenspectra of Hermitian matrices.\nimport scipy.linalg\n\n# For creating tensor networks and performing contractions.\nimport tensornetwork as tn\n\n\n\n# Assign an alias to the ``spinbosonchain`` library.\nimport spinbosonchain as sbc\n\n# For performing SVD truncation sweeps, shifting orthogonal centers,\n# and single-node SVD.\nimport spinbosonchain._svd\n\n# For performing QR sweeps, and single-node QR factorizations.\nimport spinbosonchain._qr\n\n# For finding the dominant eigenvectors of specially structured tensor networks.\nimport spinbosonchain._arnoldi\n\n\n\n############################\n## Authorship information ##\n############################\n\n__author__ = \"D-Wave Systems Inc.\"\n__copyright__ = \"Copyright 2021\"\n__credits__ = [\"Matthew Fitzpatrick\"]\n__maintainer__ = \"D-Wave Systems Inc.\"\n__email__ = \"support@dwavesys.com\"\n__status__ = \"Development\"\n\n\n\n##################################\n## Define classes and functions ##\n##################################\n\ndef apply_mpo_to_mps_and_compress(mpo_nodes,\n mps_nodes,\n compress_params,\n is_infinite):\n kwargs = {\"mpo_nodes\": mpo_nodes,\n \"mps_nodes\": mps_nodes,\n \"compress_params\": compress_params}\n if is_infinite:\n # The Schmidt spectrum for bonds between unit cells is calculated.\n schmidt_spectra = \\\n apply_infinite_mpo_to_infinite_mps_and_compress(**kwargs)\n else:\n # The Schmidt spectra is calculated for all bonds if no variational\n # compression is to be performed, otherwise schmidt_spectra is set to\n # `None`.\n schmidt_spectra = \\\n apply_finite_mpo_to_finite_mps_and_compress(**kwargs)\n\n return schmidt_spectra\n\n\n\ndef apply_infinite_mpo_to_infinite_mps_and_compress(mpo_nodes,\n mps_nodes,\n compress_params):\n apply_directly_mpo_to_mps(mpo_nodes, mps_nodes)\n\n # See comments in function spinbosonchain._svd.Lambda_Theta_form for a\n # description of the Lambda_Theta object.\n Lambda_Theta = sbc._svd.Lambda_Theta_form(mps_nodes)\n \n canonicalize_and_compress_infinite_mps(Lambda_Theta, compress_params)\n\n Lambda = Lambda_Theta[0]\n Theta_nodes = Lambda_Theta[1]\n\n L = len(mps_nodes)\n\n nodes_to_contract = [Lambda, Theta_nodes[0]]\n network_struct = [(-1, 1), (1, -2, -3)]\n mps_nodes[0] = tn.ncon(nodes_to_contract, network_struct)\n \n for r in range(1, L):\n mps_nodes[r] = Theta_nodes[r]\n\n schmidt_spectra = [Lambda]\n\n return schmidt_spectra\n\n\n\ndef apply_finite_mpo_to_finite_mps_and_compress(mpo_nodes,\n mps_nodes,\n compress_params):\n # [1]: Annals of Physics 326 (2011) 96-192.\n # [2]: New J. Phys. 12, 055026 (2010).\n \n # Put MPO in left-canonical form. MPS is assumed to be already in said form.\n kwargs = {\"nodes\": mpo_nodes, \"normalize\": False}\n sbc._qr.left_to_right_sweep(**kwargs)\n\n # See docs of class spinbosonchain.compress.Params for descriptions of the\n # various compression parameters used below.\n if compress_params.max_num_var_sweeps > 0:\n norm_of_mps_to_compress = \\\n norm_of_mpo_mps_network_wo_compression(mpo_nodes, mps_nodes)\n initial_mps_nodes = copy.deepcopy(mps_nodes)\n else:\n initial_mps_nodes = None\n\n if compress_params.method == \"direct\":\n # Here we essentially follow the discussion in the paragraph containing\n # Eq. (16) of [2], and the subsequent paragraph, with a few changes:\n # we first perform a sweep from right to left without compression,\n # followed by a return sweep from left to right. Since there is no\n # compression in first sweep, we can use QR instead of SVD.\n apply_directly_mpo_to_mps(mpo_nodes, mps_nodes)\n kwargs[\"nodes\"] = mps_nodes\n sbc._qr.right_to_left_sweep(**kwargs)\n else:\n # For a discussion on the zip-up method, see the paragraph above that\n # containing Eq. (17) of [2], and read through until the end of that\n # section. Note that mps_nodes is updated in place.\n zip_up(mpo_nodes, mps_nodes, compress_params)\n\n # Perform a return SVD truncation sweep. If the SVD truncation sweep is\n # followed by variational compression, then L-nodes are calculated and\n # cached while performing the SVD truncation sweep for efficiency. See\n # Sec. 4.5.2 of [1] for a discussion on the L-nodes and variational\n # compression. Note that mps_nodes is updated in place.\n kwargs = {\"mpo_nodes\": mpo_nodes,\n \"mps_nodes\": mps_nodes,\n \"initial_mps_nodes\": initial_mps_nodes,\n \"compress_params\": compress_params}\n L_cache, schmidt_spectra = return_svd_sweep(**kwargs)\n\n if compress_params.max_num_var_sweeps > 0:\n # If variational compression is performed, then the Schmidt spectra is\n # not calculated.\n schmidt_spectra = None\n kwargs[\"norm_of_mps_to_compress\"] = norm_of_mps_to_compress\n kwargs[\"L_cache\"] = L_cache\n variational_compression(**kwargs)\n\n return schmidt_spectra\n\n\n\ndef norm_of_mpo_mps_network_wo_compression(mpo_nodes, mps_nodes):\n # [1]: Annals of Physics 326 (2011) 96-192.\n\n # See Sec. 4.5.2 of [1] for some helpful context. In this scenario, the\n # mpo-mps network without compression is denoted by |psi> in Sec. 4.5.2 of\n # [1]. The R-nodes are discussed in Sec. 4.5.2 of [1].\n imax = len(mps_nodes) - 1\n R = trivial_R(mpo_nodes, mps_nodes, num_legs=4) # Right-most R-node.\n \n for i in range(imax, -1, -1):\n MWWR = contract_MWWR_network(mps_nodes[i], mpo_nodes[i], R)\n conj_mps_node = tn.conj(mps_nodes[i])\n conj_mps_node[1] ^ MWWR[3]\n conj_mps_node[2] ^ MWWR[4]\n output_edge_order = (MWWR[0], MWWR[1], MWWR[2], conj_mps_node[0])\n R = tn.contract_between(node1=conj_mps_node,\n node2=MWWR,\n output_edge_order=output_edge_order)\n\n nodes_to_contract = [R]\n network_struct = [(1, 2, 2, 1)]\n result = tn.ncon(nodes_to_contract, network_struct)\n result = float(np.sqrt(np.real(result.tensor)))\n\n return result\n\n\n\ndef trivial_R(mpo_nodes, mps_nodes, num_legs):\n # [1]: Annals of Physics 326 (2011) 96-192.\n\n # See Sec. 4.5.2 of [1] for a discussion on the R-nodes. The 'trivial'\n # R-node is essentially a multi-dimensional Kronecker delta.\n \n w_r = mpo_nodes[-1].shape[-1] # w_r: right dangling mpo bond dimension.\n chi_r = mps_nodes[-1].shape[-1] # chi_r: right dangling mps bond dimension.\n if num_legs == 3:\n tensor = np.zeros([chi_r, w_r, chi_r*w_r], dtype=np.complex128)\n for m2 in range(chi_r*w_r):\n m1 = 0 if chi_r == 1 else m2\n w = 0 if w_r == 1 else m2\n tensor[m1, w, m2] = 1\n R = tn.Node(tensor)\n else:\n tensor = np.zeros([chi_r, w_r, w_r, chi_r], dtype=np.complex128)\n for m in range(chi_r):\n for w in range(w_r):\n tensor[m, w, w, m] = 1\n R = tn.Node(tensor)\n\n return R\n\n\n\ndef trivial_L(mpo_nodes, mps_nodes):\n # [1]: Annals of Physics 326 (2011) 96-192.\n\n # See Sec. 4.5.2 of [1] for a discussion on the L-nodes. The 'trivial'\n # L-node is essentially a multi-dimensional Kronecker delta.\n \n if mps_nodes is None:\n L = None\n return L\n \n w_l = mpo_nodes[0].shape[0] # w_l: left dangling mpo bond dimension.\n chi_l = mps_nodes[0].shape[0] # chi_l: left dangling mps bond dimension.\n tensor = np.zeros([chi_l, w_l, chi_l*w_l], dtype=np.complex128)\n for m2 in range(chi_l*w_l):\n m1 = 0 if chi_l == 1 else m2\n w = 0 if w_l == 1 else m2\n tensor[m1, w, m2] = 1\n L = tn.Node(tensor)\n\n return L\n\n\n\ndef contract_MR_network(M, R, num_R_legs=3):\n # See comments in function contract_MWWR_network for context.\n \n nodes_to_contract = [M, R]\n if num_R_legs == 3:\n network_struct = [(-1, -2, 1), (1, -3, -4)]\n else:\n network_struct = [(-1, -2, 1), (1, -3, -4, -5)]\n MR = tn.ncon(nodes_to_contract, network_struct)\n\n return MR\n\n\n\ndef contract_MWR_network(M, W, R, num_R_legs=3):\n # See comments in function contract_MWWR_network for context.\n \n MR = contract_MR_network(M, R, num_R_legs)\n\n W[2] ^ MR[1]\n W[3] ^ MR[2]\n if num_R_legs == 3:\n output_edge_order = (MR[0], W[0], W[1], MR[3])\n \n else:\n output_edge_order = (MR[0], W[0], W[1], MR[3], MR[4])\n MWR = tn.contract_between(node1=W,\n node2=MR,\n output_edge_order=output_edge_order)\n \n return MWR\n\n\n\ndef contract_MWWR_network(M, W, R):\n # [1]: Annals of Physics 326 (2011) 96-192.\n \n # M is the MPS node at the current site of interest. W is the MPO node being\n # applied to M. R is the R-node just to the right of the current site of\n # interest. See Sec. 4.5.2 of [1] for a discussion on the R-nodes.\n \n MWR = contract_MWR_network(M, W, R, num_R_legs=4)\n W = tn.conj(W)\n\n W[2] ^ MWR[2]\n W[3] ^ MWR[3]\n output_edge_order = (MWR[0], MWR[1], W[0], W[1], MWR[4])\n MWWR = tn.contract_between(node1=W,\n node2=MWR,\n output_edge_order=output_edge_order)\n \n return MWWR\n\n\n\ndef contract_LM_network(L, M):\n # See comments in function contract_LMW_network for context.\n \n nodes_to_contract = [L, M]\n network_struct = [(1, -3, -4), (1, -2, -1)]\n LM = tn.ncon(nodes_to_contract, network_struct)\n\n return LM\n\n\n\ndef contract_LMW_network(L, M, W):\n # [1]: Annals of Physics 326 (2011) 96-192.\n \n # M is the MPS node at the current site of interest to which a MPO is to be\n # applied at some point. L is the L-node just to the left of the current\n # site of interest. See Sec. 4.5.2 of [1] for a discussion on the L-nodes.\n \n LM = contract_LM_network(L, M)\n\n LM[1] ^ W[2]\n LM[2] ^ W[0]\n output_edge_order = (LM[0], W[3], W[1], LM[3])\n LMW = tn.contract_between(node1=LM,\n node2=W,\n output_edge_order=output_edge_order)\n \n return LMW\n\n\n\ndef zip_up(mpo_nodes, mps_nodes, compress_params):\n # [2]: New J. Phys. 12, 055026 (2010).\n\n # For a discussion on the zip-up method, see the paragraph above that\n # containing Eq. (17) of [2], and read through until the end of that\n # section.\n\n imax = len(mps_nodes) - 1\n U = None\n S = None\n\n # See second last paragraph of Sec. 2.1.3 of [2] for the reasoning behind\n # the code block below.\n compress_params = copy.deepcopy(compress_params)\n if compress_params.max_num_singular_values is not None:\n compress_params.max_num_singular_values *= 2\n if compress_params.max_trunc_err is not None:\n compress_params.max_trunc_err /= 10\n if compress_params.svd_rel_tol is not None:\n compress_params.svd_rel_tol /= 10\n\n for i in range(imax, -1, -1):\n node_idx = i\n U, S = update_mps_node_in_zip_up(node_idx,\n mpo_nodes,\n mps_nodes,\n U,\n S,\n compress_params)\n\n return None\n\n\n\ndef update_mps_node_in_zip_up(node_idx,\n mpo_nodes,\n mps_nodes,\n U,\n S,\n compress_params):\n # [2]: New J. Phys. 12, 055026 (2010).\n\n # For a discussion on the zip-up method, see the paragraph above that\n # containing Eq. (17) of [2], and read through until the end of that\n # section.\n \n i = node_idx\n imax = len(mps_nodes) - 1 \n mpo_node = mpo_nodes[i]\n mps_node = mps_nodes[i]\n\n if i == imax:\n nodes_to_contract = (mpo_node, mps_node)\n network_struct = [(-1, -3, 1, -4), (-2, 1, -5)]\n temp_node_2 = tn.ncon(nodes_to_contract, network_struct)\n tn.flatten_edges([temp_node_2[3], temp_node_2[4]])\n elif 0 <= i < imax:\n nodes_to_contract = (mps_node, U, S)\n network_struct = [(-1, -2, 2), (-3, 2, 1), (1, -4)]\n temp_node_1 = tn.ncon(nodes_to_contract, network_struct)\n temp_node_1[1] ^ mpo_node[2]\n temp_node_1[2] ^ mpo_node[3]\n output_edge_order = \\\n (mpo_node[0], temp_node_1[0], mpo_node[1], temp_node_1[3])\n temp_node_2 = tn.contract_between(node1=temp_node_1,\n node2=mpo_node,\n output_edge_order=output_edge_order)\n\n if 0 < i <= imax:\n left_edges = (temp_node_2[0], temp_node_2[1])\n right_edges = (temp_node_2[2], temp_node_2[3])\n U, S, V_dagger = sbc._svd.split_node_full(temp_node_2,\n left_edges,\n right_edges,\n compress_params)\n mps_nodes[i] = V_dagger\n elif i == 0:\n tn.flatten_edges([temp_node_2[0], temp_node_2[1]])\n temp_node_2.reorder_edges([temp_node_2[2],\n temp_node_2[0],\n temp_node_2[1]])\n mps_nodes[i] = temp_node_2\n\n return U, S\n\n\n\ndef return_svd_sweep(mpo_nodes, mps_nodes, initial_mps_nodes, compress_params):\n # [1]: Annals of Physics 326 (2011) 96-192.\n \n # Perform a return SVD truncation sweep. If the SVD truncation sweep is\n # followed by variational compression, then L-nodes are calculated and\n # cached while performing the SVD truncation sweep for efficiency. See\n # Sec. 4.5.2 of [1] for a discussion on the L-nodes and variational\n # compression. Readers should note that the mpo-mps network without\n # compression is denoted by |psi> in Sec. 4.5.2 and should keep this in\n # mind when reading about the L-nodes.\n\n # Note further that initial_mps_nodes represents the MPS before the MPO\n # application, whereas at the end of this function, mps_nodes represents\n # the MPS obtained after applying the MPO.\n \n imin = 0\n imax = len(mps_nodes) - 2\n L = trivial_L(mpo_nodes, initial_mps_nodes)\n L_cache = [L]\n schmidt_spectra = []\n\n # Normalize MPS now if no variational compression is to be performed.\n # Otherwise, normalization is performed after variational compression.\n normalize_schmidt_spectra = (compress_params.max_num_var_sweeps == 0)\n \n for i in range(imin, imax+1):\n kwargs = {\"nodes\": mps_nodes,\n \"current_orthogonal_center_idx\": i,\n \"compress_params\": compress_params,\n \"normalize_schmidt_spectra\": normalize_schmidt_spectra}\n U, S, V_dagger = sbc._svd.shift_orthogonal_center_to_the_right(**kwargs)\n schmidt_spectra.insert(0, S)\n \n if compress_params.max_num_var_sweeps > 0:\n M = initial_mps_nodes[i]\n W = mpo_nodes[i]\n LMW = contract_LMW_network(L, M, W)\n conj_mps_node = tn.conj(mps_nodes[i])\n LMW[2] ^ conj_mps_node[1]\n LMW[3] ^ conj_mps_node[0]\n output_edge_order = (LMW[0], LMW[1], conj_mps_node[2])\n L = tn.contract_between(node1=LMW,\n node2=conj_mps_node,\n output_edge_order=output_edge_order)\n L_cache.append(L)\n\n if compress_params.max_num_var_sweeps == 0:\n # Normalize MPS such that its 'norm' equal unity.\n mps_nodes[-1] /= tn.norm(mps_nodes[-1])\n\n return L_cache, schmidt_spectra\n\n\n\ndef variational_compression(mpo_nodes,\n mps_nodes,\n initial_mps_nodes,\n norm_of_mps_to_compress,\n L_cache,\n compress_params):\n # [1]: Annals of Physics 326 (2011) 96-192.\n\n # This function essentially implements the variational compression procedure\n # described in Sec. 4.5.2 of [1], see therein for discussion on the L- and\n # R-nodes. Readers should note that the mpo-mps network without compression\n # is denoted by |psi> in Sec. 4.5.2 and should keep this in mind when\n # reading about the L- and R-nodes.\n\n # initial_mps_nodes represents the MPS before the MPO application, whereas\n # mps_nodes represents the MPS obtained after applying the MPO.\n \n imax = len(mps_nodes) - 1\n R_cache = [trivial_R(mpo_nodes, initial_mps_nodes, num_legs=3)]\n\n # A full sweep goes right to left, then left to right.\n sweep_count = 0\n while sweep_count < compress_params.max_num_var_sweeps:\n kwargs = {\"mpo_nodes\": mpo_nodes,\n \"mps_nodes\": mps_nodes,\n \"initial_mps_nodes\": initial_mps_nodes,\n \"norm_of_mps_to_compress\": norm_of_mps_to_compress,\n \"L_cache\": L_cache,\n \"R_cache\": R_cache,\n \"compress_params\": compress_params}\n \n if variational_compression_has_converged(**kwargs):\n break\n\n kwargs = {\"mpo_nodes\": mpo_nodes,\n \"mps_nodes\": mps_nodes,\n \"initial_mps_nodes\": initial_mps_nodes,\n \"L_cache\": L_cache,\n \"R_cache\": R_cache}\n \n for i in range(imax, 0, -1):\n update_node_and_shift_left_in_variational_compression(**kwargs)\n for i in range(imax):\n update_node_and_shift_right_in_variational_compression(**kwargs)\n\n sweep_count += 1\n\n # Normalize MPS such that its 'norm' equal unity.\n mps_nodes[-1] /= tn.norm(mps_nodes[-1])\n\n return None\n\n\n\ndef variational_compression_has_converged(mpo_nodes,\n mps_nodes,\n initial_mps_nodes,\n norm_of_mps_to_compress,\n L_cache,\n R_cache,\n compress_params):\n # [1]: Annals of Physics 326 (2011) 96-192.\n\n # See Sec. 4.5.2 of [1] for a discussion on the variational compression\n # procedure implemented in this module. Readers should note that the\n # mpo-mps network without compression is denoted by |psi> in Sec. 4.5.2.\n\n # This function checks whether the variational compression procedure has\n # achieved convergence. This is done by evaluating the left hand side of\n # Eq. (150) of [1].\n\n # 'compressed' and 'uncompressed' MPS's are refering to |psi'> and |psi>\n # in Sec. 4.5.2 [see above note on |psi>]. Hence, in both cases these are\n # MPS's obtained after applying the MPO.\n\n # initial_mps_nodes represents the MPS before the MPO application, whereas\n # mps_nodes represents the MPS obtained after applying the MPO.\n \n overlap = overlap_btwn_compressed_and_uncompressed_mps(L_cache,\n initial_mps_nodes,\n mpo_nodes,\n mps_nodes,\n R_cache)\n\n nodes_to_contract = (mps_nodes[-1], tn.conj(mps_nodes[-1]))\n network_struct = [(1, 2, 3), (1, 2, 3)]\n norm_sq_of_compressed_mps = tn.ncon(nodes_to_contract, network_struct)\n norm_of_compressed_mps = \\\n float(np.sqrt(np.real(norm_sq_of_compressed_mps.tensor)))\n\n var_rel_err_sq = (np.abs(norm_of_mps_to_compress * norm_of_mps_to_compress\n - 2 * np.real(overlap)\n + norm_of_compressed_mps * norm_of_compressed_mps)\n / norm_of_mps_to_compress)\n var_rel_err = np.sqrt(var_rel_err_sq)\n\n if var_rel_err < compress_params.var_rel_tol:\n result = True\n else:\n result = False\n\n return result\n\n\n\ndef overlap_btwn_compressed_and_uncompressed_mps(L_cache,\n initial_mps_nodes,\n mpo_nodes,\n mps_nodes,\n R_cache):\n # [1]: Annals of Physics 326 (2011) 96-192.\n\n # See Sec. 4.5.2 of [1] for a discussion on the variational compression\n # procedure implemented in this module. Readers should note that the\n # mpo-mps network without compression is denoted by |psi> in Sec. 4.5.2.\n\n # 'compressed' and 'uncompressed' MPS's are refering to |psi'> and |psi>\n # in Sec. 4.5.2 [see above note on |psi>]. Hence, in both cases these are\n # MPS's obtained after applying the MPO.\n\n # initial_mps_nodes represents the MPS before the MPO application, whereas\n # mps_nodes represents the MPS obtained after applying the MPO.\n \n L = L_cache[-1]\n M = initial_mps_nodes[-1]\n W = mpo_nodes[-1]\n R = R_cache[0]\n\n MWR = contract_MWR_network(M, W, R)\n \n L[0] ^ MWR[0]\n L[1] ^ MWR[1]\n output_edge_order = (L[2], MWR[2], MWR[3])\n LMWR = tn.contract_between(node1=L,\n node2=MWR,\n output_edge_order=output_edge_order)\n \n conj_mps_node = tn.conj(mps_nodes[-1])\n\n for edge_idx in range(3):\n conj_mps_node[edge_idx] ^ LMWR[edge_idx]\n\n overlap = tn.contract_between(node1=conj_mps_node, node2=LMWR)\n overlap = complex(overlap.tensor)\n\n return overlap\n\n\n\ndef update_node_and_shift_left_in_variational_compression(mpo_nodes,\n mps_nodes,\n initial_mps_nodes,\n L_cache,\n R_cache):\n # [1]: Annals of Physics 326 (2011) 96-192.\n\n # This function essentially implements a single shift to the left in the\n # variational compression procedure described in Sec. 4.5.2 of [1], see\n # therein for discussion on the L- and R-nodes. Readers should note that the\n # mpo-mps network without compression is denoted by |psi> in Sec. 4.5.2 and\n # should keep this in mind when reading about the L- and R-nodes.\n\n # initial_mps_nodes represents the MPS before the MPO application, whereas\n # mps_nodes represents the MPS obtained after applying the MPO.\n \n orthogonal_center_idx = len(L_cache) - 1\n L = L_cache[-1]\n M = initial_mps_nodes[orthogonal_center_idx]\n W = mpo_nodes[orthogonal_center_idx]\n R = R_cache[0]\n\n MWR = contract_MWR_network(M, W, R)\n \n L[0] ^ MWR[0]\n L[1] ^ MWR[1]\n output_edge_order = (L[2], MWR[2], MWR[3])\n LMWR = tn.contract_between(node1=L,\n node2=MWR,\n output_edge_order=output_edge_order)\n \n L_cache.pop()\n\n QR = tn.conj(LMWR)\n left_node, right_node = sbc._qr.split_node(node=QR,\n left_edges=(QR[1], QR[2]),\n right_edges=(QR[0],))\n new_edge_order = [left_node[2], left_node[0], left_node[1]]\n B = tn.conj(left_node.reorder_edges(new_edge_order))\n mps_nodes[orthogonal_center_idx] = B\n conj_B = tn.conj(B)\n \n conj_B[1] ^ MWR[2]\n conj_B[2] ^ MWR[3]\n output_edge_order = (MWR[0], MWR[1], conj_B[0])\n next_R = tn.contract_between(node1=conj_B,\n node2=MWR,\n output_edge_order=output_edge_order)\n R_cache.insert(0, next_R)\n\n return None\n\n\n\ndef update_node_and_shift_right_in_variational_compression(mpo_nodes,\n mps_nodes,\n initial_mps_nodes,\n L_cache,\n R_cache):\n # [1]: Annals of Physics 326 (2011) 96-192.\n\n # This function essentially implements a single shift to the right in the\n # variational compression procedure described in Sec. 4.5.2 of [1], see\n # therein for discussion on the L- and R-nodes. Readers should note that the\n # mpo-mps network without compression is denoted by |psi> in Sec. 4.5.2 and\n # should keep this in mind when reading about the L- and R-nodes.\n\n # initial_mps_nodes represents the MPS before the MPO application, whereas\n # mps_nodes represents the MPS obtained after applying the MPO.\n \n orthogonal_center_idx = len(L_cache) - 1\n L = L_cache[-1]\n M = initial_mps_nodes[orthogonal_center_idx]\n W = mpo_nodes[orthogonal_center_idx]\n R = R_cache[0]\n \n LMW = contract_LMW_network(L, M, W)\n\n LMW[0] ^ R[0]\n LMW[1] ^ R[1]\n output_edge_order = (LMW[3], LMW[2], R[2])\n LMWR = tn.contract_between(node1=LMW,\n node2=R,\n output_edge_order=output_edge_order)\n R_cache.pop(0)\n\n QR = LMWR\n left_node, right_node = sbc._qr.split_node(node=QR,\n left_edges=(QR[0], QR[1]),\n right_edges=(QR[2],))\n A = left_node\n mps_nodes[orthogonal_center_idx] = A\n conj_A = tn.conj(A)\n\n if orthogonal_center_idx == len(mps_nodes) - 2:\n nodes_to_contract = [right_node, mps_nodes[-1]]\n network_struct = [(-1, 1), (1, -2, -3)]\n mps_nodes[-1] = tn.ncon(nodes_to_contract, network_struct)\n \n LMW[2] ^ conj_A[1]\n LMW[3] ^ conj_A[0]\n output_edge_order = (LMW[0], LMW[1], conj_A[2])\n next_L = tn.contract_between(node1=LMW,\n node2=conj_A,\n output_edge_order=output_edge_order)\n L_cache.append(next_L)\n\n return None\n\n\n\ndef apply_directly_mpo_to_mps(mpo_nodes, mps_nodes):\n for idx, (mpo_node, mps_node) in enumerate(zip(mpo_nodes, mps_nodes)):\n mps_nodes[idx] = apply_directly_mpo_node_to_mps_node(mpo_node, mps_node)\n\n return None\n\n\n\ndef apply_directly_mpo_node_to_mps_node(mpo_node, mps_node):\n nodes_to_contract = (mpo_node, mps_node)\n network_struct = [(-1, -3, 1, -4), (-2, 1, -5)]\n new_mps_node = tn.ncon(nodes_to_contract, network_struct)\n\n # A single call to tn.flatten_edges will take the flatten edge set and move\n # it to the right end of the list of edges, hence the necessary call to\n # reorder_edges.\n tn.flatten_edges([new_mps_node[0], new_mps_node[1]])\n tn.flatten_edges([new_mps_node[1], new_mps_node[2]])\n new_mps_node.reorder_edges([new_mps_node[1],\n new_mps_node[0],\n new_mps_node[2]])\n\n return new_mps_node\n\n\n\ndef canonicalize_and_compress_infinite_mps(Lambda_Theta, compress_params):\n # [1]: Annals of Physics 326 (2011) 96-192.\n # [3]: Phys. Rev. B 78, 155117 (2008)\n # [4]: arXiv.0804.2509 (2008)\n\n # This function compresses a given infinite MPS. The procedure implemented\n # here draws from [1], [3], and [4]. Notation-wise we follow mostly [1].\n # In [1], the relevant content is found in Sec. 10.5.\n\n # See comments in function spinbosonchain._svd.Lambda_Theta_form for a\n # description of the Lambda_Theta object.\n\n # V_L, V_R, X, X_inv, Y, and Y_inv are the same as those defined in\n # Sec. 10.5 of [1] except that we have generalized to a L-site unit cell\n # where L>0.\n V_L = calc_V_L(Lambda_Theta)\n V_R = calc_V_R(Lambda_Theta)\n X, X_inv = calc_X_and_X_inv(V_L)\n Y, Y_inv = calc_Y_and_Y_inv(V_R)\n\n old_Lambda = Lambda_Theta[0]\n old_Theta_nodes = Lambda_Theta[1]\n\n # Here we obtain the new singular value matrix for the bond between unit\n # cells. Note that the singular value spectrum is truncated.\n X_old_Lambda_Y = tn.ncon([X, old_Lambda, Y], [(-1, 1), (1, 2), (2, -2)])\n U, S, V_dagger = sbc._svd.split_node_full(node=X_old_Lambda_Y,\n left_edges=(X_old_Lambda_Y[0],),\n right_edges=(X_old_Lambda_Y[1],),\n compress_params=compress_params)\n\n new_Lambda = S / tn.norm(S)\n\n L = len(old_Theta_nodes)\n\n # Here we construct the Z_L and Z_R that are used to transform the Theta\n # node, which is a part of the canonicalization procedure.\n if L == 1:\n # Here we are essentially following Fig. 2.ii of [3]. Note that our\n # V_dagger is their V; our Y_inv is their X_inv; and our X_inv is their\n # Y_T_inv.\n Z_L = tn.ncon([V_dagger, Y_inv], [(-1, 1), (1, -2)])\n Z_R = tn.ncon([X_inv, U], [(-1, 1), (1, -2)])\n else:\n # Here we are essentially following the paragraph containing Eq. (355)\n # of [1] with a few minor changes.\n new_Lambda_inv_tensor = \\\n np.diag(1 / np.diag(np.array(new_Lambda.tensor)))\n new_Lambda_inv = tn.Node(new_Lambda_inv_tensor)\n \n conj_U = tn.conj(U)\n V_T = tn.conj(V_dagger)\n\n nodes_to_contract = [new_Lambda_inv, conj_U, X, old_Lambda]\n network_struct = [(-1, 3), (1, 3), (1, 2), (2, -2)]\n Z_L = tn.ncon(nodes_to_contract, network_struct)\n\n nodes_to_contract = [old_Lambda, Y, V_T, new_Lambda_inv]\n network_struct = [(-1, 1), (1, 2), (3, 2), (3, -2)]\n Z_R = tn.ncon(nodes_to_contract, network_struct)\n\n new_Theta_nodes = old_Theta_nodes\n\n nodes_to_contract = [Z_L, new_Theta_nodes[0]]\n network_struct = [(-1, 1), (1, -2, -3)]\n new_Theta_nodes[0] = tn.ncon(nodes_to_contract, network_struct)\n\n nodes_to_contract = [new_Theta_nodes[-1], Z_R]\n network_struct = [(-1, -2, 1), (1, -3)]\n new_Theta_nodes[-1] = tn.ncon(nodes_to_contract, network_struct)\n\n compress_and_normalize_Theta(new_Lambda, new_Theta_nodes, compress_params)\n\n Lambda_Theta[0] = new_Lambda\n Lambda_Theta[1] = new_Theta_nodes\n\n return None\n\n\n\ndef compress_and_normalize_Theta(Lambda, Theta_nodes, compress_params):\n # [3]: Phys. Rev. B 78, 155117 (2008)\n\n # See comments in function spinbosonchain._svd.Lambda_Theta_form for a\n # description of the Lambda_Theta object.\n\n # Essentially following [3], here we compress and normalize the Theta node\n # of the Lambda-Theta pair. We apply a direct SVD compression procedure.\n \n kwargs = {\"nodes\": Theta_nodes, \"normalize\": False}\n sbc._qr.left_to_right_sweep(**kwargs)\n kwargs[\"compress_params\"] = compress_params\n kwargs[\"normalize\"] = True\n sbc._svd.right_to_left_sweep(**kwargs)\n\n # Normalize the Theta node such that the MPS it represents has a state\n # 'norm' equal to unity.\n M = tn.ncon([Lambda, Theta_nodes[0]], [(-1, 1), (1, -2, -3)])\n Theta_nodes[0] /= tn.norm(M)\n\n return None\n\n\n\ndef calc_V_L(Lambda_Theta):\n # [1]: Annals of Physics 326 (2011) 96-192.\n\n # V_L is the same as that defined in Sec. 10.5 of [1] except that we have\n # generalized to a L-site unit cell where L>0.\n \n kwargs = {\"Lambda_Theta\": Lambda_Theta,\n \"unit_cell_type\": \"left\",\n \"krylov_dim\": 10,\n \"epsilon_D\": 1.0e-14}\n\n mu_L, V_L = sbc._arnoldi.dominant_eigpair_of_transfer_matrix(**kwargs)\n\n return V_L\n\n\n\ndef calc_V_R(Lambda_Theta):\n # [1]: Annals of Physics 326 (2011) 96-192.\n\n # V_R is the same as that defined in Sec. 10.5 of [1] except that we have\n # generalized to a L-site unit cell where L>0.\n \n kwargs = {\"Lambda_Theta\": Lambda_Theta,\n \"unit_cell_type\": \"right\",\n \"krylov_dim\": 10,\n \"epsilon_D\": 1.0e-14}\n\n mu_R, V_R = sbc._arnoldi.dominant_eigpair_of_transfer_matrix(**kwargs)\n\n return V_R\n\n\n\ndef calc_X_and_X_inv(V_L):\n # [1]: Annals of Physics 326 (2011) 96-192.\n\n # V_L, X, and X_inv are the same as those defined in Sec. 10.5 of [1] except\n # that we have generalized to a L-site unit cell where L>0.\n \n if V_L.backend.name != \"numpy\":\n sbc._backend.tf_to_np(V_L)\n\n try:\n D, W = scipy.linalg.eigh(V_L.tensor, driver='ev')\n except TypeError as err: # Occurs with some versions scipy.\n D, W = scipy.linalg.eigh(V_L.tensor)\n D = np.abs(D)\n tol = 1.0e-14\n D[D0.\n \n if V_R.backend.name != \"numpy\":\n sbc._backend.tf_to_np(V_R)\n\n try:\n D, W = scipy.linalg.eigh(V_R.tensor, driver='ev')\n except TypeError as err: # Occurs with some versions scipy.\n D, W = scipy.linalg.eigh(V_R.tensor)\n D = np.abs(D)\n tol = 1.0e-14\n D[D 5)\n\n params = Table.read(\n os.path.join(pyoof_out, f'fitpar_n{order}.csv'),\n format='ascii'\n )\n I_coeff = params['parfit'][:5]\n\n qt.add_row([\n pyoof_info['name'], pyoof_info['tel_name'],\n pyoof_info['obs_object'], pyoof_info['obs_date'],\n pyoof_info['meanel'], I_coeff[0], I_coeff[1], I_coeff[2],\n phase_rms, phase_e_rs\n ] + pyoof_info['snr'])\n\n # updating units\n qt['phase-rms'] *= apu.rad\n qt['meanel'] *= apu.deg\n qt['obs-date'] = Time(qt['obs-date'], format='isot', scale='utc')\n qt['c_dB'] *= apu.dB\n\n qt.meta = {'order': order}\n\n return qt\n", "meta": {"hexsha": "83fd95d4ab3f0c6febdc3a47f7017d4cbd1dd54e", "size": 13673, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyoof/aux_functions.py", "max_stars_repo_name": "tcassanelli/pyoof", "max_stars_repo_head_hexsha": "94d1e324837ededf2b1886ed1ebdfcebd2fa7474", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2017-06-23T11:19:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-21T03:31:37.000Z", "max_issues_repo_path": "pyoof/aux_functions.py", "max_issues_repo_name": "tcassanelli/pyoof", "max_issues_repo_head_hexsha": "94d1e324837ededf2b1886ed1ebdfcebd2fa7474", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyoof/aux_functions.py", "max_forks_repo_name": "tcassanelli/pyoof", "max_forks_repo_head_hexsha": "94d1e324837ededf2b1886ed1ebdfcebd2fa7474", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-05-02T06:18:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-13T16:04:59.000Z", "avg_line_length": 35.058974359, "max_line_length": 79, "alphanum_fraction": 0.6187376582, "include": true, "reason": "import numpy,from astropy", "num_tokens": 3791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.1466270508932976}} {"text": "\"\"\"CAPRI module.\"\"\"\nimport os\nimport shlex\nimport shutil\nimport subprocess\nimport tempfile\nfrom functools import partial\nfrom math import sqrt\nfrom pathlib import Path\n\nimport numpy as np\nfrom Bio import Align\nfrom Bio.Align import substitution_matrices\nfrom Bio.Seq import Seq\nfrom fccpy import read_pdb\nfrom fccpy.contacts import get_intermolecular_contacts\nfrom pdbtools import pdb_segxchain\n\nfrom haddock import log\nfrom haddock.libs.libontology import PDBFile\nfrom haddock.libs.libpdb import split_by_chain\n\n\nRES_TO_BE_IGNORED = [\"SHA\"]\n\nPROT_RES = [\n \"ALA\",\n \"ARG\",\n \"ASN\",\n \"ASP\",\n \"CYS\",\n \"GLN\",\n \"GLU\",\n \"GLY\",\n \"HIS\",\n \"ILE\",\n \"LEU\",\n \"LYS\",\n \"MET\",\n \"PHE\",\n \"PRO\",\n \"SER\",\n \"THR\",\n \"TRP\",\n \"TYR\",\n \"VAL\",\n ]\n\nDNA_RES = [\"DA\", \"DC\", \"DT\", \"DG\"]\n# Backbone\nPROT_ATOMS = [\"C\", \"N\", \"CA\", \"O\"]\n# Bases\nDNA_ATOMS = [\n \"C5\",\n \"N9\",\n \"N2\",\n \"C8\",\n \"O2\",\n \"N4\",\n \"N7\",\n \"C7\",\n \"N1\",\n \"N6\",\n \"C2\",\n \"O4\",\n \"C6\",\n \"N3\",\n \"C4\",\n \"O6\",\n ]\n\n\nclass CAPRI:\n \"\"\"CAPRI class.\"\"\"\n\n def __init__(\n self,\n reference,\n model_list,\n receptor_chain,\n ligand_chain,\n aln_method,\n path,\n **params,\n ):\n self.reference = reference\n self.model_list = model_list\n self.irmsd_dic = {}\n self.lrmsd_dic = {}\n self.ilrmsd_dic = {}\n self.fnat_dic = {}\n self.dockq_dic = {}\n self.atoms = get_atoms(model_list + [reference])\n self.r_chain = receptor_chain\n self.l_chain = ligand_chain\n self.path = path\n\n # TODO: For scoring we might need to get one alignment per model\n reference = str(reference)\n model = model_list[0].rel_path\n align_func = get_align(aln_method, **params)\n self.numbering_dic = align_func(reference, model, path)\n if not self.numbering_dic:\n raise CAPRIError(\"Could not align reference and model\")\n\n # Load the models in the class\n for struct in model_list:\n _ = self.add_chain_from_segid(struct.rel_path)\n\n def irmsd(self, cutoff=5.0):\n \"\"\"Calculate the I-RMSD.\"\"\"\n # Identify reference interface\n ref_interface_resdic = self.identify_interface(self.reference, cutoff)\n\n # Load interface coordinates\n ref_coord_dic, _ = self.load_coords(\n self.reference, ref_interface_resdic, match=False\n )\n\n for model in self.model_list:\n\n mod_coord_dic, _ = self.load_coords(\n model, ref_interface_resdic, match=True\n )\n\n # Here _coord_dic keys are matched\n # and formatted as (chain, resnum, atom)\n # we will use atoms that are present in both\n P = []\n Q = []\n for k in ref_coord_dic.keys() & mod_coord_dic.keys():\n ref_xyz = ref_coord_dic[k]\n mod_xyz = mod_coord_dic[k]\n\n Q.append(ref_xyz)\n P.append(mod_xyz)\n\n Q = np.asarray(Q)\n P = np.asarray(P)\n # write_coords(\"model.pdb\", P)\n # write_coords(\"ref.pdb\", Q)\n\n Q = Q - self.centroid(Q)\n P = P - self.centroid(P)\n U = self.kabsch(P, Q)\n P = np.dot(P, U)\n i_rmsd = self.calc_rmsd(P, Q)\n # write_coords(\"model_aln.pdb\", P)\n # write_coords(\"ref_aln.pdb\", Q)\n\n self.irmsd_dic[model] = i_rmsd\n\n return self.irmsd_dic\n\n def lrmsd(self):\n \"\"\"Calculate the L-RMSD.\"\"\"\n ref_coord_dic, _ = self.load_coords(self.reference)\n\n for model in self.model_list:\n\n mod_coord_dic, _ = self.load_coords(model, match=True)\n\n Q = []\n P = []\n # Note: this MUST be sorted since we will use the indexes to\n # separate between receptor and ligand coordinates\n instersection = sorted(ref_coord_dic.keys() & mod_coord_dic.keys())\n\n chain_ranges = {}\n for i, segment in enumerate(instersection):\n chain, _, _ = segment\n if chain not in chain_ranges:\n chain_ranges[chain] = []\n chain_ranges[chain].append(i)\n\n chain_ranges = make_range(chain_ranges)\n r_start, r_end = chain_ranges[self.r_chain]\n l_start, l_end = chain_ranges[self.l_chain]\n\n for k in instersection:\n ref_xyz = ref_coord_dic[k]\n mod_xyz = mod_coord_dic[k]\n\n Q.append(ref_xyz)\n P.append(mod_xyz)\n\n Q = np.asarray(Q)\n P = np.asarray(P)\n\n # write_coord_dic(\"ref.pdb\", ref_coord_dic)\n # write_coord_dic(\"model.pdb\", mod_coord_dic)\n\n # write_coords(\"ref.pdb\", Q)\n # write_coords(\"model.pdb\", P)\n\n # # move to the origin\n Q = Q - self.centroid(Q)\n P = P - self.centroid(P)\n\n # get receptor coordinates\n Q_r = Q[r_start: r_end - 1]\n P_r = P[r_start: r_end - 1]\n\n # Center receptors and get rotation matrix\n # Q_r = Q_r - self.centroid(Q_r)\n # P_r = P_r - self.centroid(P_r)\n\n U_r = self.kabsch(P_r, Q_r)\n\n # Center complexes at receptor centroids\n Q = Q - self.centroid(Q_r)\n P = P - self.centroid(P_r)\n\n # Apply rotation to complex\n # - complex are now aligned by the receptor\n P = np.dot(P, U_r)\n\n # write_coords(\"ref.pdb\", Q)\n # write_coords(\"model.pdb\", P)\n\n # Identify the ligand coordinates\n Q_l = Q[l_start: l_end - 1]\n P_l = P[l_start: l_end - 1]\n\n # write_coords(\"ref_l.pdb\", Q_l)\n # write_coords(\"model_l.pdb\", P_l)\n\n # Calculate the RMSD of the ligands\n l_rmsd = self.calc_rmsd(P_l, Q_l)\n\n # write_coords(\"ref.pdb\", Q)\n # write_coords(\"model.pdb\", P)\n\n self.lrmsd_dic[model] = l_rmsd\n\n return self.lrmsd_dic\n\n def ilrmsd(self, cutoff=10.0):\n \"\"\"Calculate the Interface Ligand RMSD.\"\"\"\n # Identify interface\n ref_interface_resdic = self.identify_interface(self.reference, cutoff)\n\n # Load interface coordinates\n ref_coord_dic, _ = self.load_coords(self.reference, match=False)\n\n ref_int_coord_dic, _ = self.load_coords(\n self.reference, ref_interface_resdic, match=False\n )\n\n for model in self.model_list:\n\n mod_coord_dic, _ = self.load_coords(model, match=True)\n\n mod_int_coord_dic, _ = self.load_coords(\n model, ref_interface_resdic, match=True\n )\n\n # write_coord_dic(\"ref.pdb\", ref_int_coord_dic)\n # write_coord_dic(\"model.pdb\", mod_int_coord_dic)\n\n # find atoms present in both interfaces\n Q_int = []\n P_int = []\n common_keys = ref_int_coord_dic.keys() & mod_int_coord_dic.keys()\n for k in sorted(common_keys):\n ref_xyz = ref_int_coord_dic[k]\n mod_xyz = mod_int_coord_dic[k]\n\n Q_int.append(ref_xyz)\n P_int.append(mod_xyz)\n\n Q_int = np.asarray(Q_int)\n P_int = np.asarray(P_int)\n\n # write_coords(\"ref.pdb\", Q_int)\n # write_coords(\"model.pdb\", P_int)\n\n # find atoms present in both molecules\n Q = []\n P = []\n intersection = sorted(ref_coord_dic.keys() & mod_coord_dic.keys())\n chain_ranges = {}\n for i, segment in enumerate(intersection):\n chain, _, _ = segment\n if chain not in chain_ranges:\n chain_ranges[chain] = []\n chain_ranges[chain].append(i)\n\n chain_ranges = make_range(chain_ranges)\n l_start, l_end = chain_ranges[self.l_chain]\n\n for k in sorted(ref_coord_dic.keys() & mod_coord_dic.keys()):\n ref_xyz = ref_coord_dic[k]\n mod_xyz = mod_coord_dic[k]\n\n Q.append(ref_xyz)\n P.append(mod_xyz)\n\n Q = np.asarray(Q)\n P = np.asarray(P)\n\n # write_coords(\"ref.pdb\", Q)\n # write_coords(\"model.pdb\", P)\n\n # put system at origin\n Q_int = Q_int - self.centroid(Q_int)\n P_int = P_int - self.centroid(P_int)\n\n # # put interfaces at the origin\n # Q_int = Q_int - self.centroid(Q_int)\n # P_int = P_int - self.centroid(P_int)\n\n # find the rotation that minimizes the interface rmsd\n U_int = self.kabsch(P_int, Q_int)\n P_int = np.dot(P_int, U_int)\n\n # write_coords(\"ref.pdb\", Q_int)\n # write_coords(\"model.pdb\", P_int)\n\n # # move the system to the centroid of the interfaces\n Q = Q - self.centroid(Q)\n P = P - self.centroid(P)\n\n # write_coords(\"ref_1.pdb\", Q)\n # write_coords(\"model_1.pdb\", P)\n\n Q = Q - self.centroid(Q_int)\n P = P - self.centroid(P_int)\n\n # write_coords(\"ref_2.pdb\", Q)\n # write_coords(\"model_2.pdb\", P)\n\n # apply this rotation to the model\n # - complexes are now aligned by the interfaces\n P = np.dot(P, U_int)\n\n # write_coords(\"ref_i.pdb\", Q)\n # write_coords(\"model_i.pdb\", P)\n\n # Calculate the rmsd of the ligand\n Q_l = Q[l_start: l_end - 1]\n P_l = P[l_start: l_end - 1]\n\n # write_coords(\"ref_l.pdb\", Q_l)\n # write_coords(\"model_l.pdb\", P_l)\n\n # this will be the interface-ligand-rmsd\n i_l_rmsd = self.calc_rmsd(P_l, Q_l)\n self.ilrmsd_dic[model] = i_l_rmsd\n\n return self.ilrmsd_dic\n\n def fnat(self, cutoff=5.0):\n \"\"\"Calculate the frequency of native contacts.\"\"\"\n ref_contacts = self.load_contacts(self.reference, cutoff)\n for model in self.model_list:\n model_contacts = self.load_contacts(model, cutoff)\n intersection = ref_contacts & model_contacts\n fnat = len(intersection) / float(len(ref_contacts))\n self.fnat_dic[model] = fnat\n return self.fnat_dic\n\n def dockq(self):\n \"\"\"Calculate the DockQ metric.\"\"\"\n for model in self.model_list:\n irmsd = self.irmsd_dic[model]\n fnat = self.fnat_dic[model]\n lrmsd = self.lrmsd_dic[model]\n dockq = (\n float(fnat)\n + 1 / (1 + (irmsd / 1.5) * (irmsd / 1.5))\n + 1 / (1 + (lrmsd / 8.5) * (lrmsd / 8.5))\n ) / 3\n self.dockq_dic[model] = dockq\n\n return self.dockq_dic\n\n def output(\n self,\n clt_threshold,\n sortby_key,\n sort_ascending,\n ):\n \"\"\"Output the CAPRI results to a .tsv file.\"\"\"\n self._output_ss(sortby_key, sort_ascending)\n self._output_clt(clt_threshold, sortby_key, sort_ascending,)\n\n def _output_ss(self, sortby_key, sort_ascending):\n output_l = []\n for model in self.model_list:\n data = {}\n # keep always \"model\" the first key\n data[\"model\"] = model\n # create the empty rank here so that it will appear\n # as the second column\n data[\"caprieval_rank\"] = None\n data[\"score\"] = model.score\n if model in self.irmsd_dic:\n data[\"irmsd\"] = self.irmsd_dic[model]\n if model in self.fnat_dic:\n data[\"fnat\"] = self.fnat_dic[model]\n if model in self.lrmsd_dic:\n data[\"lrmsd\"] = self.lrmsd_dic[model]\n if model in self.ilrmsd_dic:\n data[\"ilrmsd\"] = self.ilrmsd_dic[model]\n if model in self.dockq_dic:\n data[\"dockq\"] = self.dockq_dic[model]\n # add cluster data\n data[\"cluster-id\"] = model.clt_id\n data[\"cluster-ranking\"] = model.clt_rank\n data[\"model-cluster-ranking\"] = model.clt_model_rank\n # list of dictionaries\n output_l.append(data)\n\n output_fname = Path(self.path, \"capri_ss.tsv\")\n self._dump_file(\n output_l,\n output_fname,\n sortby_key,\n sort_ascending,\n )\n\n def _output_clt(\n self,\n clt_threshold,\n sortby_key,\n sort_ascending,\n ):\n \"\"\"Output cluster-based results.\"\"\"\n has_cluster_info = any(m.clt_id for m in self.model_list)\n if not has_cluster_info:\n return\n\n # get the cluster data\n clt_data = dict(((m.clt_rank, m.clt_id), []) for m in self.model_list)\n\n # add models to each cluster\n for model in self.model_list:\n clt_data[(model.clt_rank, model.clt_id)].append(model)\n\n output_l = []\n for element in clt_data:\n data = {}\n number_of_models_in_cluster = len(clt_data[element])\n # TODO: Refactor these ugly try/excepts\n try:\n score_array = [v.score\n for v in clt_data[element][: clt_threshold]]\n score_mean, score_stdev = self._calc_stats(\n score_array, clt_threshold)\n except KeyError:\n score_mean = float(\"nan\")\n score_stdev = float(\"nan\")\n\n try:\n irmsd_array = [\n self.irmsd_dic[v]\n for v in clt_data[element]\n [: clt_threshold]]\n irmsd_mean, irmsd_stdev = self._calc_stats(\n irmsd_array, clt_threshold)\n except KeyError:\n irmsd_mean = float(\"nan\")\n irmsd_stdev = float(\"nan\")\n\n try:\n fnat_array = [self.fnat_dic[v]\n for v in clt_data[element][:clt_threshold]]\n fnat_mean, fnat_stdev = self._calc_stats(\n fnat_array, clt_threshold)\n except KeyError:\n fnat_mean = float(\"nan\")\n fnat_stdev = float(\"nan\")\n\n try:\n lrmsd_array = [self.lrmsd_dic[v]\n for v in clt_data[element]\n [: clt_threshold]]\n lrmsd_mean, lrmsd_stdev = self._calc_stats(\n lrmsd_array, clt_threshold)\n except KeyError:\n lrmsd_mean = float(\"nan\")\n lrmsd_stdev = float(\"nan\")\n try:\n dockq_array = [self.dockq_dic[v]\n for v in clt_data[element]\n [: clt_threshold]]\n dockq_mean, dockq_stdev = self._calc_stats(\n dockq_array, clt_threshold)\n except KeyError:\n dockq_mean = float(\"nan\")\n dockq_stdev = float(\"nan\")\n\n data[\"cluster_rank\"] = element[0]\n data[\"cluster_id\"] = element[1]\n data[\"n\"] = number_of_models_in_cluster\n if number_of_models_in_cluster < clt_threshold:\n # under-evaluated, the mean was divided by a value\n # larger than the total number of models in the cluster\n data[\"under_eval\"] = \"yes\"\n else:\n data[\"under_eval\"] = \"-\"\n\n data[\"score\"] = score_mean\n data[\"score_std\"] = score_stdev\n data[\"irmsd\"] = irmsd_mean\n data[\"irmsd_std\"] = irmsd_stdev\n data[\"fnat\"] = fnat_mean\n data[\"fnat_std\"] = fnat_stdev\n data[\"lrmsd\"] = lrmsd_mean\n data[\"lrmsd_std\"] = lrmsd_stdev\n data[\"dockqn\"] = dockq_mean\n data[\"dockq_std\"] = dockq_stdev\n\n output_l.append(data)\n\n output_fname = Path(self.path, \"capri_clt.tsv\")\n info_header = \"#\" * 40 + os.linesep\n info_header += \"# `caprieval` cluster-based analysis\" + os.linesep\n info_header += \"#\" + os.linesep\n info_header += f\"# > sortby_key={sortby_key}\" + os.linesep\n info_header += f\"# > sort_ascending={sort_ascending}\" + os.linesep\n info_header += f\"# > clt_threshold={clt_threshold}\" + os.linesep\n info_header += \"#\" + os.linesep\n info_header += (\n \"# NOTE: if under_eval=yes, it means that there were less models in\"\n \" a cluster than\" + os.linesep\n )\n info_header += (\n \"# clt_threshold, thus these values were under evaluated.\"\n + os.linesep\n )\n info_header += (\n \"# You might need to tweak the value of clt_threshold or change\"\n \" some parameters\" + os.linesep\n )\n info_header += (\n \"# in `clustfcc` depending on your analysis.\" + os.linesep\n )\n info_header += \"#\" + os.linesep\n info_header += \"#\" * 40\n\n self._dump_file(\n output_l,\n output_fname,\n sortby_key,\n sort_ascending,\n info_header=info_header,\n )\n\n def _dump_file(\n self,\n container,\n output_fname,\n sortby_key,\n sort_ascending,\n info_header=\"\",\n ):\n\n # rank\n ranked_output_l = self._rank(\n container, key='score', ascending=True\n )\n\n # sort\n sorted_keys = self._sort(\n ranked_output_l, key=sortby_key, ascending=sort_ascending\n )\n\n header = \"\\t\".join(ranked_output_l[0].keys())\n\n if info_header:\n header = info_header + os.linesep + header\n\n with open(output_fname, \"w\") as out_fh:\n out_fh.write(header + os.linesep)\n for idx, _ in sorted_keys:\n row_l = []\n for value in ranked_output_l[idx].values():\n if isinstance(value, Path):\n row_l.append(str(value))\n elif isinstance(value, PDBFile):\n row_l.append(str(value.rel_path))\n elif isinstance(value, int):\n row_l.append(f\"{value}\")\n elif isinstance(value, str):\n row_l.append(f\"{value}\")\n elif value is None:\n row_l.append(\"-\")\n else:\n row_l.append(f\"{value:.3f}\")\n out_fh.write(\"\\t\".join(row_l) + os.linesep)\n\n @staticmethod\n def _sort(container, key, ascending):\n # Sort the column\n key_values = [(i, k[key]) for i, k in enumerate(container)]\n key_values.sort(key=lambda x: x[1], reverse=not ascending)\n return key_values\n\n @staticmethod\n def _rank(container, key, ascending):\n rankkey_values = [(i, k[key]) for i, k in enumerate(container)]\n rankkey_values.sort(key=lambda x: x[1], reverse=not ascending)\n for i, k in enumerate(rankkey_values, start=1):\n idx, _ = k\n container[idx][\"caprieval_rank\"] = i\n return container\n\n @staticmethod\n def _calc_stats(data, n):\n \"\"\"Calculate the mean and stdev.\"\"\"\n mean = sum(data) / n\n var = sum((x - mean) ** 2 for x in data) / n\n stdev = sqrt(var)\n return mean, stdev\n\n @staticmethod\n def identify_interface(pdb_f, cutoff=5.0):\n \"\"\"Identify the interface.\"\"\"\n if isinstance(pdb_f, PDBFile):\n pdb_f = pdb_f.rel_path\n pdb = read_pdb(pdb_f)\n\n interface_resdic = {}\n for atom_i, atom_j in get_intermolecular_contacts(pdb, cutoff):\n\n if atom_i.chain not in interface_resdic:\n interface_resdic[atom_i.chain] = []\n if atom_j.chain not in interface_resdic:\n interface_resdic[atom_j.chain] = []\n\n if atom_i.resid not in interface_resdic[atom_i.chain]:\n interface_resdic[atom_i.chain].append(atom_i.resid)\n if atom_j.resid not in interface_resdic[atom_j.chain]:\n interface_resdic[atom_j.chain].append(atom_j.resid)\n\n return interface_resdic\n\n @staticmethod\n def load_contacts(pdb_f, cutoff=5.0):\n \"\"\"Load residue-based contacts.\"\"\"\n con_list = []\n if isinstance(pdb_f, PDBFile):\n pdb_f = pdb_f.rel_path\n structure = read_pdb(pdb_f)\n for atom_i, atom_j in get_intermolecular_contacts(structure, cutoff):\n con = (atom_i.chain, atom_i.resid, atom_j.chain, atom_j.resid)\n con_list.append(con)\n return set(con_list)\n\n @staticmethod\n def calc_rmsd(V, W):\n \"\"\"Calculate the RMSD from two vectors.\"\"\"\n diff = np.array(V) - np.array(W)\n N = len(V)\n return np.sqrt((diff * diff).sum() / N)\n\n @staticmethod\n def kabsch(P, Q):\n \"\"\"Find the rotation matrix using Kabsch algorithm.\"\"\"\n # Covariance matrix\n P = np.array(P)\n Q = np.array(Q)\n C = np.dot(np.transpose(P), Q)\n # use SVD\n V, S, W = np.linalg.svd(C)\n d = (np.linalg.det(V) * np.linalg.det(W)) < 0.0\n if d:\n S[-1] = -S[-1]\n V[:, -1] = -V[:, -1]\n # Create Rotation matrix U\n U = np.dot(V, W)\n return U\n\n @staticmethod\n def centroid(X):\n \"\"\"Get the centroid.\"\"\"\n X = np.array(X)\n return X.mean(axis=0)\n\n @staticmethod\n def add_chain_from_segid(pdb_path):\n \"\"\"Replace the chainID with the segID.\"\"\"\n temp_f = tempfile.NamedTemporaryFile(delete=False, mode=\"w+t\")\n with open(pdb_path) as fh:\n for line in list(pdb_segxchain.run(fh)):\n temp_f.writelines(line)\n temp_f.close()\n # REPLACE!\n new_pdb_path = shutil.move(temp_f.name, pdb_path)\n return new_pdb_path\n\n def load_coords(self, pdb_f, filter_resdic=None, match=False):\n \"\"\"Load coordinates from PDB.\"\"\"\n coord_dic = {}\n chain_dic = {}\n idx = 0\n if isinstance(pdb_f, PDBFile):\n pdb_f = pdb_f.rel_path\n with open(pdb_f, \"r\") as fh:\n for line in fh.readlines():\n if line.startswith(\"ATOM\"):\n\n atom_name = line[12:16].strip()\n resname = line[17:20].strip()\n chain = line[21]\n resnum = int(line[22:26])\n\n x = float(line[30:38])\n y = float(line[38:46])\n z = float(line[46:54])\n coords = np.asarray([x, y, z])\n\n if match:\n try:\n resnum = self.numbering_dic[chain][resnum]\n except KeyError:\n # this residue is not matched, and so it should\n # not be considered\n # self.log(\n # f\"WARNING: {chain}.{resnum}.{atom_name}\"\n # \" was not matched!\"\n # )\n continue\n\n # identifier = f\"{chain}.{resnum}.{atom_name}\"\n identifier = (chain, resnum, atom_name)\n\n if atom_name not in self.atoms[resname]:\n continue\n\n if chain not in chain_dic:\n chain_dic[chain] = []\n\n if filter_resdic:\n # Only retrieve coordinates from the filter_resdic\n if (\n chain in filter_resdic\n and resnum in filter_resdic[chain]\n ):\n coord_dic[identifier] = coords\n chain_dic[chain].append(idx)\n idx += 1\n\n else:\n # retrieve everything\n coord_dic[identifier] = coords\n chain_dic[chain].append(idx)\n idx += 1\n\n chain_ranges = {}\n for chain in chain_dic:\n min_idx = min(chain_dic[chain])\n max_idx = max(chain_dic[chain])\n chain_ranges[chain] = (min_idx, max_idx)\n\n return coord_dic, chain_ranges\n\n\nclass CAPRIError(Exception):\n \"\"\"Raised when something goes wrong with the CAPRI class.\"\"\"\n\n def __init__(self, msg=\"\"):\n self.msg = msg\n super().__init__(self.msg)\n\n\ndef get_atoms(pdb_list):\n \"\"\"Identify what is the molecule type of each PDB.\"\"\"\n atom_dic = {}\n atom_dic.update(dict((r, PROT_ATOMS) for r in PROT_RES))\n atom_dic.update(dict((r, DNA_ATOMS) for r in DNA_RES))\n for pdb in pdb_list:\n if isinstance(pdb, PDBFile):\n pdb = pdb.rel_path\n with open(pdb) as fh:\n for line in fh.readlines():\n if line.startswith((\"ATOM\", \"HETATM\")):\n resname = line[17:20].strip()\n atom_name = line[12:16].strip()\n element = line[76:78].strip()\n if (\n resname not in PROT_RES\n and resname not in DNA_RES\n and resname not in RES_TO_BE_IGNORED\n ):\n # its neither DNA nor protein, use the heavy atoms\n # WARNING: Atoms that belong to unknown residues must\n # be bound to a residue name;\n # For example: residue NEP, also contains\n # CB and CG atoms, if we do not bind it to the\n # residue name, the next functions will include\n # CG and CG atoms in the calculations for all\n # other residue names\n if element != \"H\":\n if resname not in atom_dic:\n atom_dic[resname] = []\n if atom_name not in atom_dic[resname]:\n atom_dic[resname].append(atom_name)\n return atom_dic\n\n\ndef pdb2fastadic(pdb_f):\n \"\"\"Write the sequence as a fasta.\"\"\"\n res_codes = dict(\n [\n (\"CYS\", \"C\"),\n (\"ASP\", \"D\"),\n (\"SER\", \"S\"),\n (\"GLN\", \"Q\"),\n (\"LYS\", \"K\"),\n (\"ILE\", \"I\"),\n (\"PRO\", \"P\"),\n (\"THR\", \"T\"),\n (\"PHE\", \"F\"),\n (\"ASN\", \"N\"),\n (\"GLY\", \"G\"),\n (\"HIS\", \"H\"),\n (\"LEU\", \"L\"),\n (\"ARG\", \"R\"),\n (\"TRP\", \"W\"),\n (\"ALA\", \"A\"),\n (\"VAL\", \"V\"),\n (\"GLU\", \"E\"),\n (\"TYR\", \"Y\"),\n (\"MET\", \"M\"),\n (\"DA\", \"A\"),\n (\"DG\", \"G\"),\n (\"DC\", \"C\"),\n (\"DT\", \"T\"),\n ]\n )\n seq_dic = {}\n with open(pdb_f) as fh:\n for line in fh.readlines():\n if line.startswith(\"ATOM\"):\n res_num = int(line[22:26])\n res_name = line[17:20].strip()\n chain = line[21]\n if res_name in RES_TO_BE_IGNORED:\n continue\n try:\n one_letter = res_codes[res_name]\n except KeyError:\n one_letter = \"X\"\n if chain not in seq_dic:\n seq_dic[chain] = {}\n seq_dic[chain][res_num] = one_letter\n return seq_dic\n\n\ndef get_align(method, **kwargs):\n \"\"\"Get the alignment function.\"\"\"\n log.info(f\"Using {method} alignment\")\n if method == \"structure\":\n return partial(align_strct, lovoalign_exec=kwargs[\"lovoalign_exec\"])\n elif method == \"sequence\":\n return partial(align_seq)\n else:\n available_alns = (\"sequence\", \"structure\")\n raise ValueError(\n f\"Alignment method {method!r} not recognized. \"\n f\"Available options are {', '.join(available_alns)}\"\n )\n\n\ndef align_strct(reference, model, output_path, lovoalign_exec=None):\n \"\"\"Structuraly align and get numbering relationship.\"\"\"\n if lovoalign_exec is None:\n log.error(\n \"Structural alignment needs LovoAlign \"\n \"get it at github.com/m3g/lovoalign\"\n )\n raise CAPRIError(\"Path to LovoAlign executable required.\")\n\n if not lovoalign_exec:\n raise CAPRIError(\"lovoalign_exec parameter not defined \")\n\n if not os.access(lovoalign_exec, os.X_OK):\n raise CAPRIError(f\"{lovoalign_exec!r} for LovoAlign is not executable\")\n\n numbering_dic = {}\n protein_a_dic = dict(\n (str(e.stem).split(\"_\")[-1], e) for e in split_by_chain(reference)\n )\n protein_b_dic = dict(\n (str(e.stem).split(\"_\")[-1], e) for e in split_by_chain(model)\n )\n\n # check if chain ids match\n if protein_a_dic.keys() != protein_b_dic.keys():\n # TODO: Make this a clearer raise\n return numbering_dic\n\n for chain in protein_a_dic.keys():\n pa_seqdic = pdb2fastadic(protein_a_dic[chain])\n pb_seqdic = pdb2fastadic(protein_b_dic[chain])\n # logging.debug(f\"Structurally aligning chain {chain}\")\n numbering_dic[chain] = {}\n cmd = (\n f\"{lovoalign_exec} -p1 {protein_a_dic[chain]} \"\n f\"-p2 {protein_b_dic[chain]} \"\n f\"-c1 {chain} -c2 {chain}\"\n )\n\n # logging.debug(f\"Command is: {cmd}\")\n p = subprocess.run(shlex.split(cmd), capture_output=True, text=True)\n lovoalign_out = p.stdout.split(os.linesep)\n\n # we don\"t need the splitted proteins anymore\n protein_a_dic[chain].unlink()\n protein_b_dic[chain].unlink()\n\n # find out where the alignment starts and ends\n alignment_pass = True\n for i, line in enumerate(lovoalign_out):\n if \"SEQUENCE ALIGNMENT\" in line:\n # there are 2 extra white lines after this header\n alignment_start_index = i + 2\n elif \"FINAL\" in line:\n # there are 2 extra white lines after this header\n alignment_end_index = i - 2\n elif \"ERROR\" in line:\n failed_pdb = line.split()[-1]\n _msg = (\n f\"LovoAlign could not read {failed_pdb} \" \"is it a ligand?\"\n )\n log.warning(_msg)\n alignment_pass = False\n\n for elem in [k for k in pa_seqdic[chain]]:\n numbering_dic[chain][elem] = elem\n\n if not alignment_pass:\n # This alignment failed, move on to the next\n log.warning(\n f\"Skipping alignment of chain {chain}, \"\n \"used sequential matching\"\n )\n continue\n\n aln_l = lovoalign_out[alignment_start_index:alignment_end_index]\n\n # dump this alignment to a file\n aln_fname = Path(output_path, f\"lovoalign_{chain}.aln\")\n log.debug(f\"Writing alignment to {aln_fname.name}\")\n with open(aln_fname, \"w\") as fh:\n fh.write(os.linesep.join(aln_l))\n\n # remove the line between the alignment segments\n alignment = [aln_l[i: i + 3][:2] for i in range(0, len(aln_l), 3)]\n # 100% (5 identical nucleotides / min(length(A),length(B))).\n len_seq_a = len(pa_seqdic[chain])\n len_seq_b = len(pb_seqdic[chain])\n identity = (\n (len_seq_a - sum([e[0].count(\"-\") for e in alignment]))\n / min(len_seq_a, len_seq_b)\n * 100\n )\n\n if identity <= 40.0:\n log.warning(\n f\"\\\"Structural\\\" identity of chain {chain} is {identity:.2f}%,\"\n \" please check the results carefully\"\n )\n else:\n log.info(\n f\"\\\"Structural\\\" identity of chain {chain} is {identity:.2f}%\"\n )\n\n # logging.debug(\"Reading alignment and matching numbering\")\n for element in alignment:\n line_a, line_b = element\n\n resnum_a, seq_a, _ = line_a.split()\n resnum_b, seq_b, _ = line_b.split()\n\n resnum_a = int(resnum_a) - 1\n resnum_b = int(resnum_b) - 1\n\n for resname_a, resname_b in zip(seq_a, seq_b):\n if resname_a != \"-\":\n resnum_a += 1\n\n if resname_b != \"-\":\n resnum_b += 1\n\n if resname_a != \"-\" and resname_b != \"-\":\n numbering_dic[chain][resnum_b] = resnum_a\n\n izone_fname = Path(output_path, \"lovoalign.izone\")\n log.debug(f\"Saving .izone to {izone_fname.name}\")\n dump_as_izone(izone_fname, numbering_dic)\n\n return numbering_dic\n\n\ndef align_seq(reference, model, output_path):\n \"\"\"Sequence align and get the numbering relationship.\"\"\"\n seqdic_a = pdb2fastadic(reference)\n seqdic_b = pdb2fastadic(model)\n\n if seqdic_a.keys() != seqdic_b.keys():\n # TODO: Implement chain-matching here\n return False\n\n align_dic = {}\n for a, b in zip(seqdic_a, seqdic_b):\n\n align_dic[a] = {}\n\n seq_a = Seq(\"\".join(seqdic_a[a].values()))\n seq_b = Seq(\"\".join(seqdic_b[b].values()))\n\n aligner = Align.PairwiseAligner()\n aligner.substitution_matrix = substitution_matrices.load(\"BLOSUM62\")\n alns = aligner.align(seq_a, seq_b)\n top_aln = alns[0]\n\n aln_fname = Path(output_path, f\"blosum62_{a}.aln\")\n log.debug(f\"Writing alignment to {aln_fname.name}\")\n with open(aln_fname, \"w\") as fh:\n fh.write(str(top_aln))\n aligned_seg_a, aligned_seg_b = top_aln.aligned\n\n # this should always be true\n assert len(aligned_seg_a) == len(aligned_seg_b)\n\n identity = (\n str(top_aln).count(\"|\") / float(min(len(seq_a), len(seq_b)))\n ) * 100\n\n if not any(e for e in top_aln.aligned):\n # No alignment!\n log.warning(\n f\"No alignment for chain {a} is it protein/dna? \"\n \"Matching sequentially\"\n )\n if all(\"X\" in s for s in seq_a) and all(\"X\" in s for s in seq_b):\n # this sequence contains only ligands, do it manually\n if len(seq_a) != len(seq_b):\n # we cannot handle this\n raise f\"Cannot align chain {b}\"\n for res_a, res_b in zip(seqdic_a[a], seqdic_b[b]):\n align_dic[a].update({res_a: res_b})\n else:\n if identity <= 40.0:\n # Identity is very low\n log.warning(\n f\"Sequence identity of chain {a} is {identity:.2f}%,\"\n \" please check the results carefully\"\n )\n log.warning(\n \"Please use alignment_method = \\\"structure\\\" instead\")\n else:\n log.info(f\"Sequence identity of chain {a} is {identity:.2f}%\")\n for seg_a, seg_b in zip(aligned_seg_a, aligned_seg_b):\n start_a, end_a = seg_a\n start_b, end_b = seg_b\n\n reslist_a = list(seqdic_a[a].keys())[start_a:end_a]\n reslist_b = list(seqdic_b[b].keys())[start_b:end_b]\n\n align_dic[a].update(\n dict((i, j) for i, j in zip(reslist_a, reslist_b))\n )\n izone_fname = Path(output_path, \"blosum62.izone\")\n log.debug(f\"Saving .izone to {izone_fname.name}\")\n dump_as_izone(izone_fname, align_dic)\n\n return align_dic\n\n\ndef make_range(chain_range_dic):\n \"\"\"Expand a chain dictionary into ranges.\"\"\"\n chain_ranges = {}\n for chain in chain_range_dic:\n min_idx = min(chain_range_dic[chain])\n max_idx = max(chain_range_dic[chain])\n chain_ranges[chain] = (min_idx, max_idx)\n return chain_ranges\n\n\ndef dump_as_izone(fname, numbering_dic):\n \"\"\"Dump the numbering dictionary as .izone.\"\"\"\n # FIXME: Collapse the izones so its faster to load in profit\n with open(fname, \"w\") as fh:\n for chain in numbering_dic:\n for bound_res in numbering_dic[chain]:\n unbound_res = numbering_dic[chain][bound_res]\n #\n izone_str = (\n \"ZONE \"\n f\"{chain}{bound_res}:{chain}{unbound_res}\"\n f\"{os.linesep}\"\n )\n fh.write(izone_str)\n\n\n# # debug only\n# def write_coord_dic(output_name, coord_dic):\n# \"\"\"Add a dummy atom to a PDB file according to a list of coordinates.\"\"\"\n# with open(output_name, \"w\") as fh:\n# for i, k in enumerate(coord_dic):\n# atom_num = f\"{i+1}\".rjust(4, \" \")\n# chain, resnum, atom = k\n# resnum = int(resnum)\n# resnum = f\"{resnum}\".rjust(3, \" \")\n# atom_name = f\"{atom}\".rjust(3, \" \")\n# x, y, z = coord_dic[k]\n# dum_x = f\"{x:.3f}\".rjust(7, \" \")\n# dum_y = f\"{y:.3f}\".rjust(7, \" \")\n# dum_z = f\"{z:.3f}\".rjust(7, \" \")\n# dummy_line = (\n# f\"ATOM {atom_num} {atom_name} DUM {chain} {resnum} \"\n# f\" {dum_x} {dum_y} {dum_z} 1.00 1.00 \"\n# \" H \" + os.linesep\n# )\n# fh.write(dummy_line)\n\n\n# # debug only\n# def write_coords(output_name, coor_list):\n# \"\"\"Add a dummy atom to a PDB file according to a list of coordinates.\"\"\"\n# with open(output_name, \"w\") as fh:\n# for i, dummy_coord in enumerate(coor_list):\n# atom_num = f\"{i}\".rjust(4, \" \")\n# resnum = f\"{i}\".rjust(3, \" \")\n# dum_x = f\"{dummy_coord[0]:.3f}\".rjust(7, \" \")\n# dum_y = f\"{dummy_coord[1]:.3f}\".rjust(7, \" \")\n# dum_z = f\"{dummy_coord[2]:.3f}\".rjust(7, \" \")\n# dummy_line = (\n# f\"ATOM {atom_num} H DUM X {resnum} \"\n# f\" {dum_x} {dum_y} {dum_z} 1.00 1.00 \"\n# \" H \" + os.linesep\n# )\n# fh.write(dummy_line)\n\n\n# # debug only\n# def write_pymol_viz(resdic):\n# \"\"\"Write PyMol vizualitation.\"\"\"\n# for k in resdic:\n# reslist = \"+\".join(map(str, resdic[k]))\n# cmd = f\"sele {k}, chain {k} and resid {reslist}\"\n# print(cmd)\n", "meta": {"hexsha": "40c0cf7f5a20eeaa247abe97eada3c1491633324", "size": 38754, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/haddock/modules/analysis/caprieval/capri.py", "max_stars_repo_name": "sverhoeven/haddock3", "max_stars_repo_head_hexsha": "d863106f21ebc128f18c6d73a0d15b97824d050c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/haddock/modules/analysis/caprieval/capri.py", "max_issues_repo_name": "sverhoeven/haddock3", "max_issues_repo_head_hexsha": "d863106f21ebc128f18c6d73a0d15b97824d050c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/haddock/modules/analysis/caprieval/capri.py", "max_forks_repo_name": "sverhoeven/haddock3", "max_forks_repo_head_hexsha": "d863106f21ebc128f18c6d73a0d15b97824d050c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7578397213, "max_line_length": 80, "alphanum_fraction": 0.5144501213, "include": true, "reason": "import numpy", "num_tokens": 9198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.26588047309981694, "lm_q1q2_score": 0.14639574684075352}} {"text": "import os\nimport numpy as np\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\nrc('font', **{'family': 'serif'})\nfrom matplotlib import rcParams\nrcParams['xtick.direction'] = 'out'\nrcParams['ytick.direction'] = 'out'\nrcParams['xtick.labelsize'] = 18\nrcParams['ytick.labelsize'] = 18\nrcParams['lines.linewidth'] = 1.85\nrcParams['axes.labelsize'] = 20\nrcParams.update({'figure.autolayout': True})\nnp.set_printoptions(threshold=10000)\nimport pickle\n\n\nclass Grouping(object):\n def __init__(self, G, geoOption, contig, name, bounds, minCutoff, ratioCutoff, groupCutoff, sig_t, E=None):\n self.name = name\n self.G = G\n self.geoOption = geoOption\n self.contig = contig\n self.minCutoff = minCutoff\n self.ratioCutoff = ratioCutoff\n self.groupCutoff = groupCutoff\n self.structure = bounds\n self.mask = np.array([i for c in range(max(bounds) + 1) for i, g in enumerate(bounds) if g == c])\n self.counts = dict(zip(*np.unique(bounds, return_counts=True)))\n self.maxOrder = np.max(list(self.counts.values()))\n self.fname = '{}_{}_{}g_m{}_r{}_g{}'.format(name, geoOption, G, round(minCutoff, 2), round(ratioCutoff, 2), groupCutoff)\n self.sig_t = sig_t\n self.E = E\n\n def __str__(self):\n s = 'Name: {}'.format(self.name)\n s += '\\nGeometry: {}'.format(self.geoOption)\n s += '\\nMaxOrder: {}'.format(self.maxOrder)\n #s += '\\nStructure: {}'.format(' '.join(self.structure.astype(str)))\n struct = np.concatenate(([0], np.cumsum([self.counts[i] for i in range(max(self.structure) + 1)])))\n s += '\\nStructure:'\n for i in range(len(struct) - 1):\n s += '\\n\\tGroup {}: '.format(i)\n s += '{}-{}'.format(struct[i] + 1, struct[i+1]) if struct[i] + 1 != struct[i+1] else '{}'.format(struct[i] + 1)\n #s += '\\nMask: {}'.format(' '.join(self.mask.astype(str)))\n s += '\\nCounts: {}'.format(', '.join(['CG-{}={}'.format(key, item) for key, item in self.counts.items()]))\n s += '\\nFileName: {}'.format(self.fname)\n\n return s\n\n def writeFile(self):\n # Get the coarse group bounds given the total cross sections\n s = '{}\\n{}'.format(self.name, self.structure.tolist())\n\n with open('XS/structure_{}'.format(self.fname), 'w') as f:\n f.write(s)\n\ndef getMats(geoOption):\n if geoOption == 'inf':\n return [0]\n elif geoOption == 'full':\n return [0, 3, 9]\n elif geoOption == 'core1':\n return [0, 1, 2, 9]\n elif geoOption == 'core2':\n return [0, 1, 3, 9]\n elif 'c5g7' in geoOption:\n return [0, 3, 9]\n if 'uo2' in geoOption:\n return [5, 9]\n elif 'mox' in geoOption:\n if 'low' in geoOption:\n return [6, 9]\n elif 'mid' in geoOption:\n return [7, 9]\n elif 'high' in geoOption:\n return [8, 9]\n else:\n return [6, 7, 8, 9]\n else:\n return [5, 6, 7, 8, 9]\n else:\n raise NotImplementedError('{} has not been implented'.format(geoOption))\n\n\ndef getXS(fname):\n '''\n Read the input file and extract the total cross sections\n\n input\n fname: name of the file to read\n\n output\n sig_t: numpy array containing the total cross sections for each material\n '''\n\n # Initialize the total cross section list\n sig_t = []\n with open(fname) as f:\n # Get the number of materials and number of groups\n nMat, nGroups = [int(d) for d in f.readline().split()[:2]]\n # Skip 2 lines to pass the energy bounds and velocity\n E = np.array(f.readline().split()).astype(float)[::-1]\n f.readline()\n\n # Loop over the materials\n for m in range(nMat):\n # Initialize temp list for total XS for material m\n t = []\n # Skip the material name\n f.readline()\n # Get the number of legendre moments\n nLegendre = int(f.readline().split()[0])\n # Loop over groups and extract the total XS\n for g in range(nGroups):\n t.append(float(f.readline().split()[0]))\n # Skip the scattering moments\n for g in range(nGroups * nLegendre):\n f.readline()\n # Append the temp XS list to the main list\n sig_t.append(t)\n\n return np.array(sig_t), E\n\n\ndef findContiguousBounds(sig_t, minCutoff, ratioCutoff, groupCutoff):\n '''\n Find the coarse group structure given a set of cross sections\n\n Inputs:\n sig_t: array of the total XS indexed by material [mat, G]\n minCutoff: XS below which the ratio cutoff is ignored\n ratioCutoff: Ratio of largest to smallest XS in a coarse group\n groupCutoff: Maximum number of fine groups in a coarse group\n Outputs:\n bounds: Starting fine group indices for each coarse group\n '''\n\n def reset(xs):\n '''Reset the min and max cutoffs to the input cross section'''\n minXS = np.maximum(xs, minCutoff)\n maxXS = xs\n return minXS, maxXS\n\n sig_t = np.array(sig_t)\n\n # Get the number of groups\n nGroup = len(sig_t[0])\n\n # Initialize the boundary at the lowest energy group\n bounds = [nGroup + 1]\n\n # Initialize the cutoff bounds\n minXS, maxXS = reset(sig_t[:,-1])\n\n # Loop through the cross sections from greatest to least\n for i, xs in enumerate(sig_t.T[::-1]):\n group = nGroup - i\n\n # Check if the xs is below the min or above the max\n minXS = np.minimum(xs, minXS)\n maxXS = np.maximum(xs, maxXS)\n ratio = maxXS - minXS\n\n # Check for a ratio that is too large\n if (max(ratio) > ratioCutoff and max(maxXS) > minCutoff) or bounds[-1] - group > groupCutoff:\n bounds.append(group + 1)\n # Reset the cutoff bounds\n minXS, maxXS = reset(xs)\n\n # Add the highest energy group bound\n bounds.append(1)\n # Reverse to the natural order of structures\n bounds = np.array(bounds[::-1])\n\n return np.array([i for i, b in enumerate(bounds[1:] - bounds[:-1]) for j in range(b)])\n\ndef findNoncontiguousBounds(sig_t, minCutoff=1.0, ratioCutoff=2.0, groupCutoff=60):\n '''\n Find the coarse group structure given a set of cross sections\n\n Inputs:\n sig_t: array of the total XS indexed by material [mat, G]\n minCutoff: XS below which the ratio cutoff is ignored\n ratioCutoff: Ratio of largest to smallest XS in a coarse group\n groupCutoff: Maximum number of fine groups in a coarse group\n Outputs:\n structure: mapping of fine group to coarse group\n '''\n\n G = len(sig_t[0])\n\n # Get the minimum and maximum of all materials\n minXS = np.min(sig_t, axis=0)\n minmap = np.argsort(minXS)[::-1]\n maxXS = np.max(sig_t, axis=0)\n maxmap = np.argsort(maxXS)[::-1]\n\n unsorted_groups = list(range(G))\n\n # Initialize a dictionary\n structure = np.zeros(G) - 1\n coarse_group_index = 0\n while len(unsorted_groups) > 0:\n # Get the largest unsorted cross section\n maximum = maxXS[maxmap[0]]\n # If above the minimum cross section cutoff\n if maximum > minCutoff:\n # Find the ratio for the current group\n #cutoff = max(ratioCutoff, maximum / minXS[maxmap[0]])\n cutoff = ratioCutoff\n # Select all groups with a smaller ratio than the cutoff\n cutmap = minmap[maximum - minXS[minmap] <= cutoff]\n if len(cutmap) == 0:\n cutmap = [maxmap[0]]\n else:\n # Select all remaining groups\n cutmap = minmap\n # Only allow groupCutoff groups into the current group\n cutmap = cutmap[:groupCutoff]\n # Assign selected groups to the coarse_group_index\n structure[cutmap] = coarse_group_index\n # Remove the assigned groups from minmap, maxmap, and unsorted_groups\n minmap = np.array([g for g in minmap if g not in cutmap])\n maxmap = np.array([g for g in maxmap if g not in cutmap])\n unsorted_groups = [g for g in unsorted_groups if g not in cutmap]\n # Increment the coarse_group_index\n coarse_group_index += 1\n\n return (structure * -1 + max(structure)).astype(int)\n\ndef computeBounds(G, geoOption, contig, minCutoff, ratioCutoff, groupCutoff):\n '''\n This function determines which fine groups should belong to each coarse group\n\n The boundaries will not necessarily be contiguous\n\n Inputs:\n fname: name of the cross section file in anlxs format\n '''\n\n # Contig options\n names = {0: 'contiguous_min',\n 1: 'contiguous_max',\n 2: 'contiguous_mean',\n 3: 'continuous_difference',\n 4: 'noncontiguous_min',\n 5: 'noncontiguous_max',\n 6: 'noncontiguous_mean',\n 7: 'noncontiguous_difference'}\n\n # Select the material types for the geoOption\n mats = getMats(geoOption)\n\n # Load the total cross section for group G\n sig_t, E = getXS('XS/{}gXS.anlxs'.format(G))\n\n # Slice out only the cross sections used for the current geo\n mask = np.array([r in mats for r in range(len(sig_t))]).astype(bool)\n sig_t = sig_t[mask]\n\n # Number the energy groups\n groups = np.arange(G)\n\n # Get the minimum XS across all materials\n minXS = np.min(sig_t, axis=0)\n # Get the maximum XS across all materials\n maxXS = np.max(sig_t, axis=0)\n # Get the mean XS across all materials\n meanXS = np.mean(sig_t, axis=0)\n\n # Select which XS upon which to compute the bounds\n if contig == 0: # contiguous min\n mask = findContiguousBounds([minXS], minCutoff, ratioCutoff, groupCutoff)\n elif contig == 1: # contiguous max\n mask = findContiguousBounds([maxXS], minCutoff, ratioCutoff, groupCutoff)\n elif contig == 2: # contiguous mean\n mask = findContiguousBounds([meanXS], minCutoff, ratioCutoff, groupCutoff)\n elif contig == 3: # continuous difference\n mask = findContiguousBounds(sig_t, minCutoff, ratioCutoff, groupCutoff)\n elif contig == 4: # non-contiguous min\n mask = findNoncontiguousBounds([minXS], minCutoff, ratioCutoff, groupCutoff)\n elif contig == 5: # non-contiguous max\n mask = findNoncontiguousBounds([maxXS], minCutoff, ratioCutoff, groupCutoff)\n elif contig == 6: # non-contiguous mean\n mask = findNoncontiguousBounds([meanXS], minCutoff, ratioCutoff, groupCutoff)\n elif contig == 7: # non-contiguous difference\n mask = findNoncontiguousBounds(sig_t, minCutoff, ratioCutoff, groupCutoff)\n\n structure = Grouping(G, geoOption, contig, names[contig], mask, minCutoff, ratioCutoff, groupCutoff, sig_t, E)\n\n makePlot(structure, minXS, maxXS)\n\n return structure\n\n\ndef makePlot(structure, minXS, maxXS):\n # Plot the cross sections\n colors = ['b', 'g', 'r', 'c', 'm', 'orange', 'purple', 'grey']\n ls = '-' if structure.contig < 4 else '--'\n\n groups = np.arange(structure.G)\n mask = structure.structure\n\n for i, m in enumerate(mask):\n submask = mask == m\n plt.fill_between(groups[submask] + 1, minXS[submask], maxXS[submask], label='Group {}'.format(m), linestyle=ls, color=colors[m%len(colors)])\n #plt.semilogy(groups[i], minXS[i], label='Group {}'.format(m), ls=ls, marker='o', c=colors[m%len(colors)])\n #plt.semilogy(groups[i], maxXS[i], label='Group {}'.format(m), ls=ls, marker='s', c=colors[m%len(colors)])\n plt.yscale('log')\n plt.xlabel('Fine group number')\n plt.ylabel('Total cross section [cm$^{-1}$]')\n plt.xlim([0, structure.G+1])\n plt.grid(True)\n #plt.title(structure.name + ' {}'.format(len(structure.counts.keys())))\n plt.savefig('XS/structure_plot_{}.png'.format(structure.fname), transparent=True)\n plt.clf()\n\n E = structure.E[::-1]\n E = 0.5 * (E[1:] + E[:-1])\n\n for i, m in enumerate(mask):\n submask = mask == m\n plt.fill_between(E[submask], minXS[submask], maxXS[submask], label='Group {}'.format(m), linestyle=ls, color=colors[m%len(colors)])\n #plt.semilogy(groups[i], minXS[i], label='Group {}'.format(m), ls=ls, marker='o', c=colors[m%len(colors)])\n #plt.semilogy(groups[i], maxXS[i], label='Group {}'.format(m), ls=ls, marker='s', c=colors[m%len(colors)])\n plt.yscale('log')\n plt.xscale('log')\n plt.xlabel('Energy [MeV]')\n plt.ylabel('Total cross section [cm$^{-1}$]')\n plt.grid(True)\n #plt.title(structure.name + ' {}'.format(len(structure.counts.keys())))\n plt.savefig('XS/structure_plot_{}_E.png'.format(structure.fname), transparent=True)\n plt.clf()\n\ndef getInfo(task, kill=False):\n Gs = [44, 238, 1968]\n geos = ['inf', 'full', 'core1', 'core2', 'c5g7-small']\n contigs = [1]\n mins = [0]\n ratios = [1.3]\n groups = [60]\n\n item = 0\n groupBounds = []\n\n for geo in geos:\n for G in Gs:\n for contig in contigs:\n for min_cutoff in mins:\n for ratio_cutoff in ratios:\n for group_cutoff in groups:\n if item == task and not kill:\n return G, geo, contig, min_cutoff, ratio_cutoff, group_cutoff\n else:\n item += 1\n groupBounds.append(item)\n if kill:\n groupBounds = [0] + groupBounds\n for i, G in enumerate(Gs):\n print('Group {:4d} cutoffs: {:>5d}-{:<5d}'.format(G, groupBounds[i] + 1, groupBounds[i+1]))\n exit()\n\ndef f(s):\n '''Convert a structure into a proper string'''\n try:\n return '{}'.format(s[0] + 1) if s[1] - 1 == s[0] else '{}-{}'.format(s[0] + 1, s[1])\n except IndexError:\n return ''\n\n\nif __name__ == '__main__':\n # getInfo(1, True)\n\n #task = os.environ['SLURM_ARRAY_TASK_ID']\n #task = int(task) - 1\n\n\n for geo in ['full', 'core1', 'core2']:\n print(geo)\n s = '& 44-group & \\multicolumn{2}{c|}{238-group} & \\multicolumn{4}{c}{1968-group}\\\\\\\\\\n'\n s += '\\hline\\n'\n s += 'add\\'l. \\# & (+0) & (+0) & (+20) & (+0) & (+20) & (+40) & (+60)\\\\\\\\\\n'\n s += '\\hline\\n'\n\n # Build the coarse-group structure\n s44 = computeBounds(44, geo, 1, 0.0, 1.3, 60)\n c44 = np.concatenate(([0], np.cumsum([s44.counts[i] for i in range(max(s44.structure)+1)])))\n s238 = computeBounds(238, geo, 1, 0.0, 1.3, 60)\n c238 = np.concatenate(([0], np.cumsum([s238.counts[i] for i in range(max(s238.structure)+1)])))\n s1968 = computeBounds(1968, geo, 1, 0.0, 1.3, 60)\n c1968 = np.concatenate(([0], np.cumsum([s1968.counts[i] for i in range(max(s1968.structure)+1)])))\n\n for i in range(20):\n s += 'CG {:2d} & {:5s} & {:7s} & {:7s} & {:9s} & {:9s} & {:9s} & {:9s} \\\\\\\\\\n'.format(i+1, f(c44[i:i+2]), f(c238[i:i+2]), f(c238[i+20:i+22]), f(c1968[i+0:i+2]), f(c1968[i+20:i+22]), f(c1968[i+40:i+42]), f(c1968[i+60:i+62]))\n print(s)\n\n\n\n\n\n\n\n #pickle.dump(structure, open('XS/structure{}_{}_{}g_m{}_r{}_g{}.p'.format(contig, geo, G, min_cutoff, ratio_cutoff, group_cutoff), 'wb'))\n\n", "meta": {"hexsha": "f240f46c7b06418df85157805a1df64bb8435c19", "size": 15182, "ext": "py", "lang": "Python", "max_stars_repo_path": "SPH/coarseBounds.py", "max_stars_repo_name": "RLReed/unotran", "max_stars_repo_head_hexsha": "b317107e1a39490dda732f86a731872f5207a167", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SPH/coarseBounds.py", "max_issues_repo_name": "RLReed/unotran", "max_issues_repo_head_hexsha": "b317107e1a39490dda732f86a731872f5207a167", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SPH/coarseBounds.py", "max_forks_repo_name": "RLReed/unotran", "max_forks_repo_head_hexsha": "b317107e1a39490dda732f86a731872f5207a167", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-12-02T23:01:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T04:48:41.000Z", "avg_line_length": 37.2107843137, "max_line_length": 235, "alphanum_fraction": 0.5950467659, "include": true, "reason": "import numpy", "num_tokens": 4215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.256832002764217, "lm_q1q2_score": 0.1463563977431972}} {"text": "#!/usr/bin/env python -u \n'''\npDMET: Density Matrix Embedding theory for Periodic Systems\nCopyright (C) 2018 Hung Q. Pham. All Rights Reserved.\nA few functions in pDMET are modifed from QC-DMET Copyright (C) 2015 Sebastian Wouters\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nEmail: Hung Q. Pham \n'''\n\nimport numpy as np\nimport scipy.optimize as optimize\n\n\n'''DFT XC library'''\nGGA_X = {\n'GGA_X_GAM' : 32 , # H. S. Yu, W. Zhang, P. Verma, X. He, and D. G. Truhlar, Phys. Chem. Chem. Phys. 17, 12146 (2015)\n'GGA_X_HCTH_A' : 34 , # F. A. Hamprecht, A. J. Cohen, D. J. Tozer, and N. C. Handy, J. Chem. Phys. 109, 6264 (1998)\n'GGA_X_EV93' : 35 , # E. Engel and S. H. Vosko, Phys. Rev. B 47, 13164 (1993)\n'GGA_X_BCGP' : 38 , # K. Burke, A. Cancio, T. Gould, and S. Pittalis, ArXiv e-prints (2014), arXiv:1409.4834 [cond-mat.mtrl-sci]\n'GGA_X_LAMBDA_OC2_N' : 40 , # M. M. Odashima, K. Capelle, and S. B. Trickey, J. Chem. Theory Comput. 5, 798 (2009)\n'GGA_X_B86_R' : 41 , # I. Hamada, Phys. Rev. B 89, 121103 (2014)\n'GGA_X_LAMBDA_CH_N' : 44 , # M. M. Odashima, K. Capelle, and S. B. Trickey, J. Chem. Theory Comput. 5, 798 (2009)\n'GGA_X_LAMBDA_LO_N' : 45 , # M. M. Odashima, K. Capelle, and S. B. Trickey, J. Chem. Theory Comput. 5, 798 (2009)\n'GGA_X_HJS_B88_V2' : 46 , # E. Weintraub, T. M. Henderson, and G. E. Scuseria, J. Chem. Theory Comput. 5, 754 (2009)\n'GGA_X_Q2D' : 48 , # L. Chiodo, L. A. Constantin, E. Fabiano, and F. Della Sala, Phys. Rev. Lett. 108, 126402 (2012)\n'GGA_X_PBE_MOL' : 49 , # J. M. del Campo, J. L. G\\'azquez, S. B. Trickey, and A. Vela, J. Chem. Phys. 136, 104108 (2012)\n'GGA_X_AK13' : 56 , # R. Armiento and S. Kummel, Phys. Rev. Lett. 111, 036402 (2013)\n'GGA_X_LV_RPW86' : 58 , # K. Berland and P. Hyldgaard, Phys. Rev. B 89, 035412 (2014)\n'GGA_X_PBE_TCA' : 59 , # V. Tognetti, P. Cortona, and C. Adamo, Chem. Phys. Lett. 460, 536 (2008)\n'GGA_X_PBEINT' : 60 , # E. Fabiano, L. A. Constantin, and F. Della Sala, Phys. Rev. B 82, 113104 (2010)\n'GGA_X_VMT84_GE' : 68 , # A. Vela, J. C. Pacheco-Kato, J. L. G\\'azquez, J. M. del Campo, and S. B. Trickey, J. Chem. Phys. 136, 144115 (2012)\n'GGA_X_VMT84_PBE' : 69 , # A. Vela, J. C. Pacheco-Kato, J. L. G\\'azquez, J. M. del Campo, and S. B. Trickey, J. Chem. Phys. 136, 144115 (2012)\n'GGA_X_VMT_GE' : 70 , # A. Vela, V. Medel, and S. B. Trickey, J. Chem. Phys. 130, 244103 (2009)\n'GGA_X_VMT_PBE' : 71 , # A. Vela, V. Medel, and S. B. Trickey, J. Chem. Phys. 130, 244103 (2009)\n'GGA_X_N12' : 82 , # R. Peverati and D. G. Truhlar, J. Chem. Theory Comput. 8, 2310 (2012)\n'GGA_X_SSB_SW' : 90 , # M. Swart, M. Sol\\'a, and F. M. Bickelhaupt, J. Comput. Methods Sci. Eng. 9, 69 (2009)\n'GGA_X_SSB' : 91 , # M. Swart, M. Sol\\'a, and F. M. Bickelhaupt, J. Chem. Phys. 131, 094103 (2009)\n'GGA_X_SSB_D' : 92 , # M. Swart, M. Sol\\'a, and F. M. Bickelhaupt, J. Chem. Phys. 131, 094103 (2009)\n'GGA_X_BPCCAC' : 98 , # E. Br\\'emond, D. Pilard, I. Ciofini, H. Chermette, C. Adamo, and P. Cortona, Theor. Chem. Acc. 131, 1184 (2012)\n'GGA_X_PBE' : 101, # J. P. Perdew, K. Burke, and M. Ernzerhof, Phys. Rev. Lett. 77, 3865 (1996)\n'GGA_X_PBE_R' : 102, # Y. Zhang and W. Yang, Phys. Rev. Lett. 80, 890 (1998)\n'GGA_X_B86' : 103, # A. D. Becke, J. Chem. Phys. 84, 4524 (1986)\n'GGA_X_HERMAN' : 104, # F. Herman, J. P. V. Dyke, and I. B. Ortenburger, Phys. Rev. Lett. 22, 807 (1969)\n'GGA_X_B86_MGC' : 105, # A. D. Becke, J. Chem. Phys. 84, 4524 (1986)\n'GGA_X_B88' : 106, # A. D. Becke, Phys. Rev. A 38, 3098 (1988)\n'GGA_X_G96' : 107, # P. M. W. Gill, Mol. Phys. 89, 433 (1996)\n'GGA_X_PW86' : 108, # J. P. Perdew and W. Yue, Phys. Rev. B 33, 8800 (1986)\n'GGA_X_PW91' : 109, # J. P. Perdew, in Proceedings of the 75. WE-Heraeus-Seminar and 21st Annual International Symposium on Electronic Structure of Solids, edited by P. Ziesche and H. Eschrig (Akademie Verlag, Berlin, 1991) p. 11\n'GGA_X_OPTX' : 110, # N. C. Handy and A. J. Cohen, Mol. Phys. 99, 403 (2001)\n'GGA_X_DK87_R1' : 111, # A. E. DePristo and J. D. Kress, J. Chem. Phys. 86, 1425 (1987)\n'GGA_X_DK87_R2' : 112, # A. E. DePristo and J. D. Kress, J. Chem. Phys. 86, 1425 (1987)\n'GGA_X_LG93' : 113, # D. J. Lacks and R. G. Gordon, Phys. Rev. A 47, 4681 (1993)\n'GGA_X_FT97_A' : 114, # M. Filatov and W. Thiel, Mol. Phys. 91, 847 (1997)\n'GGA_X_FT97_B' : 115, # M. Filatov and W. Thiel, Mol. Phys. 91, 847 (1997)\n'GGA_X_PBE_SOL' : 116, # J. P. Perdew, A. Ruzsinszky, G. I. Csonka, O. A. Vydrov, G. E. Scuseria, L. A. Constantin, X. Zhou, and K. Burke, Phys. Rev. Lett. 100, 136406 (2008)\n'GGA_X_RPBE' : 117, # B. Hammer, L. B. Hansen, and J. K. Norskov, Phys. Rev. B 59, 7413 (1999)\n'GGA_X_WC' : 118, # Z. Wu and R. E. Cohen, Phys. Rev. B 73, 235116 (2006)\n'GGA_X_MPW91' : 119, # C. Adamo and V. Barone, J. Chem. Phys. 108, 664 (1998)\n'GGA_X_AM05' : 120, # R. Armiento and A. E. Mattsson, Phys. Rev. B 72, 085108 (2005)\n'GGA_X_PBEA' : 121, # G. K. H. Madsen, Phys. Rev. B 75, 195108 (2007)\n'GGA_X_MPBE' : 122, # C. Adamo and V. Barone, J. Chem. Phys. 116, 5933 (2002)\n'GGA_X_XPBE' : 123, # X. Xu and W. A. Goddard, J. Chem. Phys. 121, 4068 (2004)\n'GGA_X_2D_B86_MGC' : 124, # S. Pittalis, E. Rasanen, J. G. Vilhena, and M. A. L. Marques, Phys. Rev. A 79, 012503 (2009)\n'GGA_X_BAYESIAN' : 125, # J. J. Mortensen, K. Kaasbjerg, S. L. Frederiksen, J. K. Norskov, J. P. Sethna, and K. W. Jacobsen, Phys. Rev. Lett. 95, 216401 (2005)\n'GGA_X_PBE_JSJR' : 126, # L. S. Pedroza, A. J. R. da Silva, and K. Capelle, Phys. Rev. B 79, 201106 (2009)\n'GGA_X_2D_B88' : 127, # J. G. Vilhena and M. A. L. Marques, unpublished (2014)\n'GGA_X_2D_B86' : 128, # J. G. Vilhena and M. A. L. Marques, unpublished (2014)\n'GGA_X_2D_PBE' : 129, # J. G. Vilhena and M. A. L. Marques, unpublished (2014)\n'GGA_X_OPTB88_VDW' : 139, # J. Klime\\v{s}, D. R. Bowler, and A. Michaelides, J. Phys.: Condens. Matter 22, 022201 (2010)\n'GGA_X_PBEK1_VDW' : 140, # J. Klime\\v{s}, D. R. Bowler, and A. Michaelides, J. Phys.: Condens. Matter 22, 022201 (2010)\n'GGA_X_OPTPBE_VDW' : 141, # J. Klime\\v{s}, D. R. Bowler, and A. Michaelides, J. Phys.: Condens. Matter 22, 022201 (2010)\n'GGA_X_RGE2' : 142, # A. Ruzsinszky, G. I. Csonka, and G. E. Scuseria, J. Chem. Theory Comput. 5, 763 (2009)\n'GGA_X_RPW86' : 144, # E. D. Murray, K. Lee, and D. C. Langreth, J. Chem. Theory Comput. 5, 2754 (2009)\n'GGA_X_KT1' : 145, # T. W. Keal and D. J. Tozer, J. Chem. Phys. 119, 3015 (2003)\n'GGA_X_MB88' : 149, # V. Tognetti and C. Adamo, J. Phys. Chem. A 113, 14415 (2009)\n'GGA_X_SOGGA' : 150, # Y. Zhao and D. G. Truhlar, J. Chem. Phys. 128, 184109 (2008)\n'GGA_X_SOGGA11' : 151, # R. Peverati, Y. Zhao, and D. G. Truhlar, J. Phys. Chem. Lett. 2, 1991 (2011)\n'GGA_X_C09X' : 158, # V. R. Cooper, Phys. Rev. B 81, 161104 (2010)\n'GGA_X_OL2' : 183, # P. Fuentealba and O. Reyes, Chem. Phys. Lett. 232, 31 (1995)\n'GGA_X_APBE' : 184, # L. A. Constantin, E. Fabiano, S. Laricchia, and F. Della Sala, Phys. Rev. Lett. 106, 186406 (2011)\n'GGA_X_HTBS' : 191, # P. Haas, F. Tran, P. Blaha, and K. Schwarz, Phys. Rev. B 83, 205117 (2011)\n'GGA_X_AIRY' : 192, # L. A. Constantin, A. Ruzsinszky, and J. P. Perdew, Phys. Rev. B 80, 035125 (2009)\n'GGA_X_LAG' : 193, # L. Vitos, B. Johansson, J. Koll\\'ar, and H. L. Skriver, Phys. Rev. B 62, 10046 (2000)\n'GGA_X_PBEFE' : 265, # R. Sarmiento-P\\'erez, S. Botti, and M. A. L. Marques, J. Chem. Theory Comput. 11, 3844 (2015)\n'GGA_X_CAP' : 270, # J. Carmona-Esp\\'indola, J. L. G\\'azquez, A. Vela, and S. B. Trickey, J. Chem. Phys. 142, 054105 (2015), 10.1063/1.4906606\n'GGA_X_EB88' : 271, # P. Elliott and K. Burke, Can. J. Chem. 87, 1485 (2009)\n'GGA_X_BEEFVDW' : 285, # J. Wellendorff, K. T. Lundgaard, A. M\\o{gelh\\o{j}, V. Petzold, D. D. Landis, J. K. N\\o{rskov}, T. Bligaard, and K. W. Jacobsen, }Phys. Rev. B 85, 235149 (2012)\n'GGA_X_PBETRANS' : 291, # Eric Bremond, I. Ciofini, and C. Adamo, Mol. Phys. 114, 1059 (2016)\n'GGA_X_CHACHIYO' : 298, # T. {Chachiyo and H. {Chachiyo}, }ArXiv e-prints (2017), arXiv:1706.01343 [cond-mat.mtrl-sci]\n'GGA_X_WPBEH' : 524, # J. Heyd, G. E. Scuseria, and M. Ernzerhof, J. Chem. Phys. 118, 8207 (2003)\n'GGA_X_HJS_PBE' : 525, # T. M. Henderson, B. G. Janesko, and G. E. Scuseria, J. Chem. Phys. 128, 194105 (2008)\n'GGA_X_HJS_PBE_SOL' : 526, # T. M. Henderson, B. G. Janesko, and G. E. Scuseria, J. Chem. Phys. 128, 194105 (2008)\n'GGA_X_HJS_B97X' : 528, # T. M. Henderson, B. G. Janesko, and G. E. Scuseria, J. Chem. Phys. 128, 194105 (2008)\n'GGA_X_ITYH' : 529, # H. Iikura, T. Tsuneda, T. Yanai, and K. Hirao, J. Chem. Phys. 115, 3540 (2001)\n'GGA_X_SFAT' : 530, # A. Savin and H.-J. Flad, Int. J. Quantum Chem. 56, 327 (1995)\n'GGA_X_SG4' : 533, # L. A. Constantin, A. Terentjevs, F. Della Sala, P. Cortona, and E. Fabiano, Phys. Rev. B 93, 045126 (2016)\n'GGA_X_GG99' : 535, # A. T. Gilbert and P. M. Gill, Chem. Phys. Lett. 312, 511 (1999)\n'GGA_X_PBEPOW' : 539, # Eric Bremond, J. Chem. Phys. 145, 244102 (2016)\n'GGA_X_KGG99' : 544, # A. T. Gilbert and P. M. Gill, Chem. Phys. Lett. 312, 511 (1999)\n'GGA_X_B88M' : 570, # E. Proynov, H. Chermette, and D. R. Salahub, J. Chem. Phys. 113, 10013 (2000)\n}\n\nGGA_C = {\n'GGA_C_GAM' : 33 , # H. S. Yu, W. Zhang, P. Verma, X. He, and D. G. Truhlar, Phys. Chem. Chem. Phys. 17, 12146 (2015)\n'GGA_C_BCGP' : 39 , # K. Burke, A. Cancio, T. Gould, and S. Pittalis, ArXiv e-prints (2014), arXiv:1409.4834 [cond-mat.mtrl-sci]\n'GGA_C_Q2D' : 47 , # L. Chiodo, L. A. Constantin, E. Fabiano, and F. Della Sala, Phys. Rev. Lett. 108, 126402 (2012)\n'GGA_C_ZPBEINT' : 61 , # L. A. Constantin, E. Fabiano, and F. Della Sala, Phys. Rev. B 84, 233103 (2011)\n'GGA_C_PBEINT' : 62 , # E. Fabiano, L. A. Constantin, and F. Della Sala, Phys. Rev. B 82, 113104 (2010)\n'GGA_C_ZPBESOL' : 63 , # L. A. Constantin, E. Fabiano, and F. Della Sala, Phys. Rev. B 84, 233103 (2011)\n'GGA_C_N12_SX' : 79 , # R. Peverati and D. G. Truhlar, Phys. Chem. Chem. Phys. 14, 16187 (2012)\n'GGA_C_N12' : 80 , # R. Peverati and D. G. Truhlar, J. Chem. Theory Comput. 8, 2310 (2012)\n'GGA_C_REGTPSS' : 83 , # J. P. Perdew, A. Ruzsinszky, G. I. Csonka, L. A. Constantin, and J. Sun, Phys. Rev. Lett. 103, 026403 (2009)\n'GGA_C_OP_XALPHA' : 84 , # T. Tsuneda, T. Suzumura, and K. Hirao, J. Chem. Phys. 110, 10664 (1999)\n'GGA_C_OP_G96' : 85 , # T. Tsuneda, T. Suzumura, and K. Hirao, J. Chem. Phys. 110, 10664 (1999)\n'GGA_C_OP_PBE' : 86 , # T. Tsuneda, T. Suzumura, and K. Hirao, J. Chem. Phys. 110, 10664 (1999)\n'GGA_C_OP_B88' : 87 , # T. Tsuneda, T. Suzumura, and K. Hirao, J. Chem. Phys. 110, 10664 (1999)\n'GGA_C_FT97' : 88 , # M. Filatov and W. Thiel, Int. J. Quantum Chem. 62, 603 (1997)\n'GGA_C_HCTH_A' : 97 , # F. A. Hamprecht, A. J. Cohen, D. J. Tozer, and N. C. Handy, J. Chem. Phys. 109, 6264 (1998)\n'GGA_C_REVTCA' : 99 , # V. Tognetti, P. Cortona, and C. Adamo, Chem. Phys. Lett. 460, 536 (2008)\n'GGA_C_TCA' : 100, # V. Tognetti, P. Cortona, and C. Adamo, J. Chem. Phys. 128, 034101 (2008)\n'GGA_C_PBE' : 130, # J. P. Perdew, K. Burke, and M. Ernzerhof, Phys. Rev. Lett. 77, 3865 (1996)\n'GGA_C_LYP' : 131, # C. Lee, W. Yang, and R. G. Parr, Phys. Rev. B 37, 785 (1988)\n'GGA_C_P86' : 132, # J. P. Perdew, Phys. Rev. B 33, 8822 (1986)\n'GGA_C_PBE_SOL' : 133, # J. P. Perdew, A. Ruzsinszky, G. I. Csonka, O. A. Vydrov, G. E. Scuseria, L. A. Constantin, X. Zhou, and K. Burke, Phys. Rev. Lett. 100, 136406 (2008)\n'GGA_C_PW91' : 134, # J. P. Perdew, in Proceedings of the 75. WE-Heraeus-Seminar and 21st Annual International Symposium on Electronic Structure of Solids, edited by P. Ziesche and H. Eschrig (Akademie Verlag, Berlin, 1991) p. 11\n'GGA_C_AM05' : 135, # R. Armiento and A. E. Mattsson, Phys. Rev. B 72, 085108 (2005)\n'GGA_C_XPBE' : 136, # X. Xu and W. A. Goddard, J. Chem. Phys. 121, 4068 (2004)\n'GGA_C_LM' : 137, # D. C. Langreth and M. J. Mehl, Phys. Rev. Lett. 47, 446 (1981)\n'GGA_C_PBE_JRGX' : 138, # L. S. Pedroza, A. J. R. da Silva, and K. Capelle, Phys. Rev. B 79, 201106 (2009)\n'GGA_C_RGE2' : 143, # A. Ruzsinszky, G. I. Csonka, and G. E. Scuseria, J. Chem. Theory Comput. 5, 763 (2009)\n'GGA_C_WL' : 147, # L. C. Wilson and M. Levy, Phys. Rev. B 41, 12930 (1990)\n'GGA_C_WI' : 148, # L. C. Wilson and S. Ivanov, Int. J. Quantum Chem. 69, 523 (1998)\n'GGA_C_SOGGA11' : 152, # R. Peverati, Y. Zhao, and D. G. Truhlar, J. Phys. Chem. Lett. 2, 1991 (2011)\n'GGA_C_WI0' : 153, # L. C. Wilson and S. Ivanov, Int. J. Quantum Chem. 69, 523 (1998)\n'GGA_C_SOGGA11_X' : 159, # R. Peverati and D. G. Truhlar, J. Chem. Phys. 135, 191102 (2011)\n'GGA_C_APBE' : 186, # L. A. Constantin, E. Fabiano, S. Laricchia, and F. Della Sala, Phys. Rev. Lett. 106, 186406 (2011)\n'GGA_C_OPTC' : 200, # A. J. Cohen and N. C. Handy, Mol. Phys. 99, 607 (2001)\n'GGA_C_PBELOC' : 246, # L. A. Constantin, E. Fabiano, and F. Della Sala, Phys. Rev. B 86, 035130 (2012)\n'GGA_C_PBEFE' : 258, # R. Sarmiento-P\\'erez, S. Botti, and M. A. L. Marques, J. Chem. Theory Comput. 11, 3844 (2015)\n'GGA_C_OP_PW91' : 262, # T. Tsuneda, T. Suzumura, and K. Hirao, J. Chem. Phys. 110, 10664 (1999)\n'GGA_C_PBE_MOL' : 272, # J. M. del Campo, J. L. G\\'azquez, S. B. Trickey, and A. Vela, J. Chem. Phys. 136, 104108 (2012)\n'GGA_C_BMK' : 280, # A. D. Boese and J. M. L. Martin, J. Chem. Phys. 121, 3405 (2004)\n'GGA_C_TAU_HCTH' : 281, # A. D. Boese and N. C. Handy, J. Chem. Phys. 116, 9559 (2002)\n'GGA_C_HYB_TAU_HCTH' : 283, # A. D. Boese and N. C. Handy, J. Chem. Phys. 116, 9559 (2002)\n'GGA_C_SG4' : 534, # L. A. Constantin, A. Terentjevs, F. Della Sala, P. Cortona, and E. Fabiano, Phys. Rev. B 93, 045126 (2016)\n'GGA_C_SCAN_E0' : 553, # J. Sun, A. Ruzsinszky, and J. P. Perdew, Phys. Rev. Lett. 115, 036402 (2015)\n'GGA_C_GAPC' : 555, # E. Fabiano, P. E. Trevisanutto, A. Terentjevs, and L. A. Constantin, J. Chem. Theory Comput. 10, 2016 (2014), pMID: 26580528\n'GGA_C_GAPLOC' : 556, # E. Fabiano, P. E. Trevisanutto, A. Terentjevs, and L. A. Constantin, J. Chem. Theory Comput. 10, 2016 (2014), pMID: 26580528\n'GGA_C_ZVPBEINT' : 557, # L. A. Constantin, E. Fabiano, and F. D. Sala, J. Chem. Phys. 137, 194105 (2012)\n'GGA_C_ZVPBESOL' : 558, # L. A. Constantin, E. Fabiano, and F. D. Sala, J. Chem. Phys. 137, 194105 (2012)\n'GGA_C_TM_LYP' : 559, # A. J. Thakkar and S. P. McCarthy, J. Chem. Phys. 131, 134109 (2009)\n'GGA_C_TM_PBE' : 560, # A. J. Thakkar and S. P. McCarthy, J. Chem. Phys. 131, 134109 (2009)\n'GGA_C_W94' : 561, # L. C. Wilson, Chemical Physics 181, 337 (1994)\n'GGA_C_CS1' : 565, # N. C. Handy a\n}\n\n\n'''Smaller set of XC to test'''\nGGA_X = {\n\n'GGA_X_PBE' : 101, # J. P. Perdew, K. Burke, and M. Ernzerhof, Phys. Rev. Lett. 77, 3865 (1996)\n'GGA_X_B88' : 106, # A. D. Becke, Phys. Rev. A 38, 3098 (1988)\n'GGA_X_PW91' : 109, # J. P. Perdew, in Proceedings of the 75. WE-Heraeus-Seminar and 21st Annual International Symposium on Electronic Structure of Solids, edited by P. Ziesche and H. Eschrig (Akademie Verlag, Berlin, 1991) p. 11\n'GGA_X_WC' : 118, # Z. Wu and R. E. Cohen, Phys. Rev. B 73, 235116 (2006)\n'GGA_X_AM05' : 120, # R. Armiento and A. E. Mattsson, Phys. Rev. B 72, 085108 (2005)\n}\n\nGGA_C = {\n'GGA_C_PBE' : 130, # J. P. Perdew, K. Burke, and M. Ernzerhof, Phys. Rev. Lett. 77, 3865 (1996)\n'GGA_C_LYP' : 131, # C. Lee, W. Yang, and R. G. Parr, Phys. Rev. B 37, 785 (1988)\n'GGA_C_P86' : 132, # J. P. Perdew, Phys. Rev. B 33, 8822 (1986)\n'GGA_C_AM05' : 135, # R. Armiento and A. E. Mattsson, Phys. Rev. B 72, 085108 (2005)\n'GGA_C_SCAN_E0' : 553, # J. Sun, A. Ruzsinszky, and J. P. Perdew, Phys. Rev. Lett. 115, 036402 (2015)\n}\n\n\ndef get_init_uvec(xc_type='PBE0', dft_HF=None):\n '''Initialize uvec corresponding to each type of the DF-like cost function'''\n if dft_HF is not None:\n HF_percent = dft_HF\n else:\n HF_percent = 1.0\n\n if xc_type == 'PBE0':\n uvec = [HF_percent] + [0.] * 2\n elif xc_type == 'RSH-PBE0':\n uvec = [1.] + [1.] + [0.] * 2 \n elif xc_type == 'B3LYP':\n uvec = [HF_percent] + [0.] * 4 \n elif xc_type == 'CAMB3LYP':\n uvec = [HF_percent , .0000001, 1. , 0., 0., 0., 0.] \n elif xc_type == 'manyGGA':\n uvec = [HF_percent] + [0.] * (len(GGA_X) + len(GGA_C)) \n\n return uvec\n\ndef get_bounds(xc_type='PBE0', constraint=1, dft_HF=None):\n '''Prodive the bounds to optimize the DF-like cost function'''\n \n if constraint == 1:\n if xc_type == 'PBE0':\n lower = [-1.0] + [.0] * 2\n upper = [ 1.0] + [1.0] * 2\n bounds = optimize.Bounds(lower, upper)\n elif xc_type == 'RSH-PBE0':\n lower = [ -1.] * 2 + [.0] * 2\n upper = [ 1.0] * 4\n bounds = optimize.Bounds(lower, upper)\n elif xc_type == 'B3LYP':\n lower = [-1.0] + [.0] * 4\n upper = [ 1.0] + [1.0] * 4\n bounds = optimize.Bounds(lower, upper)\n elif xc_type == 'CAMB3LYP':\n bounds = optimize.Bounds([0.0,.0000001,.0,.0,.0,.0,.0], [1.,1.0,1.,1.,1.,1.,1.])\n elif xc_type == 'manyGGA':\n lower = [-1.0] + [.0] * (len(GGA_X) + len(GGA_C))\n upper = [ 1.0] + [.1] * (len(GGA_X) + len(GGA_C))\n bounds = optimize.Bounds(lower, upper)\n elif constraint == 2:\n if xc_type == 'PBE0':\n lower = [-1.0] * 3\n upper = [ 1.0] * 3\n bounds = optimize.Bounds(lower, upper)\n elif xc_type == 'RSH-PBE0':\n lower = [-1] * 4\n upper = [ 1.0]* 4\n elif xc_type == 'B3LYP':\n lower = [-1.0] * 5\n upper = [ 1.0] * 5\n bounds = optimize.Bounds(lower, upper)\n elif xc_type == 'CAMB3LYP':\n bounds = optimize.Bounds([0.0,.0000001,.0,.0,.0,.0,.0], [1.,1.0,1.,1.,1.,1.,1.])\n elif xc_type == 'manyGGA':\n lower = [-1.0] + [-1.0] * (len(GGA_X) + len(GGA_C))\n upper = [ 1.0] + [ 1.0] * (len(GGA_X) + len(GGA_C))\n bounds = optimize.Bounds(lower, upper)\n elif constraint == 3:\n if xc_type == 'manyGGA':\n lower = [ 0.0] * (len(GGA_X) + len(GGA_C))\n upper = [ 1.0] * (len(GGA_X) + len(GGA_C))\n bounds = optimize.Bounds(lower, upper)\n return bounds\n \n \ndef get_OEH_kpts(local, umat, xc_type='PBE0', dft_HF=None):\n '''Construct the mf Hamiltonian'''\n \n if dft_HF is not None and xc_type is not 'RSH-PBE0':\n umat[0] = np.float64(dft_HF)\n \n if xc_type == 'PBE0':\n xc = \"{:.12f}*HF + {:.12f}*PBE, {:.12f}*PBE\".format(*umat)\n n, exc, vxc = local.kks._numint.nr_rks(local.cell, local.kks.grids, xc, local.dm_kpts, 0, local.kpts, None)\n veff = vxc + local.vj - umat[0] * 0.5 * local.vk\n OEH_kpts = local.h_core + veff\n if local._is_KROHF:\n OEH_kpts = 0.5 * (OEH_kpts[0] + OEH_kpts[1])\n OEH_kpts = local.ao_2_loc(OEH_kpts, local.ao2lo)\n \n elif xc_type == 'B3LYP':\n xc = \"{:.12f}*HF + {:.12f}*LDA + {:.12f}*B88, {:.12f}*LYP + {:.12f}*VWN\".format(*umat)\n n, exc, vxc = local.kks._numint.nr_rks(local.cell, local.kks.grids, xc, local.dm_kpts, 0, local.kpts, None)\n veff = vxc + local.vj - umat[0] * 0.5 * local.vk \n OEH_kpts = local.h_core + veff\n if local._is_KROHF:\n OEH_kpts = 0.5 * (OEH_kpts[0] + OEH_kpts[1])\n OEH_kpts = local.ao_2_loc(OEH_kpts, local.ao2lo) \n\n elif xc_type == 'RSH-PBE0':\n # TODO: right now the range-seperation parameter is fixed, it is super expensive to update it every cycle\n # because the vk long-range needed to be generated \n umat = [local.xc_omega] + np.asarray(umat).tolist()\n xc = \"{1:.12f}*SR_HF({0:.2f})+ {2:.12f}*LR_HF({0:.2f}) + {3:.12f}*PBE, {4:.12f}*PBE\".format(*umat)\n n, exc, vxc = local.kks._numint.nr_rks(local.cell, local.kks.grids, xc, local.dm_kpts, 0, local.kpts, None)\n veff = vxc + local.vj - 0.5 * (umat[1]*local.vksr + umat[2]*local.vklr)\n OEH_kpts = local.h_core + veff\n OEH_kpts = local.ao_2_loc(OEH_kpts, local.ao2lo)\n \n elif xc_type == 'CAMB3LYP':\n # TODO: need to debug\n xc = '{:.12f}*SR_HF({:.12f}) + {:.12f}*LR_HF({:.12f}) + {:.12f}*ITYH + {:.12f}*B88, {:.12f}*VWN5 + {:.12f}*LYP'.format(umat)\n n, exc, vxc = local.kks._numint.nr_rks(local.cell, local.kks.grids, xc, local.dm_kpts, 0, local.kpts, None)\n veff = vxc + local.vj - umat[0] * 0.5 * local.vk \n OEH_kpts = local.h_core + veff\n OEH_kpts = local.ao_2_loc(OEH_kpts, local.ao2lo) \n\n elif xc_type == 'manyGGA':\n x = '{:.12f}*HF + {:.12f}*' + '+ {:.12f}*'.join(GGA_X.keys())\n c = ', {:.12f}*' + '+ {:.12f}*'.join(GGA_C.keys())\n xc = (x + c).format(*umat)\n n, exc, vxc = local.kks._numint.nr_rks(local.cell, local.kks.grids, xc, local.dm_kpts, 0, local.kpts, None)\n veff = vxc + local.vj - umat[0] * 0.5 * local.vk \n OEH_kpts = local.h_core + veff\n OEH_kpts = local.ao_2_loc(OEH_kpts, local.ao2lo) \n \n return OEH_kpts\n \n \n \n ", "meta": {"hexsha": "45ccdfb8488b7657b58ad6dca29d85ac32e79f1f", "size": 23653, "ext": "py", "lang": "Python", "max_stars_repo_path": "pdmet/df_hamiltonian.py", "max_stars_repo_name": "hungpham2017/pdmet", "max_stars_repo_head_hexsha": "50848c9f22879f8154e86af783d8036f304bac54", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pdmet/df_hamiltonian.py", "max_issues_repo_name": "hungpham2017/pdmet", "max_issues_repo_head_hexsha": "50848c9f22879f8154e86af783d8036f304bac54", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pdmet/df_hamiltonian.py", "max_forks_repo_name": "hungpham2017/pdmet", "max_forks_repo_head_hexsha": "50848c9f22879f8154e86af783d8036f304bac54", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 75.8108974359, "max_line_length": 247, "alphanum_fraction": 0.550205048, "include": true, "reason": "import numpy,import scipy", "num_tokens": 9426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.24220562872535942, "lm_q1q2_score": 0.14627568949485498}} {"text": "# Matthew Smith, 12/5/19\n# Shuo Gu, 02/18/20\n# Shoichet Lab: Torsion Strain Rotation Project\n# This Python script will contain all of the functions for using the Torsion\n# Library method for estimating torsion strain energy. To use these functions,\n# source this script in either another Python script or a Python commandline\n# session as:\n# exec(open(\"TL_Functions.py\").read())\n# when in the same directory.\n\n# We will use TL_2.1_VERSION_6.xml as the Torsion Library.\n\n# Explanation of how this works from TL_Lookup_Test.py:\n# Since the Torsion Library contains very specific SMARTS patterns to define\n# the torsion patterns (also called torsion rules in the acutal library) and\n# there are only 514 torsion patterns in TL_2.1, it is best to just search\n# over all of the torsion rules in the library, instead of trying to find\n# and classify every substructure in the molecule. This was Ying's suggestion.\n# For each torsion rule, we will use the GetSubstructMatches function in\n# the package rdkit.Chem to find the indeces of the atoms that match the\n# torsion rule. If there are multiple such substructures, then this function\n# should return multiple sets of indeces. We will then find the information\n# we need (dihedral angle, method, estimate, lower bound, upper bound, and\n# flag). Since the same torsion pattern in the molecule can have multiple\n# torsion rules in the library applying to it, we need to choose the intended\n# torsion rule. The authors of the original Torsion Library ordered the\n# torsion rules within each subclass in decreasing specificity, so we will\n# keep track of the number of the torsion rule for each matching substructure.\n# We will then pick the set of information with the lowest counting index,\n# assuming that this is the most specific. Since the first hierarchy class in\n# the Torsion Library is the general class, we will need to loop over all of\n# the specific classes first. This process is not the most efficient, since\n# we are looking up and calculating information that we immediately throw away,\n# but we can optimize this procedure later.\n\n# Once we have one set of information for each set of indeces defining the\n# bonds, we need to condense these by torsion pattern. We must do this because,\n# for a given bond, each atom can be bonded to 2 or 3 other atoms in a torsion\n# pattern. This gives between 2*2=4 and 3*3=9 possible lists of 4 atom indeces\n# defining the torsion pattern, not including reversing the order of the\n# indeces! Therefore we need to find all of the information sets (angle,\n# estimate, etc.) with the same atom indeces defining the bond (listed\n# forwards and backwards) and decide which one we will keep. Since we are\n# using these energy estimates for identifying unstable conformations in\n# DOCK-ing campaigns, being conservstive with our hit-picking means being\n# liberal in our energy assignments. We thus keep the set of information with\n# the highest energy estimate, prioritizing the estimates from specific\n# hierarchy classes over ones from the general hierarchy class.\n\n# Shuo Gu, 01/10/20, fixed a bug of input reading\n# Shuo Gu, 01/12/20, Introduced interpolation between energy bins\n# Shuo Gu, 02/18/20, Changed the initial energy 0 to 100 for the approximate method\n\nimport xml.etree.ElementTree as ET #For reading XML files\nfrom rdkit import Chem #The module with the RDKit functions we will need\nimport os #For the function to read in the molecules from the .mol2 file\nimport numpy as np #For arrays and NumPy function\nfrom math import sqrt, atan2, pi #For calculating dihedral angles\nfrom math import ceil #Ceiling function\n\n\n# Import the XML file, using this as a guide:\n# https://docs.python.org/3/library/xml.etree.elementtree.html\ntree = ET.parse(\"TL_2.1_VERSION_6.xml\")\nroot = tree.getroot()\n\n\n# We will turn the procedure for estimating torsion strain energy in\n# TL_Lookup_Test.py into a function that we can call on every molecule\n# in the list, which will return an object of the following class:\nclass TP_list(object):\n def __init__(self, indeces, angles, smarts, hc, methods, E,\n CI_l, CI_u, flags):\n self.indeces = indeces #List of lists of indeces\n self.angles = angles #List of angles\n self.smarts = smarts #List of SMARTS strings\n self.hc = hc #List of strings for hierarchy class\n self.methods = methods #List of strings of energy-estimation methods\n self.E = E #List of energy estimates\n self.CI_l = CI_l #List of lower bounds for 95% CI of energy estimates\n self.CI_u = CI_u #List of upper bounds for 95% CI of energy estimates\n self.flags = flags\n # List of Booleans flagging whether an angle whose \"method\" is\n # \"approximate\" is not observed\n self.TP_indeces = [j for j in range(len(indeces))]\n # Indeces of the torsion patterns, not the atoms!\n\n # Getters and setters:\n def get_indeces(self):\n return(self.indeces)\n def set_indeces(self, inds):\n self.indeces = inds\n def get_angles(self):\n return(self.angles)\n def set_angles(self, angs):\n self.angles = angs\n def get_smarts(self):\n return(self.smarts)\n def set_smarts(self, sms):\n self.smarts = sms\n def get_hc(self):\n return(self.hc)\n def set_hc(self, hcs):\n self.hc = hcs\n def get_methods(self):\n return(self.methods)\n def set_methods(self, meths):\n self.methods = meths\n def get_E(self):\n return(self.E)\n def set_E(self, Es):\n self.E = Es\n def get_CI_l(self):\n return(self.CI_l)\n def set_CI_l(self, ls):\n self.CI_l = ls\n def get_CI_u(self):\n return(self.CI_u)\n def set_CI_u(self, us):\n self.CI_u = us\n def get_flags(self):\n return(self.flags)\n def set_flags(self, fs):\n self.flags = fs\n def get_TP_indeces(self): #Don't need a setter for this\n return(self.TP_indeces)\n\n # A method to return the information for a subset of the torsion patterns\n def get_TPs(self, inds = None):\n # The parameter inds is a list of indeces for the torsion patterns,\n # not the atoms! We default to using all of the torsion patterns\n if inds == None:\n inds = [j for j in range(len(self.indeces))]\n # Create a list of torsion pattern info to be returned:\n tps = [] #Initialize\n for j in inds:\n tps.append([self.TP_indeces[j], self.E[j],\n self.CI_l[j], self.CI_u[j], self.indeces[j], self.angles[j],\n self.smarts[j], self.hc[j], self.methods[j], self.flags[j]])\n return(tps)\n\n # A method to find the sum of the energy estimates, with the 95% CI\n def sum(self, cutoff = None):\n # If at least one of the torsion patterns is flagged, then we\n # do not calculate the estimate or CI. We return -1 * (number flagged)\n flagged = sum(self.flags) #Treats True = 1 and False = 0\n if flagged > 0:\n return([-1*flagged, 0, 0]) #We do not try to calculate the CI\n else:\n if cutoff == None:\n cutoff == 0 #The default cutoff is 0, or using every angle\n ret = [0] * 3 #Initialize the returned array\n for i in range(len(self.E)):\n if self.E[i] >= cutoff:\n # If the energy estimate is larger than the cutoff\n ret[0] += self.E[i]\n ret[1] += self.CI_l[i]\n ret[2] += self.CI_u[i]\n return(ret)\n\n\n# We need a function to read in .mol2 files, which RDKit does not supply to us\n# We will use a function from\n# https://chem-workflows.com/articles/2019/07/18/building-a-multi-molecule-mol2-reader-for-rdkit/\n# Shuo has modified this function significantly to get it to work with the\n# .mol2 files that this lab uses, which contain many lines of comments before\n# each line \"@MOLECULE\"\ndef Mol2MolSupplier (file = None):\n names = [] #Make a list to hold the molecule names\n mols = {} #Make a dictionary\n with open(file, 'r') as f:\n fileend = os.fstat(f.fileno()).st_size\n count = 0\n line = f.readline()\n\n while not f.tell() == fileend:\n if line.startswith(\"#\") or line == '\\n':\n line = f.readline()\n if line.startswith(\"@MOLECULE\"):\n count += 1\n mol = []\n mol.append(line)\n line = f.readline()\n if line != \"\\n\" and line.split()[0].strip() not in names:\n name = line.split()[0].strip()\n print(name)\n else:\n name = \"mol2Number\" + str(count)\n print(name)\n\n while not line.startswith(\"@MOLECULE\"):\n mol.append(line)\n line = f.readline()\n\n if f.tell() == fileend:\n mol.append(line)\n break\n block = \",\".join(mol).replace(',','')\n m = Chem.rdmolfiles.MolFromMol2Block(block, sanitize=False, removeHs = False)\n names.append(name)\n mols[name] = m\n return(names, mols)\n\n# Here is an updated version to use with the output \"file\" string buffer object\n# created by the db2_file_like function in the db2_to_mol2.py script\ndef db2MolSupplier(file):\n names = [] #Make a list to hold the molecule names\n mols = {} #Make a dictionary\n with file as f: #file is already opened as a string buffer\n bufferend = len(f.getvalue())\n count = 0\n line = f.readline()\n while not f.tell() == bufferend:\n if line.startswith(\"#\") or line == '\\n':\n line = f.readline()\n if line.startswith(\"@MOLECULE\"):\n count += 1\n mol = []\n mol.append(line)\n line = f.readline()\n\n name = \"db2Number\" + str(count)\n\n while not line.startswith(\"@MOLECULE\"):\n mol.append(line)\n line = f.readline()\n\n if f.tell() == bufferend:\n mol.append(line)\n break\n block = \",\".join(mol).replace(',','')\n m = Chem.rdmolfiles.MolFromMol2Block(block, sanitize=False, removeHs = False)\n names.append(name)\n mols[name] = m\n return(names, mols)\n\n\n# The first function we will need to make TP_list objects is the dihedral angle\n# calculator. I made this function (and its helper function) for my iPQB\n# summer project of writing a script that creates Ramachandran plots\n# (Make_Rama.py). I have changed some of the comments explaining the math\n# First a helper function for creating unit vectors\ndef unit(a):\n # The argument should be a NumPy array with 1 axis\n return(a / sqrt(np.dot(a,a))) #Scales a by its norm\n\ndef dihedral(a_1, a_2, a_3, a_4):\n # The arguments should all be NumPy arrays with 1 axis and length 3\n # These atoms should be in order, with a_2 and a_3 defining the bond\n # of interest\n\n # The 3 displacement vectors:\n b_1 = a_2 - a_1\n b_2 = a_3 - a_2\n b_3 = a_4 - a_3\n\n n_1 = unit(np.cross(b_1, b_2))\n n_2 = unit(np.cross(b_2, b_3))\n\n # Imagine the first atom (a_1) is above the middle bond (from a_2 to a_3),\n # so that b_1 points downward. Then n_1 points out of the page\n\n m = unit(np.cross(n_1, b_2))\n # I moved the normalization to be after the cross product. Moving\n # the normalization should not change the end result because the cross\n # product commutes with scalar multiplication and ||n_1|| = 1\n\n # Looking down b_2, we can consider n_1 to be the x-axis and\n # m to be the y-axis. Then the dihedral angle is the angle that\n # n_2 makes with the x-axis when projected into this plane. Since dihedral\n # angles are measured going clockwise, we need to negate the angle\n # that we get back from atan\n x = np.dot(n_1, n_2) #Project n_2 onto n_1\n y = np.dot(m, n_2) #Project n_2 onto m\n return(-atan2(y,x) * 180 / pi) #Return the angle in degrees\n\n\n# The next function we will need will calculate angular differences,\n# in degrees. This function will calculate theta_1 - theta_2. See my notes\n# from 9/19/19\ndef ang_diff(theta_1, theta_2):\n # (-180,180] -> [0, 360)\n if theta_1 < 0:\n theta_1 += 360\n if theta_2 < 0:\n theta_2 += 360\n del_theta = (theta_1 - theta_2) % 360 #Angular difference\n # [0, 360) -> (-180, 180]\n if del_theta > 180:\n del_theta -= 360\n return(del_theta)\n # Test this works: ang_diff(0, 179), ang_diff(0, -179),\n # and ang_diff(-179, 179)\n\n\n# This function will allow us to do the matching for each torsion rule\ndef tp_match(tp, hc, j, mol, pos, bi):\n # tp is a torsion pattern, hc is the type of hierarchyClass (\"general\" or\n # \"specific\", and j is the current value for i\n # This function turned the global variables mol, positions, and bond_info\n # in TL_Lookup_Test.py into parameters mol, pos and bi, respectively\n smarts = tp.get(\"smarts\")\n # Create the histograms for energy estimates and bounds of confidence\n # intervals, if available\n hist_E = [] #Initialize for energy estimates\n hist_l = [] #Initialize for lower bounds of CIs\n hist_u = [] #Initialize for upper bounds of CIs\n if tp.get(\"method\") == \"exact\":\n for bin in tp.find(\"histogram_converted\").findall(\"bin\"):\n hist_E.append(float(bin.get(\"energy\")))\n hist_l.append(float(bin.get(\"lower\")))\n hist_u.append(float(bin.get(\"upper\")))\n matches = mol.GetSubstructMatches(Chem.MolFromSmarts(smarts))\n # A list of lists\n for match in matches: #For each match\n # Some of the SMARTS for the torion patterns actually have 5 atoms.\n # We need to ingore these\n if len(match) > 4:\n continue #Go to the next match\n\n # First get the atom locations\n # Based on https://github.com/rdkit/rdkit/issues/1982\n r_1 = np.array(pos[match[0]])\n r_2 = np.array(pos[match[1]])\n r_3 = np.array(pos[match[2]])\n r_4 = np.array(pos[match[3]])\n\n theta = dihedral(r_1, r_2, r_3, r_4) #Dihedral angle\n\n # Changed next line from \"TP.get\" to \"tp.get\"\n if tp.get(\"method\") == \"exact\": #If using the exact method\n # First figure out what bin we are in in the histogram.\n # We define the bins by the right endpoints, like we did\n # when we made the plots of the energy profiles\n bin_num = ceil(theta / 10) + 17\n # Starting with the -170 deg bin\n energy = (hist_E[bin_num]-hist_E[(bin_num+35)%36])/10.0*(theta-(bin_num-17)*10)+hist_E[bin_num]\n lower = (hist_l[bin_num]-hist_l[(bin_num+35)%36])/10.0*(theta-(bin_num-17)*10)+hist_l[bin_num]\n upper = (hist_u[bin_num]-hist_u[(bin_num+35)%36])/10.0*(theta-(bin_num-17)*10)+hist_u[bin_num]\n\n bi.append(\n [\n list(match), #Convert tuple to list\n theta,\n smarts,\n hc, #\"general\" or \"specific\"\n \"exact\",\n energy,\n lower,\n upper,\n False, #This only could apply for the approximate method\n j #We will take this out when we create the final object\n ]\n )\n\n else: #If using the approximate method\n not_observed = True\n # Initialize the flag for not observing that angle\n energy = 100\n # Initialize the energy, in case we cannot estimate it\n # Loop over all the possible angle peaks\n for angle in tp.find(\"angleList\").findall(\"angle\"):\n theta_0 = float(angle.get(\"theta_0\")) #Peak location\n delta = ang_diff(theta, theta_0) #Angular displacement\n if abs(delta) <= float(angle.get(\"tolerance2\")):\n # If within the tolerance range for that peak\n beta_1 = float(angle.get(\"beta_1\"))\n beta_2 = float(angle.get(\"beta_2\"))\n # The coefficients for the regression\n energy = beta_1*(delta ** 2) + beta_2*(delta ** 4)\n # Using the \"not-as-small angle approximation\"\n not_observed = False\n break\n # Break the for loop to avoid problems if the\n # observed angle sits at the border between two\n # peaks\n bi.append(\n [\n list(match), #Convert tuple to list\n theta,\n smarts,\n hc, #\"general\" or \"specific\"\n \"approximate\",\n energy,\n energy, #Lower bound for CI, which we cannot find for approx. method\n energy, #Upper bound for CI, which we cannot find for approx. method\n not_observed,\n j #We will take this out when we create the final object\n ]\n )\n\n\n# This most general function will automate what we did in TL_Lookup_Test.py\ndef TL_lookup(mol): #mol is read in from the .mol2 file\n positions = mol.GetConformer().GetPositions()\n # List of lists of atom coordinates. Luckily RDKit starts indexing at 0\n bond_info = []\n # Initialize an empty list that will hold the information for each bond\n i = 0 #Initialize count of torsion rules\n\n # Loop over all of the specific hierarchy classes\n for HC in root.findall(\"hierarchyClass\"):\n if HC.get(\"name\") != \"GG\": #Not the general class\n for TP in HC.iter(\"torsionRule\"): #Loop over each torsion rule\n tp_match(TP, \"specific\", i, mol, positions, bond_info)\n i += 1 #Increase the count for the torsion rule\n\n # Now for the general method:\n for TP in root.find(\"hierarchyClass[@name='GG']\").iter(\"torsionRule\"):\n tp_match(TP, \"general\", i, mol, positions, bond_info)\n i += 1 #Increase the count for the torsion rule\n\n # Now that we have all of the torsion patterns, we need to be able to find\n # duplicates. The first such way is if the entire pattern is reversed. We\n # can fix this problem by making sure that all of the lists of indeces have\n # the second index (the first in the bond of interest) lower than the third\n # index (the second in the bond of interest)\n for bond in bond_info: #Loop over every bond\n if bond[0][1] > bond[0][2]:\n bond[0].reverse() #Reverse this list\n bond.append(True) #Mark that we reversed this bond's indeces\n else:\n bond.append(False) #Mark that we did not reverse this bond's\n # indeces. We will remove this marking later\n\n # Next we condense the bond_info by the lists of 4 atoms defining the bonds.\n # We will pick the entry of bond_info that has the lowest value for i for\n # each match, since the torsion rules in the Torsion Library are arranged\n # (within each hierarchy class or hierarchy subclass) in decreasing\n # specificity, and we loop over all of the specific hierarchy classes\n # before the general one\n bond_info_red = [bond_info[0]] #Initialize a list for the reduced bond info\n # This reduced list needs at least one element for checking subelements\n for j in range(1, len(bond_info)):\n # Skip the first bond, which is already in the reduced list\n atom_0 = bond_info[j][0][0] #First atom index\n atom_1 = bond_info[j][0][1] #Second atom index\n atom_2 = bond_info[j][0][2] #Third bond index\n atom_3 = bond_info[j][0][3] #Fourth bond index\n\n unmatched = True #Initialize not finding a match\n for k in range(len(bond_info_red)):\n # Check against everything in the growing reduced list\n if bond_info_red[k][0][0] == atom_0 \\\n and bond_info_red[k][0][1] == atom_1 \\\n and bond_info_red[k][0][2] == atom_2 \\\n and bond_info_red[k][0][3] == atom_3:\n # If there is a match in ALL of the atom indeces\n unmatched = False\n if bond_info[j][9] < bond_info_red[k][9]:\n # The ninth index gives the value for i\n # If the new bond has a lower value, then we use it\n # to replace the current one\n bond_info_red[k] = bond_info[j]\n break\n # No need to continue looking for matches, since there\n # should be no more than 1\n\n if unmatched: #If no match\n bond_info_red.append(bond_info[j]) #Append the current bond\n\n # Now we condense the bond_info_red by the 2 atoms actually defining the\n # bond. We will pick the entry of bond_info_red for each match that has\n # the highest energy estimate, prioritizing torsion patterns from\n # \"specific\" hierarchy classes over ones from the \"general\" hierarchy class\n b_i_r = [bond_info_red[0]] #Initialize a list for the further reduced bond info\n # I used the name b_i_r over bond_info_red_2\n for j in range(1, len(bond_info_red)):\n # Skip the first bond, which is already in the reduced list\n atom_1 = bond_info_red[j][0][1] #First atom index of the bond\n atom_2 = bond_info_red[j][0][2] #Second atom index of the bond\n\n unmatched = True #Initialize not finding a match\n for k in range(len(b_i_r)):\n # Check against everything in the growing list\n if b_i_r[k][0][1] == atom_1 and b_i_r[k][0][2] == atom_2:\n # If there is a match in the two atom indeces defining the bond\n unmatched = False\n if bond_info_red[j][3][0] > b_i_r[k][3][0] \\\n or (\n bond_info_red[j][5] > b_i_r[k][5] \\\n and\n bond_info_red[j][3][0] == b_i_r[k][3][0]\n ):\n # The third index gives \"general\" or \"specific\", and we\n # access the first char in that string. We use:\n # 's' > 's' gives False\n # 'g' > 'g' gives False\n # 'g' > 's' gives False\n # 's' > 'g' gives True\n # to prioritize using the specific classe over the general one.\n # The fifth index gives the energy estimate\n b_i_r[k] = bond_info_red[j] #Replace the current bond info\n break\n # No need to continue looking for matches, since there\n # should be no more than 1\n\n if unmatched: #If no match\n b_i_r.append(bond_info_red[j]) #Append the current bond\n\n # Now that we have only the bond information that we want, we need to\n # un-do any times we reversed the atom indeces\n for bond in b_i_r:\n if bond[10]:\n # The tenth index gives whether or not we reversed the indeces\n bond[0].reverse() #Reverse this list\n\n # Now that we have all the information we need, we can return the\n # object that contains it\n return(\n TP_list([bond[0] for bond in b_i_r], [bond[1] for bond in b_i_r],\n [bond[2] for bond in b_i_r], [bond[3] for bond in b_i_r],\n [bond[4] for bond in b_i_r], [bond[5] for bond in b_i_r],\n [bond[6] for bond in b_i_r], [bond[7] for bond in b_i_r],\n [bond[8] for bond in b_i_r]) #Using Python list comprehension\n )\n", "meta": {"hexsha": "b33e56f545423290a467cf01686d07d03162f2af", "size": 23523, "ext": "py", "lang": "Python", "max_stars_repo_path": "KCNQ/docking/scripts/strainfilter/TL_Functions.py", "max_stars_repo_name": "jilimcaoco/MPProjects", "max_stars_repo_head_hexsha": "5b930ce2fdf5def49444f1953457745af964efe9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "KCNQ/docking/scripts/strainfilter/TL_Functions.py", "max_issues_repo_name": "jilimcaoco/MPProjects", "max_issues_repo_head_hexsha": "5b930ce2fdf5def49444f1953457745af964efe9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "KCNQ/docking/scripts/strainfilter/TL_Functions.py", "max_forks_repo_name": "jilimcaoco/MPProjects", "max_forks_repo_head_hexsha": "5b930ce2fdf5def49444f1953457745af964efe9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-14T20:08:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-14T20:08:32.000Z", "avg_line_length": 45.499032882, "max_line_length": 107, "alphanum_fraction": 0.6220720146, "include": true, "reason": "import numpy", "num_tokens": 5943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.2814056194821861, "lm_q1q2_score": 0.14619621943813296}} {"text": "#!/usr/bin/env python\n\"\"\"\nradarData.py\nThis file holds the RadarData class that hold the radar data and processes it.\n\n@author: John Swoboda\n\"\"\"\nimport ipdb\nimport scipy as sp\n# My modules\nfrom isrutilities.physConstants import v_C_0, v_Boltz\nfrom SimISR import Path\nfrom SimISR.IonoContainer import IonoContainer\nfrom SimISR.utilFunctions import CenteredLagProduct, MakePulseDataRepLPC,dict2h5,h52dict,readconfigfile, BarkerLag, update_progress\n#from SimISR import specfunctions\n#from SimISR.analysisplots import plotspecsgen\n\nclass RadarDataFile(object):\n \"\"\"\n This class will will take the ionosphere class and create radar data both\n at the IQ and fitted level.\n\n Variables\n simparams - A dictionary that holds simulation parameters the keys are the\n following\n 'angles': Angles (in degrees) for the simulation. The az and el angles\n are stored in a list of tuples [(az_0,el_0),(az_1,el_1)...]\n 'IPP' : Interpulse period in seconds, this is the IPP from position to\n position. In other words if a IPP is 10 ms and there are 10 beams it will\n take 100 ms to go through all of the beams.\n 'Tint' This is the integration time in seconds.\n 'Timevec': This is the time vector for each frame. It is referenced to\n the begining of the frame. Also in seconds\n 'Pulse': The shape of the pulse. This is a numpy array.\n 'TimeLim': The length of time that the experiment will run, which cooresponds\n to how many pulses per position are used.\n sensdict - A dictionary that holds the sensor parameters.\n rawdata: This is a NbxNpxNr numpy array that holds the raw IQ data.\n rawnoise: This is a NbxNpxNr numpy array that holds the raw noise IQ data.\n \"\"\"\n\n\n def __init__(self, Ionodict, inifile, outdir, outfilelist=None):\n \"\"\"\n This function will create an instance of the RadarData class. It will\n take in the values and create the class and make raw IQ data.\n Inputs:\n sensdict - A dictionary of sensor parameters\n angles - A list of tuples which the first position is the az angle\n and the second position is the el angle.\n IPP - The interpulse period in seconds represented as a float.\n Tint - The integration time in seconds as a float. This will be the\n integration time of all of the beams.\n time_lim - The length of time of the simulation the number of time points\n will be calculated.\n pulse - A numpy array that represents the pulse shape.\n rng_lims - A numpy array of length 2 that holds the min and max range\n that the radar will cover.\n \"\"\"\n (sensdict, simparams) = readconfigfile(inifile)\n self.simparams = simparams\n N_angles = len(self.simparams['angles'])\n\n NNs = int(self.simparams['NNs'])\n self.sensdict = sensdict\n Npall = sp.floor(self.simparams['TimeLim']/self.simparams['IPP'])\n Npall = int(sp.floor(Npall/N_angles)*N_angles)\n Np = Npall/N_angles\n\n print(\"All spectrums created already\")\n filetimes = Ionodict.keys()\n filetimes.sort()\n ftimes = sp.array(filetimes)\n simdtype = self.simparams['dtype']\n pulsetimes = sp.arange(Npall)*self.simparams['IPP'] +ftimes.min()\n pulsefile = sp.array([sp.where(itimes-ftimes >= 0)[0][-1] for itimes in pulsetimes])\n # differentiate between phased arrays and dish antennas\n if sensdict['Name'].lower() in ['risr', 'pfisr', 'risr-n']:\n\n beams = sp.tile(sp.arange(N_angles), Npall/N_angles)\n else:\n\n # for dish arrays\n brate = simparams['beamrate']\n beams2 = sp.repeat(sp.arange(N_angles), brate)\n beam3 = sp.concatenate((beams2, beams2[::-1]))\n ntile = int(sp.ceil(Npall/len(beam3)))\n leftover = int(Npall-ntile*len(beam3))\n if ntile > 0:\n beams = sp.tile(beam3, ntile)\n beams = sp.concatenate((beams, beam3[:leftover]))\n else:\n beams = beam3[:leftover]\n\n pulsen = sp.repeat(sp.arange(Np), N_angles)\n pt_list = []\n pb_list = []\n pn_list = []\n fname_list = []\n self.datadir = outdir\n self.maindir = outdir.parent\n self.procdir = self.maindir/'ACF'\n Nf = len(filetimes)\n progstr = 'Data from {:d} of {:d} being processed Name: {:s}.'\n if outfilelist is None:\n print('\\nData Now being created.')\n\n Noisepwr = v_Boltz*sensdict['Tsys']*sensdict['BandWidth']\n self.outfilelist = []\n for ifn, ifilet in enumerate(filetimes):\n\n outdict = {}\n ifile = Ionodict[ifilet]\n ifilename = Path(ifile).name\n update_progress(float(ifn)/Nf, progstr.format(ifn, Nf, ifilename))\n curcontainer = IonoContainer.readh5(ifile)\n if ifn == 0:\n self.timeoffset = curcontainer.Time_Vector[0, 0]\n pnts = pulsefile == ifn\n pt = pulsetimes[pnts]\n pb = beams[pnts]\n pn = pulsen[pnts].astype(int)\n rawdata = self.__makeTime__(pt, curcontainer.Time_Vector,\n curcontainer.Sphere_Coords,\n curcontainer.Param_List, pb)\n d_shape = rawdata.shape\n n_tempr = sp.random.randn(*d_shape).astype(simdtype)\n n_tempi = 1j*sp.random.randn(*d_shape).astype(simdtype)\n noise = sp.sqrt(Noisepwr/2)*(n_tempr+n_tempi)\n outdict['AddedNoise'] = noise\n outdict['RawData'] = rawdata+noise\n outdict['RawDatanonoise'] = rawdata\n outdict['NoiseData'] = sp.sqrt(Noisepwr/2)*(sp.random.randn(len(pn), NNs).astype(simdtype)+\n 1j*sp.random.randn(len(pn), NNs).astype(simdtype))\n outdict['Pulses'] = pn\n outdict['Beams'] = pb\n outdict['Time'] = pt\n fname = '{0:d} RawData.h5'.format(ifn)\n newfn = self.datadir/fname\n self.outfilelist.append(str(newfn))\n dict2h5(str(newfn), outdict)\n\n #Listing info\n pt_list.append(pt)\n pb_list.append(pb)\n pn_list.append(pn)\n fname_list.append(fname)\n infodict = {'Files':fname_list, 'Time':pt_list, 'Beams':pb_list, 'Pulses':pn_list}\n dict2h5(str(outdir.joinpath('INFO.h5')), infodict)\n\n else:\n infodict = h52dict(str(outdir.joinpath('INFO.h5')))\n alltime = sp.hstack(infodict['Time'])\n self.timeoffset = alltime.min()\n self.outfilelist = outfilelist\n\n\n#%% Make functions\n def __makeTime__(self,pulsetimes,spectime,Sphere_Coords,allspecs,beamcodes):\n \"\"\"This is will make raw radar data for a given time period and set of\n spectrums. This is an internal function called by __init__.\n Inputs-\n self - RadarDataFile object.\n pulsetimes - The time the pulses are sent out in reference to the spectrums.\n spectime - The times for the spectrums.\n Sphere_Coords - An Nlx3 array that holds the spherical coordinates of the spectrums.\n allspecs - An NlxNdtimexNspec array that holds the spectrums.\n beamcodes - A NBx4 array that holds the beam codes along with the beam location\n in az el along with a system constant in the array. \"\"\"\n\n range_gates = self.simparams['Rangegates']\n pulse = self.simparams['Pulse']\n sensdict = self.sensdict\n pulse2spec = sp.array([sp.where(itimes-spectime >= 0)[0][-1] for itimes in pulsetimes])\n Np = len(pulse2spec)\n lp_pnts = len(pulse)\n samp_num = sp.arange(lp_pnts)\n #N_rg = len(range_gates)# take the size\n N_samps = len(range_gates)\n angles = self.simparams['angles']\n Nbeams = len(angles)\n rho = Sphere_Coords[:, 0]\n Az = Sphere_Coords[:, 1]\n El = Sphere_Coords[:, 2]\n rng_len = self.sensdict['t_s']*v_C_0*1e-3/2.\n speclen = allspecs.shape[-1]\n simdtype = self.simparams['dtype']\n out_data = sp.zeros((Np, N_samps), dtype=simdtype)\n weights = {ibn:self.sensdict['ArrayFunc'](Az, El, ib[0], ib[1], sensdict['Angleoffset'])\n for ibn, ib in enumerate(angles)}\n for istn in range(len(spectime)):\n for ibn in range(Nbeams):\n #print('\\t\\t Making Beam {0:d} of {1:d}'.format(ibn, Nbeams))\n weight = weights[ibn]\n for isamp in range(N_samps):\n range_g = range_gates[isamp]\n\n if range_g <= 0:\n continue\n range_m = range_g*1e3\n rnglims = [range_g-rng_len/2.0, range_g+rng_len/2.0]\n rangelog = (rho >= rnglims[0])&(rho < rnglims[1])\n # Get the number of points covered\n cur_pnts = samp_num+isamp\n keep_pnt = sp.logical_and(cur_pnts >= 0, cur_pnts < N_samps)\n cur_pnts = cur_pnts[keep_pnt]\n # This is a nearest neighbors interpolation for the\n # spectrums in the range domain\n if sp.sum(rangelog) == 0:\n minrng = sp.argmin(sp.absolute(range_g-rho))\n rangelog[minrng] = True\n\n #create the weights and weight location based on the beams pattern.\n weight_cur = weight[rangelog]\n weight_cur = weight_cur/weight_cur.sum()\n specsinrng = allspecs[rangelog]\n if specsinrng.ndim == 3:\n specsinrng = specsinrng[:, istn]\n elif specsinrng.ndim == 2:\n specsinrng = specsinrng[istn]\n specsinrng = specsinrng*sp.tile(weight_cur[:, sp.newaxis], (1, speclen))\n cur_spec = specsinrng.sum(0)\n # based off new way of calculating\n pow_num = sensdict['Pt']*sensdict['Ksys'][ibn]*sensdict['t_s']\n pow_den = range_m**2\n curdataloc = sp.where(sp.logical_and((pulse2spec == istn),\n (beamcodes == ibn)))[0]\n # create data\n if len(curdataloc) == 0:\n print('\\t\\t No data for {0:d} of {1:d} in this time period'.format(ibn, Nbeams))\n continue\n cur_pulse_data = MakePulseDataRepLPC(pulse, cur_spec, 20,\n len(curdataloc), numtype=simdtype)\n cur_pulse_data = cur_pulse_data*sp.sqrt(pow_num/pow_den)\n for idatn, idat in enumerate(curdataloc):\n d_pnts = cur_pnts[::-1]-isamp\n cursum = cur_pulse_data[idatn, d_pnts]+out_data[idat, cur_pnts]\n out_data[idat, cur_pnts] = cursum\n return out_data\n #%% Processing\n def processdataiono(self):\n \"\"\" This will perform the the data processing and create the ACF estimates\n for both the data and noise but put it in an Ionocontainer.\n Inputs:\n\n Outputs:\n Ionocontainer- This is an instance of the ionocontainer class that will hold the acfs.\n \"\"\"\n (datalags, noiselags) = self.processdata()\n return lagdict2ionocont(datalags, noiselags, self.sensdict, self.simparams,\n datalags['Time'])\n\n def processdata(self):\n \"\"\" This will perform the the data processing and create the ACF estimates\n for both the data and noise.\n Inputs:\n timevec - A numpy array of times in seconds where the integration will begin.\n inttime - The integration time in seconds.\n lagfunc - A function that will make the desired lag products.\n Outputs:\n DataLags: A dictionary with keys 'Power' 'ACF','RG','Pulses' that holds\n the numpy arrays of the data.\n NoiseLags: A dictionary with keys 'Power' 'ACF','RG','Pulses' that holds\n the numpy arrays of the data.\n \"\"\"\n timevec = self.simparams['Timevec'] +self.timeoffset\n inttime = self.simparams['Tint']\n # Get array sizes\n\n NNs = int(self.simparams['NNs'])\n range_gates = self.simparams['Rangegates']\n N_samps = len(range_gates)# take the size\n pulse = self.simparams['Pulse']\n Pulselen = len(pulse)\n N_rg = N_samps - Pulselen+1\n simdtype = self.simparams['dtype']\n Ntime = len(timevec)\n\n if 'outangles' in self.simparams.keys():\n Nbeams = len(self.simparams['outangles'])\n inttime = inttime\n else:\n Nbeams = len(self.simparams['angles'])\n\n # Choose type of processing\n if self.simparams['Pulsetype'].lower() == 'barker':\n lagfunc = BarkerLag\n Nlag = 1\n else:\n lagfunc = CenteredLagProduct\n Nlag = Pulselen\n # initialize output arrays\n outdata = sp.zeros((Ntime, Nbeams, N_rg, Nlag), dtype=simdtype)\n outaddednoise = sp.zeros((Ntime, Nbeams, N_rg, Nlag), dtype=simdtype)\n outnoise = sp.zeros((Ntime, Nbeams, NNs-Pulselen+1, Nlag), dtype=simdtype)\n pulses = sp.zeros((Ntime, Nbeams))\n pulsesN = sp.zeros((Ntime, Nbeams))\n timemat = sp.zeros((Ntime, 2))\n Ksysvec = self.sensdict['Ksys']\n # set up arrays that hold the location of pulses that are to be processed together\n infoname = self.datadir / 'INFO.h5'\n # Just going to assume that the info file is in the directory\n infodict = h52dict(str(infoname))\n flist = infodict['Files']\n file_list = [str(self.datadir/i) for i in flist]\n pulsen_list = infodict['Pulses']\n beamn_list = infodict['Beams']\n time_list = infodict['Time']\n file_loclist = [ifn*sp.ones(len(ifl)) for ifn, ifl in enumerate(beamn_list)]\n\n\n pulsen = sp.hstack(pulsen_list).astype(int)# pulse number\n beamn = sp.hstack(beamn_list).astype(int)# beam numbers\n ptimevec = sp.hstack(time_list).astype(float)# time of each pulse\n file_loc = sp.hstack(file_loclist).astype(int)# location in the file\n\n # run the time loop\n print(\"Forming ACF estimates\")\n\n # For each time go through and read only the necisary files\n for itn, it in enumerate(timevec):\n update_progress(float(itn)/Ntime, \"Time {0:d} of {1:d}\".format(itn, Ntime))\n # do the book keeping to determine locations of data within the files\n cur_tlim = (it, it+inttime)\n curcases = sp.logical_and(ptimevec >= cur_tlim[0], ptimevec < cur_tlim[1])\n if not sp.any(curcases):\n prog_str = \"No pulses for time {0:d} of {1:d}, lagdata adjusted accordinly\"\n update_progress(float(itn)/Ntime, prog_str.format(itn, Ntime))\n outdata = outdata[:itn]\n outnoise = outnoise[:itn]\n pulses = pulses[:itn]\n pulsesN = pulsesN[:itn]\n timemat = timemat[:itn]\n continue\n pulseset = set(pulsen[curcases])\n poslist = [sp.where(pulsen == item)[0] for item in pulseset]\n pos_all = sp.hstack(poslist)\n try:\n pos_all = sp.hstack(poslist)\n curfileloc = file_loc[pos_all]\n except:\n ipdb.set_trace()\n # Find the needed files and beam numbers\n curfiles = set(curfileloc)\n beamlocs = beamn[pos_all]\n timemat[itn, 0] = ptimevec[pos_all].min()\n timemat[itn, 1] = ptimevec[pos_all].max()\n # cur data pulls out all data from all of the beams and posisions\n curdata = sp.zeros((len(pos_all), N_samps), dtype=simdtype)\n curaddednoise = sp.zeros((len(pos_all), N_samps), dtype=simdtype)\n curnoise = sp.zeros((len(pos_all), NNs), dtype=simdtype)\n # Open files and get required data\n # XXX come up with way to get open up new files not have to reread in data that is already in memory\n for ifn in curfiles:\n curfileit = [sp.where(pulsen_list[ifn] == item)[0] for item in pulseset]\n curfileitvec = sp.hstack(curfileit)\n ifile = file_list[ifn]\n curh5data = h52dict(ifile)\n file_arlocs = sp.where(curfileloc == ifn)[0]\n curdata[file_arlocs] = curh5data['RawData'][curfileitvec]\n\n curaddednoise[file_arlocs] = curh5data['AddedNoise'].astype(simdtype)[curfileitvec]\n # Read in noise data when you have don't have ACFs\n\n curnoise[file_arlocs] = curh5data['NoiseData'].astype(simdtype)[curfileitvec]\n\n # differentiate between phased arrays and dish antennas\n if self.sensdict['Name'].lower() in ['risr', 'pfisr', 'risr-n']:\n # After data is read in form lags for each beam\n for ibeam in range(Nbeams):\n prog_num = float(itn)/Ntime+float(ibeam)/Ntime/Nbeams\n update_progress(prog_num, \"Beam {0:d} of {1:d}\".format(ibeam, Nbeams))\n beamlocstmp = sp.where(beamlocs == ibeam)[0]\n pulses[itn, ibeam] = len(beamlocstmp)\n\n outdata[itn, ibeam] = lagfunc(curdata[beamlocstmp].copy(),\n numtype=self.simparams['dtype'],\n pulse=pulse, lagtype=self.simparams['lagtype'])\n\n pulsesN[itn, ibeam] = len(beamlocstmp)\n outnoise[itn, ibeam] = lagfunc(curnoise[beamlocstmp].copy(),\n numtype=self.simparams['dtype'],\n pulse=pulse, lagtype=self.simparams['lagtype'])\n outaddednoise[itn, ibeam] = lagfunc(curaddednoise[beamlocstmp].copy(),\n numtype=self.simparams['dtype'],\n pulse=pulse, lagtype=self.simparams['lagtype'])\n else:\n for ibeam, ibeamlist in enumerate(self.simparams['outangles']):\n prog_num = float(itn)/Ntime+float(ibeam)/Ntime/Nbeams\n update_progress(prog_num, \"Beam {0:d} of {1:d}\".format(ibeam, Nbeams))\n beamlocstmp = sp.where(sp.in1d(beamlocs, ibeamlist))[0]\n inputdata = curdata[beamlocstmp].copy()\n noisedata = curnoise[beamlocstmp].copy()\n noisedataadd = curaddednoise[beamlocstmp].copy()\n pulses[itn, ibeam] = len(beamlocstmp)\n pulsesN[itn, ibeam] = len(beamlocstmp)\n outdata[itn, ibeam] = lagfunc(inputdata, numtype=self.simparams['dtype'],\n pulse=pulse, lagtype=self.simparams['lagtype'])\n outnoise[itn, ibeam] = lagfunc(noisedata, numtype=self.simparams['dtype'],\n pulse=pulse, lagtype=self.simparams['lagtype'])\n outaddednoise[itn, ibeam] = lagfunc(noisedataadd, numtype=self.simparams['dtype'],\n pulse=pulse, lagtype=self.simparams['lagtype'])\n # Create output dictionaries and output data\n DataLags = {'ACF':outdata, 'Pow':outdata[:, :, :, 0].real, 'Pulses':pulses,\n 'Time':timemat, 'AddedNoiseACF':outaddednoise}\n NoiseLags = {'ACF':outnoise, 'Pow':outnoise[:, :, :, 0].real, 'Pulses':pulsesN,\n 'Time':timemat}\n return(DataLags, NoiseLags)\n\n#%% Make Lag dict to an iono container\ndef lagdict2ionocont(DataLags, NoiseLags, sensdict, simparams, time_vec):\n \"\"\"This function will take the data and noise lags and create an instance of the\n Ionocontanier class. This function will also apply the summation rule to the lags.\n Inputs\n DataLags - A dictionary \"\"\"\n # Pull in Location Data\n angles = simparams['angles']\n ang_data = sp.array([[iout[0], iout[1]] for iout in angles])\n rng_vec = simparams['Rangegates']\n n_samps = len(rng_vec)\n # pull in other data\n pulse = simparams['Pulse']\n p_samps = len(pulse)\n pulsewidth = p_samps*sensdict['t_s']\n txpower = sensdict['Pt']\n if sensdict['Name'].lower() in ['risr', 'pfisr', 'risr-n']:\n Ksysvec = sensdict['Ksys']\n else:\n\n beamlistlist = sp.array(simparams['outangles']).astype(int)\n inplist = sp.array([i[0] for i in beamlistlist])\n Ksysvec = sensdict['Ksys'][inplist]\n ang_data_temp = ang_data.copy()\n ang_data = sp.array([ang_data_temp[i].mean(axis=0) for i in beamlistlist])\n\n sumrule = simparams['SUMRULE']\n rng_vec2 = simparams['Rangegatesfinal']\n Nrng2 = len(rng_vec2)\n minrg = p_samps-1+sumrule[0].min()\n maxrg = Nrng2+minrg\n\n\n # Copy the lags\n lagsData = DataLags['ACF'].copy()\n # Set up the constants for the lags so they are now\n # in terms of density fluxtuations.\n angtile = sp.tile(ang_data, (Nrng2, 1))\n rng_rep = sp.repeat(rng_vec2, ang_data.shape[0], axis=0)\n coordlist = sp.zeros((len(rng_rep), 3))\n [coordlist[:, 0], coordlist[:, 1:]] = [rng_rep, angtile]\n (Nt, Nbeams, Nrng, Nlags) = lagsData.shape\n\n # make a range average to equalize out the conntributions from each gate\n\n plen2 = int(sp.floor(float(p_samps-1)/2))\n samps = sp.arange(0, p_samps, dtype=int)\n\n rng_ave = sp.zeros((Nrng, p_samps))\n\n for isamp in range(plen2, Nrng+plen2):\n for ilag in range(p_samps):\n toplag = int(sp.floor(float(ilag)/2))\n blag = int(sp.ceil(float(ilag)/2))\n if toplag == 0:\n sampsred = samps[blag:]\n else:\n sampsred = samps[blag:-toplag]\n cursamps = isamp-sampsred\n\n keepsamps = sp.logical_and(cursamps >= 0, cursamps < Nrng)\n cursamps = cursamps[keepsamps]\n rng_samps = rng_vec[cursamps]**2*1e6\n keepsamps2 = rng_samps > 0\n if keepsamps2.sum() == 0:\n continue\n rng_samps = rng_samps[keepsamps2]\n rng_ave[isamp-plen2, ilag] = 1./(sp.mean(1./(rng_samps)))\n rng_ave_temp = rng_ave.copy()\n if simparams['Pulsetype'].lower() is 'barker':\n rng_ave_temp = rng_ave[:,0][:,sp.newaxis]\n # rng_ave = rng_ave[int(sp.floor(plen2)):-int(sp.ceil(plen2))]\n # rng_ave = rng_ave[minrg:maxrg]\n rng3d = sp.tile(rng_ave_temp[sp.newaxis, sp.newaxis, :, :], (Nt, Nbeams, 1, 1))\n ksys3d = sp.tile(Ksysvec[sp.newaxis,:, sp.newaxis, sp.newaxis], (Nt, 1, Nrng, Nlags))\n\n # rng3d = sp.tile(rng_ave[:, sp.newaxis, sp.newaxis, sp.newaxis], (1, Nlags, Nt, Nbeams))\n # ksys3d = sp.tile(Ksysvec[sp.newaxis, sp.newaxis, sp.newaxis, :], (Nrng2, Nlags, Nt, 1))\n radar2acfmult = rng3d/(pulsewidth*txpower*ksys3d)\n pulses = sp.tile(DataLags['Pulses'][:, :, sp.newaxis, sp.newaxis], (1, 1, Nrng, Nlags))\n time_vec = time_vec[:Nt]\n # Divid lags by number of pulses\n lagsData = lagsData/pulses\n # Set up the noise lags and divid out the noise.\n lagsNoise = NoiseLags['ACF'].copy()\n lagsNoise = sp.mean(lagsNoise, axis=2)\n pulsesnoise = sp.tile(NoiseLags['Pulses'][:, :, sp.newaxis], (1, 1, Nlags))\n lagsNoise = lagsNoise/pulsesnoise\n lagsNoise = sp.tile(lagsNoise[:, :, sp.newaxis, :], (1, 1, Nrng, 1))\n\n # multiply the data and the sigma by inverse of the scaling from the radar\n lagsData = lagsData*radar2acfmult\n lagsNoise = lagsNoise*radar2acfmult\n # Apply summation rule\n # lags transposed from (time,beams,range,lag)to (range,lag,time,beams)\n lagsData = sp.transpose(lagsData, axes=(2, 3, 0, 1))\n lagsNoise = sp.transpose(lagsNoise, axes=(2, 3, 0, 1))\n lagsDatasum = sp.zeros((Nrng2, Nlags, Nt, Nbeams), dtype=lagsData.dtype)\n lagsNoisesum = sp.zeros((Nrng2, Nlags, Nt, Nbeams), dtype=lagsNoise.dtype)\n\n for irngnew, irng in enumerate(sp.arange(minrg, maxrg)):\n for ilag in range(Nlags):\n lsumtemp = lagsData[irng+sumrule[0, ilag]:irng+sumrule[1, ilag]+1, ilag].sum(axis=0)\n lagsDatasum[irngnew, ilag] = lsumtemp\n nsumtemp = lagsNoise[irng+sumrule[0, ilag]:irng+sumrule[1, ilag]+1, ilag].sum(axis=0)\n lagsNoisesum[irngnew, ilag] = nsumtemp\n # subtract out noise lags\n lagsDatasum = lagsDatasum-lagsNoisesum\n\n # Put everything in a parameter list\n Paramdata = sp.zeros((Nbeams*Nrng2, Nt, Nlags), dtype=lagsData.dtype)\n # Put everything in a parameter list\n # transpose from (range,lag,time,beams) to (beams,range,time,lag)\n # lagsDatasum = lagsDatasum*radar2acfmult\n # lagsNoisesum = lagsNoisesum*radar2acfmult\n lagsDatasum = sp.transpose(lagsDatasum, axes=(3, 0, 2, 1))\n lagsNoisesum = sp.transpose(lagsNoisesum, axes=(3, 0, 2, 1))\n\n # multiply the data and the sigma by inverse of the scaling from the radar\n # lagsDatasum = lagsDatasum*radar2acfmult\n # lagsNoisesum = lagsNoisesum*radar2acfmult\n\n # Calculate a variance using equation 2 from Hysell's 2008 paper. Done use full covariance matrix because assuming nearly diagonal.\n # Get the covariance matrix\n pulses_s = sp.transpose(pulses, axes=(1, 2 ,0, 3))[:, :Nrng2]\n Cttout = makeCovmat(lagsDatasum, lagsNoisesum, pulses_s, Nlags)\n\n Paramdatasig = sp.zeros((Nbeams*Nrng2 ,Nt, Nlags, Nlags), dtype=Cttout.dtype)\n\n curloc = 0\n for irng in range(Nrng2):\n for ibeam in range(Nbeams):\n Paramdata[curloc] = lagsDatasum[ibeam, irng].copy()\n Paramdatasig[curloc] = Cttout[ibeam, irng].copy()\n curloc += 1\n ionodata = IonoContainer(coordlist, Paramdata, times=time_vec, ver=1,\n paramnames=sp.arange(Nlags)*sensdict['t_s'])\n ionosigs = IonoContainer(coordlist, Paramdatasig, times=time_vec, ver=1,\n paramnames=sp.arange(Nlags**2).reshape(Nlags, Nlags)*sensdict['t_s'])\n return (ionodata, ionosigs)\n\ndef makeCovmat(lagsDatasum, lagsNoisesum, pulses_s, Nlags):\n \"\"\"\n Makes the covariance matrix for the lags given the noise acf and number\n of pulses.\n \"\"\"\n axvec = sp.roll(sp.arange(lagsDatasum.ndim), 1)\n # Get the covariance matrix\n R = sp.transpose(lagsDatasum/sp.sqrt(2.*pulses_s), axes=axvec)\n Rw = sp.transpose(lagsNoisesum/sp.sqrt(2.*pulses_s), axes=axvec)\n l = sp.arange(Nlags)\n T1, T2 = sp.meshgrid(l, l)\n R0 = R[sp.zeros_like(T1)]\n Rw0 = Rw[sp.zeros_like(T1)]\n Td = sp.absolute(T1-T2)\n Tl = T1>T2\n R12 = R[Td]\n R12[Tl] = sp.conjugate(R12[Tl])\n Rw12 = Rw[Td]\n Rw12[Tl] = sp.conjugate(Rw12[Tl])\n Ctt = R0*R12+R[T1]*sp.conjugate(R[T2])+Rw0*Rw12+Rw[T1]*sp.conjugate(Rw[T2])\n avecback = sp.roll(sp.arange(Ctt.ndim), -2)\n Cttout = sp.transpose(Ctt, avecback)\n return Cttout\n", "meta": {"hexsha": "25009d2a16cdae6c16597db36c2701fdde904b20", "size": 27589, "ext": "py", "lang": "Python", "max_stars_repo_path": "SimISR/radarData.py", "max_stars_repo_name": "jswoboda/RadarDataSim", "max_stars_repo_head_hexsha": "3eb6fcd8601e8ae25acc375e6d933169d14bb40f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-10-06T14:15:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T21:29:07.000Z", "max_issues_repo_path": "SimISR/radarData.py", "max_issues_repo_name": "jswoboda/SimISR", "max_issues_repo_head_hexsha": "3eb6fcd8601e8ae25acc375e6d933169d14bb40f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2016-12-03T23:27:19.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-06T03:04:06.000Z", "max_forks_repo_path": "SimISR/radarData.py", "max_forks_repo_name": "jswoboda/SimISR", "max_forks_repo_head_hexsha": "3eb6fcd8601e8ae25acc375e6d933169d14bb40f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-11-18T08:00:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T13:47:57.000Z", "avg_line_length": 48.0644599303, "max_line_length": 135, "alphanum_fraction": 0.5833846823, "include": true, "reason": "import scipy", "num_tokens": 7356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.28776780965284365, "lm_q1q2_score": 0.1461319078993538}} {"text": "\"\"\"Implementation of target attack.\n Three models (base_incep, adv_incep, res_incep) are used.\n The models are ensembled using mean norm gradient methrod.\n The inferstructure code is based on\n https://github.com/tensorflow/cleverhans/cleverhans/tree/master/\n examples/nips17_adversarial_competition/sample_targeted_attacks/iter_target_class\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport time\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.contrib import slim\n\nfrom lib_adv import utils, attack\n\n\ntf.flags.DEFINE_string(\n 'output_dir',\n '../../intermediate_results/targeted_attacks_output/target_mng',\n 'Output directory with images.')\n\ntf.flags.DEFINE_string(\n 'input_dir', '../../dataset/images_4/', 'Input directory with images.')\n\ntf.flags.DEFINE_string(\n 'checkpoint_path', 'mul_inception_v1.ckpt',\n 'Path to checkpoint for inception network.')\n\ntf.flags.DEFINE_string(\n 'model_names',\n 'base_inception,base_incpt_resnet,adv_inception,adv_incpt_resnet',\n 'names of the multiple models, no space!')\n\ntf.flags.DEFINE_string(\n 'master', '', 'The address of the TensorFlow master to use.')\n\ntf.flags.DEFINE_integer('image_width', 299, 'Width of each input images.')\ntf.flags.DEFINE_integer('image_height', 299, 'Height of each input images.')\ntf.flags.DEFINE_integer('image_depth', 3, 'Depth of each input images.')\ntf.flags.DEFINE_integer('num_classes', 1001, 'Number of classes.')\ntf.flags.DEFINE_integer('num_iter', 20, 'Number of iterations.')\n\ntf.flags.DEFINE_integer('batch_size', 4, '#images process at one time.')\ntf.flags.DEFINE_float('max_epsilon', 16.0, 'Max size of perturbation.')\ntf.flags.DEFINE_integer('norm_ord', 1, 'order of norm to use')\ntf.flags.DEFINE_string('labels_file', 'target_class.csv', 'target classes')\n\n\nclass ModelAttacker():\n \"\"\"A target attacker model, multi-model ensembled.\"\"\"\n def __init__(self, num_classes, image_pixels, model_names, max_epsilon,\n norm_ord, batch_shape):\n \"\"\"Constructs a `ModelAttacker`.\n Set the parameters and build the base and adversarial graph\"\"\"\n prev = time.time()\n\n # image_factor is model dependent\n # Images for inception classifier are normalized to be in [-1, 1] interval\n # scale from [0, 255], range 255 to [-1, 1), range 2\n image_factor = 2.0 / 255.0\n\n list_mnames = model_names.split(',')\n eps, alpha = attack.parameters(max_epsilon, image_factor,\n image_pixels, norm_ord)\n\n utils.logger.debug('norm_ord = %d, alpha = %.3f, models: %s' % (\n norm_ord, alpha, list_mnames))\n\n # Prepare graph\n self._batch_shape = batch_shape\n self._x_input = tf.placeholder(tf.float32, shape=batch_shape)\n self._x_ref = tf.placeholder(tf.float32, shape=batch_shape)\n self._target_labels = tf.placeholder(tf.int32, shape=[batch_shape[0]])\n\n _, pred_labels, logits_w = attack.graph_base(self._x_input,\n num_classes,\n list_mnames)\n self._x_adv, _ = attack.graph_adv(self._x_input, num_classes,\n self._x_ref, self._target_labels,\n pred_labels, logits_w,\n alpha, eps, norm_ord)\n\n utils.logger.debug('graph init: %.3f seconds' % (time.time() - prev))\n\n def run(self, checkpoint_path, master, input_dir, labels_file, output_dir,\n num_iter):\n \"\"\"Run the computation and generate adversarial images\"\"\"\n saver = tf.train.Saver(slim.get_model_variables())\n session_creator = tf.train.ChiefSessionCreator(\n scaffold=tf.train.Scaffold(saver=saver),\n checkpoint_filename_with_path=checkpoint_path,\n master=master)\n\n with tf.train.MonitoredSession(session_creator=session_creator) as sess:\n for filenames, images, labels in utils.load_images(input_dir,\n self._batch_shape,\n labels_file):\n adv_images = np.copy(images)\n for _ in range(num_iter):\n adv_images = sess.run(\n self._x_adv,\n feed_dict={\n self._x_input: adv_images,\n self._x_ref: images,\n self._target_labels: labels})\n utils.save_images(adv_images, filenames, output_dir)\n\n\ndef main(_):\n tf.logging.set_verbosity(tf.logging.INFO)\n prev = time.time()\n\n FLG = tf.flags.FLAGS\n batch_shape = [FLG.batch_size, FLG.image_height, FLG.image_width,\n FLG.image_depth]\n image_pixels = FLG.image_height * FLG.image_width * FLG.image_depth\n\n with tf.Graph().as_default():\n attacker = ModelAttacker(FLG.num_classes, image_pixels, FLG.model_names,\n FLG.max_epsilon, FLG.norm_ord, batch_shape)\n attacker.run(FLG.checkpoint_path, FLG.master, FLG.input_dir,\n FLG.labels_file, FLG.output_dir, FLG.num_iter)\n\n utils.logger.debug('%.3f seconds' % (time.time() - prev))\n\n\nif __name__ == '__main__':\n tf.app.run()\n", "meta": {"hexsha": "1c17307bfb8772c95dd5cfe2108a67acba793a6b", "size": 5176, "ext": "py", "lang": "Python", "max_stars_repo_path": "models_targeted_attacks/target_mng/attack_target_mng.py", "max_stars_repo_name": "huschen/kaggle_nips17_adversarial", "max_stars_repo_head_hexsha": "aa619d937a77ef5f2efee6475b573aea652cf3cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-10-07T06:52:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-29T20:15:12.000Z", "max_issues_repo_path": "models_targeted_attacks/target_mng/attack_target_mng.py", "max_issues_repo_name": "huschen/kaggle_nips17_adversarial", "max_issues_repo_head_hexsha": "aa619d937a77ef5f2efee6475b573aea652cf3cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-10-21T20:01:40.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-19T23:49:20.000Z", "max_forks_repo_path": "models_targeted_attacks/target_mng/attack_target_mng.py", "max_forks_repo_name": "huschen/kaggle_nips17_adversarial", "max_forks_repo_head_hexsha": "aa619d937a77ef5f2efee6475b573aea652cf3cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6268656716, "max_line_length": 83, "alphanum_fraction": 0.6613214838, "include": true, "reason": "import numpy", "num_tokens": 1172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.2598256379609837, "lm_q1q2_score": 0.146067867989326}} {"text": "#!/usr/bin/env python\n#\n# Original filename: loci.py\n#\n# Author: Tim Brandt\n# Email: tbrandt@astro.princeton.edu\n# Date: July 2011\n# \n# Summary: Run LOCI on the input frame sequence.\n# \n\nimport sys, re, gc\nimport numpy as np\nfrom scipy import interpolate\nimport multiprocessing\nfrom progressbar import ProgressBar\nfrom locitools import *\nfrom parallel import *\n\ndef loci(flux, pa, locipar, mem, mode='LOCI', fluxref=None, \n pca_arr=None, rmin=None, r_ex=None, niter=0,\n corr=None, method='matrix', do_partial_sub=True,\n sub_dir='.'):\n\n \"\"\"\n\n Function loci performs Locally Optimized Combination of Images\n on an input dataset (argument 1). It takes at least 4 arguments:\n \n 1. A three-dimensional flux array. The first dimension should run\n over frames.\n 2. The position angle of the image rotator (in radians) in each frame\n 3. The LOCI configuration parameters. This is an object defined in\n adiparam.lociparam\n 4. The available memory (in bytes)\n\n Optional arguments:\n \n 5. 'mode': The mode in which to run the routine. Currently\n accepted values are 'LOCI' (normal LOCI) and 'refine', in\n which case the LOCI coefficients minimize the difference\n between a frame and and a linear combination of the other\n frames with fluxref (argument 6) added. Default 'LOCI'\n 6. 'fluxref': A reference array, to be computed using PCA, to fit\n the PSF locally in each frame. This is treated as an extra\n set of reference frames with infinite angular displacement.\n Ignored if None. Default None.\n 7. 'pca_arr': The flux array used to compute the LOCI subtraction\n coefficients. This can be different from the array (argument\n 1) on which those subtraction coefficients are used. Ignored\n if None, mandatory if mode=='refine'. Default None.\n 8. 'rmin': The minimum radius at which to perform LOCI. If None,\n this is the smaller of the saturation radius and minimum\n radius at which there are always frames to satisfy LOCI's\n angular displacement criterion. Default None.\n 9. 'r_ex': Exclusion/saturation radius. Ignored if None; should\n be calculated using the centroiding algorithm. Default None.\n 10. 'niter': Number of steps in which to split execution to limit\n memory usage. If 0, this is calculated within the routine.\n Default 0.\n 11. 'corr': Cross-correlation coefficients between frames, to use\n only good matches in LOCI. Possibly useful for very large\n datasets, but it can increase run time significantly. Ignored\n if None. Default None.\n 12. 'method': Method for solving the LOCI matrix equation.\n Default is 'matrix', in which case the problem matrix is\n formed and solved using LU- decomposition. Other choices:\n 'lstsq' (SVD), 'eqcoef' (all coefficients are equal and sum to\n 1--similar to mean subtraction). Default: 'matrix'. 'lstsq'\n is more robust but will be significantly slower in most cases.\n 13. 'do_partial_sub': Compute the fractional flux suppression\n using the method described in Brandt+2012. This requires\n argument 'method' to be 'matrix', as it uses the LU\n decomposition of the problem matrix, and it requires argument\n 'mode' to be 'LOCI'. Default True\n\n Function loci returns the flux suppression map if argument\n 'do_partial_sub' is True; otherwise, it returns None.\n \n \"\"\"\n\n np.seterr(all='ignore')\n \n ######################################################################\n # Check arrays and sizes.\n ######################################################################\n \n if mode == 'refine' and fluxref is None:\n print \"Cannot apply feedback to LOCI without reference output.\"\n sys.exit(1)\n if fluxref is not None:\n assert fluxref.shape == flux.shape, \\\n \"Flux and reference arrays must have the same shape.\"\n assert len(flux.shape) == 3, \"Flux array must have three dimensions.\"\n assert niter >= 0 and niter < flux.shape[0], \\\n \"Argument niter to loci must be at least 0 and less than nframes\"\n assert mode == 'refine' or mode == 'LOCI', \\\n \"Argument mode = \" + mode + \" to routine loci is not understood.\" \\\n + \"\\nPlease use either 'refine' or 'LOCI'.\"\n \n ######################################################################\n # Create and populate array fluxsmooth to calculate LOCI coefficients\n ######################################################################\n \n nframes = flux.shape[0]\n #ngroup = 1 + int((nframes - 1) / locipar.max_n)\n ngroup = 1\n oldshape = flux.shape\n fluxsmooth = np.ndarray(flux.shape, np.float32)\n\n if mode == 'LOCI' and fluxref is not None:\n fluxsmooth[:] = fluxref[i]\n elif mode == 'refine' and fluxref is not None:\n fluxsmooth[:] = flux + fluxref\n elif mode == 'refine':\n print \"Cannot call loci in 'refine' mode without a reference array.\"\n sys.exit()\n else:\n fluxsmooth[:] = flux\n\n fluxsmooth = np.reshape(fluxsmooth, (nframes, -1))\n flux = np.reshape(flux, (nframes, -1))\n if pca_arr is not None:\n pca_arr = np.reshape(pca_arr, (pca_arr.shape[0], -1))\n\n ######################################################################\n # Create arrays sorted by radius to facilitate division of frames\n # into optimization and subtraction regions.\n ######################################################################\n\n print \"\\nSorting radius array to compute indices at annuli.\"\n rindex, rsort, thetasort = sorted_arrays(oldshape)\n\n optreg = int(np.pi * locipar.fwhm**2 / 4 * locipar.npsf)\n minsep = locipar.nfwhm * locipar.fwhm\n if rmin is None:\n rmin = int(minsep * 2 / (pa.max() - pa.min())) + 1\n rmin = max(r_ex - r_ex % 5, rmin - rmin % 5) + 5\n if r_ex is None:\n r_ex = rmin\n\n ######################################################################\n # Calculate the total number of subtraction regions and the \n # (r, theta) boundaries of those regions. \n ######################################################################\n \n totn, r1, r2, theta1, theta2 = calczones(rmin, locipar.rmax, locipar.dr0, \n optreg)\n\n ######################################################################\n # Coefficients for flux suppression by a displaced source\n # They are pre-computed for an azimuthally averaged HiCIAO PSF.\n ######################################################################\n\n if do_partial_sub:\n try:\n sub_coefs = np.zeros((totn, nframes), np.float32)\n x, y = np.loadtxt(sub_dir + '/partial_sub.dat').T\n partial_sub = interpolate.UnivariateSpline(x, y, k=3, s=0)\n except:\n print \"Unable to read flux loss data from file partial_sub.dat.\"\n print \"Cannot calculate a fractional flux loss map in loci.\"\n do_partial_sub = False\n \n ######################################################################\n # Calculate where to add mock sources for flux loss analysis.\n # We will add a positive source (one at a time) at the center of\n # each subtraction region, and negative sources azimuthally\n # displaced from it. See Appendix of Brandt+2012 for explanation.\n ######################################################################\n \n r_avg = 0.5 * (r1 + r2)\n phi = 0.5 * (theta1 + theta2)\n dphi = minsep * 2. / r_avg\n if do_partial_sub:\n np.putmask(dphi, dphi < np.std(pa), np.std(pa))\n\n ######################################################################\n # Size of PSF regions will be 2 * n + 1. We will compute them\n # later; just store r**2 for now.\n ######################################################################\n \n n = 7\n x, y = np.meshgrid(np.arange(2 * n + 1) - n, np.arange(2 * n + 1) - n)\n r_sq_psf = (x**2 + y**2 + 0.) / (locipar.fwhm / 2)**2\n dy, dx = [oldshape[1] // 2 + 0.5, oldshape[2] // 2 + 0.5]\n\n xp0 = (-r_avg * np.cos(phi) + dx).astype(int) - n\n yp0 = (-r_avg * np.sin(phi) + dy).astype(int) - n\n xp1 = (-r_avg * np.cos(phi - dphi) + dx).astype(int) - n\n yp1 = (-r_avg * np.sin(phi - dphi) + dy).astype(int) - n\n xp2 = (-r_avg * np.cos(phi + dphi) + dx).astype(int) - n\n yp2 = (-r_avg * np.sin(phi + dphi) + dy).astype(int) - n\n xp3 = (-r_avg * np.cos(phi - 2 * dphi) + dx).astype(int) - n\n yp3 = (-r_avg * np.sin(phi - 2 * dphi) + dy).astype(int) - n\n xp4 = (-r_avg * np.cos(phi + 2 * dphi) + dx).astype(int) - n\n yp4 = (-r_avg * np.sin(phi + 2 * dphi) + dy).astype(int) - n\n\n ######################################################################\n # Two references to the same array, so that we can modify it\n # with two indices and access it with one\n ######################################################################\n \n sub_arr_full = np.zeros((oldshape[1], oldshape[2]))\n sub_arr = np.reshape(sub_arr_full, -1)\n\n p = ProgressBar('green', width=30, block='=', lastblock='>', empty=' ')\n \n if mode == 'LOCI':\n print \"Running LOCI on {0} regions in {1} frames out to {2} pixels in radius.\".format(totn, pa.size, int(locipar.rmax))\n elif mode == 'refine':\n print \"Refining LOCI on {0} regions in {1} frames out to {2} pixels in radius.\".format(totn, pa.size, int(locipar.rmax))\n else:\n print \"Argument mode=\" + mode + \" to loci.py not recognized.\"\n sys.exit()\n \n ######################################################################\n # Run LOCI on each optimization section. Do the sections in parallel,\n # with all of the frames processed in each job. Split into multiple\n # execution blocks due to the large memory demands of the index\n # arrays.\n ######################################################################\n\n ######################################################################\n # Automatically set niter to use < 10% of the total memory.\n # In the 'refine' mode, this will be doubled, and incomplete freeing\n # seems to add a further factor of 2.\n ######################################################################\n\n if niter == 0:\n mem_iter = optreg * 4. * nframes / mem\n if mode == 'refine':\n niter = max(int(totn * mem_iter * 60), 1)\n else:\n niter = max(int(totn * mem_iter * 30), 1)\n\n for i in range(niter):\n\n tasks = multiprocessing.Queue()\n results = multiprocessing.Queue()\n ncpus = multiprocessing.cpu_count()\n consumers = [ Consumer(tasks, results)\n for j in range(ncpus) ]\n for w in consumers:\n w.start()\n\n i1 = totn // niter * i\n i2 = totn // niter * (i + 1)\n if i == niter - 1:\n i2 = totn\n\n ##################################################################\n # Compute the indices in the original flux array corresponding\n # to the optimization and subtraction regions, using the \n # sorted radius and angle arrays to make initial guesses.\n ##################################################################\n\n iopt, isub, nopt, nsub = annulus_indices(\n r_ex, r1[i1:i2], r2[i1:i2], theta1[i1:i2], theta2[i1:i2], \n optreg, rindex, rsort, thetasort, p, i1, totn,\n locipar.fwhm, innerfrac=locipar.innerfrac) \n \n for j in range(i1, i2):\n k = j - i1\n\n ##################################################################\n # Add pseudo-test sources to compute the fractional flux loss.\n # We need to do this independently for each region, so we will\n # remove these same sources after submitting the jobs.\n ##################################################################\n\n if do_partial_sub:\n n = r_sq_psf.shape[0]\n \n sig = np.sort([2.5, (dphi[j] * r_avg[j] / 3), 4])[1]\n sig /= locipar.fwhm / 2.\n psf = np.exp(-r_sq_psf) + 0.05 * np.exp(-r_sq_psf / 3.)\n psf1 = np.exp(-r_sq_psf / (2. * sig**2))\n psf2 = np.exp(-r_sq_psf / (2. * 2 * sig**2))\n psf1 *= np.sum(psf) / np.sum(psf1) / 3.\n psf2 *= np.sum(psf) / np.sum(psf2) / 6.\n \n sub_arr_full[yp0[j]:yp0[j] + n, xp0[j]:xp0[j] + n] += psf\n sub_arr_full[yp1[j]:yp1[j] + n, xp1[j]:xp1[j] + n] -= psf1\n sub_arr_full[yp2[j]:yp2[j] + n, xp2[j]:xp2[j] + n] -= psf1\n sub_arr_full[yp3[j]:yp3[j] + n, xp3[j]:xp3[j] + n] -= psf2\n sub_arr_full[yp4[j]:yp4[j] + n, xp4[j]:xp4[j] + n] -= psf2\n \n sub = sub_arr[iopt[k, :nopt[k]]].copy()\n \n sub_arr_full[yp0[j]:yp0[j] + n, xp0[j]:xp0[j] + n] = 0\n sub_arr_full[yp1[j]:yp1[j] + n, xp1[j]:xp1[j] + n] = 0\n sub_arr_full[yp2[j]:yp2[j] + n, xp2[j]:xp2[j] + n] = 0\n sub_arr_full[yp3[j]:yp3[j] + n, xp3[j]:xp3[j] + n] = 0\n sub_arr_full[yp4[j]:yp4[j] + n, xp4[j]:xp4[j] + n] = 0\n else:\n sub = None\n \n if corr is not None:\n corr_rad = corr[int(r1[j])]\n else:\n corr_rad = None\n if pca_arr is not None:\n pcaopt = pca_arr[:, iopt[k, 0:nopt[k]]]\n pcasub = pca_arr[:, isub[k, 0:nsub[k]]]\n else:\n pcaopt = None\n pcasub = None\n \n tasks.put(Task(j, loci_sub, (fluxsmooth[:, iopt[k, 0:nopt[k]]],\n flux[:, isub[k, 0:nsub[k]]],\n pa, minsep, r_avg[j], pcaopt, pcasub,\n partial_sub, ngroup, method,\n corr_rad, sub))) \n \n ##################################################################\n # \"Poison Pills\" to break execution\n ##################################################################\n \n for j in range(ncpus):\n tasks.put(None)\n\n for j in range(i1, i2):\n p.render([i2 * 100 / totn, (j + 1) * 100 / totn],\n ['Calculating Indices for Region {0}'.format(i2),\n 'Processing Region {0} at Radius {1}'.format(j + 1, int(r1[j]))])\n index, result = results.get()\n if mode == 'LOCI':\n flux[:, isub[index - i1, 0:nsub[index - i1]]], \\\n sub_coefs[index] = result\n elif mode == 'refine':\n flux[:, isub[index - i1, 0:nsub[index - i1]]] = result\n \n del iopt, isub, nopt, nsub\n del tasks, results, consumers\n gc.collect()\n\n flux = np.reshape(flux, oldshape)\n if pca_arr is not None:\n pca_arr = np.reshape(pca_arr, (pca_arr.shape[0], oldshape[1], oldshape[2]))\n\n ##################################################################\n # Go from fractional flux loss points to a smoothed map\n ##################################################################\n \n if do_partial_sub:\n print \"Calculating map of fractional flux loss.\"\n return partial_sub_map(r1, r2, theta1, theta2, sub_coefs, pa)\n else:\n return None\n", "meta": {"hexsha": "89a90d7629334ca37c85b0baaedde3fc159bff4a", "size": 15753, "ext": "py", "lang": "Python", "max_stars_repo_path": "loci/loci.py", "max_stars_repo_name": "t-brandt/acorns-adi", "max_stars_repo_head_hexsha": "6645fae7878a1801beeda0c6604b01e61f37ca15", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-10-30T16:29:51.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-30T16:29:51.000Z", "max_issues_repo_path": "loci/loci.py", "max_issues_repo_name": "t-brandt/acorns-adi", "max_issues_repo_head_hexsha": "6645fae7878a1801beeda0c6604b01e61f37ca15", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "loci/loci.py", "max_forks_repo_name": "t-brandt/acorns-adi", "max_forks_repo_head_hexsha": "6645fae7878a1801beeda0c6604b01e61f37ca15", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.8803418803, "max_line_length": 128, "alphanum_fraction": 0.4965403415, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.2628418489200747, "lm_q1q2_score": 0.14573804218177222}} {"text": "\"\"\"This module implements an ORIGEN v2.2 transmutation solver.\n\"\"\"\nfrom __future__ import print_function, division\n\nimport os\nimport subprocess\nimport tempfile\nfrom collections import Mapping\nfrom warnings import warn\nfrom pyne.utils import QAWarning\n\nimport numpy as np\n\nfrom pyne import data\nfrom pyne import rxname\nfrom pyne import nucname\nfrom pyne import nuc_data\nfrom pyne import origen22\nfrom pyne import utils\nfrom pyne.material import Material, from_atom_frac\nfrom pyne.xs.data_source import NullDataSource, SimpleDataSource, EAFDataSource\nfrom pyne.xs.cache import XSCache\n\nwarn(__name__ + \" is not yet QA compliant.\", QAWarning)\n\nclass Transmuter(object):\n \"\"\"A class for transmuting materials using ORIGEN v2.2.\"\"\"\n\n def __init__(self, t=0.0, phi=0.0, temp=300.0, tol=1e-7, cwd='',\n base_tape9=origen22.BASE_TAPE9, xscache=None, \n o2exe='o2_therm_linux.exe', *args, **kwargs):\n \"\"\"Parameters\n ----------\n t : float\n Transmutations time [sec].\n phi : float or array of floats\n Neutron flux vector [n/cm^2/sec]. Currently this must either be \n a scalar or match the group structure of EAF.\n temp : float, optional\n Temperature [K] of material, defaults to 300.0.\n tol : float\n Tolerance level for chain truncation.\n cwd : str, optional\n Current working directory for origen runs. Defaults to this dir.\n base_tape9 : str or dict, optional\n A base TAPE9.INP file. If this is a str it is interpreted as a path \n to a file, which is then read in and parsed. If this is a dict, it is\n assumed to be in the format described in the main origen22 module.\n xscache : XSCache, optional\n A cross section cache to generate cross sections with.\n o2exe : str, optional\n Name or path to ORIGEN 2.2 executable.\n args : tuple, optional\n Other arguments ignored for compatibility with other Transmuters.\n kwargs : dict, optional\n Other keyword arguments ignored for compatibility with other Transmuters.\n \"\"\"\n if not isinstance(base_tape9, Mapping):\n base_tape9 = origen22.parse_tape9(tape9=base_tape9)\n self.base_tape9 = base_tape9\n\n if xscache is None:\n eafds = EAFDataSource()\n eafds.load(temp=temp)\n gs = np.array([eafds.src_group_struct[0], eafds.src_group_struct[-1]])\n eafds.dst_group_struct = gs\n xscache = XSCache(group_struct=gs, data_source_classes=[SimpleDataSource, \n NullDataSource])\n xscache.load(temp=temp)\n xscache.data_sources.insert(0, eafds)\n self.xscache = xscache\n\n self.t = t\n self._phi = None\n self.phi = phi\n self.temp = temp\n self.tol = tol\n self.cwd = os.path.abspath(cwd)\n self.o2exe = o2exe\n\n @property\n def phi(self):\n return self._phi\n\n @phi.setter\n def phi(self, flux):\n \"\"\"Ensures that the flux is correctly formatted.\"\"\"\n flux = np.asarray(flux)\n if flux.ndim == 0:\n _ = np.empty(175, float)\n _.fill(flux / 175.0)\n flux = _\n elif flux.ndim == 1 and flux.shape[0] != 175:\n raise ValueError(\"Group structure must match EAF.\")\n elif flux.ndim > 1:\n raise ValueError(\"The flux vector must be 0- or 1-dimensional.\")\n if not np.all(flux >= 0.0):\n raise ValueError(\"Flux entries must be non-negative.\")\n for ds in self.xscache.data_sources:\n ds.src_phi_g = flux\n self.xscache['phi_g'] = np.array([flux.sum()])\n self._phi = flux\n\n def transmute(self, x, t=None, phi=None, tol=None, cwd=None, xscache=None, \n o2exe=None, *args, **kwargs):\n \"\"\"Transmutes a material into its daughters.\n\n Parameters\n ----------\n x : Material or similar\n Input material for transmutation.\n t : float\n Transmutations time [sec].\n phi : float or array of floats\n Neutron flux vector [n/cm^2/sec]. Currently this must either be \n a scalar or match the group structure of EAF.\n tol : float\n Tolerance level for chain truncation.\n cwd : str, optional\n Current working directory for origen runs. Defaults to this dir.\n xscache : XSCache, optional\n A cross section cache to generate cross sections with.\n o2exe : str, optional\n Name or path to ORIGEN 2.2 executable.\n\n Returns\n -------\n y : Material\n The output material post-transmutation.\n\n \"\"\"\n if not isinstance(x, Material):\n x = Material(x)\n if t is not None:\n self.t = t\n if phi is not None:\n self.phi = phi\n if tol is not None:\n self.tol = tol\n if cwd is not None:\n self.cwd = os.path.abspath(cwd)\n if xscache is not None:\n self.xscache = xscache\n if o2exe is not None:\n self.o2exe = o2exe\n\n # prepare new tape9\n nucs = set(x.comp.keys())\n base_tape9 = self.base_tape9\n decay_nlb, xsfpy_nlb = origen22.nlbs(base_tape9)\n new_tape9 = origen22.xslibs(nucs=nucs, xscache=self.xscache, nlb=xsfpy_nlb)\n t9 = origen22.merge_tape9([new_tape9, base_tape9])\n\n # write out files\n origen22.write_tape4(x, outfile=os.path.join(self.cwd, 'TAPE4.INP'))\n origen22.write_tape5_irradiation('IRF', self.t/86400.0, self.xscache['phi_g'][0], \n outfile=os.path.join(self.cwd, 'TAPE5.INP'), decay_nlb=decay_nlb, \n xsfpy_nlb=xsfpy_nlb, cut_off=self.tol)\n origen22.write_tape9(t9, outfile=os.path.join(self.cwd, 'TAPE9.INP'))\n\n # run origen & get results\n f = tempfile.NamedTemporaryFile()\n try:\n subprocess.check_call([self.o2exe], cwd=self.cwd, stdout=f, stderr=f)\n except subprocess.CalledProcessError:\n f.seek(0)\n print(\"ORIGEN output:\\n\\n{0}\".format(f.read()))\n raise\n finally:\n f.close()\n t6 = origen22.parse_tape6(tape6=os.path.join(self.cwd, 'TAPE6.OUT'))\n y = t6['materials'][-1]\n return y\n\n", "meta": {"hexsha": "f774c2233b9eb69a83b58c597ddb2eed30e59313", "size": 6437, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyne/transmute/origen22.py", "max_stars_repo_name": "makoziol0/pyne", "max_stars_repo_head_hexsha": "660b1bdd608d9b227d6a432737303f7e82af4a25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-10T14:14:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-10T14:14:11.000Z", "max_issues_repo_path": "pyne/transmute/origen22.py", "max_issues_repo_name": "makoziol0/pyne", "max_issues_repo_head_hexsha": "660b1bdd608d9b227d6a432737303f7e82af4a25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 58, "max_issues_repo_issues_event_min_datetime": "2019-01-07T16:13:26.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-09T15:56:26.000Z", "max_forks_repo_path": "pyne/transmute/origen22.py", "max_forks_repo_name": "makoziol0/pyne", "max_forks_repo_head_hexsha": "660b1bdd608d9b227d6a432737303f7e82af4a25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7828571429, "max_line_length": 90, "alphanum_fraction": 0.5968618922, "include": true, "reason": "import numpy", "num_tokens": 1614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.2628418373713166, "lm_q1q2_score": 0.14573803577832695}} {"text": "from jax.config import config; config.update(\"jax_enable_x64\", True)\n\nimport jax\nimport numpy as np\n\nfrom fe import topology\n\nfrom timemachine.lib import potentials, custom_ops\nfrom timemachine.lib import LangevinIntegrator\n\nfrom ff.handlers import openmm_deserializer\n\ndef get_romol_conf(mol):\n \"\"\"Coordinates of mol's 0th conformer, in nanometers\"\"\"\n conformer = mol.GetConformer(0)\n guest_conf = np.array(conformer.GetPositions(), dtype=np.float64)\n return guest_conf/10 # from angstroms to nm\n\nclass BaseFreeEnergy():\n\n @staticmethod\n def _get_integrator(combined_masses):\n \"\"\"\n Get a integrator. The resulting impl must be bound to a python handle\n whose lifetime is concurrent with that of the context.\n \"\"\"\n seed = np.random.randint(np.iinfo(np.int32).max)\n\n return LangevinIntegrator(\n 300.0,\n 1.5e-3,\n 1.0,\n combined_masses,\n seed\n )\n\n # this will be eventually gRPC'd out to a worker\n @staticmethod\n def _simulate(lamb, box, x0, v0, final_potentials, integrator, equil_steps, prod_steps):\n all_impls = []\n bonded_impls = []\n nonbonded_impls = []\n\n # set up observables for du_dps here as well.\n\n du_dp_obs = []\n\n for bps in final_potentials:\n obs_list = []\n\n for bp in bps:\n impl = bp.bound_impl(np.float32)\n\n if isinstance(bp, potentials.InterpolatedPotential) or isinstance(bp, potentials.LambdaPotential):\n bp = bp.get_u_fn()\n\n if isinstance(bp, potentials.Nonbonded):\n nonbonded_impls.append(impl)\n else:\n bonded_impls.append(impl)\n\n all_impls.append(impl)\n obs_list.append(custom_ops.AvgPartialUPartialParam(impl, 5))\n\n du_dp_obs.append(obs_list)\n\n intg_impl = integrator.impl()\n # context components: positions, velocities, box, integrator, energy fxns\n ctxt = custom_ops.Context(\n x0,\n v0,\n box,\n intg_impl,\n all_impls\n )\n\n # equilibration\n for step in range(equil_steps):\n ctxt.step(lamb)\n\n bonded_du_dl_obs = custom_ops.FullPartialUPartialLambda(bonded_impls, 5)\n nonbonded_du_dl_obs = custom_ops.FullPartialUPartialLambda(nonbonded_impls, 5)\n\n # add observable\n ctxt.add_observable(bonded_du_dl_obs)\n ctxt.add_observable(nonbonded_du_dl_obs)\n\n for obs_list in du_dp_obs:\n for obs in obs_list:\n ctxt.add_observable(obs)\n\n for _ in range(prod_steps):\n ctxt.step(lamb)\n\n bonded_full_du_dls = bonded_du_dl_obs.full_du_dl()\n nonbonded_full_du_dls = nonbonded_du_dl_obs.full_du_dl()\n\n bonded_mean, bonded_std = np.mean(bonded_full_du_dls), np.std(bonded_full_du_dls)\n nonbonded_mean, nonbonded_std = np.mean(nonbonded_full_du_dls), np.std(nonbonded_full_du_dls)\n\n # keep the structure of grads the same as that of final_potentials so we can properly\n # form their vjps.\n grads = []\n for obs_list in du_dp_obs:\n grad_list = []\n for obs in obs_list:\n grad_list.append(obs.avg_du_dp())\n grads.append(grad_list)\n\n return (bonded_mean, bonded_std), (nonbonded_mean, nonbonded_std), grads\n\n\n# this class is serializable.\nclass AbsoluteFreeEnergy(BaseFreeEnergy):\n\n def __init__(self, mol, ff):\n \"\"\"\n Compute the absolute free energy of a molecule via 4D decoupling.\n\n Parameters\n ----------\n mol: rdkit mol\n Ligand to be decoupled\n\n ff: ff.Forcefield\n Ligand forcefield\n\n \"\"\"\n self.mol = mol\n self.ff = ff\n self.top = topology.BaseTopology(mol, ff)\n\n # this can be used for both the solvent leg and the complex leg\n def host_edge(self, lamb, host_system, host_coords, box, equil_steps=10000, prod_steps=100000):\n \"\"\"\n Run equilibrium decoupling simulation at a given value of lambda in a host environment.\n\n Parameters\n ----------\n lamb: float [0, 1]\n 0 is the fully interacting system, and 1 is the non-interacting system\n\n host_system: openmm.System\n OpenMM System object to be deserialized. The host can be simply a box of water, or a fully\n solvated protein\n\n host_coords: np.array of shape [..., 3]\n Host coordinates, in nanometers. It should be properly minimized and not have clashes\n with the ligand coordinates.\n\n box: np.array [3,3]\n Periodic boundary conditions, in nanometers.\n\n equil_steps: float\n Number of steps to run equilibration. Statistics are not gathered.\n\n prod_steps: float\n Number of steps to run production. Statistics are gathered.\n\n\n Returns\n -------\n float, float\n Returns a pair of average du_dl values for bonded and nonbonded terms.\n\n \"\"\"\n\n ligand_masses = [a.GetMass() for a in self.mol.GetAtoms()]\n ligand_coords = get_romol_conf(self.mol)\n\n host_bps, host_masses = openmm_deserializer.deserialize_system(host_system, cutoff=1.2)\n num_host_atoms = host_coords.shape[0]\n\n final_potentials = []\n final_vjp_and_handles = []\n\n for bp in host_bps:\n if isinstance(bp, potentials.Nonbonded):\n host_p = bp\n else:\n final_potentials.append([bp])\n final_vjp_and_handles.append(None)\n\n hgt = topology.HostGuestTopology(host_p, self.top)\n\n # setup the parameter handlers for the ligand\n bonded_tuples = [\n [hgt.parameterize_harmonic_bond, self.ff.hb_handle],\n [hgt.parameterize_harmonic_angle, self.ff.ha_handle],\n [hgt.parameterize_proper_torsion, self.ff.pt_handle],\n [hgt.parameterize_improper_torsion, self.ff.it_handle]\n ]\n\n # instantiate the vjps while parameterizing (forward pass)\n for fn, handle in bonded_tuples:\n params, vjp_fn, potential = jax.vjp(fn, handle.params, has_aux=True)\n final_potentials.append([potential.bind(params)])\n final_vjp_and_handles.append((vjp_fn, handle))\n\n nb_params, vjp_fn, nb_potential = jax.vjp(hgt.parameterize_nonbonded, self.ff.q_handle.params, self.ff.lj_handle.params, has_aux=True)\n final_potentials.append([nb_potential.bind(nb_params)])\n final_vjp_and_handles.append([vjp_fn])\n\n combined_masses = np.concatenate([host_masses, ligand_masses])\n combined_coords = np.concatenate([host_coords, ligand_coords])\n\n return self._simulate(\n lamb,\n box,\n combined_coords,\n np.zeros_like(combined_coords),\n final_potentials,\n self._get_integrator(combined_masses),\n equil_steps,\n prod_steps\n )\n\n\n# this class is serializable.\nclass RelativeFreeEnergy(BaseFreeEnergy):\n\n def __init__(self, mol_a, mol_b, core, ff):\n self.mol_a = mol_a\n self.mol_b = mol_b\n self.core = core\n self.ff = ff\n self.top = topology.SingleTopology(mol_a, mol_b, core, ff)\n\n def _get_integrator(self, combined_masses):\n \"\"\"\n Get a integrator. The resulting impl must be bound to a python handle\n whose lifetime is concurrent with that of the context.\n \"\"\"\n seed = np.random.randint(np.iinfo(np.int32).max)\n\n return LangevinIntegrator(\n 300.0,\n 1.5e-3,\n 1.0,\n combined_masses,\n seed\n )\n\n def vacuum_edge(self, lamb, equil_steps=10000, prod_steps=100000):\n \"\"\"\n Run a vacuum decoupling simulation at a given value of lambda.\n\n Parameters\n ----------\n lamb: float [0, 1]\n 0 is the fully interacting system, and 1 is the non-interacting system\n\n equil_steps: float\n Number of steps to run equilibration. Statistics are not gathered.\n\n prod_steps: float\n Number of steps to run production. Statistics are gathered.\n\n Returns\n -------\n float, float\n Returns a pair of average du_dl values for bonded and nonbonded terms.\n\n \"\"\"\n final_potentials = []\n final_vjp_and_handles = []\n\n ligand_masses_a = [a.GetMass() for a in self.mol_a.GetAtoms()]\n ligand_masses_b = [b.GetMass() for b in self.mol_b.GetAtoms()]\n\n ligand_coords_a = get_romol_conf(self.mol_a)\n ligand_coords_b = get_romol_conf(self.mol_b)\n\n bonded_tuples = [\n [self.top.parameterize_harmonic_bond, self.ff.hb_handle],\n [self.top.parameterize_harmonic_angle, self.ff.ha_handle],\n [self.top.parameterize_proper_torsion, self.ff.pt_handle],\n [self.top.parameterize_improper_torsion, self.ff.it_handle]\n ]\n\n # instantiate the vjps while parameterizing (forward pass)\n for fn, handle in bonded_tuples:\n (src_params, dst_params, uni_params), vjp_fn, (src_potential, dst_potential, uni_potential) = jax.vjp(fn, handle.params, has_aux=True)\n final_potentials.append([src_potential.bind(src_params), dst_potential.bind(dst_params), uni_potential.bind(uni_params)])\n final_vjp_and_handles.append((vjp_fn, handle))\n\n nb_params, vjp_fn, nb_potential = jax.vjp(self.top.parameterize_nonbonded, self.ff.q_handle.params, self.ff.lj_handle.params, has_aux=True)\n final_potentials.append([nb_potential.bind(nb_params)])\n final_vjp_and_handles.append([vjp_fn])\n\n combined_masses = np.mean(self.top.interpolate_params(ligand_masses_a, ligand_masses_b), axis=0)\n\n src_conf, dst_conf = self.top.interpolate_params(ligand_coords_a, ligand_coords_b)\n combined_coords = np.mean(self.top.interpolate_params(ligand_coords_a, ligand_coords_b), axis=0)\n\n box = np.eye(3) * 100.0\n\n return self._simulate(\n lamb,\n box,\n combined_coords,\n np.zeros_like(combined_coords),\n final_potentials,\n self._get_integrator(combined_masses),\n equil_steps,\n prod_steps\n )\n\n def host_edge(self, lamb, host_system, host_coords, box, equil_steps=10000, prod_steps=100000):\n \"\"\"\n Run equilibrium decoupling simulation at a given value of lambda in a host environment.\n\n Parameters\n ----------\n lamb: float [0, 1]\n 0 is the fully interacting system, and 1 is the non-interacting system\n\n host_system: openmm.System\n OpenMM System object to be deserialized. The host can be simply a box of water, or a fully\n solvated protein\n\n host_coords: np.array of shape [..., 3]\n Host coordinates, in nanometers. It should be properly minimized and not have clashes\n with the ligand coordinates.\n\n box: np.array [3,3]\n Periodic boundary conditions, in nanometers.\n\n equil_steps: float\n Number of steps to run equilibration. Statistics are not gathered.\n\n prod_steps: float\n Number of steps to run production. Statistics are gathered.\n\n Returns\n -------\n float, float\n Returns a pair of average du_dl values for bonded and nonbonded terms.\n\n \"\"\"\n\n ligand_masses_a = [a.GetMass() for a in self.mol_a.GetAtoms()]\n ligand_masses_b = [b.GetMass() for b in self.mol_b.GetAtoms()]\n\n # extract the 0th conformer\n ligand_coords_a = get_romol_conf(self.mol_a)\n ligand_coords_b = get_romol_conf(self.mol_b)\n\n host_bps, host_masses = openmm_deserializer.deserialize_system(host_system, cutoff=1.2)\n num_host_atoms = host_coords.shape[0]\n\n final_potentials = []\n final_vjp_and_handles = []\n\n # keep the bonded terms in the host the same.\n # but we keep the nonbonded term for a subsequent modification\n for bp in host_bps:\n if isinstance(bp, potentials.Nonbonded):\n host_p = bp\n else:\n final_potentials.append([bp])\n # (ytz): no protein ff support for now, so we skip their vjps\n final_vjp_and_handles.append(None)\n\n hgt = topology.HostGuestTopology(host_p, self.top)\n\n # setup the parameter handlers for the ligand\n bonded_tuples = [\n [hgt.parameterize_harmonic_bond, self.ff.hb_handle],\n [hgt.parameterize_harmonic_angle, self.ff.ha_handle],\n [hgt.parameterize_proper_torsion, self.ff.pt_handle],\n [hgt.parameterize_improper_torsion, self.ff.it_handle]\n ]\n\n # instantiate the vjps while parameterizing (forward pass)\n for fn, handle in bonded_tuples:\n (src_params, dst_params, uni_params), vjp_fn, (src_potential, dst_potential, uni_potential) = jax.vjp(fn, handle.params, has_aux=True)\n final_potentials.append([src_potential.bind(src_params), dst_potential.bind(dst_params), uni_potential.bind(uni_params)])\n final_vjp_and_handles.append((vjp_fn, handle))\n\n nb_params, vjp_fn, nb_potential = jax.vjp(hgt.parameterize_nonbonded, self.ff.q_handle.params, self.ff.lj_handle.params, has_aux=True)\n final_potentials.append([nb_potential.bind(nb_params)])\n final_vjp_and_handles.append([vjp_fn, (self.ff.q_handle, self.ff.lj_handle)]) # (ytz): note the handlers are a tuple, this is checked later\n\n combined_masses = np.concatenate([host_masses, np.mean(self.top.interpolate_params(ligand_masses_a, ligand_masses_b), axis=0)])\n\n src_conf, dst_conf = self.top.interpolate_params(ligand_coords_a, ligand_coords_b)\n combined_coords = np.concatenate([host_coords, np.mean(self.top.interpolate_params(ligand_coords_a, ligand_coords_b), axis=0)])\n\n # (ytz): us is short form for mean and std dev.\n bonded_us, nonbonded_us, grads = self._simulate(\n lamb,\n box,\n combined_coords,\n np.zeros_like(combined_coords),\n final_potentials,\n self._get_integrator(combined_masses),\n equil_steps,\n prod_steps\n )\n\n\n grads_and_handles = []\n\n for du_dqs, vjps_and_handles in zip(grads, final_vjp_and_handles):\n if vjps_and_handles is not None:\n vjp_fn = vjps_and_handles[0]\n handles = vjps_and_handles[1]\n\n # we need to get the shapes correct (eg. nonbonded vjp emits an ndarray, not a list.)\n\n # (ytz): so far nonbonded grads is the only term that map back out to two \n # vjp handlers (charge and lj). the vjp also expects an nd.array, not a list. So we kill\n # two birds with one stone here, but this is quite brittle and should be refactored later on.\n if type(handles) == tuple:\n # handle nonbonded terms\n du_dps = vjp_fn(du_dqs[0])\n for du_dp, handler in zip(du_dps, handles):\n grads_and_handles.append((du_dp, type(handler)))\n else:\n du_dp = vjp_fn(du_dqs)\n # bonded terms return a list, so we need to flatten it here\n grads_and_handles.append((du_dp[0], type(handles)))\n\n return bonded_us, nonbonded_us, grads_and_handles", "meta": {"hexsha": "60f1b08ba139b031baf021bc476329a3079aa62a", "size": 15645, "ext": "py", "lang": "Python", "max_stars_repo_path": "fe/free_energy.py", "max_stars_repo_name": "schmolly/timemachine", "max_stars_repo_head_hexsha": "7d13a0406dc2d09ac67892988641ba4965bfb206", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fe/free_energy.py", "max_issues_repo_name": "schmolly/timemachine", "max_issues_repo_head_hexsha": "7d13a0406dc2d09ac67892988641ba4965bfb206", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fe/free_energy.py", "max_forks_repo_name": "schmolly/timemachine", "max_forks_repo_head_hexsha": "7d13a0406dc2d09ac67892988641ba4965bfb206", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8117647059, "max_line_length": 147, "alphanum_fraction": 0.6297219559, "include": true, "reason": "import numpy,import jax,from jax", "num_tokens": 3658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604274, "lm_q2_score": 0.26284182582255894, "lm_q1q2_score": 0.14573802937488192}} {"text": "# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\n# Need to put the functions in the path\n# Probably not necessary if I understood Python/Git/modules better\nimport os \nimport sys\nparent_directory = os.getcwd().rsplit(sep='\\\\',maxsplit=1)[0]\nif parent_directory not in sys.path:\n sys.path.insert(1, parent_directory)\n \n\nimport initElements_P3\ned = initElements_P3.initElements()\n\nimport numpy as np\n\ndef In_doped_GaN():\n # N Ga In Da\n # Define possible peaks\n pk_data = np.array( [ (1, 0, 0, ed['N'].isotopes[14][0]/2),\n (1, 0, 0, ed['N'].isotopes[14][0]/1),\n (1, 0, 0, ed['N'].isotopes[15][0]/1),\n (1, 0, 0, ed['N'].isotopes[15][0]+ed['H'].isotopes[1][0]),\n (0, 1, 0, ed['Ga'].isotopes[69][0]/3),\n (0, 1, 0, ed['Ga'].isotopes[71][0]/3),\n (2, 0, 0, ed['N'].isotopes[14][0]*2),\n (2, 0, 0, ed['N'].isotopes[14][0]+ed['N'].isotopes[15][0]),\n (2, 0, 0, ed['N'].isotopes[14][0]+ed['N'].isotopes[15][0]+ed['H'].isotopes[1][0]),\n (0, 1, 0, ed['Ga'].isotopes[69][0]/2),\n (0, 1, 0, ed['Ga'].isotopes[71][0]/2),\n (1, 1, 0, (ed['N'].isotopes[14][0] + ed['Ga'].isotopes[69][0])/2),\n (3, 0, 0, ed['N'].isotopes[14][0]*3),\n (1, 1, 0, (ed['N'].isotopes[14][0] + ed['Ga'].isotopes[71][0])/2),\n (3, 1, 0, (ed['Ga'].isotopes[69][0]+3*ed['N'].isotopes[14][0])/2),\n (3, 1, 0, (ed['Ga'].isotopes[71][0]+3*ed['N'].isotopes[14][0])/2),\n (0, 1, 0, ed['Ga'].isotopes[69][0]),\n (0, 1, 0, ed['Ga'].isotopes[71][0]),\n (0, 1, 0, ed['Ga'].isotopes[71][0]+ed['H'].isotopes[1][0]),\n (0, 0, 1, ed['In'].isotopes[113][0]/2),\n (0, 0, 1, ed['In'].isotopes[115][0]/2),\n (0, 0, 1, ed['In'].isotopes[113][0]),\n (0, 0, 1, ed['In'].isotopes[115][0]),\n ],\n dtype=[('N','i4'),('Ga','i4'),('In','i4'),('m2q','f4')] )\n return pk_data\n\ndef Mg_doped_GaN():\n # N Ga Mg Da\n # Define possible peaks\n pk_data = np.array( [ (1, 0, 0, ed['N'].isotopes[14][0]/2),\n (1, 0, 0, ed['N'].isotopes[14][0]/1),\n (1, 0, 0, ed['N'].isotopes[15][0]/1),\n (1, 0, 0, ed['N'].isotopes[15][0]+ed['H'].isotopes[1][0]),\n (0, 1, 0, ed['Ga'].isotopes[69][0]/3),\n (0, 1, 0, ed['Ga'].isotopes[71][0]/3),\n (2, 0, 0, ed['N'].isotopes[14][0]*2),\n (2, 0, 0, ed['N'].isotopes[14][0]+ed['N'].isotopes[15][0]),\n (2, 0, 0, ed['N'].isotopes[14][0]+ed['N'].isotopes[15][0]+ed['H'].isotopes[1][0]),\n (0, 1, 0, ed['Ga'].isotopes[69][0]/2),\n (0, 1, 0, ed['Ga'].isotopes[71][0]/2),\n (1, 1, 0, (ed['N'].isotopes[14][0] + ed['Ga'].isotopes[69][0])/2),\n (3, 0, 0, ed['N'].isotopes[14][0]*3),\n (1, 1, 0, (ed['N'].isotopes[14][0] + ed['Ga'].isotopes[71][0])/2),\n (3, 1, 0, (ed['Ga'].isotopes[69][0]+3*ed['N'].isotopes[14][0])/2),\n (3, 1, 0, (ed['Ga'].isotopes[71][0]+3*ed['N'].isotopes[14][0])/2),\n (0, 1, 0, ed['Ga'].isotopes[69][0]),\n (0, 1, 0, ed['Ga'].isotopes[71][0]),\n (0, 1, 0, ed['Ga'].isotopes[71][0]+ed['H'].isotopes[1][0]),\n (0, 0, 1, ed['Mg'].isotopes[24][0]/2),\n (0, 0, 1, ed['Mg'].isotopes[24][0])\n ],\n dtype=[('N','i4'),('Ga','i4'),('Mg','i4'),('m2q','f4')] )\n return pk_data\n \n\ndef AlGaN():\n # N Ga Al Da\n # Define possible peaks\n pk_data = np.array( [ (1, 0, 0, ed['N'].isotopes[14][0]/2),\n (1, 0, 0, ed['N'].isotopes[14][0]/1),\n (1, 0, 0, ed['N'].isotopes[15][0]/1),\n (1, 0, 0, ed['N'].isotopes[15][0]+ed['H'].isotopes[1][0]),\n (0, 1, 0, ed['Ga'].isotopes[69][0]/3),\n (0, 1, 0, ed['Ga'].isotopes[71][0]/3),\n (2, 0, 0, ed['N'].isotopes[14][0]*2),\n (2, 0, 0, ed['N'].isotopes[14][0]+ed['N'].isotopes[15][0]),\n (2, 0, 0, ed['N'].isotopes[14][0]+ed['N'].isotopes[15][0]+ed['H'].isotopes[1][0]),\n (0, 1, 0, ed['Ga'].isotopes[69][0]/2),\n (0, 1, 0, ed['Ga'].isotopes[71][0]/2),\n (1, 1, 0, (ed['N'].isotopes[14][0] + ed['Ga'].isotopes[69][0])/2),\n (3, 0, 0, ed['N'].isotopes[14][0]*3),\n (1, 1, 0, (ed['N'].isotopes[14][0] + ed['Ga'].isotopes[71][0])/2),\n (3, 1, 0, (ed['Ga'].isotopes[69][0]+3*ed['N'].isotopes[14][0])/2),\n (3, 1, 0, (ed['Ga'].isotopes[71][0]+3*ed['N'].isotopes[14][0])/2),\n (0, 1, 0, ed['Ga'].isotopes[69][0]),\n (0, 1, 0, ed['Ga'].isotopes[71][0]),\n (0, 1, 0, ed['Ga'].isotopes[71][0]+ed['H'].isotopes[1][0]),\n (0, 0, 1, ed['Al'].isotopes[27][0]/3),\n (0, 0, 1, ed['Al'].isotopes[27][0]/2),\n (1, 0, 1, (ed['Al'].isotopes[27][0]+ed['N'].isotopes[14][0])/2),\n (0, 0, 1, ed['Al'].isotopes[27][0]/1)\n ],\n dtype=[('N','i4'),('Ga','i4'),('Al','i4'),('m2q','f4')] )\n return pk_data\n\ndef GaN():\n # N Ga Da\n # Define possible peaks\n pk_data = np.array( [ (1, 0, ed['N'].isotopes[14][0]/2),\n (1, 0, ed['N'].isotopes[14][0]/1),\n (1, 0, ed['N'].isotopes[15][0]/1),\n (1, 0, ed['N'].isotopes[15][0]+ed['H'].isotopes[1][0]),\n (0, 1, ed['Ga'].isotopes[69][0]/3),\n (0, 1, ed['Ga'].isotopes[71][0]/3),\n (2, 0, ed['N'].isotopes[14][0]*2),\n (2, 0, ed['N'].isotopes[14][0]+ed['N'].isotopes[15][0]),\n (2, 0, ed['N'].isotopes[14][0]+ed['N'].isotopes[15][0]+ed['H'].isotopes[1][0]),\n (0, 1, ed['Ga'].isotopes[69][0]/2),\n (0, 1, ed['Ga'].isotopes[71][0]/2),\n (1, 1, (ed['N'].isotopes[14][0] + ed['Ga'].isotopes[69][0])/2),\n (3, 0, ed['N'].isotopes[14][0]*3),\n (1, 1, (ed['N'].isotopes[14][0] + ed['Ga'].isotopes[71][0])/2),\n (3, 1, (ed['Ga'].isotopes[69][0]+3*ed['N'].isotopes[14][0])/2),\n (3, 1, (ed['Ga'].isotopes[71][0]+3*ed['N'].isotopes[14][0])/2),\n (0, 1, ed['Ga'].isotopes[69][0]),\n (0, 1, ed['Ga'].isotopes[71][0]),\n (0, 1, ed['Ga'].isotopes[71][0]+ed['H'].isotopes[1][0])\n ],\n dtype=[('N','i4'),('Ga','i4'),('m2q','f4')] )\n return pk_data\n\ndef GaN_with_H():\n # N Ga Da\n # Define possible peaks\n pk_data = np.array( [ (0, 0, ed['H'].isotopes[1][0]),\n (0, 0, ed['H'].isotopes[1][0]*2),\n (0, 0, ed['H'].isotopes[1][0]*3),\n (1, 0, ed['N'].isotopes[14][0]/2),\n (1, 0, ed['N'].isotopes[14][0]/1),\n (1, 0, ed['N'].isotopes[15][0]/1),\n (1, 0, ed['N'].isotopes[15][0]+ed['H'].isotopes[1][0]),\n (0, 1, ed['Ga'].isotopes[69][0]/3),\n (0, 1, ed['Ga'].isotopes[71][0]/3),\n (2, 0, ed['N'].isotopes[14][0]*2),\n (2, 0, ed['N'].isotopes[14][0]+ed['N'].isotopes[15][0]),\n (2, 0, ed['N'].isotopes[14][0]+ed['N'].isotopes[15][0]+ed['H'].isotopes[1][0]),\n (0, 1, ed['Ga'].isotopes[69][0]/2),\n (0, 1, ed['Ga'].isotopes[71][0]/2),\n (1, 1, (ed['N'].isotopes[14][0] + ed['Ga'].isotopes[69][0])/2),\n (3, 0, ed['N'].isotopes[14][0]*3),\n (1, 1, (ed['N'].isotopes[14][0] + ed['Ga'].isotopes[71][0])/2),\n (3, 1, (ed['Ga'].isotopes[69][0]+3*ed['N'].isotopes[14][0])/2),\n (3, 1, (ed['Ga'].isotopes[71][0]+3*ed['N'].isotopes[14][0])/2),\n (0, 1, ed['Ga'].isotopes[69][0]),\n (0, 1, ed['Ga'].isotopes[71][0]),\n (0, 1, ed['Ga'].isotopes[71][0]+ed['H'].isotopes[1][0])\n ],\n dtype=[('N','i4'),('Ga','i4'),('m2q','f4')] )\n return pk_data\n", "meta": {"hexsha": "9b583f61f9095d825b6f6185d0f91710cc3bacd5", "size": 11095, "ext": "py", "lang": "Python", "max_stars_repo_path": "nistapttools/GaN_type_peak_assignments.py", "max_stars_repo_name": "bcaplins/NIST_APT_TOOLS", "max_stars_repo_head_hexsha": "80c25498e8b069b8ee289a2d09c76c932c054cea", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nistapttools/GaN_type_peak_assignments.py", "max_issues_repo_name": "bcaplins/NIST_APT_TOOLS", "max_issues_repo_head_hexsha": "80c25498e8b069b8ee289a2d09c76c932c054cea", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nistapttools/GaN_type_peak_assignments.py", "max_forks_repo_name": "bcaplins/NIST_APT_TOOLS", "max_forks_repo_head_hexsha": "80c25498e8b069b8ee289a2d09c76c932c054cea", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 67.2424242424, "max_line_length": 124, "alphanum_fraction": 0.2980621902, "include": true, "reason": "import numpy", "num_tokens": 3719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.26588047309981694, "lm_q1q2_score": 0.14536699851138873}} {"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Project: Azimuthal integration\n# https://github.com/silx-kit/pyFAI\n#\n# Copyright (C) 2014-2018 European Synchrotron Radiation Facility, Grenoble, France\n#\n# Principal author: Jérôme Kieffer (Jerome.Kieffer@ESRF.eu)\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\n__author__ = \"Jérôme Kieffer\"\n__contact__ = \"Jerome.Kieffer@ESRF.eu\"\n__license__ = \"MIT\"\n__copyright__ = \"European Synchrotron Radiation Facility, Grenoble, France\"\n__date__ = \"17/10/2018\"\n__status__ = \"production\"\n\nimport sys\nimport os\nimport threading\nfrom math import ceil, sqrt\nimport logging\nlogger = logging.getLogger(__name__)\nimport numpy\nimport fabio\nfrom scipy.ndimage import label, distance_transform_edt\nfrom scipy.ndimage.filters import median_filter\nfrom .utils.decorators import deprecated\nfrom .ext.bilinear import Bilinear\nfrom .utils import gaussian_filter, binning, unbinning, is_far_from_group\nfrom .third_party import six\n\nif os.name != \"nt\":\n WindowsError = RuntimeError\n\n\nclass Massif(object):\n \"\"\"\n A massif is defined as an area around a peak, it is used to find neighboring peaks\n \"\"\"\n TARGET_SIZE = 1024\n\n def __init__(self, data=None, mask=None):\n \"\"\"Constructor of the class...\n \n :param data: 2D array or filename (discouraged)\n :param mask: array with non zero for invalid data \n \"\"\"\n if isinstance(data, six.string_types) and os.path.isfile(data):\n self.data = fabio.open(data).data.astype(\"float32\")\n elif isinstance(data, fabio.fabioimage.fabioimage):\n self.data = data.data.astype(\"float32\")\n else:\n try:\n self.data = data.astype(\"float32\")\n except Exception as error:\n logger.error(\"Unable to understand this type of data %s: %s\", data, error)\n self.mask = mask\n self._cleaned_data = None\n self._bilin = Bilinear(self.data)\n self._blurred_data = None\n self._median_data = None\n self._labeled_massif = None\n self._number_massif = None\n self._valley_size = None\n self._binned_data = None\n self._reconstruct_used = None\n self.binning = None # Binning is 2-list usually\n self._sem = threading.Semaphore()\n self._sem_label = threading.Semaphore()\n self._sem_binning = threading.Semaphore()\n self._sem_median = threading.Semaphore()\n\n def nearest_peak(self, x):\n \"\"\"\n :param x: coordinates of the peak\n :returns: the coordinates of the nearest peak\n \"\"\"\n out = self._bilin.local_maxi(x)\n if isinstance(out, tuple):\n res = out\n elif isinstance(out, numpy.ndarray):\n res = tuple(out)\n else:\n res = [int(i) for idx, i in enumerate(out) if 0 <= i < self.data.shape[idx]]\n if (len(res) != 2) or not((0 <= out[0] < self.data.shape[0]) and (0 <= res[1] < self.data.shape[1])):\n logger.warning(\"in nearest_peak %s -> %s\", x, out)\n return\n elif (self.mask is not None) and self.mask[int(res[0]), int(res[1])]:\n logger.info(\"Masked pixel %s -> %s\", x, out)\n return\n else:\n return res\n\n def calculate_massif(self, x):\n \"\"\"\n defines a map of the massif around x and returns the mask\n \"\"\"\n labeled = self.get_labeled_massif()\n if labeled[x[0], x[1]] > 0: # without relabeled the background is 0 labeled.max():\n return (labeled == labeled[x[0], x[1]])\n\n def find_peaks(self, x, nmax=200, annotate=None, massif_contour=None, stdout=sys.stdout):\n \"\"\"\n All in one function that finds a maximum from the given seed (x)\n then calculates the region extension and extract position of the neighboring peaks.\n :param x: coordinates of the peak, seed for the calculation\n :type x: tuple of integer\n :param nmax: maximum number of peak per region\n :param annotate: call back method taking number of points + coordinate as input.\n :param massif_contour: callback to show the contour of a massif with the given index.\n :param stdout: this is the file where output is written by default.\n :return: list of peaks\n \"\"\"\n listpeaks = []\n region = self.calculate_massif(x)\n if region is None:\n logger.error(\"You picked a background point at %s\", x)\n return listpeaks\n xinit = self.nearest_peak(x)\n if xinit is None:\n logger.error(\"Unable to find peak in the vinicy of %s\", x)\n return listpeaks\n else:\n if not region[int(xinit[0] + 0.5), int(xinit[1] + 0.5)]:\n logger.error(\"Nearest peak %s is not in the same region %s\", xinit, x)\n return listpeaks\n\n if annotate is not None:\n try:\n annotate(xinit, x)\n except Exception as error:\n logger.error(\"Error in annotate %i: %i %i. %s\", len(listpeaks), xinit[0], xinit[1], error)\n\n listpeaks.append(xinit)\n cleaned_data = self.cleaned_data\n mean = cleaned_data[region].mean(dtype=numpy.float64)\n region2 = region * (cleaned_data > mean)\n idx = numpy.vstack(numpy.where(region2)).T\n numpy.random.shuffle(idx)\n nmax = min(nmax, int(ceil(sqrt(idx.shape[0]))))\n if massif_contour is not None:\n try:\n massif_contour(region)\n except (WindowsError, MemoryError) as error:\n logger.error(\"Error in plotting region: %s\", error)\n nbFailure = 0\n for j in idx:\n xopt = self.nearest_peak(j)\n if xopt is None:\n nbFailure += 1\n continue\n if (region2[int(xopt[0] + 0.5), int(xopt[1] + 0.5)]) and not (xopt in listpeaks):\n stdout.write(\"[ %4i, %4i ] --> [ %5.1f, %5.1f ] after %3i iterations %s\" % (tuple(j) + tuple(xopt) + (nbFailure, os.linesep)))\n listpeaks.append(xopt)\n nbFailure = 0\n else:\n nbFailure += 1\n if (len(listpeaks) > nmax) or (nbFailure > 2 * nmax):\n break\n return listpeaks\n\n def peaks_from_area(self, mask, Imin=numpy.finfo(numpy.float64).min,\n keep=1000, dmin=0.0, seed=None, **kwarg):\n \"\"\"\n Return the list of peaks within an area\n\n :param mask: 2d array with mask.\n :param Imin: minimum of intensity above the background to keep the point\n :param keep: maximum number of points to keep\n :param kwarg: ignored parameters\n :param dmin: minimum distance to another peak\n :param seed: list of good guesses to start with\n :return: list of peaks [y,x], [y,x], ...]\n \"\"\"\n all_points = numpy.vstack(numpy.where(mask)).T\n res = []\n cnt = 0\n dmin2 = dmin * dmin\n if len(all_points) > 0:\n numpy.random.shuffle(all_points)\n if seed:\n seeds = numpy.array(list(seed))\n if len(seeds) > 0:\n numpy.random.shuffle(seeds)\n all_points = numpy.concatenate((seeds, all_points))\n for idx in all_points:\n out = self.nearest_peak(idx)\n if out is not None:\n msg = \"[ %3i, %3i ] -> [ %.1f, %.1f ]\"\n logger.debug(msg, idx[1], idx[0], out[1], out[0])\n p0, p1 = int(round(out[0])), int(round(out[1]))\n if mask[p0, p1]:\n if (self.data[p0, p1] > Imin) and is_far_from_group(out, res, dmin2):\n res.append(out)\n cnt = 0\n if len(res) >= keep or cnt > keep:\n break\n else:\n cnt += 1\n return res\n\n def init_valley_size(self):\n if self._valley_size is None:\n self.valley_size = max(5., max(self.data.shape) / 50.)\n\n @property\n def valley_size(self):\n \"Defines the minimum distance between two massifs\"\n if self._valley_size is None:\n self.init_valley_size()\n return self._valley_size\n\n @valley_size.setter\n def valley_size(self, size):\n new_size = float(size)\n if self._valley_size != new_size:\n self._valley_size = new_size\n t = threading.Thread(target=self.get_labeled_massif)\n t.start()\n\n @valley_size.deleter\n def valley_size(self):\n self._valley_size = None\n self._blurred_data = None\n\n @property\n def cleaned_data(self):\n if self.mask is None:\n return self.data\n else:\n if self._cleaned_data is None:\n idx = distance_transform_edt(self.mask,\n return_distances=False,\n return_indices=True)\n self._cleaned_data = self.data[tuple(idx)]\n return self._cleaned_data\n\n def get_binned_data(self):\n \"\"\"\n :return: binned data\n \"\"\"\n if self._binned_data is None:\n with self._sem_binning:\n if self._binned_data is None:\n logger.info(\"Image size is %s\", self.data.shape)\n self.binning = []\n for i in self.data.shape:\n if i % self.TARGET_SIZE == 0:\n self.binning.append(max(1, i // self.TARGET_SIZE))\n else:\n for j in range(i // self.TARGET_SIZE - 1, 0, -1):\n if i % j == 0:\n self.binning.append(max(1, j))\n break\n else:\n self.binning.append(1)\n# self.binning = max([max(1, i // self.TARGET_SIZE) for i in self.data.shape])\n logger.info(\"Binning size is %s\", self.binning)\n self._binned_data = binning(self.cleaned_data, self.binning)\n return self._binned_data\n\n def get_median_data(self):\n \"\"\"\n :return: a spatial median filtered image 3x3\n \"\"\"\n if self._median_data is None:\n with self._sem_median:\n if self._median_data is None:\n self._median_data = median_filter(self.cleaned_data, 3)\n return self._median_data\n\n def get_blurred_data(self):\n \"\"\"\n :return: a blurred image\n \"\"\"\n if self._blurred_data is None:\n with self._sem:\n if self._blurred_data is None:\n logger.debug(\"Blurring image with kernel size: %s\", self.valley_size)\n self._blurred_data = gaussian_filter(self.get_binned_data(),\n [self.valley_size / i for i in self.binning],\n mode=\"reflect\")\n return self._blurred_data\n\n def get_labeled_massif(self, pattern=None, reconstruct=True):\n \"\"\"\n :param pattern: 3x3 matrix \n :param reconstruct: if False, split massif at masked position, else reconstruct missing part.\n :return: an image composed of int with a different value for each massif\n \"\"\"\n if self._labeled_massif is None:\n with self._sem_label:\n if self._labeled_massif is None:\n if pattern is None:\n pattern = numpy.ones((3, 3), dtype=numpy.int8)\n logger.debug(\"Labeling all massifs. This takes some time !!!\")\n massif_binarization = (self.get_binned_data() > self.get_blurred_data())\n if (self.mask is not None) and (not reconstruct):\n binned_mask = binning(self.mask.astype(int), self.binning, norm=False)\n massif_binarization = numpy.logical_and(massif_binarization, binned_mask == 0)\n self._reconstruct_used = reconstruct\n labeled_massif, self._number_massif = label(massif_binarization,\n pattern)\n # TODO: investigate why relabel fails\n # relabeled = relabel(labeled_massif, self.get_binned_data(), self.get_blurred_data())\n relabeled = labeled_massif\n self._labeled_massif = unbinning(relabeled, self.binning, False)\n logger.info(\"Labeling found %s massifs.\", self._number_massif)\n return self._labeled_massif\n\n @deprecated(reason=\"switch to pep8 style\", replacement=\"init_valley_size\", since_version=\"0.16.0\")\n def initValleySize(self):\n self.init_valley_size()\n\n @deprecated(reason=\"switch to PEP8 style\", replacement=\"get_median_data\", since_version=\"0.16.0\")\n def getMedianData(self):\n return self.get_median_data()\n\n @deprecated(reason=\"switch to PEP8 style\", replacement=\"get_binned_data\", since_version=\"0.16.0\")\n def getBinnedData(self):\n return self.get_binned_data()\n\n @deprecated(reason=\"switch to PEP8 style\", replacement=\"get_blurred_data\", since_version=\"0.16.0\")\n def getBluredData(self):\n return self.get_blurred_data()\n\n @deprecated(reason=\"switch to PEP8 style\", replacement=\"get_labeled_massif\", since_version=\"0.16.0\")\n def getLabeledMassif(self, pattern=None):\n return self.get_labeled_massif(pattern)\n", "meta": {"hexsha": "dc0588da9e7a56c4d14dca42578889ed46b66438", "size": 14634, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyFAI/massif.py", "max_stars_repo_name": "jangarrevoet/pyFAI", "max_stars_repo_head_hexsha": "0779ac9aa5d72ac582413921989a8375bb7a990a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyFAI/massif.py", "max_issues_repo_name": "jangarrevoet/pyFAI", "max_issues_repo_head_hexsha": "0779ac9aa5d72ac582413921989a8375bb7a990a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyFAI/massif.py", "max_forks_repo_name": "jangarrevoet/pyFAI", "max_forks_repo_head_hexsha": "0779ac9aa5d72ac582413921989a8375bb7a990a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.8114285714, "max_line_length": 142, "alphanum_fraction": 0.5830258303, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.2658804672827598, "lm_q1q2_score": 0.14536699533098169}} {"text": "import numpy as np\nfrom astropy.io import fits\nfrom astropy.table import Table, vstack\nfrom astropy.wcs import WCS\nimport os\nimport argparse\nimport logging, traceback\nimport pandas as pd\nfrom copy import copy\n\nfrom bkg_rate_estimation import get_avg_lin_cub_rate_quad_obs\nfrom config import quad_dicts, EBINS0, EBINS1,\\\n solid_angle_dpi_fname, bright_source_table_fname\nfrom sqlite_funcs import write_rate_fits_from_obj, get_conn\nfrom dbread_funcs import get_info_tab, guess_dbfname, get_files_tab\nfrom event2dpi_funcs import filter_evdata\nfrom models import Bkg_Model_wFlatA, CompoundModel, Point_Source_Model_Binned_Rates\nfrom LLH import LLH_webins\nfrom minimizers import NLLH_ScipyMinimize, NLLH_ScipyMinimize_Wjacob\nfrom ray_trace_funcs import RayTraces\nfrom coord_conv_funcs import convert_radec2imxy\nfrom gti_funcs import add_bti2gti, bti2gti, gti2bti, union_gtis\nfrom wcs_funcs import world2val\n\n\ndef cli():\n parser = argparse.ArgumentParser()\n parser.add_argument('--evfname', type=str,\\\n help=\"Event data file\",\n default=None)\n parser.add_argument('--dmask', type=str,\\\n help=\"Detmask fname\",\n default=None)\n parser.add_argument('--dbfname', type=str,\\\n help=\"Name to save the database to\",\\\n default=None)\n parser.add_argument('--job_id', type=int,\\\n help=\"Job ID\",\\\n default=0)\n parser.add_argument('--Njobs', type=int,\\\n help=\"Number of jobs\",\\\n default=1)\n parser.add_argument('--twind', type=float,\\\n help=\"Number of seconds to go +/- from the trigtime\",\\\n default=20)\n parser.add_argument('--bkg_dur', type=float,\\\n help=\"bkg duration\",\\\n default=40.0)\n parser.add_argument('--bkg_nopost',\\\n help=\"Don't use time after signal window for bkg\",\\\n action='store_true')\n parser.add_argument('--bkg_nopre',\\\n help=\"Don't use time before signal window for bkg\",\\\n action='store_true')\n parser.add_argument('--pcfname', type=str,\\\n help=\"partial coding file name\",\\\n default='pc_2.img')\n\n\n\n args = parser.parse_args()\n return args\n\n\ndef ang_sep(ra0, dec0, ra1, dec1):\n\n dcos = np.cos(np.radians(np.abs(ra0 - ra1)))\n angsep = np.arccos(np.cos(np.radians(90-dec0))*np.cos(np.radians(90-dec1)) +\\\n np.sin(np.radians(90-dec0))*np.sin(np.radians(90-dec1))*dcos)\n return np.rad2deg(angsep)\n\ndef im_dist(imx0, imy0, imx1, imy1):\n return np.hypot((imx1 - imx0), (imy1 - imy0))\n\ndef add_imxy2src_tab(src_tab, attfile, t0):\n\n att_ind = np.argmin(np.abs(attfile['TIME'] - t0))\n att_quat = attfile['QPARAM'][att_ind]\n pnt_ra, pnt_dec = attfile['POINTING'][att_ind,:2]\n imxs = np.zeros(len(src_tab))\n imys = np.zeros(len(src_tab))\n src_tab['PntSep'] = ang_sep(pnt_ra, pnt_dec, src_tab['RAJ2000'], src_tab['DEJ2000'])\n for i in range(len(imxs)):\n if src_tab['PntSep'][i] > 80.0:\n imxs[i], imys[i] = np.nan, np.nan\n continue\n imxs[i], imys[i] = convert_radec2imxy(src_tab['RAJ2000'][i],\\\n src_tab['DEJ2000'][i],\\\n att_quat)\n src_tab['imx'] = imxs\n src_tab['imy'] = imys\n return src_tab\n\ndef get_srcs_infov(attfile, t0, pcfname=None, pcmin=5e-2):\n\n brt_src_tab = Table.read(bright_source_table_fname)\n add_imxy2src_tab(brt_src_tab, attfile, t0)\n bl_infov = (np.abs(brt_src_tab['imy'])<.95)&(np.abs(brt_src_tab['imx'])<1.75)\n if pcfname is not None:\n PC = fits.open(pcfname)[0]\n pc = PC.data\n w_t = WCS(PC.header, key='T')\n pcvals = world2val(w_t, pc, brt_src_tab['imx'],\\\n brt_src_tab['imy'])\n bl_infov = bl_infov&(pcvals>=pcmin)\n N_infov = np.sum(bl_infov)\n return brt_src_tab[bl_infov]\n\n\ndef bkg_withPS_fit(PS_tab, model, llh_obj, t0s, t1s,\\\n dimxy=2e-3, im_steps=5, test_null=False):\n\n Nps = len(PS_tab)\n imax = np.linspace(-dimxy, dimxy, im_steps)\n if im_steps == 3:\n imax = np.linspace(-dimxy/2., dimxy/2., im_steps)\n elif im_steps == 2:\n imax = np.linspace(-dimxy/2., dimxy/2., im_steps)\n elif im_steps == 1:\n imax = np.array([0.0])\n\n\n imlist = []\n for i in range(Nps):\n imlist += [imax,imax]\n imgs = np.meshgrid(*imlist)\n Npnts = imgs[0].size\n\n bkg_miner = NLLH_ScipyMinimize_Wjacob('')\n bkg_miner.set_llh(llh_obj)\n llh_obj.set_time(t0s,t1s)\n\n bf_params_list = []\n bkg_nllhs = np.zeros(Npnts)\n\n nebins = model.nebins\n\n for i in range(Npnts):\n bf_params = {}\n im_names = []\n for j in range(Nps):\n row = PS_tab[j]\n psname = row['Name']\n bf_params[psname+'_imx'] = imgs[2*j].ravel()[i] + row['imx']\n bf_params[psname+'_imy'] = imgs[2*j+1].ravel()[i] + row['imy']\n im_names = [psname+'_imx', psname+'_imy']\n im_vals = [bf_params[nm] for nm in im_names]\n\n for e0 in range(nebins):\n bkg_miner.set_fixed_params(bkg_miner.param_names)\n bkg_miner.set_fixed_params(im_names, im_vals)\n e0_pnames = []\n for pname in bkg_miner.param_names:\n try:\n if int(pname[-1])==e0:\n e0_pnames.append(pname)\n except:\n pass\n bkg_miner.set_fixed_params(e0_pnames, fixed=False)\n llh_obj.set_ebin(e0)\n\n bf_vals, bkg_nllh, res = bkg_miner.minimize()\n bkg_nllhs[i] += bkg_nllh[0]\n for ii, pname in enumerate(e0_pnames):\n bf_params[pname] = bf_vals[0][ii]\n bf_params_list.append(bf_params)\n\n bf_ind = np.argmin(bkg_nllhs)\n bf_params = bf_params_list[bf_ind]\n bf_nllh = bkg_nllhs[bf_ind]\n\n if test_null:\n TS_nulls = {}\n for i in range(Nps):\n params_ = copy(bf_params)\n row = PS_tab[i]\n psname = row['Name']\n for j in range(nebins):\n params_[psname+'_rate_'+str(j)] = 0.0\n llh_obj.set_ebin(-1)\n nllh_null = -llh_obj.get_logprob(params_)\n TS_nulls[psname] = np.sqrt(2.*(nllh_null - bf_nllh))\n if np.isnan(TS_nulls[psname]):\n TS_nulls[psname] = 0.0\n return bf_nllh, bf_params, TS_nulls\n\n\n return bf_nllh, bf_params\n\n\ndef do_init_bkg_wPSs(bkg_mod, llh_obj, src_tab, rt_obj, GTI, sig_twind):\n\n gti_bkg = add_bti2gti(sig_twind, GTI)\n bkg_t0s = gti_bkg['START']\n bkg_t1s = gti_bkg['STOP']\n\n Nsrcs = len(src_tab)\n nebins = bkg_mod.nebins\n\n for ii in range(Nsrcs):\n mod_list = [bkg_mod]\n im_steps = 5\n if Nsrcs >= 3:\n im_steps = 3\n if Nsrcs >= 5:\n im_steps = 2\n if Nsrcs >= 7:\n im_steps = 1\n\n ps_mods = []\n for i in range(Nsrcs):\n row = src_tab[i]\n mod = Point_Source_Model_Binned_Rates(row['imx'], row['imy'], 0.1,\\\n [llh_obj.ebins0,llh_obj.ebins1],\\\n rt_obj, llh_obj.bl_dmask,\\\n use_deriv=True, name=row['Name'])\n ps_mods.append(mod)\n\n mod_list += ps_mods\n comp_mod = CompoundModel(mod_list)\n\n llh_obj.set_model(comp_mod)\n\n bf_nllh, bf_params, TS_nulls = bkg_withPS_fit(src_tab, comp_mod,\\\n llh_obj, bkg_t0s, bkg_t1s,\\\n test_null=True, im_steps=im_steps)\n\n logging.debug(\"TS_nulls: \")\n logging.debug(TS_nulls)\n\n bkg_rates = np.array([bf_params['Background'+'_bkg_rate_'+str(j)]\\\n for j in range(nebins)])\n min_rate = 1e-1*bkg_rates\n logging.debug(\"min_rate: \")\n logging.debug(min_rate)\n PSs2keep = []\n for name, TS in TS_nulls.items():\n if TS < 8.0:\n ps_rates = np.array([bf_params[name+'_rate_'+str(j)] for j in range(nebins)])\n logging.debug(name + \" rates: \")\n logging.debug(ps_rates)\n # print ps_rates\n if np.all(ps_rates 0:\n\n rt_dir = files_tab['rtDir'][0]\n rt_obj = RayTraces(rt_dir)\n\n sig_dtwind = (-10*1.024, 20*1.024)\n sig_twind = (trigtime + sig_dtwind[0], trigtime + sig_dtwind[1])\n\n init_bf_params, src_tab = do_init_bkg_wPSs(bkg_mod, llh_obj, src_tab, rt_obj, GTI, sig_twind)\n\n Nsrcs = len(src_tab)\n\n logging.debug(\"Final src_tab:\")\n logging.debug(src_tab)\n\n # Now need to do each time, with these PSs and these imxys\n\n else:\n init_bf_params = {k:bkg_mod.param_dict[k]['val'] for k in bkg_mod.param_names}\n\n\n if Nsrcs > 0:\n fixed_pars = [pname for pname in list(init_bf_params.keys()) if '_flat_' in pname\\\n or '_imx' in pname or '_imy' in pname]\n\n mod_list = [bkg_mod]\n ps_mods = []\n for i in range(Nsrcs):\n row = src_tab[i]\n mod = Point_Source_Model_Binned_Rates(row['imx'], row['imy'], 0.1,\\\n [ebins0,ebins1], rt_obj, bl_dmask,\\\n use_deriv=True, name=row['Name'])\n ps_mods.append(mod)\n\n mod_list += ps_mods\n mod = CompoundModel(mod_list)\n\n else:\n init_bf_params = {k:bkg_mod.param_dict[k]['val'] for k in bkg_mod.param_names}\n mod = bkg_mod\n fixed_pars = []\n\n\n bkg_dur = args.bkg_dur*1.024\n twind = args.twind*1.024\n bkg_tstep = 2*1.024\n dt_ax = np.arange(-twind, twind+1, bkg_tstep)\n t_ax = dt_ax + trigtime\n Ntpnts = len(dt_ax)\n logging.info('Ntpnts: %d'%(Ntpnts))\n logging.info('min(dt_ax): %.3f'%(np.min(dt_ax)))\n logging.info('max(dt_ax): %.3f'%(np.max(dt_ax)))\n sig_wind = 10*1.024\n # sig_twind = (trigger_time + sig_dtwind[0], trigger_time + sig_dtwind[1])\n\n bkg_bf_dicts = []\n\n\n for i in range(Ntpnts):\n\n tmid = t_ax[i]\n sig_twind = (-sig_wind/2. + tmid, sig_wind/2. + tmid)\n gti_ = add_bti2gti(sig_twind, GTI)\n bkg_t0 = tmid - sig_wind/2. - bkg_dur/2.\n bkg_t1 = tmid + sig_wind/2. + bkg_dur/2.\n bkg_bti = Table(data=([-np.inf, bkg_t1], [bkg_t0, np.inf]), names=('START', 'STOP'))\n gti_ = add_bti2gti(bkg_bti, gti_)\n print(tmid - trigtime)\n print(gti_)\n t0s = gti_['START']\n t1s = gti_['STOP']\n\n nllh, params, errs_dict, corrs_dict = bkg_withPS_fit_fiximxy(src_tab, mod, llh_obj, t0s, t1s,\\\n copy(init_bf_params),\\\n fixed_pnames=fixed_pars)\n\n params.update(errs_dict)\n params.update(corrs_dict)\n params['nllh'] = nllh\n params['time'] = tmid\n params['dt'] = tmid - trigtime\n bkg_bf_dicts.append(params)\n params['exp'] = llh_obj.dt\n\n bkg_df = pd.DataFrame(bkg_bf_dicts)\n\n save_fname = 'bkg_estimation.csv'\n logging.info(\"Saving results in a DataFrame to file: \")\n logging.info(save_fname)\n bkg_df.to_csv(save_fname, index=False)\n\n\n\nif __name__ == \"__main__\":\n\n args = cli()\n\n main(args)\n", "meta": {"hexsha": "2d27923dcb47c3358583aa8e10660e2f896698a2", "size": 16896, "ext": "py", "lang": "Python", "max_stars_repo_path": "archive/do_bkg_estimation_wPSs.py", "max_stars_repo_name": "parsotat/NITRATES", "max_stars_repo_head_hexsha": "f5ce071410795c044ed7c139d6d07fd21e2dba9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "archive/do_bkg_estimation_wPSs.py", "max_issues_repo_name": "parsotat/NITRATES", "max_issues_repo_head_hexsha": "f5ce071410795c044ed7c139d6d07fd21e2dba9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "archive/do_bkg_estimation_wPSs.py", "max_forks_repo_name": "parsotat/NITRATES", "max_forks_repo_head_hexsha": "f5ce071410795c044ed7c139d6d07fd21e2dba9e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2442748092, "max_line_length": 107, "alphanum_fraction": 0.5838660038, "include": true, "reason": "import numpy,from astropy", "num_tokens": 4892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.2658804672827598, "lm_q1q2_score": 0.14536699533098169}} {"text": "# Copyright 2019 Pascal Audet\n#\n# This file is part of RfPy.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\"\"\"\nFunctions to calculate piercing points from a velocity model and slowness\nvalues, bin them, and produce CCP stacks using receiver functions.\n\n\"\"\"\n\nimport os\nimport sys\nimport pickle\nimport numpy as np\nimport scipy as sp\nfrom scipy.signal import hilbert\nfrom rfpy import binning\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\n\n\nclass CCPimage(object):\n \"\"\"\n A CCPimage object contains attributes and methods to produce\n Common Conversion Point (CCP) stacks for each of the main\n three main phases (Ps, Pps and Pss) using radial-component\n receiver functions. The object is used to project the stacks along\n a linear profile, specified by start and end geographical coordinate \n locations, which are subsequently averaged to produce a final \n CCP image. The averaging can be done using a linear weighted sum, \n or a phase-weighted sum. Methods should be used in the appropriate\n sequence (see ``rfpy_ccp.py`` for details).\n\n Note\n ----\n By default, the object initializes with un-defined coordinate locations for \n the profile. If not specified during initialization, make sure\n they are specified later, before the other methods are used, e.g.\n ``ccpimage.xs_lat1 = 10.; ccpimage.xs_lon1 = 110.``, etc. Note also that the \n default 1D velocity model may not be applicable to your region of \n interest and a different model can be implemented during initialization\n or later during processing. \n\n Parameters\n ----------\n coord_start : list\n List of two floats corresponding to the (latitude, longitude)\n pair for the start point of the profile \n coord_end : list\n List of two floats corresponding to the (latitude, longitude)\n pair for the end point of the profile \n weights : list\n List of three floats with corresponding weights for the Ps, Pps\n and Pss phases used during linear, weighted averaging\n dep : :class:`~numpy.ndarray`\n Array of depth values defining the 1D background seismic velocity model.\n Note that the maximum depth defined here sets the maximum depth \n in each of the CCP stacks and the final CCP image.\n vp : :class:`~numpy.ndarray`\n Array of Vp values defining the 1D background seismic velocity model\n vpvs : float\n Constant Vp/Vs ratio for the 1D model. \n\n Other Parameters\n ----------------\n radialRF : list\n List of :class:`~obspy.core.Stream` objects containing the radial\n receiver functions along the line. Each item in the list contains the\n streams for one single station.\n vs : :class:`~numpy.ndarray`\n Array of Vp values defining the 1D background seismic velocity model\n xs_lat1 : float\n Latitude of start point defining the linear profile.\n xs_lon1 : float\n Longitude of start point defining the linear profile.\n xs_lat2 : float\n Latitude of end point defining the linear profile.\n xs_lon2 : float\n Longitude of end point defining the linear profile.\n is_ready_for_prep : boolean\n Whether or not the object is ready for the method ``prep_data``\n is_ready_for_prestack : boolean\n Whether or not the object is ready for the method ``prestack``\n is_ready_for_ccp : boolean\n Whether or not the object is ready for the method ``ccp``\n is_ready_for_gccp : boolean\n Whether or not the object is ready for the method ``gccp``\n\n \"\"\"\n\n def __init__(self, coord_start=[None, None], coord_end=[None, None],\n weights=[1., 3., -3.],\n dep=np.array([0., 4., 8., 14., 30., 35., 45., 110.]),\n vp=np.array([4.0, 5.9, 6.2, 6.3, 6.8, 7.2, 8.0, 8.1]),\n vs=None, vpvs=1.73, dx=2.5, dz=1.):\n\n self.radialRF = []\n self.dep = dep\n self.weights = weights\n self.xs_lat1 = coord_start[0]\n self.xs_lon1 = coord_start[1]\n self.xs_lat2 = coord_end[0]\n self.xs_lon2 = coord_end[1]\n self.is_ready_for_prep = False\n self.is_ready_for_prestack = False\n self.is_ready_for_ccp = False\n self.is_ready_for_gccp = False\n\n # Define grid parameters\n self.dz = dz\n self.dx = dx\n\n # Get total length of grid from end points\n xlength = haversine(self.xs_lat1, self.xs_lon1,\n self.xs_lat2, self.xs_lon2)\n\n # number of cells laterally and vertically\n self.nx = int(np.rint(xlength/self.dx))\n self.nz = int(self.dep[-1]/self.dz)\n\n self.xarray = np.arange(self.nx)*self.dx\n self.zarray = np.arange(self.nz)*self.dz\n\n # Interpolate Vp and Vs models on depth grid\n if vs is None:\n vs = vp/vpvs\n else:\n if not vp.shape == vs.shape:\n raise(Exception(\"vp and vs arrays have a different shape\"))\n\n self.vp = sp.interpolate.interp1d(dep, vp, kind='linear')(self.zarray)\n self.vs = sp.interpolate.interp1d(dep, vs, kind='linear')(self.zarray)\n\n def add_rfstream(self, rfstream):\n \"\"\"\n Method to add a :class:`~obspy.core.Stream` object to the list\n ``radialRF``. With at least one stream in ``radialRF``, the object\n is ready for the ``prep_data`` method, and the corresponding flag is\n updated. \n\n Parameters\n ----------\n rfstream : :class:`~obspy.core.Stream`\n Stream object containing radial receiver functions for one station\n\n \"\"\"\n if len(rfstream) > 0:\n # fftshift if the time axis starts at negative lags \n if rfstream[0].stats.taxis[0]<0.:\n for tr in rfstream:\n tr.data = np.fft.fftshift(tr.data)\n\n self.radialRF.append(rfstream)\n self.is_ready_for_prep = True\n\n def prep_data(self, f1=0.05, f2ps=0.5, f2pps=0.25, f2pss=0.2,\n nbaz=36+1, nslow=40+1):\n \"\"\"\n Method to pre-process the data and calculate the CCP points for each \n of the receiver functions. Pre-processing includes the binning to\n back-azimuth and slowness bins to reduce processing time and generate\n cleaner stacks, as well as filtering to emphasize the energy of the\n various phases as a function of depth. As a general rule, the high \n frequency corner of the 2 reverberated phases (Pps and Pss) should be \n approximately half of the high frequency corner of the direct \n (Ps) phase. At the end of this step, the object is updated with\n the amplitude at the lat, lon and depth values corresponding to the\n raypath for each receiver function. The object is now ready for the\n method ``prestack``, with the corresponding flag updated.\n\n Parameters\n ----------\n f1 : float\n Low-frequency corner of the bandpass filter used for all phases (Hz)\n f2ps : float\n High-frequency corner of the bandpass filter used for the Ps phase (Hz)\n f2pps : float\n High-frequency corner of the bandpass filter used for the Pps phase (Hz)\n f2pss : float\n High-frequency corner of the bandpass filter used for the Pss phase (Hz)\n nbaz : int\n Number of increments in the back-azimuth bins\n nslow : int\n Number of increments in the slowness bins\n\n The following attributes are added to the object:\n\n Other Parameters\n ----------------\n amp_ps_depth : :class:`numpy.ndarray`\n 2D array of amplitudes as a function of depth for the Ps phase\n amp_pps_depth : :class:`numpy.ndarray`\n 2D array of amplitudes as a function of depth for the Pps phase\n amp_pss_depth : :class:`numpy.ndarray`\n 2D array of amplitudes as a function of depth for the Pss phase\n lon_depth : :class:`numpy.ndarray`\n 2D array of longitude as a function of depth (i.e., piercing points)\n lat_depth : :class:`numpy.ndarray`\n 2D array of latitude as a function of depth (i.e., piercing points)\n is_ready_for_presstack : boolean\n Flag specifying that the object is ready for the presstack() method\n n_traces : float\n Total number of traces used in creating the CCP image.\n\n \"\"\"\n\n if not self.is_ready_for_prep:\n raise(Exception(\"CCPimage not ready for pre-prep\"))\n\n ikey = 0\n total_traces = 0\n\n # Process streams one at a time\n for RF in self.radialRF:\n\n # Bin RFs into back-azimuth and slowness bins to speed up\n # calculations\n RFbin = binning.bin_baz_slow(\n RF, nbaz=nbaz, nslow=nslow)[0]\n n_traces = len(RFbin)\n total_traces += n_traces\n\n amp_ps_tr = np.empty([n_traces, self.nz])\n amp_pps_tr = np.empty([n_traces, self.nz])\n amp_pss_tr = np.empty([n_traces, self.nz])\n lon_tr = np.empty([n_traces, self.nz])\n lat_tr = np.empty([n_traces, self.nz])\n\n st_ps = RFbin.copy()\n st_pps = RFbin.copy()\n st_pss = RFbin.copy()\n\n # Filter Ps, Pps and Pss\n st_ps.filter(\n 'bandpass', freqmin=f1, freqmax=f2ps,\n corners=4, zerophase=True)\n st_pps.filter(\n 'bandpass', freqmin=f1, freqmax=f2pps,\n corners=4, zerophase=True)\n st_pss.filter(\n 'bandpass', freqmin=f1, freqmax=f2pss,\n corners=4, zerophase=True)\n del RFbin\n\n print(\"Station: \"+st_ps[0].stats.station)\n for itr in _progressbar(range(len(st_ps)), '', 25):\n\n # Get raypath and travel time for all phases\n tt_ps, tt_pps, tt_pss, plon, plat = \\\n raypath(st_ps[itr], dep=self.zarray, vp=self.vp, vs=self.vs)\n\n # Now get amplitude of RF at corresponding travel\n # time along the raypath\n lon_tr[itr, :] = plon\n lat_tr[itr, :] = plat\n\n amp_ps = []\n amp_pps = []\n amp_pss = []\n\n # Loop through travel times and shift RFs to get amplitudes\n for tt in tt_ps:\n a, phase = timeshift(st_ps[itr], tt)\n amp_ps.append(a)\n amp_ps_tr[itr, :] = amp_ps\n\n # Loop through travel times and shift RFs to get amplitudes\n for tt in tt_pps:\n a, phase = timeshift(st_pps[itr], tt)\n amp_pps.append(a)\n amp_pps_tr[itr, :] = amp_pps\n\n # Loop through travel times and shift RFs to get amplitudes\n for tt in tt_pss:\n a, phase = timeshift(st_pss[itr], tt)\n amp_pss.append(a)\n amp_pss_tr[itr, :] = amp_pss\n\n if ikey == 0:\n amp_ps_depth = amp_ps_tr.transpose()\n amp_pps_depth = amp_pps_tr.transpose()\n amp_pss_depth = amp_pss_tr.transpose()\n lon_depth = lon_tr.transpose()\n lat_depth = lat_tr.transpose()\n\n elif ikey > 0:\n amp_ps_depth = np.concatenate(\n (amp_ps_depth, amp_ps_tr.transpose()), axis=1)\n amp_pps_depth = np.concatenate(\n (amp_pps_depth, amp_pps_tr.transpose()), axis=1)\n amp_pss_depth = np.concatenate(\n (amp_pss_depth, amp_pss_tr.transpose()), axis=1)\n lon_depth = np.concatenate(\n (lon_depth, lon_tr.transpose()), axis=1)\n lat_depth = np.concatenate(\n (lat_depth, lat_tr.transpose()), axis=1)\n\n ikey += 1\n\n self.amp_ps_depth = amp_ps_depth\n self.amp_pps_depth = amp_pps_depth\n self.amp_pss_depth = amp_pss_depth\n self.lon_depth = lon_depth\n self.lat_depth = lat_depth\n self.is_ready_for_prestack = True\n self.n_traces = total_traces\n\n del self.radialRF\n\n def prestack(self):\n \"\"\"\n Method to project the raypaths onto the 2D profile for each of the three\n phases. The final grid is defined here, using the parameter ``dx`` in km.\n The horizontal extent is pre-determined from the start and end points of \n the profile. At the end of this step, the object contains the set of \n amplitudes at each of the 2D grid points, for each of the three phases.\n The object is now ready for the methods ``ccp`` and/or ``gccp``, with \n the corresponding flag updated.\n\n The following attributes are added to the object:\n\n Other Parameters\n ----------------\n xs_amps_ps : :class:`numpy.ndarray`\n 3D array of amplitudes (1D array of amplitudes at each grid cell)\n for the Ps phase\n xs_amps_pps : :class:`numpy.ndarray`\n 3D array of amplitudes (1D array of amplitudes at each grid cell)\n for the Pps phase\n xs_amps_pss : :class:`numpy.ndarray`\n 3D array of amplitudes (1D array of amplitudes at each grid cell)\n for the Pss phase\n is_ready_for_ccp : boolean\n Flag specifying that the object is ready for the ccp() method\n is_ready_for_gccp : boolean\n Flag specifying that the object is ready for the gccp() method\n\n \"\"\"\n\n if not self.is_ready_for_prestack:\n raise(Exception(\"CCPimage not ready for prestack\"))\n\n xs_latitudes = np.asarray(\n np.linspace(self.xs_lat1, self.xs_lat2, self.nx))\n xs_longitudes = np.asarray(\n np.linspace(self.xs_lon1, self.xs_lon2, self.nx))\n\n xs_amps_ps = np.zeros((self.nz, self.nx, self.n_traces))\n xs_amps_pps = np.zeros((self.nz, self.nx, self.n_traces))\n xs_amps_pss = np.zeros((self.nz, self.nx, self.n_traces))\n\n for iz in _progressbar(range(self.nz), '', 25):\n\n for i_coor in range(self.n_traces):\n\n lat_tr = self.lat_depth[iz, i_coor]\n lon_tr = self.lon_depth[iz, i_coor]\n distance_tests = np.empty(self.nx)\n\n for i_xs in range(self.nx):\n lat_xs = xs_latitudes[i_xs]\n lon_xs = xs_longitudes[i_xs]\n distance_tests[i_xs] = haversine(\n lat_xs, lon_xs, lat_tr, lon_tr)\n\n minimum_distance = np.amin(distance_tests)\n ix = np.where(distance_tests ==\n np.amin(distance_tests))[0][0]\n\n nonzero_count = np.count_nonzero(\n xs_amps_ps[iz, ix, :])\n new_amp_ps = self.amp_ps_depth[iz, i_coor]\n if xs_amps_ps[iz, ix, 0] == 0.:\n xs_amps_ps[iz, ix, 0] = new_amp_ps\n else:\n xs_amps_ps[iz, ix, nonzero_count] = new_amp_ps\n\n nonzero_count = np.count_nonzero(\n xs_amps_pps[iz, ix, :])\n new_amp_pps = self.amp_pps_depth[iz, i_coor]\n if xs_amps_pps[iz, ix, 0] == 0.:\n xs_amps_pps[iz, ix, 0] = new_amp_pps\n else:\n xs_amps_pps[iz, ix, nonzero_count] = new_amp_pps\n\n nonzero_count = np.count_nonzero(\n xs_amps_pss[iz, ix, :])\n new_amp_pss = self.amp_pss_depth[iz, i_coor]\n if xs_amps_pss[iz, ix, 0] == 0.:\n xs_amps_pss[iz, ix, 0] = new_amp_pss\n else:\n xs_amps_pss[iz, ix, nonzero_count] = new_amp_pss\n\n self.xs_amps_ps = xs_amps_ps\n self.xs_amps_pps = xs_amps_pps\n self.xs_amps_pss = xs_amps_pss\n self.is_ready_for_ccp = True\n self.is_ready_for_gccp = True\n\n del self.amp_ps_depth\n del self.amp_pps_depth\n del self.amp_pss_depth\n del self.lon_depth\n del self.lat_depth\n\n def ccp(self):\n \"\"\"\n Method to average the amplitudes at each grid point to produce 2D images\n for each of the three phases. At the end of this step, the object\n contains the three 2D arrays that can be further averaged into a single\n final image. \n\n The following attributes are added to the object:\n\n Other Parameters\n ----------------\n xs_ps_avg : :class:`numpy.ndarray`\n 2D array of stacked amplitudes for the Ps phase\n xs_pps_avg : :class:`numpy.ndarray`\n 2D array of stacked amplitudes for the Pps phase\n xs_pss_avg : :class:`numpy.ndarray`\n 2D array of stacked amplitudes for the Pss phase\n\n \"\"\"\n\n if not self.is_ready_for_ccp:\n raise(Exception(\"CCPimage not ready for ccp\"))\n\n xs_ps_avg = np.zeros((self.nz, self.nx))\n xs_pps_avg = np.zeros((self.nz, self.nx))\n xs_pss_avg = np.zeros((self.nz, self.nx))\n\n for iz in _progressbar(range(self.nz), '', 25):\n\n for ix in range(self.nx):\n\n nonzero_count = np.count_nonzero(self.xs_amps_ps[iz, ix, :])\n if nonzero_count != 0:\n amps_ps = self.xs_amps_ps[iz, ix, 0:nonzero_count]\n xs_ps_avg[iz, ix] = np.mean(amps_ps)\n\n nonzero_count = np.count_nonzero(self.xs_amps_pps[iz, ix, :])\n if nonzero_count != 0:\n amps_pps = self.xs_amps_pps[iz, ix, 0:nonzero_count]\n xs_pps_avg[iz, ix] = np.mean(amps_pps)\n\n nonzero_count = np.count_nonzero(self.xs_amps_pss[iz, ix, :])\n if nonzero_count != 0:\n amps_pss = self.xs_amps_pss[iz, ix, 0:nonzero_count]\n xs_pss_avg[iz, ix] = np.mean(amps_pss)\n\n self.xs_ps_avg = xs_ps_avg\n self.xs_pps_avg = xs_pps_avg\n self.xs_pss_avg = xs_pss_avg\n\n del self.xs_amps_ps\n del self.xs_amps_pps\n del self.xs_amps_pss\n\n def gccp(self, wlen=15.):\n \"\"\"\n Method to average the amplitudes at each grid point to produce 2D images\n for each of the three phases. In this method, the grid points are further\n smoothed in the horizontal direction using a Gaussian function to simulate\n P-wave sensitivity kernels. At the end of this step, the object\n contains the three 2D smoothed arrays that can be further averaged into a \n single final image. \n\n Parameters\n ----------\n wlen : float\n Wavelength of the P-wave for smoothing (km).\n\n The following attributes are added to the object:\n\n Other Parameters\n ----------------\n xs_gauss_ps : :class:`numpy.ndarray`\n 2D array of stacked and Gaussian-filtered amplitudes for the Ps phase\n xs_gauss_pps : :class:`numpy.ndarray`\n 2D array of stacked and Gaussian-filtered amplitudes for the Pps phase\n xs_gauss_pss : :class:`numpy.ndarray`\n 2D array of stacked and Gaussian-filtered amplitudes for the Pss phase\n\n \"\"\"\n\n if not self.is_ready_for_gccp:\n raise(Exception(\"CCPimage not ready for gccp\"))\n if not hasattr(self, 'xs_ps_avg'):\n self.ccp()\n\n dlat = max(self.xarray)/self.nx\n\n import scipy.ndimage as ndimage\n\n self.xs_gauss_ps = ndimage.filters.gaussian_filter(\n self.xs_ps_avg, sigma=(0, wlen/dlat))\n self.xs_gauss_pps = ndimage.filters.gaussian_filter(\n self.xs_pps_avg, sigma=(0, wlen/dlat))\n self.xs_gauss_pss = ndimage.filters.gaussian_filter(\n self.xs_pss_avg, sigma=(0, wlen/dlat))\n\n def linear_stack(self, typ='ccp'):\n \"\"\"\n Method to average the three 2D images into a final, weighted CCP image\n using the weights defined in the attribute.\n\n Parameters\n ----------\n typ : str\n Type of phase stacks to use (either `ccp` or `gccp`)\n\n The following attributes are added to the object:\n\n Other Parameters\n ----------------\n tot_trace : :class:`numpy.ndarray`\n 2D array of amplitudes for the linearly combined Ps, Pps and Pss phases\n\n \"\"\"\n\n tot_trace = np.zeros((self.nz, self.nx))\n\n if typ=='ccp':\n if not hasattr(self, \"xs_ps_avg\"):\n self.ccp()\n xs_ps = self.xs_ps_avg*self.weights[0]\n xs_pps = self.xs_pps_avg*self.weights[1]\n xs_pss = self.xs_pss_avg*self.weights[2]\n elif typ=='gccp':\n if not hasattr(self, 'xs_gauss_ps'):\n self.gccp()\n xs_ps = self.xs_gauss_ps*self.weights[0]\n xs_pps = self.xs_gauss_pps*self.weights[1]\n xs_pss = self.xs_gauss_pss*self.weights[2]\n\n for ix in range(self.nx):\n ps_trace = xs_ps[:, ix]\n pps_trace = xs_pps[:, ix]\n pss_trace = xs_pss[:, ix]\n tot_trace[:, ix] = (ps_trace + pps_trace + pss_trace)\n\n self.tot_trace = tot_trace\n\n def phase_weighted_stack(self, typ='gccp'):\n \"\"\"\n Method to average the three 2D smoothed images into a final, \n phase-weighted CCP image.\n\n Parameters\n ----------\n typ : str\n Type of phase stacks to use (either `ccp` or `gccp`)\n\n The following attributes are added to the object:\n\n Other Parameters\n ----------------\n tot_trace : :class:`numpy.ndarray`\n 2D array of amplitudes for the phase-weighted, combined \n Ps, Pps and Pss phases\n\n \"\"\"\n\n tot_trace = np.zeros((self.nz, self.nx))\n\n if typ=='ccp':\n if not hasattr(self, \"xs_ps_avg\"):\n self.ccp()\n xs_ps = self.xs_ps_avg*self.weights[0]\n xs_pps = self.xs_pps_avg*self.weights[1]\n xs_pss = self.xs_pss_avg*self.weights[2]\n elif typ=='gccp':\n if not hasattr(self, 'xs_gauss_ps'):\n self.gccp()\n xs_ps = self.xs_gauss_ps*self.weights[0]\n xs_pps = self.xs_gauss_pps*self.weights[1]\n xs_pss = self.xs_gauss_pss*self.weights[2]\n\n for ix in range(self.nx):\n ps_trace = xs_ps[:, ix]\n pps_trace = xs_pps[:, ix]\n pss_trace = xs_pss[:, ix]\n\n weight = np.zeros(len(ps_trace), dtype=complex)\n ps_hilb = hilbert(ps_trace)\n ps_phase = np.arctan2(ps_hilb.imag, ps_hilb.real)\n weight += np.exp(1j*ps_phase)\n\n pps_hilb = hilbert(pps_trace)\n pps_phase = np.arctan2(pps_hilb.imag, pps_hilb.real)\n weight += np.exp(1j*pps_phase)\n\n pss_hilb = hilbert(pss_trace)\n pss_phase = np.arctan2(pss_hilb.imag, pss_hilb.real)\n weight += np.exp(1j*pss_phase)\n\n weight = np.abs(weight)/3.\n\n tot_trace[:, ix] = (ps_trace + pps_trace + pss_trace)*weight**2\n\n self.tot_trace = tot_trace\n\n\n def save(self, title):\n \"\"\"\n Method to save the `ccpimage` object to file.\n\n Parameters\n ----------\n title : str\n File name for the saved object\n\n \"\"\"\n\n if title is None:\n title = \"CCP_image.pkl\"\n\n if not \".pkl\" in title:\n file = open(title+\".pkl\", \"wb\")\n else:\n file = open(title, \"wb\")\n pickle.dump(self, file)\n file.close()\n\n\n def plot_ccp(self, vmin=-0.05, vmax=0.05, \n save=False, title='', fmt='png'):\n \"\"\"\n Method to plot the final CCP stacks along the line.\n\n Parameters\n ----------\n vmin : float\n Maximum negative value for the color scale\n vmax : float\n Maximum positive value for the color scale\n save : boolean\n Whether or not to save the figure.\n fmt : str\n Format of saved figure\n xlen : float\n Total length of profile\n\n \"\"\"\n\n xlen = self.nx*self.dx\n xm = 1.5 + 0.0065*xlen\n fig, (ax1, ax2, ax3, ax4) = plt.subplots(\n 4, 1, figsize=(xm, 8))\n\n # plt.pcolormesh(xarray,zarray,xs_ps_avg,cmap=cm.coolwarm,vmin=vmin,vmax=vmax)\n im1 = ax1.pcolormesh(self.xarray, self.zarray,\n self.xs_ps_avg*self.weights[0], \n cmap=cm.RdBu_r,\n vmin=vmin, vmax=vmax)\n bar = plt.colorbar(im1, ax=ax1)\n ax1.set_xlim((min(self.xarray)),\n (max(self.xarray)))\n ax1.set_ylim((min(self.zarray)), (max(self.zarray)))\n bar.ax.set_ylabel('Amplitude', size=10)\n # ax1.set_xlabel('Lateral Distance (km)', size=10)\n ax1.set_ylabel('Depth (km)', size=10)\n ax1.set_title('Ps CCP image', size=10)\n ax1.invert_yaxis()\n\n # plt.pcolormesh(xarray,zarray,xs_pps_avg,cmap=cm.coolwarm,vmin=vmin,vmax=vmax)\n im2 = ax2.pcolormesh(self.xarray, self.zarray,\n self.xs_pps_avg*self.weights[1], \n cmap=cm.RdBu_r,\n vmin=vmin, vmax=vmax)\n bar = plt.colorbar(im2, ax=ax2)\n ax2.set_xlim((min(self.xarray)),\n (max(self.xarray)))\n ax2.set_ylim((min(self.zarray)), (max(self.zarray)))\n bar.ax.set_ylabel('Amplitude', size=10)\n # ax2.set_xlabel('Lateral Distance (km)', size=10)\n ax2.set_ylabel('Depth (km)', size=10)\n ax2.set_title('Pps CCP image', size=10)\n ax2.invert_yaxis()\n\n im3 = ax3.pcolormesh(self.xarray, self.zarray,\n self.xs_pss_avg*self.weights[2], \n cmap=cm.RdBu_r,\n vmin=vmin, vmax=vmax)\n bar = plt.colorbar(im3, ax=ax3)\n ax3.set_xlim((min(self.xarray)),\n (max(self.xarray)))\n ax3.set_ylim((min(self.zarray)), (max(self.zarray)))\n bar.ax.set_ylabel('Amplitude', size=10)\n # ax3.set_xlabel('Lateral Distance (km)', size=10)\n ax3.set_ylabel('Depth (km)', size=10)\n ax3.set_title('Pss CCP image', size=10)\n ax3.invert_yaxis()\n\n im4 = ax4.pcolormesh(self.xarray, self.zarray,\n self.tot_trace, cmap=cm.RdBu_r,\n vmin=vmin, vmax=vmax)\n bar = plt.colorbar(im4, ax=ax4)\n ax4.set_xlim((min(self.xarray)),\n (max(self.xarray)))\n ax4.set_ylim((min(self.zarray)), (max(self.zarray)))\n bar.ax.set_ylabel('Amplitude', size=10)\n ax4.set_xlabel('Lateral Distance (km)', size=10)\n ax4.set_ylabel('Depth (km)', size=10)\n ax4.set_title('Weighted CCP image', size=10)\n ax4.invert_yaxis()\n plt.tight_layout()\n\n if save:\n if not os.path.isdir(\"FIGURES\"):\n os.makedirs(\"FIGURES\")\n plt.savefig('FIGURES/ccp.' + title + '.' + fmt)\n\n plt.show()\n\n def plot_gccp(self, vmin=-0.015, vmax=0.015, \n save=False, title='', fmt='png'):\n \"\"\"\n Method to plot the final GCCP stacks along the line.\n\n Parameters\n ----------\n vmin : float\n Maximum negative value for the color scale\n vmax : float\n Maximum positive value for the color scale\n save : boolean\n Whether or not to save the figure.\n fmt : str\n Format of saved figure\n xlen : float\n Total length of profile\n\n \"\"\"\n\n xlen = self.nx*self.dx\n xm = 1.5 + 0.0065*xlen\n fig, (ax1, ax2, ax3, ax4) = plt.subplots(\n 4, 1, figsize=(xm, 8))\n\n # plt.pcolormesh(xarray,zarray,xs_ps_avg,cmap=cm.coolwarm,vmin=vmin,vmax=vmax)\n im1 = ax1.pcolormesh(self.xarray, self.zarray,\n self.xs_gauss_ps*self.weights[0], \n cmap=cm.RdBu_r,\n vmin=vmin, vmax=vmax)\n bar = plt.colorbar(im1, ax=ax1)\n ax1.set_xlim((min(self.xarray)),\n (max(self.xarray)))\n ax1.set_ylim((min(self.zarray)), (max(self.zarray)))\n bar.ax.set_ylabel('Amplitude', size=10)\n # ax1.set_xlabel('Lateral Distance (km)', size=10)\n ax1.set_ylabel('Depth (km)', size=10)\n ax1.set_title('Ps GCCP image', size=10)\n ax1.invert_yaxis()\n\n # plt.pcolormesh(xarray,zarray,xs_pps_avg,cmap=cm.coolwarm,vmin=vmin,vmax=vmax)\n im2 = ax2.pcolormesh(self.xarray, self.zarray,\n self.xs_gauss_pps*self.weights[1], \n cmap=cm.RdBu_r,\n vmin=vmin, vmax=vmax)\n bar = plt.colorbar(im2, ax=ax2)\n ax2.set_xlim((min(self.xarray)),\n (max(self.xarray)))\n ax2.set_ylim((min(self.zarray)), (max(self.zarray)))\n bar.ax.set_ylabel('Amplitude', size=10)\n # ax2.set_xlabel('Lateral Distance (km)', size=10)\n ax2.set_ylabel('Depth (km)', size=10)\n ax2.set_title('Pps GCCP image', size=10)\n ax2.invert_yaxis()\n\n im3 = ax3.pcolormesh(self.xarray, self.zarray,\n self.xs_gauss_pss*self.weights[2], \n cmap=cm.RdBu_r,\n vmin=vmin, vmax=vmax)\n bar = plt.colorbar(im3, ax=ax3)\n ax3.set_xlim((min(self.xarray)),\n (max(self.xarray)))\n ax3.set_ylim((min(self.zarray)), (max(self.zarray)))\n bar.ax.set_ylabel('Amplitude', size=10)\n # ax3.set_xlabel('Lateral Distance (km)', size=10)\n ax3.set_ylabel('Depth (km)', size=10)\n ax3.set_title('Pss GCCP image', size=10)\n ax3.invert_yaxis()\n\n import scipy.ndimage as ndimage\n self.tot_trace = ndimage.filters.gaussian_filter(\n self.tot_trace, sigma=(3, 0), order=0)\n\n im4 = ax4.pcolormesh(self.xarray, self.zarray,\n self.tot_trace, cmap=cm.RdBu_r,\n vmin=vmin, vmax=vmax)\n bar = plt.colorbar(im4, ax=ax4)\n ax4.set_xlim((min(self.xarray)),\n (max(self.xarray)))\n ax4.set_ylim((min(self.zarray)), (max(self.zarray)))\n bar.ax.set_ylabel('Amplitude', size=10)\n ax4.set_xlabel('Lateral Distance (km)', size=10)\n ax4.set_ylabel('Depth (km)', size=10)\n ax4.set_title('Phase-weighted GCCP image', size=10)\n ax4.invert_yaxis()\n plt.tight_layout()\n\n if save:\n if not os.path.isdir(\"FIGURES\"):\n os.makedirs(\"FIGURES\")\n plt.savefig('FIGURES/gccp.' + title + '.' + fmt)\n\n plt.show()\n\n\ndef ppoint_distance(tr, delta_z, vs):\n \"\"\"\n Calculate horizontal distance for interval delta_z and velocity vs\n\n Parameters\n ----------\n tr : :class:`~obspy.core.Trace`\n Single trace object to migrate to depth\n delta_z : float\n Vertical sampling distance\n vs : float\n S-wave velocity (km/s)\n\n \"\"\"\n\n # Calculate distance\n delta_x = delta_z*np.tan(np.arcsin(tr.stats.slow*vs))\n\n return delta_x\n\n\ndef ppoint(tr, dist):\n \"\"\"\n Determine geographic location of piercing point\n\n Parameters\n ----------\n tr : :class:`~obspy.core.Trace`\n Single trace object to migrate to depth\n dist : float\n Horizontal istance from the station (km)\n\n \"\"\"\n\n # Conversion factors\n lat2km = 111.\n lon2km = 90.\n\n # Get lat and lon of station location\n slat = tr.stats.stla\n slon = tr.stats.stlo\n\n # Back-azimuth of event\n baz = tr.stats.baz*np.pi/180.\n\n # location of piercing point on geographical grid\n plat = dist*np.sin(-baz+np.pi/2.)/lat2km + slat\n plon = dist*np.cos(-baz+np.pi/2.)/lon2km + slon\n\n return plon, plat\n\n\ndef ttime(tr, delta_z, vp, vs, phase=None):\n \"\"\"\n Calculate travel time for interval delta_z and velocities vp and vs\n\n Parameters\n ----------\n tr : :class:`~obspy.core.Trace`\n Single trace object to migrate to depth\n delta_z : float\n Vertical sampling distance (km)\n vp : float\n P-wave velocity\n vs : float\n S-wave velocity\n phase : str\n Phase of interest\n \"\"\"\n\n # Get horizontal slowness\n slow = tr.stats.slow\n\n # Calculate travel time for phase\n if phase == 'Ps':\n tt = delta_z*(np.sqrt((1./vs)**2 - slow**2) -\n np.sqrt((1./vp)**2 - slow**2))\n elif phase == 'Pps':\n tt = delta_z*(np.sqrt((1./vs)**2 - slow**2) +\n np.sqrt((1./vp)**2 - slow**2))\n elif phase == 'Pss':\n tt = 2.*delta_z*(np.sqrt((1./vs)**2 - slow**2))\n else:\n print('Error - unrecognized phase, ', phase)\n print('Returning tt = 0')\n tt = 0.\n\n return tt\n\n\ndef timeshift(tr, tt):\n \"\"\"\n Shift a trace by a travel time tt and take amplitude at zero\n\n Parameters\n ----------\n tr : :class:`~obspy.core.Trace`\n Single trace object to migrate to depth\n tt : float\n Travel time (sec)\n\n \"\"\"\n\n # Define frequencies\n nt = int(tr.stats.npts)\n dt = tr.stats.delta\n freq = np.fft.fftfreq(int(nt), d=dt)\n\n # Hilbert transform and instantaneous phase\n hilb = hilbert(tr.data)\n hilb_index = np.rint(tt/dt)\n hilb_tt = hilb[int(hilb_index)]\n hilb_tt_phase = np.arctan2(hilb_tt.imag, hilb_tt.real)\n\n # Fourier transform\n ftr = np.fft.fft(tr.data)\n\n # Shift using Fourier transform\n for i in range(len(freq)):\n # Fourier timeshift theorem\n ftr[i] = ftr[i]*np.exp(2.*np.pi*1j*freq[i]*tt)\n\n # Back to time domain (inverse Fourier transform)\n rtr = np.fft.ifft(ftr)\n\n # Take first sample from trace (convert to real value)\n amp = np.real(rtr[0])\n\n return amp, hilb_tt_phase\n\n\ndef raypath(tr, dep=None, vp=None, vs=None):\n \"\"\"\n Calculate travel times through velocity model for all phases of interest\n\n Parameters\n ----------\n tr : :class:`~obspy.core.Trace`\n Single trace object to migrate to depth\n nz : int\n Number of layers in interpolation\n dep : :class:`~numpy.ndarray`\n Depth array for velocity model\n vp : :class:`~numpy.ndarray`\n P-wave velocity array for velocity model\n vs : :class:`~numpy.ndarray`\n S-wave velocity array for velocity model\n\n \"\"\"\n\n # Get exact depth parameters\n delta_z = dep[1] - dep[0]\n nz = len(dep)\n\n # Define arrays with zeros\n plat = np.zeros(nz)\n plon = np.zeros(nz)\n ttps = np.zeros(nz)\n ttpps = np.zeros(nz)\n ttpss = np.zeros(nz)\n\n # Now loop through all depths\n for iz in range(nz):\n\n # Initialize travel time and distance counters\n dtps = 0.\n dtpps = 0.\n dtpss = 0.\n delta_x = 0.\n\n # Sum over depths from 0 to iz\n for i in range(iz):\n dtps += ttime(tr, delta_z, vp[i], vs[i], 'Ps')\n dtpps += ttime(tr, delta_z, vp[i], vs[i], 'Pps')\n dtpss += ttime(tr, delta_z, vp[i], vs[i], 'Pss')\n delta_x += ppoint_distance(tr, delta_z, vs[i])\n\n # Get piercing point from distance\n plo, pla = ppoint(tr, delta_x)\n\n # Assign values to arrays\n ttps[iz] = dtps\n ttpps[iz] = dtpps\n ttpss[iz] = dtpss\n plon[iz] = plo\n plat[iz] = pla\n\n return ttps, ttpps, ttpss, plon, plat\n\n\ndef haversine(lat, lon, xs_lat, xs_lon): # great-circle distance (kilometres)\n\n earth_radius = 6371. # kilometres\n\n lat = np.radians(lat)\n lon = np.radians(lon)\n xs_lat = np.radians(xs_lat)\n xs_lon = np.radians(xs_lon)\n dlat = lat - xs_lat\n dlon = lon - xs_lon\n a = ((np.sin(dlat/2.))**2.) + \\\n (np.cos(xs_lat)*np.cos(lat)*((np.sin(dlon/2.))**2.))\n distance = np.abs(2.*earth_radius*np.arcsin(np.sqrt(a)), dtype=float)\n\n return np.abs(distance)\n\n\ndef _progressbar(it, prefix=\"\", size=60, file=sys.stdout):\n \"\"\"\n Show progress bar while looping in for loop\n\n \"\"\"\n\n count = len(it)\n\n def show(j):\n x = int(size*j/count)\n file.write(\"%s[%s%s] %i/%i\\r\" %\n (prefix, \"#\"*x, \".\"*(size-x), j, count))\n file.flush()\n show(0)\n for i, item in enumerate(it):\n yield item\n show(i+1)\n file.write(\"\\n\")\n file.flush()\n", "meta": {"hexsha": "7a6c8370f1b7b1fb45ac25bc92605f2c41006802", "size": 37487, "ext": "py", "lang": "Python", "max_stars_repo_path": "rfpy/ccp.py", "max_stars_repo_name": "wsja/RfPy", "max_stars_repo_head_hexsha": "5b4b26bef131faa25c00b7a40f6bea7dd7bfe9b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2020-01-06T13:46:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:08:50.000Z", "max_issues_repo_path": "rfpy/ccp.py", "max_issues_repo_name": "wsja/RfPy", "max_issues_repo_head_hexsha": "5b4b26bef131faa25c00b7a40f6bea7dd7bfe9b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2020-02-19T00:44:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:15:58.000Z", "max_forks_repo_path": "rfpy/ccp.py", "max_forks_repo_name": "wsja/RfPy", "max_forks_repo_head_hexsha": "5b4b26bef131faa25c00b7a40f6bea7dd7bfe9b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2020-01-13T03:32:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T19:03:09.000Z", "avg_line_length": 35.4990530303, "max_line_length": 87, "alphanum_fraction": 0.5771600822, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 9520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.2814056194821862, "lm_q1q2_score": 0.14509834180138786}} {"text": "#! /usr/bin/env python\n# coding=utf-8\n\"\"\" Find best PSF stars using GA to minimize mean error.\n\n .. seealso:: :ref:`gapick`\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\n# For now:\n# TODO: --neigbours option: once for generation neightbour removal\n# TODO: --timestamp: add current timestamp to directory name (+)\n# TODO: conf option for\n# TODO: warnings about: daophot.opt, allstar.opt\n# TODO: single parameter --aperture, instead of photo.opt\n# TODO: write down text based statistics from logbook.pkl\n# TODO: some docs, and link to them in --help\n# TODO: allstar.opt missing in result dir!\n# For later, on request:\n# TODO: Option for provide own PSF stars set, used for comaprision, including in candidates, put in initial population\n# TODO: Checkpoints - continue calculation\n\n\n\nimport os\nimport logging\nimport random\nimport pickle\nimport time\nfrom datetime import timedelta\nfrom copy import deepcopy\n\ntry:\n from itertools import izip_longest as zip_longest\nexcept ImportError:\n from itertools import zip_longest\n\nimport numpy\nfrom bitarray import bitarray\nfrom scipy.stats import sigmaclip\nfrom deap import base\nfrom deap import creator\nfrom deap import tools\n\nimport astwro.tools.__commons as commons\nimport astwro.starlist as sl\nimport astwro.pydaophot as dao\nimport astwro.tools\nimport astwro.utils as utils\nfrom astwro.phot import PhotError\n\n_time_format = '%a %H:%M:%S'\n\n\n# Definitions for genetic algorithm:\n# 'individual' - subset of candidates competing with other subsets to be the best in fitness\n# 'genome' - the individual's definition with subset of candidates stars, is represented by binary string\n# of length equal to number of candidate stars. '1' means that star is in subset.\n# 'fitness' - minimized function on individual, mean of errors form allstar if individual's stars are\n# taken as PSF stars\n# 'population' - set of all individuals in some iteration\n\n# 2.1 Definition of routines used by algorithms: initializations, scoring\ndef select_stars(starlist, genome):\n # type: (sl.StarList, bitarray) -> sl.StarList\n # Select stars present in genome\n return starlist[genome.tolist()]\n\n\ndef random_genome(ind_class, len, prob_limits):\n # type: (type, int, [float, float]) -> bitarray\n # Create random genome of length `len` in which probability of '1' on any position is from `prob_limits` range.\n prob = random.uniform(prob_limits[0], prob_limits[1])\n return ind_class([random.random() <= prob for _ in range(len)])\n\n\ndef clone_individual(individual):\n # type: (bitarray) -> bitarray\n # Make a deepcopy-clone - deepcopy genome bitarray and associated fitness\n n = deepcopy(individual)\n n.fitness = deepcopy(individual.fitness)\n return n\n\n\ndef calc_spectrum(pop):\n # calculates 'spectrogram' of population\n # which is a statistic of stars occurrences in population individuals\n spec = numpy.zeros(len(pop[0]))\n for ind in pop:\n spec += ind.tolist()\n return spec\n\n\n# === astwro version <= 0.7.0\n# def fitness_for_als(als):\n# # type: (sl.StarList) -> (float,)\n# # Calucalates fitness from allstar result\n# clipped = sigmaclip(als.chi)[0]\n# return numpy.sqrt((clipped * clipped).sum()), # fitness is tuple (val,)\n\n# === astwro version > 0.7.0\n# def fitness_for_als(als):\n# # type: (sl.StarList) -> (float,)\n# # Calucalates fitness from allstar result\n# w = 100*(-als.mag/5)\n#\n# return (als.chi*w).sum()/w.sum(), # fitness is tuple (val,)\n\n# === astwro version > 0.7.2\ndef fitness_for_als(als):\n # type: (sl.StarList) -> (float,)\n # Calucalates fitness from allstar result\n w = 100*(-als.mag/5)\n\n return (als.mag_err*w).sum()/w.sum(), # fitness is tuple (val,)\n\n\ndef eval_population(population, candidates, workers, show_progress, fine_tune):\n if fine_tune:\n return eval_population_fine_psf(population, candidates, workers, show_progress)\n else:\n return eval_population_simple(population, candidates, workers, show_progress)\n\n\ndef eval_population_fine_psf(population, candidates, workers, show_progress):\n # type: (list(bitarray), sl.StarList, list(dict), bool) -> list\n # Evaluates fitness for all individual in population.\n\n # This version uses sofisticated process from daophot_bialkow\n # Uses daophots and allstars processes form `workers` running them in parallel.\n # :return: list fitnesses (1-element couples as `deap` lib likes)\n\n progress = None\n if show_progress:\n progress = utils.progressbar(total=len(population), step=len(workers))\n progress.print_progress(0)\n fitnesses = []\n f_max = None\n # https://docs.python.org/3/library/itertools.html#itertools-recipes grouper()\n # grouping population into chunks of size `parallel`\n for chunk in zip_longest(*([iter(population)] * len(workers))):\n active = [g is not None for g in chunk] # all active, on errors some could be deactivated\n # PSF\n for individual, worker in zip(chunk, workers):\n if individual:\n pdf_s = select_stars(candidates, individual)\n worker['daophot'].write_starlist(pdf_s, 'i.lst')\n worker['daophot'].PSf(psf_stars='i.lst') # add to queue only - batch mode\n worker['daophot'].run(wait=False) # parallel start all workers without waiting\n # wait for PSF and start ALLSTAR nei\n for i, worker in enumerate(workers):\n if active[i]:\n worker['daophot'].wait_for_results() # now wait before using results\n active[i] = worker['daophot'].PSf_result.converged # PSF is not always successful\n if active[i]:\n worker['allstar'].ALlstar(stars='i.nei') # enqueue calculation\n worker['allstar'].run(wait=False) # asynchronous / parallel\n # second PSF\n for i, worker in enumerate(workers):\n if active[i]:\n worker['allstar'].wait_for_results()\n if worker['allstar'].ALlstars_result.success:\n worker['daophot'].SUbstar(subtract='i.als', leave_in='i.lst')\n worker['daophot'].run() # quick run\n worker['daophot'].ATtach('is')\n worker['daophot'].PSf(photometry='i.als', psf_stars='i.lst')\n worker['daophot'].run(wait=False)\n else:\n active[i] = False\n # second allstar\n for i, worker in enumerate(workers):\n if active[i]:\n worker['daophot'].wait_for_results()\n if worker['daophot'].PSf_result.success:\n worker['allstar'].ALlstar(stars='i.nei') # enqueue calculation\n worker['allstar'].run(wait=False) # asynchronous / parallel\n else:\n active[i] = False\n # third PSF\n for i, worker in enumerate(workers):\n if active[i]:\n worker['allstar'].wait_for_results()\n if worker['allstar'].ALlstars_result.success:\n worker['daophot'].SUbstar(subtract='i.als', leave_in='i.lst')\n worker['daophot'].run() # quick run\n worker['daophot'].ATtach('is')\n worker['daophot'].PSf(photometry='i.als', psf_stars='i.lst')\n worker['daophot'].run(wait=False)\n else:\n active[i] = False\n # final allstar\n for i, worker in enumerate(workers):\n if active[i]:\n worker['daophot'].wait_for_results()\n if worker['daophot'].PSf_result.success:\n worker['allstar'].ALlstar(stars='als.ap') # enqueue calculation\n worker['allstar'].run(wait=False) # asynchronous / parallel\n else:\n active[i] = False\n\n # wait for allstar for workers and process results\n for i, worker in enumerate(workers):\n if active[i]:\n worker['allstar'].wait_for_results()\n all_s = worker['allstar'].ALlstars_result.als_stars\n f = fitness_for_als(all_s)\n fitnesses.append(f) # fitness is tuple (val,)\n f_max = f if f_max is None or f_max[0] < f[0] else f_max\n # f_max = f[0] if f_max is None else max(f_max, f[0])\n else:\n fitnesses.append(None)\n # cut fitnesses if longer than population\n # (finesses mod parallel == 0, some None at the end can appear if population mod parallel != 0)\n fitnesses = fitnesses[:len(population)]\n # fill gaps in fitnesses with maximum of rest of population\n for i, f in enumerate(fitnesses):\n if f is None:\n fitnesses[i] = f_max\n if progress:\n progress.print_progress()\n\n return fitnesses\n\n\ndef eval_population_simple(population, candidates, workers, show_progress):\n # type: (list(bitarray), sl.StarList, list(dict), bool) -> list\n # Evaluates fitness for all individual in population.\n # Uses daophots and allstars processes form `workers` running them in parallel.\n # :return: list fitnesses (1-element couples as `deap` lib likes)\n\n progress = None\n if show_progress:\n progress = utils.progressbar(total=len(population), step=len(workers))\n progress.print_progress(0)\n fitnesses = []\n f_max = None\n # https://docs.python.org/3/library/itertools.html#itertools-recipes grouper()\n # grouping population into chunks of size `parallel`\n for chunk in zip_longest(*([iter(population)] * len(workers))):\n active = [g is not None for g in chunk] # all active, on errors some could be deactivated\n # PSF\n for individual, worker in zip(chunk, workers):\n if individual:\n pdf_s = select_stars(candidates, individual)\n worker['daophot'].PSf(psf_stars=pdf_s) # add to queue only - batch mode\n worker['daophot'].run(wait=False) # parallel start all workers without waiting\n # wait for PSF and start ALLSTAR\n for i, worker in enumerate(workers):\n if active[i]:\n worker['daophot'].wait_for_results() # now wait before using results\n active[i] = worker['daophot'].PSf_result.converged # PSF is not always successful\n if active[i]:\n worker['allstar'].ALlstar(stars='als.ap') # enqueue calculation\n worker['allstar'].run(wait=False) # asynchronous / parallel\n # wait for allstar for workers and process results\n for i, worker in enumerate(workers):\n if active[i]:\n worker['allstar'].wait_for_results()\n all_s = worker['allstar'].ALlstars_result.als_stars\n f = fitness_for_als(all_s)\n fitnesses.append(f) # fitness is tuple (val,)\n f_max = f if f_max is None or f_max[0] < f[0] else f_max\n # f_max = max(f_max, f)\n else:\n fitnesses.append(None)\n # cut fitnesses if longer than population\n # (finesses mod parallel == 0, some None at the end can appear if population mod parallel != 0)\n fitnesses = fitnesses[:len(population)]\n # fill gaps in fitnesses by maximum of rest of population\n for i, f in enumerate(fitnesses):\n if f is None:\n fitnesses[i] = f_max\n if progress:\n progress.print_progress()\n\n return fitnesses\n\n\ndef _prepare_output_dir(outdir, overwrite, srcdir, arg):\n # type: (str, bool, str, object) -> (utils.CycleFile, utils.CycleFile, utils.CycleFile, str)\n # Prepare output directory for results\n if outdir:\n from shutil import copytree, rmtree\n\n outdir = os.path.abspath(os.path.expanduser(outdir))\n if os.path.exists(outdir):\n if overwrite:\n rmtree(outdir)\n else:\n logging.error('--out-dir:{} already exists and no --overwrite requested.'.format(outdir))\n raise Exception('Output directory {} exists.'.format(outdir))\n copytree(srcdir, outdir)\n logging.info('Results dir created: {}'.format(outdir))\n # todo allstar.opt missing in result dir!\n basename = 'gen'\n lst_file = utils.cyclefile(outdir, basename, '.lst')\n reg_file = utils.cyclefile(outdir, basename, '.reg')\n gen_file = utils.cyclefile(outdir, basename, '.gen')\n # write down parameters\n with open(os.path.join(outdir, 'about.txt'), 'w') as f:\n print(\"astwro pydaophot/tools version: {}/{}\\n\".format(dao.__version__, astwro.tools.__version__), file=f)\n for k, v in arg.__dict__.items():\n print('{}\\t= {}'.format(k, v), file=f)\n return lst_file, reg_file, gen_file, outdir\n else:\n return None, None, None, None\n\n\ndef _plot_err(pe, pe_psf, psf, fig_file):\n # type: (PhotError) -> None\n try:\n import matplotlib\n matplotlib.use('pdf')\n import matplotlib.pyplot as plt\n except ImportError:\n logging.warning(\"'matplotlib' cannot be imported. No control diagrams will be generated\")\n except:\n logging.warning('matplotlib PDF output cannot be initialized. No control diagrams will be generated')\n return\n else:\n try:\n plt.rc('text', usetex=True)\n except:\n pass\n\n ax = plt.subplot()\n ls = numpy.linspace(pe.mag.min(), pe.mag.max())\n ax.plot(pe.mag[~pe.outlayers_mask], pe.err[~pe.outlayers_mask], '.', alpha=0.7, ms=2,\n label='training set')\n ax.errorbar(pe.mag_means, pe.err_means, yerr=pe.err_means_stderr * 1.0, fmt='D', markerfacecolor='none', alpha=0.7, lw=1,\n label='error bins')\n ax.plot(ls, pe.evaluate_fit(ls), lw=1,\n label='error fit')\n ax.plot(ls, pe.evaluate_fit_plus_sigmas(ls), '--', lw=1,\n label='error$+{:.1f}\\\\sigma$ fit (training limit)'.format(pe.fitplussigma))\n ax.plot(ls, pe_psf.evaluate_fit_plus_sigmas(ls), '--', lw=1,\n label='error$+{:.1f}\\\\sigma$ fit (PSF limit)'.format(pe_psf.fitplussigma))\n ax.plot(pe.mag[pe.outlayers_mask], pe.err[pe.outlayers_mask], '.', alpha=0.7, ms=3,\n label='outlayers')\n ax.plot(psf.mag, psf.mag_err, '.', alpha=0.7, ms=3,\n label='PSF candidates')\n ax.set_xlabel('mag'); ax.set_ylabel('mag error')\n ax.legend()\n ax.figure.savefig(fig_file, bbox_inches='tight')\n ax.set_ylim(0,0.2)\n ax.figure.savefig('{}_zoomed{}'.format(*os.path.splitext(fig_file)), bbox_inches='tight')\n logging.info('Control plot mag/err {} generated'.format(fig_file))\n\n\ndef __do(arg):\n # Main routine, common for command line, and python scripts call\n # :type arg: Namespace\n\n start_time = time.time()\n\n # Configure progress logging\n clogger = logging.getLogger('clean logger') # create another logger for stats without prefixes (clean)\n chandler = logging.StreamHandler()\n chandler.setFormatter(logging.Formatter('%(message)s'))\n clogger.propagate = False\n clogger.addHandler(chandler)\n\n check_arguments(arg)\n\n # image_file\n if arg.image is None:\n from astwro.sampledata import fits_image\n arg.image = fits_image() # sample image\n\n logging.warning('No image file argument provided (-h for help), using demonstration image: %s', arg.image)\n\n # expand patches of file parameters\n arg.all_stars_file = dao.Daophot.expand_path(arg.all_stars_file)\n arg.psf_stars_file = dao.Daophot.expand_path(arg.psf_stars_file)\n arg.photo_opt = dao.Daophot.expand_path(arg.photo_opt)\n arg.daophot_opt = dao.Daophot.expand_path(arg.daophot_opt)\n\n # get single daophot and ATtach file\n dp = dao.Daophot(image=arg.image, daophotopt=arg.daophot_opt)\n al = dao.Allstar(image=arg.image, dir=dp.dir)\n\n # all stars file\n if not arg.all_stars_file:\n logging.warning('No all-stars-file provided, Stars will be found by daophot FIND (frames av/sum: %d/%d)',\n arg.frames_av, arg.frames_sum)\n find = dp.FInd(arg.frames_av, arg.frames_sum)\n logging.info('{} stars found by FIND, sky estimation: {}, err/dev: {}/{}'.format(find.stars, find.sky, find.err,\n find.skydev))\n arg.all_stars_file = find.starlist_file\n\n # photometry\n if not arg.photo_opt: # no file no problem, but recreate default radius if not provided\n if arg.photo_is == 0:\n arg.photo_is = 35\n if arg.photo_os == 0:\n arg.photo_os = 50\n if not arg.photo_ap:\n arg.photo_ap = [8]\n logging.info('Performing preliminary {} pixels aperture photometry'.format(arg.photo_ap[0]))\n photometry = dp.PHotometry(photoopt=arg.photo_opt,\n IS=arg.photo_is,\n OS=arg.photo_os,\n apertures=arg.photo_ap,\n stars=arg.all_stars_file)\n\n # pick PFS stars candidates\n PICKcandidates = not arg.psf_stars_file\n if PICKcandidates:\n pick = dp.PIck(arg.stars_to_pick, arg.faintest_to_pick)\n arg.psf_stars_file = pick.picked_stars_file\n\n # psf (for errors collection)\n PSf_result = dp.PSf(psf_stars=arg.psf_stars_file)\n\n # all stars (filtering by photometry errors and magnitudes)\n stars = photometry.photometry_starlist\n count0 = stars.shape[0]\n stars = stars[stars.mag < arg.max_ph_mag]\n count1 = stars.shape[0]\n stars = stars[stars.mag_err < arg.max_ph_err]\n count2 = stars.shape[0]\n logging.info('{} (of {}) stars left after filtering against {:.2f} photometry magnitude threshold, '\n .format(count1, count0, arg.max_ph_mag))\n logging.info('{} left after {:.2f} aperture photometry error threshold'\n .format(count2, arg.max_ph_err))\n\n logging.info('Performing preliminary PSF profile photometry')\n ALlstar_result = al.ALlstar(stars=stars)\n logging.info('{} stars converged in PSF profile photometry'\n .format(ALlstar_result.stars_no[0]))\n logging.info('Fitting PSF profile photometry errors')\n pe = PhotError(ALlstar_result.als_stars.mag, ALlstar_result.als_stars.mag_err, fitplussigma=arg.clip_fit_sigmas)\n logging.info('{} stars left, after excluding profile photometry error {} sigma outliers'\n .format((~pe.outlayers_mask).sum(), arg.clip_fit_sigmas))\n stars = ALlstar_result.als_stars[~pe.outlayers_mask]\n\n # for the sake of optimisation we write starlist to file to avoid multiple serialization of this list\n # (instead of more obvious providing starlist as the allstar argument)\n dp.write_starlist(stars, 'als.ap', sl.DAO.AP_FILE)\n\n # candidates (filter out big psf errors)\n pe2 = None\n if PICKcandidates: # do it again\n if arg.clip_fit_sigmas > arg.clip_psf_fit_sigmas: # tighter filtering for PSF candids\n logging.info('Excluding {} sigma outlayers for PICK'.format(arg.clip_psf_fit_sigmas))\n pe2 = PhotError(ALlstar_result.als_stars.mag, ALlstar_result.als_stars.mag_err,\n fitplussigma=arg.clip_psf_fit_sigmas)\n cands_for_cands = ALlstar_result.als_stars[~pe2.outlayers_mask]\n else:\n cands_for_cands = stars\n pick = dp.PIck(arg.stars_to_pick, arg.faintest_to_pick, photometry=cands_for_cands)\n logging.info('{} PSF stars candidates selected by PICK'.format(pick.stars))\n arg.psf_stars_file = pick.picked_stars_file\n PSf_result = dp.PSf(psf_stars=arg.psf_stars_file) # collect PSF errors\n candidates = dp.read_starlist(arg.psf_stars_file, add_psf_errors=True)\n org_cand_no = candidates.stars_number()\n err = PSf_result.errors\n averr = err.psf_err.mean()\n err = err[(err.psf_err < arg.max_psf_err_mult * averr) & (\n err.flag == ' ')] # filter out big errors and * or ? marked stars\n candidates = candidates.loc[err.index]\n\n # candidates = candidates[candidates.psf_err < arg.max_psf_err] # old filter, new above\n logging.info(\n \"{} good candidates ({} rejected: * or ? or psf error exceeded max-psf-err-mult*averge-error \"\n \"= {:.2f}*{:.2f} = {:.2f})\"\n .format(\n candidates.stars_number(),\n org_cand_no - candidates.stars_number(),\n arg.max_psf_err_mult,\n averr,\n arg.max_psf_err_mult * averr)\n )\n if arg.include_psf:\n logging.info('PSF star candidates stays in training set (--include-psf)')\n else:\n overlapping = stars.index.isin(candidates.index)\n stars = stars[~overlapping]\n logging.info('{} stars left in training set after exclusion PSF star candidates (no --include-psf)'\n .format(stars.stars_number()))\n\n if candidates.stars_number() < 15:\n logging.error(\"Number of candidates lass than 15. GA needs more. Sorry...\")\n\n if stars.stars_number() < 15:\n logging.error(\"Number stars in training set lass than 15. GA needs more. Sorry...\")\n\n # Prepare output directory for results\n lst_file, reg_file, gen_file, result_dir = _prepare_output_dir(arg.out_dir, arg.overwrite, str(dp.dir), arg)\n _plot_err(pe, pe2, candidates, os.path.join(arg.out_dir, 'prel_psf_filtering.pdf'))\n\n # From all candidates find best subset, where best means minimizing mean of errors form allstar\n # using genetic algorithm\n # For details about setting up genetic algorithm with DEAP visit:\n # http://deap.gel.ulaval.ca/doc/default/examples/ga_onemax.html\n\n creator.create(\"FitnessMax\", base.Fitness, weights=(-1.0,))\n creator.create(\"Individual\", bitarray, fitness=creator.FitnessMax)\n\n toolbox = base.Toolbox()\n # Structure initializes\n toolbox.register(\"individual\", random_genome, creator.Individual, candidates.stars_number(), arg.ga_init_prob)\n toolbox.register(\"population\", tools.initRepeat, list, toolbox.individual)\n toolbox.register('clone', clone_individual)\n\n # The Genetic Operators\n\n # set min_stars to all_cand_no*ga_init_prob/2\n toolbox.register('mate', tools.cxTwoPoint)\n toolbox.register('mutate', tools.mutFlipBit, indpb=arg.ga_mut_str)\n toolbox.register('select', tools.selTournament, tournsize=3)\n\n # setup stats\n stats_fits = tools.Statistics(key=lambda ind: ind.fitness.values)\n stats_star = tools.Statistics(key=sum) # number of stars is an sum of bitarray: [001101010001] has 5 stars\n stats = tools.MultiStatistics(fitness=stats_fits, size=stats_star)\n stats.register('avg', numpy.mean)\n stats.register('std', numpy.std)\n stats.register('min', numpy.min)\n stats.register('max', numpy.max)\n\n # Initiate workers. Each worker has Daophot and Allstar objects sharing runner directory,\n # working in batch mode.\n workers = []\n workers_logger = logging.getLogger('worker')\n workers_logger.setLevel('ERROR') # prevent workers flood output with logrecords\n for i in range(arg.parallel):\n d = dp.clone() # clone previously used daophot\n d.batch_mode = True\n a = dao.Allstar(dir=d.dir, image=d.image, batch=True, options={'MA': 100})\n d.logger = workers_logger\n a.logger = workers_logger\n workers.append({'daophot': d, 'allstar': a})\n\n # Setup initial population, HoF and logbook and or load it from checkpoint when continuing previous calculation\n start_gen = 0\n\n # if arg.checkpoint: ## Not implemented\n if False:\n with open(os.path.expanduser(arg.checkpoint), \"rb\") as f:\n checkpoint = pickle.load(f)\n pop = checkpoint['population']\n start_gen = checkpoint['generation']\n hof = checkpoint['halloffame']\n logbook = checkpoint['logbook']\n logging.info('Restoring genetic algorithm on {} of {} generations'.format(start_gen, arg.ga_max_iter))\n else:\n hof = tools.HallOfFame(maxsize=10)\n\n logbook = tools.Logbook()\n logbook.header = 'gen', 'fitness', 'size'\n logbook.chapters['fitness'].header = 'min', 'avg', 'max', 'std'\n logbook.chapters['size'].header = 'min', 'avg', 'max'\n\n pop = toolbox.population(n=arg.ga_pop)\n logging.info('Starting genetic algorithm for {} generations at {}'.format(\n arg.ga_max_iter,\n time.strftime(_time_format, time.localtime())\n ))\n logging.info('{} parallel threads, ETA will be calculated after generation 1'.format(arg.parallel))\n\n # Calculate fitnesses of initial population\n fitnesses = eval_population(pop, candidates, workers, show_progress=not arg.no_progress, fine_tune=arg.fine)\n for ind, fit in zip(pop, fitnesses):\n ind.fitness.values = fit\n\n record = stats.compile(pop)\n logbook.record(gen=0, spectrum=calc_spectrum(pop), **record)\n clogger.info('{}\\t ETA: [... to be determined]'.format(logbook.stream))\n\n evolution_start_time = time.time()\n\n # Begin the evolution\n for g in range(start_gen + 1, arg.ga_max_iter):\n # New Generation\n # select the next generation individuals\n offspring = toolbox.select(pop, len(pop))\n # Clone the selected individuals\n offspring = list(map(toolbox.clone, offspring))\n # Apply crossover and mutation on the offspring\n for child1, child2 in zip(offspring[::2], offspring[1::2]):\n if random.random() < arg.ga_cross_prob:\n toolbox.mate(child1, child2)\n del child1.fitness.values\n del child2.fitness.values\n for mutant in offspring:\n if random.random() < arg.ga_mut_prob:\n toolbox.mutate(mutant)\n del mutant.fitness.values\n\n # calculate fitnesses of new individuals\n invalid_ind = [ind for ind in offspring if not ind.fitness.valid]\n fitnesses = eval_population(invalid_ind, candidates, workers, show_progress=not arg.no_progress,\n fine_tune=arg.fine)\n for ind, fit in zip(invalid_ind, fitnesses):\n ind.fitness.values = fit\n # New population from offspring\n pop[:] = offspring\n\n # Stats\n # hof.update(pop) # not implemented yet, __deapcopy__ of the Individual should work first\n ETA = time.strftime(_time_format, time.localtime(\n evolution_start_time + (time.time() - evolution_start_time) * arg.ga_max_iter / g))\n record = stats.compile(pop)\n logbook.record(gen=g, spectrum=calc_spectrum(pop), **record)\n clogger.info('{}\\t ETA: {}'.format(logbook.stream, ETA))\n\n # For every generation create lst file and ds9 reg file of best and point symlinks to last generation\n if result_dir:\n best_ind = tools.selBest(pop, 1)[0]\n best_stars = select_stars(candidates, best_ind)\n lst_file.next_file(g)\n reg_file.next_file(g)\n gen_file.next_file(g)\n sl.write_dao_file(best_stars, lst_file.file, sl.DAO.LST_FILE)\n sl.write_ds9_regions(best_stars, reg_file.file)\n for ind in pop:\n gen_file.file.write(ind.to01() + '\\n')\n with open(os.path.join(result_dir, 'logbook.pkl'), 'wb') as f:\n pickle.dump(logbook, f)\n checkpoint = dict(population=pop, generation=g, halloffame=hof, logbook=logbook)\n with open(os.path.join(result_dir, 'checkpoint.chk'), 'wb') as f:\n pickle.dump(checkpoint, f)\n\n # end of evolution loop\n\n if result_dir:\n lst_file.close()\n reg_file.close()\n gen_file.close()\n\n logging.info('Successful evolution finished at {} (elapsed time: {:s})'.format(\n time.strftime(_time_format, time.localtime()),\n str(timedelta(seconds=time.time() - start_time))\n ))\n\n best_ind = tools.selBest(pop, 1)[0]\n logging.info('Best individual is {}, {}'.format(best_ind, best_ind.fitness.values))\n\n best_stars = select_stars(candidates, best_ind)\n return best_stars\n\n\n__arg_parser_singlethon = None\n\n\ndef __arg_parser():\n global __arg_parser_singlethon\n if __arg_parser_singlethon:\n return __arg_parser_singlethon\n import argparse\n parser = argparse.ArgumentParser(\n description='Find best PSF stars using genetic algorithm running the daophot/allstar'\n ' workflow for number of a PSF stars sets.'\n ' Minimized function'\n ' is the mean of allstar\\'s chi statistic, weighted by flux, calculated on '\n ' training subset of of all stars. Results'\n ' are stored in --dir directory if provided. List of star ids'\n ' of the best set found, is printed to stdout (until suppressed by -no_stdout)',\n epilog=commons.version_string(),\n )\n parser.add_argument('image', default=None, nargs='?',\n help='FITS image file (obligatory if no --demo)')\n g_dao = parser.add_argument_group('DAOPHOT/ALLSTARS related parameters',\n 'Those parameters are used by DAOPHOT/ALLSTARS workflow. gapick optimizes PSF '\n 'fitting errors of that workflow applied to training set stars as a function'\n 'of \\'PSF stars\\' sets - stars used to derive PSF function')\n g_dao.add_argument('-c', '--all-stars-file', metavar='FILE', default=None,\n help='all stars input file in one of daophot\\'s formats (default: obtained by daophot FIND)')\n g_dao.add_argument('-D', '--daophot-opt', metavar='FILE', default=None,\n help='daophot.opt file for daophot (default: internal)')\n g_dao.add_argument('--frames-av', metavar='n', type=int, default=1,\n help='frames ave - parameter of daophot FIND when --all-stars-file not provided (default: 1)')\n g_dao.add_argument('--frames-sum', metavar='n', type=int, default=1,\n help='frames summed - parameter of daophot FIND when --all-stars-file not provided (default: 1)')\n g_dao.add_argument('-O', '--photo-opt', metavar='FILE', default=None,\n help='photo.opt file for aperture photometry (default: none)')\n g_dao.add_argument('--photo-is', metavar='r', type=int, default=0,\n help='PHOTOMETRY inner sky radius, overwrites photo.opt, (default: from --photo-opt or 35)')\n g_dao.add_argument('--photo-os', metavar='r', type=int, default=0,\n help='PHOTOMETRY outher sky radius, overwrites photo.opt, (default: from --photo-opt or 50)')\n g_dao.add_argument('--photo-ap', metavar='r', type=int, default=[], nargs='+',\n help='PHOTOMETRY apertures radius (up to 12), overwrites photo.opt, '\n '(default: from --photo-opt or 8)')\n g_dao.add_argument('-l', '--psf-stars-file', metavar='FILE', default=None,\n help='PSF candidates input file in one of daophot\\'s formats, the result of algorithm is '\n 'a subset of those stars (default: obtained by daophot PICK)')\n g_dao.add_argument('-P', '--stars-to-pick', metavar='n', type=int, default=100,\n help='number of stars to PICK as candidates when --stars-to-pick not provided (default: 100)')\n g_dao.add_argument('--faintest-to-pick', metavar='MAG', type=int, default=20,\n help='faintest magnitude to PICK as candidates when --stars-to-pick not provided (default: 20)')\n g_dao.add_argument('-f', '--fine', action='store_true',\n help='fine tuned PSF calculation (3 iter) for crowded fields, without this option no neighbours'\n 'subtraction will be performed (slower, usually not needed)')\n g_flt = parser.add_argument_group('Filtering training set stars',\n 'Options controls which stars will be included in a training set -- whose '\n 'residuals after the PSF fitting will be minimized by genetic algorithm')\n g_flt.add_argument('-x', '--include-psf', action='store_true',\n help='NEW | include candidates of PSF stars in training set; by default PSF candidates are'\n 'excluded from calculation of minimized PSF error; may be included if there is low number'\n 'of stars')\n g_flt.add_argument('--max-ph-err', metavar='x', type=float, default=0.1,\n help='threshold of aperture photometry error for training set stars; '\n 'stars for which aperture photometry (daophot PHOTO) error is greater than x '\n 'will be excluded and have no effect on minimization '\n '(default 0.1)')\n g_flt.add_argument('--max-ph-mag', metavar='m', type=float, default=20,\n help='threshold of aperture photometry magnitude of stars for for training set stars; '\n '(analogous to --max-ph-err)stars for which aperture photometry (daophot PHOTO) magnitude '\n 'is greater than m (fainter than m) will be excluded form allstar run and have no effect '\n 'on quality measurement (default 20)')\n g_flt.add_argument('--clip-fit-sigmas', metavar='x', type=float, default=3.0,\n help='NEW | threshold of errors from the preliminary PSF fitting (allstars) in sigmas above '\n 'mean error level for specific magnitude (a mean error level for the magnitude is fitted) '\n 'stars with preliminary PSF fitting error greater than mean_err(mag)+x*sigma will '\n 'be rejected from training set (default 3.0)')\n g_psf = parser.add_argument_group('Filtering candidates for PSF stars',\n 'Options controls which stars can be considered as PSF candidates. '\n 'Filtering is applied to stars provided in --psf-stars-fil or found by '\n 'daophot/PICK')\n g_psf.add_argument('--max-psf-err-mult', metavar='x', type=float, default=3.0,\n help='threshold of PSF errors of PSF candidates - as multiplier of average PSF error; '\n 'candidates with PSF error (from daophot PSF command) greater than x*av_err will '\n 'be rejected (as well as other marked ? or * by daophot/PSF command)'\n '(default 3.0)')\n g_psf.add_argument('--clip-psf-fit-sigmas', metavar='x', type=float, default=2.0,\n help='NEW | threshold of errors from the preliminary PSF fitting (allstars) in sigmas above '\n 'mean error level for specific magnitude (a mean error level for the magnitude is fitted) '\n 'candidates with preliminary PSF fitting error greater than mean_err(mag)+x*sigma will '\n 'be rejected (default 2.0)')\n g_ga = parser.add_argument_group('Genetic algorithm parameters')\n g_ga.add_argument('-I', '--ga-init-prob', metavar='x', default=[0.3, 0.8], type=float, nargs='+',\n help='what portion of candidates is used to initialize GA individuals;'\n ' e.g. if there is 100 candidates, each of them will be '\n ' chosen to initialize individual genome with probability x; '\n ' in other words if x=0.3 first population in GA will contain'\n ' individuals with around 30 stars each; '\n ' two numbers (e.g. -I 0.3 0.8) indicates range: for each initial genome'\n ' random number from that range will be taken (spreading number of initial stars)'\n ' (default: 0.3 0.8)')\n g_ga.add_argument('-i', '--ga-max-iter', metavar='n', default=50, type=int,\n help='maximum number of iterations of generic algorithm - generations (default: 50)')\n g_ga.add_argument('-n', '--ga-pop', metavar='n', default=80, type=int,\n help='population size of GA (default: 80)')\n g_ga.add_argument('--ga-cross-prob', metavar='x', default=0.5, type=float,\n help='crossover probability of GA (default: 0.5)')\n g_ga.add_argument('--ga-mut-prob', metavar='x', default=0.2, type=float,\n help='mutation probability of GA - probability to became a mutant (default: 0.2)')\n g_ga.add_argument('--ga-mut-str', metavar='x', default=0.05, type=float,\n help='mutation strength of GA - probability of every bit flip in mutant (default: 0.05)')\n g_cnt = parser.add_argument_group('gapick run control parameters')\n g_cnt.add_argument('-p', '--parallel', metavar='n', type=int, default=8,\n help='how many parallel processes can be forked; '\n 'n=1 avoids parallelism (default: 8)')\n g_cnt.add_argument('-d', '--out-dir', metavar='output_dir', type=str, default='RESULTS',\n help='output directory; directory will be created and result files will be stored there;'\n ' directory should not exist or --overwrite flag should be set'\n ' (default: RESULTS)')\n g_cnt.add_argument('-o', '--overwrite', action='store_true',\n help='if directory specified by --out_dir parameter exists, '\n 'then ALL its content WILL BE DELETED')\n # g_cnt.add_argument('-C', '--checkpoint', metavar='file.chk', type=str, default=None,\n # help='restore evaluation from checkpoint; algorithm saves checkpoint.chk file every generation,'\n # ' which allows resuming evolution, even with another parameters')\n g_cnt.add_argument('-L', '--loglevel', metavar='level', default='info',\n help='logging level: debug, info, warning, error, critical (default: info)')\n g_cnt.add_argument('-t', '--no-stdout', action='store_true',\n help='suppress printing result (list of best choice of PSF stars) to stdout at finish')\n g_cnt.add_argument('-b', '--no-progress', action='store_true',\n help='suppress showing progress bar')\n g_cnt.add_argument('-v', '--version', action='store_true',\n help='show version and exit')\n g_cnt.add_argument('--demo', action='store_true',\n help='use internal demo FITS file')\n __arg_parser_singlethon = parser\n return parser\n\n\ndef main(**kwargs):\n \"\"\"Entry point for python script calls. Parameters identical to command line\"\"\"\n\n args = commons.bunch_kwargs(__arg_parser(), **kwargs)\n # call main routine - common form command line and python calls\n return __do(args)\n\n\ndef check_arguments(arg, parser=None):\n if len(arg.ga_init_prob) > 2:\n exit_error('--ga-init-prob parameter be one or two numbers', parser)\n if len(arg.ga_init_prob) == 1:\n arg.ga_init_prob = [arg.ga_init_prob[0], arg.ga_init_prob[0]]\n if max(arg.ga_init_prob) > 0.99 or min(arg.ga_init_prob) < 0.01:\n exit_error('--ga-init-prob must be in range [0.01 : 0.99]', parser)\n if arg.ga_init_prob[0] > arg.ga_init_prob[1]:\n exit_error('--ga-init-prob a b : a <= b must hold', parser)\n if not arg.demo and not arg.image:\n exit_error('FITS image parameter not provided (and no --version, --help or --demo)', parser)\n\n\ndef exit_error(message, parser):\n logging.error(message)\n if parser:\n parser.error()\n parser.exit(1)\n else:\n raise ValueError(message)\n\n\ndef info():\n \"\"\"Prints commandline help message\"\"\"\n commons.info(__arg_parser())\n\n\ndef commandline_entry():\n # Entry point for command line\n __args = __arg_parser().parse_args() # parse command line arguments\n if __args.version:\n print('astwro.tools ' + astwro.tools.__version__)\n exit()\n\n # Configure logging\n # logging.basicConfig(format='[%(levelname)s] %(module)s: %(message)s', level=__args.loglevel.upper())\n logging.basicConfig(format='%(levelname)7s | %(message)s', level=__args.loglevel.upper())\n check_arguments(__args, __arg_parser())\n __stars = __do(__args) # call main routine - common form command line and python calls\n if __stars is None:\n return 1\n if not __args.no_stdout:\n print('\\n'.join(map(str, __stars.index)))\n return 0\n\n\nif __name__ == '__main__':\n code = commandline_entry()\n exit(code)\n", "meta": {"hexsha": "ff3dfbe2798a275905d8679d96e3ff51aa239141", "size": 41097, "ext": "py", "lang": "Python", "max_stars_repo_path": "astwro/tools/gapick.py", "max_stars_repo_name": "majkelx/astwro", "max_stars_repo_head_hexsha": "4a9bbe3e4757c4076ad7c0d90cf08e38dab4e794", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2017-06-15T20:34:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-15T14:21:43.000Z", "max_issues_repo_path": "astwro/tools/gapick.py", "max_issues_repo_name": "majkelx/astwro", "max_issues_repo_head_hexsha": "4a9bbe3e4757c4076ad7c0d90cf08e38dab4e794", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2017-08-15T20:53:55.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-05T23:40:34.000Z", "max_forks_repo_path": "astwro/tools/gapick.py", "max_forks_repo_name": "majkelx/astwro", "max_forks_repo_head_hexsha": "4a9bbe3e4757c4076ad7c0d90cf08e38dab4e794", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-11-06T15:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T21:06:05.000Z", "avg_line_length": 49.1590909091, "max_line_length": 129, "alphanum_fraction": 0.6252037862, "include": true, "reason": "import numpy,from scipy", "num_tokens": 9665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.28140561345566495, "lm_q1q2_score": 0.14509833869399347}} {"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 17 19:11:22 2018\n\n@author: Jian\n\"\"\"\n\nimport numpy as np\n\nfrom . import utils\n\nfrom . import BSSA14\nfrom . import CB14\nfrom . import CY14\nfrom . import ASK14\nfrom . import helper\n\n#%%----------------------------------------------------------------------------\ndef GMPE(model_name, Mw, Rjb, Vs30, period, epislon=0, NGAs=None,\n rake=None, Mech=3, Ftype=None, Fnm=None, Frv=None,\n dip=None, W=None, Ztor=None, Zhypo=None, Fas=0,\n Rrup=None, Rx=None, Fhw=None, azimuth=None,\n VsFlag=0, Z25=None, Z15=None, Z10=None,\n ArbCB=0, SJ=0,\n country='California', region='CA',\n Dregion='GlobalCATW',\n CRjb=15, Ry0=None,\n D_DPP=0):\n\n model_name = helper.check_model_name(model_name)\n\n if NGAs == None:\n NGAs={'CB':{'NewCoefs':None,'terms':(1,1,1,1,1,1,1,1,1)},\n 'BSSA':{'NewCoefs':None,'terms':(1,1,1)},\n 'CY':{'NewCoefs':None,'terms':(1,1,1,1,1,1,1)},\n 'ASK':{'NewCoefs':None,'terms':(1,1,1,1,1,1,1)}}\n else:\n if 'BSSA' not in list(NGAs.keys()):\n NGAs['BSSA'] = NGAs['BA']\n if 'ASK' not in list(NGAs.keys()):\n NGAs['ASK'] = NGAs['AS']\n\n dict1 = NGAs\n\n # check the input period\n # Note: this function is better used at a given period with a set of other parameters (not with a set of periods)\n if period > 10.0 or 0 < period < 0.01:\n raise ValueError('Positive period value should be within [0.01,10] for SA at corresponding periods')\n if period < 0 and period not in [-1,-2]:\n raise ValueError('negative period should be -1,-2 for PGA and PGV')\n\n if model_name == 'BSSA':\n ngaM = BSSA14.BSSA14_nga()\n kwds = {'Mech': Mech, 'Ftype': Ftype, 'Z10': Z10, 'Dregion': Dregion,\n 'country': country, 'CoefTerms': dict1[model_name]}\n elif model_name == 'CB':\n ngaM = CB14.CB14_nga()\n if Fhw is None:\n Fhw = 0\n kwds = {'Ftype': Ftype, 'Rrup': Rrup, 'Ztor': Ztor, 'dip': dip,\n 'Z25': Z25, 'W': W, 'Zhypo': Zhypo, 'azimuth': azimuth,\n 'Fhw': Fhw, 'Z10': Z10, 'Z15': Z15, 'Arb': ArbCB, 'SJ': SJ,\n 'region': region, 'CoefTerms': dict1[model_name]}\n elif model_name == 'CY':\n ngaM = CY14.CY14_nga()\n kwds = {'Ftype': Ftype, 'Rrup': Rrup, 'Rx': Rx, 'Ztor': Ztor,\n 'dip': dip, 'W': W, 'Zhypo': Zhypo, 'azimuth': azimuth,\n 'Fhw': Fhw, 'Z10': Z10, 'AS': Fas, 'VsFlag': VsFlag,\n 'country': country, 'D_DPP': D_DPP,\n 'CoefTerms': dict1[model_name]}\n # the new CY model treat PGA = SA(0.01)\n if period == -1:\n period = 0.01\n elif model_name == 'ASK':\n ngaM = ASK14.ASK14_nga()\n kwds = {'Ftype': Ftype, 'Rrup': Rrup, 'Rx': Rx, 'Ztor': Ztor,\n 'dip': dip, 'W': W, 'Zhypo': Zhypo, 'azimuth': azimuth,\n 'Fhw': Fhw, 'Z10': Z10, 'Fas': Fas, 'CRjb': CRjb, 'Ry0': Ry0,\n 'region': region, 'country': country, 'VsFlag': VsFlag,\n 'CoefTerms': dict1[model_name]}\n else:\n raise ValueError(\"`model_name` must be one of {'ASK', 'BSSA', 'CB', 'CY'}\")\n\n # common interpolate for all models\n periods = np.array(ngaM.periods)\n if period in periods:\n # compute median, std directly for the existing period in the period list of the NGA model\n values = utils.mapfunc( ngaM, Mw, Rjb, Vs30, period, rake, **kwds )\n values = np.array( values )\n else:\n #print 'do the interpolation for periods that is not in the period list of the NGA model'\n ind_low = (periods <= period*1.0).nonzero()[0]\n ind_high = (periods >= period*1.0).nonzero()[0]\n\n period_low = max( periods[ind_low] )\n period_high = min( periods[ind_high] )\n values_low = np.array(utils.mapfunc(ngaM, Mw, Rjb, Vs30, period_low,\n rake, **kwds))\n values_high = np.array(utils.mapfunc(ngaM, Mw, Rjb, Vs30, period_high,\n rake, **kwds))\n N1,N2 = np.array(values_low).shape\n values = np.zeros( (N1,N2) )\n for icmp in range( N2 ):\n if icmp != 0:\n # stardand values are in ln (g)\n values[:,icmp] = utils.logline(np.log(period_low),\n np.log(period_high),\n values_low[:,icmp],\n values_high[:,icmp],\n np.log(period) )\n else:\n # median value is in g\n values[:,icmp] = utils.logline(np.log(period_low),\n np.log(period_high),\n np.log(values_low[:,icmp]),\n np.log(values_high[:,icmp]),\n np.log(period))\n values[:,icmp] = np.exp( values[:,icmp] ) # change the median into g unit (logline gives the result in ln(g))\n\n # outputs\n NGAsigmaT = values[:,1]\n NGAtau = values[:,2]\n NGAsigma = values[:,3]\n\n if epislon:\n NGAmedian = np.exp( np.log(values[:,0]) + epislon * NGAsigmaT )\n else:\n NGAmedian = values[:,0]\n\n # returned quantities are all in g, not in log(g), event for the standard deviations\n return NGAmedian[0], \\\n np.exp(NGAsigmaT)[0], \\\n np.exp(NGAtau)[0], \\\n np.exp(NGAsigma)[0] # all in g, include the standard deviation\n\n#%%----------------------------------------------------------------------------\ndef GMPE_array(model_name, Mw, Rjb, Vs30, period_array, epislon=0, NGAs=None,\n rake=None, Mech=3, Ftype=None, Fnm=None, Frv=None,\n dip=None, W=None, Ztor=None, Zhypo=None, Fas=0,\n Rrup=None, Rx=None, Fhw=None, azimuth=None,\n VsFlag=0, Z25=None, Z15=None, Z10=None,\n ArbCB=0, SJ=0,\n country='California', region='CA',\n Dregion='GlobalCATW',\n CRjb=15, Ry0=None,\n D_DPP=0):\n\n import collections\n if not isinstance(period_array, collections.Iterable):\n raise TypeError('`period_array` must be a array-like object.')\n\n model_name = helper.check_model_name(model_name)\n\n results = []\n for period in period_array:\n if period < 0:\n raise ValueError('Period value must be positive')\n result_ = GMPE(model_name, Mw, Rjb, Vs30, period, epislon=epislon,\n NGAs=NGAs, rake=rake, Mech=Mech, Ftype=Ftype, Fnm=Fnm,\n Frv=Frv, dip=dip, W=W, Ztor=Ztor, Zhypo=Zhypo, Fas=Fas,\n Rrup=Rrup, Rx=Rx, Fhw=Fhw, azimuth=azimuth,\n VsFlag=VsFlag, Z25=Z25, Z15=Z15, Z10=Z10,\n ArbCB=ArbCB, SJ=SJ,country=country, region=region,\n Dregion=Dregion, CRjb=CRjb, Ry0=Ry0, D_DPP=D_DPP)\n\n results.append(result_)\n\n results_T = list(zip(*results))\n\n return tuple([np.array(_) for _ in results_T])\n\n", "meta": {"hexsha": "2f4a493b3af0af069a820baa8a8ba408f3aad288", "size": 7139, "ext": "py", "lang": "Python", "max_stars_repo_path": "ngawest2/GMPE.py", "max_stars_repo_name": "Caltech-geoquake/ngawest2", "max_stars_repo_head_hexsha": "ea0652fe70bb05c399389c503868aae8e0782a3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-04T07:08:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-04T07:08:12.000Z", "max_issues_repo_path": "ngawest2/GMPE.py", "max_issues_repo_name": "Caltech-geoquake/ngawest2", "max_issues_repo_head_hexsha": "ea0652fe70bb05c399389c503868aae8e0782a3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ngawest2/GMPE.py", "max_forks_repo_name": "Caltech-geoquake/ngawest2", "max_forks_repo_head_hexsha": "ea0652fe70bb05c399389c503868aae8e0782a3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-16T18:17:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T18:17:53.000Z", "avg_line_length": 41.5058139535, "max_line_length": 128, "alphanum_fraction": 0.5188401737, "include": true, "reason": "import numpy", "num_tokens": 2028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.28140561345566495, "lm_q1q2_score": 0.14509833869399347}} {"text": "import os\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom utils import utils_sr\nimport torch\nfrom argparse import ArgumentParser\nfrom utils.utils_restoration import rgb2y, psnr, array2tensor, tensor2array\nimport sys\nfrom matplotlib.ticker import MaxNLocator\n\n\nclass PnP_restoration():\n\n def __init__(self, hparams):\n\n self.hparams = hparams\n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n self.initialize_cuda_denoiser()\n\n def initialize_cuda_denoiser(self):\n '''\n Initialize the denoiser model with the given pretrained ckpt\n '''\n sys.path.append('../GS_denoising/')\n from lightning_denoiser import GradMatch\n parser2 = ArgumentParser(prog='utils_restoration.py')\n parser2 = GradMatch.add_model_specific_args(parser2)\n parser2 = GradMatch.add_optim_specific_args(parser2)\n hparams = parser2.parse_known_args()[0]\n if 'nb_4' in self.hparams.pretrained_checkpoint :\n hparams.DRUNET_nb = 4\n hparams.grad_matching = self.hparams.grad_matching\n hparams.act_mode = 's'\n self.denoiser_model = GradMatch(hparams)\n checkpoint = torch.load(self.hparams.pretrained_checkpoint, map_location=self.device)\n self.denoiser_model.load_state_dict(checkpoint['state_dict'])\n self.denoiser_model.eval()\n for i, v in self.denoiser_model.named_parameters():\n v.requires_grad = False\n self.denoiser_model = self.denoiser_model.to(self.device)\n if self.hparams.precision == 'double' :\n if self.denoiser_model is not None:\n self.denoiser_model.double()\n\n\n def initialize_prox(self, img, degradation):\n '''\n calculus for future prox computatations\n :param img: degraded image\n :param degradation: 2D blur kernel for deblurring and SR, mask for inpainting\n '''\n if self.hparams.degradation_mode == 'deblurring' :\n self.k = degradation\n self.k_tensor = array2tensor(np.expand_dims(self.k, 2)).double().to(self.device)\n self.FB, self.FBC, self.F2B, self.FBFy = utils_sr.pre_calculate_prox(img, self.k_tensor, 1)\n elif self.hparams.degradation_mode == 'SR':\n self.k = degradation\n self.k_tensor = array2tensor(np.expand_dims(self.k, 2)).double().to(self.device)\n self.FB, self.FBC, self.F2B, self.FBFy = utils_sr.pre_calculate_prox(img, self.k_tensor, 2)\n elif self.hparams.degradation_mode == 'inpainting':\n self.M = array2tensor(degradation).double().to(self.device)\n self.My = self.M*img\n else:\n print('degradation mode not treated')\n\n\n def calculate_prox(self, img):\n '''\n Calculation of the proximal mapping of the data term f\n :param img: input for the prox\n :return: prox_f(img)\n '''\n if self.hparams.degradation_mode == 'deblurring':\n rho = torch.tensor([1/self.hparams.lamb]).double().repeat(1, 1, 1, 1).to(self.device)\n px = utils_sr.prox_solution(img.double(), self.FB, self.FBC, self.F2B, self.FBFy, rho, 1)\n elif self.hparams.degradation_mode == 'SR':\n rho = torch.tensor([1 /self.hparams.lamb]).double().repeat(1, 1, 1, 1).to(self.device)\n px = utils_sr.prox_solution(img.double(), self.FB, self.FBC, self.F2B, self.FBFy, rho, self.hparams.sf)\n elif self.hparams.degradation_mode == 'inpainting':\n if self.hparams.noise_level_img > 1e-2:\n px = (self.hparams.lamb*self.My + img)/(self.hparams.lamb*self.M+1)\n else :\n px = self.My + (1-self.M)*img\n else:\n print('degradation mode not treated')\n return px\n\n def calculate_grad(self, img):\n '''\n Calculation of the gradient of the data term f\n :param img: input for the prox\n :return: \\nabla_f(img)\n '''\n if self.hparams.degradation_mode == 'deblurring' :\n grad = utils_sr.grad_solution(img.double(), self.FB, self.FBC, self.FBFy, 1)\n if self.hparams.degradation_mode == 'SR' :\n grad = utils_sr.grad_solution(img.double(), self.FB, self.FBC, self.FBFy, self.hparams.sf)\n return grad\n\n def calculate_regul(self,y,x,g):\n '''\n Calculation of the regularization (1/tau)*phi_sigma(y)\n :param y: Point where to evaluate\n :param x: D^{-1}(y)\n :param g: Precomputed regularization function value at x\n :return: regul(y)\n '''\n regul = (1 / self.hparams.lamb) * (g - (1 / 2) * torch.norm(x - y, p=2) ** 2)\n return regul\n\n def calulate_data_term(self,y,img):\n '''\n Calculation of the data term value f(y)\n :param y: Point where to evaluate F\n :param img: Degraded image\n :return: f(y)\n '''\n if self.hparams.degradation_mode == 'deblurring':\n deg_y = utils_sr.imfilter(y.double(), self.k_tensor[0].double().flip(1).flip(2).expand(3, -1, -1, -1))\n f = 0.5 * torch.norm(img - deg_y, p=2) ** 2\n elif self.hparams.degradation_mode == 'SR':\n deg_y = utils_sr.imfilter(y.double(), self.k_tensor[0].double().flip(1).flip(2).expand(3, -1, -1, -1))\n deg_y = deg_y[..., 0::self.hparams.sf, 0::self.hparams.sf]\n f = 0.5 * torch.norm(img - deg_y, p=2) ** 2\n elif self.hparams.degradation_mode == 'inpainting':\n deg_y = self.M * y.double()\n f = 0.5 * torch.norm(img - deg_y, p=2) ** 2\n else:\n print('degradation not implemented')\n return f\n\n def calculate_F(self, y, x, g, img):\n '''\n Calculation of the objective function value f(y) + (1/tau)*phi_sigma(y)\n :param y: Point where to evaluate F\n :param x: D^{-1}(y)\n :param g: Precomputed regularization function value at x\n :param img: Degraded image\n :return: F(y)\n '''\n regul = self.calculate_regul(y,x,g)\n if self.hparams.no_data_term:\n F = regul\n else:\n f = self.calulate_data_term(y,img)\n F = f + regul\n return F.item()\n\n def calculate_lyapunov_DRS(self,y,z,x,g,img):\n '''\n Calculation of the Lyapunov function value Psi(x)\n :param x: Point where to evaluate F\n :param y,z: DRS iterations initialized at x\n :param g: Precomputed regularization function value at x\n :param img: Degraded image\n :return: Psi(x)\n '''\n regul = self.calculate_regul(y,x,g)\n f = self.calulate_data_term(z, img)\n Psi = regul + f + (1 / self.hparams.lamb) * (torch.sum(torch.mul(y-x,y-z)) + (1/2) * torch.norm(y - z, p=2) ** 2)\n return Psi\n\n\n def restore(self, img, init_im, clean_img, degradation,extract_results=False):\n '''\n Compute GS-PnP restoration algorithm\n :param img: Degraded image\n :param clean_img: ground-truth clean image\n :param degradation: 2D blur kernel for deblurring and SR, mask for inpainting\n :param extract_results: Extract information for subsequent image or curve saving\n '''\n\n if extract_results:\n y_list, z_list, x_list, Dg_list, psnr_tab, g_list, Dx_list, F_list, Psi_list = [], [], [], [], [], [], [], [], []\n\n i = 0 # iteration counter\n\n img_tensor = array2tensor(init_im).to(self.device) # for GPU computations (if GPU available)\n self.initialize_prox(img_tensor, degradation) # prox calculus that can be done outside of the loop\n\n # Initialization of the algorithm\n if self.hparams.degradation_mode == 'SR':\n x0 = cv2.resize(init_im, (img.shape[1] * self.hparams.sf, img.shape[0] * self.hparams.sf),interpolation=cv2.INTER_CUBIC)\n x0 = utils_sr.shift_pixel(x0, self.hparams.sf)\n x0 = array2tensor(x0).to(self.device)\n else:\n x0 = array2tensor(init_im).to(self.device)\n\n if extract_results: # extract np images and PSNR values\n out_x = tensor2array(x0.cpu())\n current_x_psnr = psnr(clean_img, out_x)\n if self.hparams.print_each_step:\n print('current x PSNR : ', current_x_psnr)\n psnr_tab.append(current_x_psnr)\n x_list.append(out_x)\n\n x = x0\n\n if self.hparams.use_hard_constraint:\n x = torch.clamp(x, 0, 1)\n\n # Initialize Lyapunov\n diff_Psi = 1\n Psi_old = 1\n Psi = Psi_old\n\n\n while i < self.hparams.maxitr and abs(diff_Psi)/Psi_old > self.hparams.relative_diff_Psi_min:\n\n if self.hparams.inpainting_init :\n if i < self.hparams.n_init:\n self.sigma_denoiser = 50\n else :\n self.sigma_denoiser = self.hparams.sigma_denoiser\n else :\n self.sigma_denoiser = self.hparams.sigma_denoiser\n\n\n x_old = x\n Psi_old = Psi\n\n if self.hparams.PnP_algo == 'PGD':\n # Gradient step\n gradx = self.calculate_grad(x_old)\n z = x_old - self.hparams.lamb*gradx\n # Denoising step\n torch.set_grad_enabled(True)\n Dg, N = self.denoiser_model.calculate_grad(z, self.hparams.sigma_denoiser / 255.)\n torch.set_grad_enabled(False)\n Dg = Dg.detach()\n N = N.detach()\n g = 0.5 * (torch.norm(z.double() - N.double(), p=2) ** 2)\n Dz = z - Dg\n Dx = Dz\n x = (1 - self.hparams.alpha) * z + self.hparams.alpha*Dz\n y = x\n # Hard constraint\n if self.hparams.use_hard_constraint:\n x = torch.clamp(x,0,1)\n # Calculate Objective\n F = self.calculate_F(x, z, g, img_tensor)\n\n elif self.hparams.PnP_algo == 'DRS':\n # Denoising step\n torch.set_grad_enabled(True)\n Dg, N = self.denoiser_model.calculate_grad(x_old, self.hparams.sigma_denoiser / 255.)\n torch.set_grad_enabled(False)\n Dg = Dg.detach()\n N = N.detach()\n g = 0.5 * (torch.norm(x_old.double() - N.double(), p=2) ** 2)\n Dx = x_old - Dg\n y = (1 - self.hparams.alpha)*x_old + self.hparams.alpha*Dx\n # Hard constraint\n if self.hparams.use_hard_constraint:\n y = torch.clamp(y,0,1)\n # Proximal step\n z = self.calculate_prox(2*y-x_old)\n # Calculate Lyapunov\n Psi = self.calculate_lyapunov_DRS(y,z,x,g,img_tensor)\n diff_Psi = Psi-Psi_old\n # Calculate Objective\n F = self.calculate_F(y, x, g, img_tensor)\n # Final step\n x = x_old + (z-y)\n\n elif self.hparams.PnP_algo == 'DRSdiff':\n\n # Proximal step\n y = self.calculate_prox(x_old)\n y2 = 2*y-x_old\n\n # Denoising step\n torch.set_grad_enabled(True)\n Dg, N = self.denoiser_model.calculate_grad(y2, self.hparams.sigma_denoiser / 255.)\n torch.set_grad_enabled(False)\n Dg = Dg.detach()\n N = N.detach()\n g = 0.5 * (torch.norm(y2.double() - N.double(), p=2) ** 2)\n Dx = y2 - Dg\n z = (1 - self.hparams.alpha) * y2 + self.hparams.alpha * Dx\n # Hard constraint\n if self.hparams.use_hard_constraint:\n z = torch.clamp(z, 0, 1)\n\n # Calculate Lyapunov\n Psi = self.calculate_lyapunov_DRS(y,z,x,g,img_tensor)\n diff_Psi = Psi-Psi_old\n # Calculate Objective\n F = self.calculate_F(y, x, g, img_tensor)\n # Final step\n x = x_old + (z-y)\n\n else :\n print('algo not implemented')\n\n # Logging\n if extract_results:\n out_y = tensor2array(y.cpu())\n out_z = tensor2array(z.cpu())\n out_x = tensor2array(x.cpu())\n current_y_psnr = psnr(clean_img, out_y)\n current_z_psnr = psnr(clean_img, out_z)\n current_x_psnr = psnr(clean_img, out_x)\n if self.hparams.print_each_step:\n print('iteration : ', i)\n print('current y PSNR : ', current_y_psnr)\n print('current z PSNR : ', current_z_psnr)\n print('current x PSNR : ', current_x_psnr)\n y_list.append(out_y)\n x_list.append(out_x)\n z_list.append(out_z)\n Dx_list.append(tensor2array(Dx.cpu()))\n Dg_list.append(torch.norm(Dg).cpu().item())\n g_list.append(g.cpu().item())\n psnr_tab.append(current_x_psnr)\n F_list.append(F)\n Psi_list.append(Psi)\n\n # next iteration\n i += 1\n\n output_img = tensor2array(y.cpu())\n output_psnr = psnr(clean_img, output_img)\n output_psnrY = psnr(rgb2y(clean_img), rgb2y(output_img))\n\n if extract_results:\n return output_img, output_psnr, output_psnrY, x_list, np.array(z_list), np.array(y_list), np.array(Dg_list), np.array(psnr_tab), np.array(Dx_list), np.array(g_list), np.array(F_list), np.array(Psi_list)\n else:\n return output_img, output_psnr, output_psnrY\n\n def initialize_curves(self):\n\n self.conv = []\n self.PSNR = []\n self.g = []\n self.Dg = []\n self.F = []\n self.Psi = []\n self.lip_algo = []\n self.lip_D = []\n self.lip_Dg = []\n\n def update_curves(self, x_list, Dx_list, psnr_tab, Dg_list, g_list, F_list, Psi_list):\n\n self.F.append(F_list)\n self.Psi.append(Psi_list)\n self.g.append(g_list)\n self.Dg.append(Dg_list)\n self.PSNR.append(psnr_tab)\n self.conv.append(np.array([(np.linalg.norm(x_list[k + 1] - x_list[k]) ** 2) for k in range(len(x_list) - 1)]) / np.sum(np.abs(x_list[0]) ** 2))\n self.lip_algo.append(np.sqrt(np.array([np.sum(np.abs(x_list[k + 1] - x_list[k]) ** 2) for k in range(1, len(x_list) - 1)]) / np.array([np.sum(np.abs(x_list[k] - x_list[k - 1]) ** 2) for k in range(1, len(x_list[:-1]))])))\n self.lip_D.append(np.sqrt(np.array([np.sum(np.abs(Dx_list[i + 2] - Dx_list[i+1]) ** 2) for i in range(len(Dx_list) - 2)]) / np.array([np.sum(np.abs(x_list[i+1] - x_list[i]) ** 2) for i in range(len(Dx_list) - 2)])))\n self.lip_Dg.append(np.sqrt(np.array([np.sum(np.abs(Dg_list[i + 2] - Dg_list[i+1]) ** 2) for i in range(len(Dx_list) - 2)]) / np.array([np.sum(np.abs(x_list[i+1] - x_list[i]) ** 2) for i in range(len(Dg_list) - 2)])))\n\n\n def save_curves(self, save_path):\n\n import matplotlib\n matplotlib.rcParams.update({'font.size': 10})\n matplotlib.rcParams['lines.linewidth'] = 2\n matplotlib.style.use('seaborn-darkgrid')\n\n plt.figure(0)\n fig, ax = plt.subplots()\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n for i in range(len(self.g)):\n plt.plot(self.g[i], markevery=10)\n ax.xaxis.set_major_locator(MaxNLocator(integer=True))\n plt.legend()\n plt.savefig(os.path.join(save_path, 'g.png'),bbox_inches=\"tight\")\n\n plt.figure(1)\n fig, ax = plt.subplots()\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n for i in range(len(self.PSNR)):\n plt.plot(self.PSNR[i], markevery=10)\n ax.xaxis.set_major_locator(MaxNLocator(integer=True))\n plt.legend()\n plt.savefig(os.path.join(save_path, 'PSNR.png'),bbox_inches=\"tight\")\n\n plt.figure(2)\n fig, ax = plt.subplots()\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n for i in range(len(self.F)):\n plt.plot(self.Psi[i], markevery=10)\n ax.xaxis.set_major_locator(MaxNLocator(integer=True))\n plt.legend()\n plt.savefig(os.path.join(save_path, 'Liapunov.png'), bbox_inches=\"tight\")\n\n plt.figure(22)\n fig, ax = plt.subplots()\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n for i in range(len(self.F)):\n plt.plot(self.F[i], markevery=10)\n ax.xaxis.set_major_locator(MaxNLocator(integer=True))\n plt.legend()\n plt.savefig(os.path.join(save_path, 'F.png'), bbox_inches=\"tight\")\n\n plt.figure(4)\n fig, ax = plt.subplots()\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n for i in range(len(self.Dg)):\n Ds_norm = [np.linalg.norm(np.array(self.Dg[i][j])) for j in range(len(self.Dg[i]))]\n plt.plot(Ds_norm, linewidth=1.5, markevery=10)\n ax.xaxis.set_major_locator(MaxNLocator(integer=True))\n plt.legend()\n plt.savefig(os.path.join(save_path, 'Dg.png'), bbox_inches=\"tight\")\n\n plt.figure(5)\n fig, ax = plt.subplots()\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n for i in range(len(self.conv)):\n plt.plot(self.conv[i], '-o', markevery=10)\n ax.xaxis.set_major_locator(MaxNLocator(integer=True))\n plt.legend()\n plt.savefig(os.path.join(save_path, 'conv_log.png'), bbox_inches=\"tight\")\n\n self.conv2 = [[np.min(self.conv[i][:k]) for k in range(1, len(self.conv[i]))] for i in range(len(self.conv))]\n conv_rate = [self.conv2[i][0]*np.array([(1/k) for k in range(1,len(self.conv2[i]))]) for i in range(len(self.conv2))]\n plt.figure(6)\n fig, ax = plt.subplots()\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n for i in range(len(self.conv)):\n plt.plot(self.conv2[i], '-', markevery=10)\n plt.plot(conv_rate[i], '--', color='red', label=r'$\\mathcal{O}(\\frac{1}{K})$')\n plt.semilogy()\n plt.legend()\n ax.xaxis.set_major_locator(MaxNLocator(integer=True))\n plt.savefig(os.path.join(save_path, 'conv_log2.png'), bbox_inches=\"tight\")\n\n self.conv_sum = [[np.sum(self.conv[i][:k]) for k in range(1, len(self.conv[i]))] for i in range(len(self.conv))]\n\n plt.figure(7)\n fig, ax = plt.subplots()\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n for i in range(len(self.conv_sum)):\n plt.plot(self.conv_sum[i], markevery=10)\n ax.xaxis.set_major_locator(MaxNLocator(integer=True))\n plt.legend()\n plt.savefig(os.path.join(save_path, 'conv_log_sum.png'), bbox_inches=\"tight\")\n\n\n plt.figure(8)\n fig, ax = plt.subplots()\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n for i in range(len(self.lip_algo)):\n plt.plot(self.lip_algo[i], '-o', markersize=10)\n ax.xaxis.set_major_locator(MaxNLocator(integer=True))\n plt.savefig(os.path.join(save_path, 'lip_algo.png'))\n\n plt.figure(9)\n fig, ax = plt.subplots()\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n for i in range(len(self.lip_D)):\n plt.plot(self.lip_D[i], '-o', markersize=10)\n ax.xaxis.set_major_locator(MaxNLocator(integer=True))\n plt.savefig(os.path.join(save_path, 'lip_D.png'))\n\n plt.figure(10)\n fig, ax = plt.subplots()\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n for i in range(len(self.lip_Dg)):\n plt.plot(self.lip_Dg[i], '-o', markersize=10)\n ax.xaxis.set_major_locator(MaxNLocator(integer=True))\n plt.savefig(os.path.join(save_path, 'lip_Dg.png'))\n\n\n def add_specific_args(parent_parser):\n parser = ArgumentParser(parents=[parent_parser], add_help=False)\n parser.add_argument('--dataset_path', type=str, default='../datasets')\n parser.add_argument('--pretrained_checkpoint', type=str,default='../GS_denoising/ckpts/Prox_DRUNet.ckpt')\n parser.add_argument('--PnP_algo', type=str, default='PGD')\n parser.add_argument('--dataset_name', type=str, default='CBSD68')\n parser.add_argument('--sigma_denoiser', type=float)\n parser.add_argument('--sigma_k_denoiser', type=float)\n parser.add_argument('--noise_level_img', type=float, default=2.55)\n parser.add_argument('--maxitr', type=int, default=1000)\n parser.add_argument('--alpha', type=float, default=1)\n parser.add_argument('--lamb', type=float)\n parser.add_argument('--n_images', type=int, default=68)\n parser.add_argument('--relative_diff_Psi_min', type=float, default=1e-8)\n parser.add_argument('--inpainting_init', dest='inpainting_init', action='store_true')\n parser.set_defaults(inpainting_init=False)\n parser.add_argument('--precision', type=str, default='simple')\n parser.add_argument('--n_init', type=int, default=10)\n parser.add_argument('--patch_size', type=int, default=256)\n parser.add_argument('--extract_curves', dest='extract_curves', action='store_true')\n parser.set_defaults(extract_curves=False)\n parser.add_argument('--extract_images', dest='extract_images', action='store_true')\n parser.set_defaults(extract_images=False)\n parser.add_argument('--print_each_step', dest='print_each_step', action='store_true')\n parser.set_defaults(print_each_step=False)\n parser.add_argument('--no_grad_matching', dest='grad_matching', action='store_false')\n parser.set_defaults(grad_matching=True)\n parser.add_argument('--no_data_term', dest='no_data_term', action='store_true')\n parser.set_defaults(no_data_term=False)\n parser.add_argument('--use_hard_constraint', dest='use_hard_constraint', action='store_true')\n parser.set_defaults(no_data_term=False)\n return parser\n", "meta": {"hexsha": "74e6f249f025889ce75d414912435599cdc772f4", "size": 22307, "ext": "py", "lang": "Python", "max_stars_repo_path": "PnP_restoration/prox_PnP_restoration.py", "max_stars_repo_name": "samuro95/Prox-PnP", "max_stars_repo_head_hexsha": "c05a48a586f0ef27c8ddc14e0a4c2c3d6814f8c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PnP_restoration/prox_PnP_restoration.py", "max_issues_repo_name": "samuro95/Prox-PnP", "max_issues_repo_head_hexsha": "c05a48a586f0ef27c8ddc14e0a4c2c3d6814f8c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PnP_restoration/prox_PnP_restoration.py", "max_forks_repo_name": "samuro95/Prox-PnP", "max_forks_repo_head_hexsha": "c05a48a586f0ef27c8ddc14e0a4c2c3d6814f8c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.568359375, "max_line_length": 229, "alphanum_fraction": 0.5873492626, "include": true, "reason": "import numpy", "num_tokens": 5591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.2814056074291438, "lm_q1q2_score": 0.14509833139742115}} {"text": "# test protocols for setting up relative binding free energy calculations.\n\n\nimport argparse\nimport os\nimport numpy as np\nfrom rdkit import Chem\nfrom rdkit.Chem import AllChem\n\nfrom timemachine.lib import potentials, custom_ops\nfrom timemachine.lib import LangevinIntegrator\n\nfrom ff.handlers import openmm_deserializer\nfrom ff.handlers.deserialize import deserialize_handlers\n\nfrom fe import pdb_writer\nfrom fe import rbfe\nfrom md import Recipe\nfrom md import builders\n\nfrom multiprocessing import Pool\n\ndef get_romol_conf(mol):\n conformer = mol.GetConformer(0)\n guest_conf = np.array(conformer.GetPositions(), dtype=np.float64)\n guest_conf = guest_conf/10 # from angstroms to nm\n return np.array(guest_conf, dtype=np.float64)\n\ndef run(args):\n\n lamb, intg, bound_potentials, masses, x0, box, gpu_idx, stage = args\n # print(\"running on\", gpu_idx)\n os.environ['CUDA_VISIBLE_DEVICES'] = str(gpu_idx)\n u_impls = []\n for bp in bound_potentials:\n u_impls.append(bp.bound_impl(precision=np.float32))\n\n # important that we reseed here.\n intg.seed = np.random.randint(np.iinfo(np.int32).max)\n intg_impl = intg.impl()\n\n v0 = np.zeros_like(x0)\n\n ctxt = custom_ops.Context(\n x0,\n v0,\n box,\n intg_impl,\n u_impls\n )\n\n # secondary minimization needed only for stage 1\n if stage == 1:\n for l in np.linspace(0.35, lamb, 500):\n ctxt.step(l)\n\n # equilibration\n for step in range(20000):\n # for step in range(1000):\n ctxt.step(lamb)\n\n\n # print(ctxt.get_x_t())\n\n du_dl_obs = custom_ops.AvgPartialUPartialLambda(u_impls, 10)\n ctxt.add_observable(du_dl_obs)\n\n # add observable for \n for step in range(50000):\n # for step in range(5000):\n ctxt.step(lamb)\n\n print(lamb, du_dl_obs.avg_du_dl())\n\n assert np.any(np.abs(ctxt.get_x_t()) > 100) == False\n assert np.any(np.isnan(ctxt.get_x_t())) == False\n assert np.any(np.isinf(ctxt.get_x_t())) == False\n\n return du_dl_obs.avg_du_dl()\n\ndef minimize(args):\n\n bound_potentials, masses, x0, box = args\n\n u_impls = []\n for bp in bound_potentials:\n u_impls.append(bp.bound_impl(precision=np.float32))\n\n seed = np.random.randint(np.iinfo(np.int32).max)\n\n intg = LangevinIntegrator(\n 300.0,\n 1.5e-3,\n 1.0,\n masses,\n seed\n ).impl()\n\n v0 = np.zeros_like(x0)\n\n ctxt = custom_ops.Context(\n x0,\n v0,\n box,\n intg,\n u_impls\n )\n\n steps = 500\n\n lambda_schedule = np.linspace(0.35, 0.0, 500)\n for lamb in lambda_schedule:\n ctxt.step(lamb)\n\n return ctxt.get_x_t()\n\ndef minimize_setup(r_host, r_ligand):\n r_combined = r_host.combine(r_ligand)\n\n print(len(r_combined.masses))\n\n # assert 0\n host_atom_idxs = np.arange(len(r_host.masses))\n ligand_atom_idxs = np.arange(len(r_ligand.masses)) + len(r_host.masses)\n rbfe.set_nonbonded_lambda_idxs(r_combined, ligand_atom_idxs, 0, 1)\n\n # for bp in r_combined.bound_potentials:\n # if isinstance(bp, potentials.Nonbonded):\n # print(len(bp.get_lambda_offset_idxs()))\n # print(len(bp.get_lambda_plane_idxs()))\n # assert 0\n\n return r_combined\n\ndef main(args, stage):\n\n # benzene = Chem.AddHs(Chem.MolFromSmiles(\"c1ccccc1\")) # a\n # phenol = Chem.AddHs(Chem.MolFromSmiles(\"Oc1ccccc1\")) # b\n #01234567890\n benzene = Chem.AddHs(Chem.MolFromSmiles(\"C1=CC=C2C=CC=CC2=C1\")) # a\n phenol = Chem.AddHs(Chem.MolFromSmiles(\"C1=CC=C2C=CC=CC2=C1\")) # b\n\n AllChem.EmbedMolecule(benzene)\n AllChem.EmbedMolecule(phenol)\n\n ff_handlers = deserialize_handlers(open('ff/params/smirnoff_1_1_0_ccc.py').read())\n r_benzene = Recipe.from_rdkit(benzene, ff_handlers)\n r_phenol = Recipe.from_rdkit(phenol, ff_handlers)\n\n r_combined = r_benzene.combine(r_phenol)\n core_pairs = np.array([\n [0,0],\n [1,1],\n [2,2],\n [3,3],\n [4,4],\n [5,5],\n [6,6],\n [7,7],\n [8,8],\n [9,9],\n # [10,10]\n ], dtype=np.int32)\n core_pairs[:, 1] += benzene.GetNumAtoms()\n\n a_idxs = np.arange(benzene.GetNumAtoms())\n b_idxs = np.arange(phenol.GetNumAtoms()) + benzene.GetNumAtoms()\n\n\n core_k = 20.0\n\n if stage == 0:\n centroid_k = 200.0\n rbfe.stage_0(r_combined, b_idxs, core_pairs, centroid_k, core_k)\n # lambda_schedule = np.linspace(0.0, 1.0, 2)\n # lambda_schedule = np.array([0.0, 0.0, 0.0, 0.0, 0.0])\n lambda_schedule = np.array([0.0, 0.0, 0.0, 0.0, 0.0])\n elif stage == 1:\n rbfe.stage_1(r_combined, a_idxs, b_idxs, core_pairs, core_k)\n lambda_schedule = np.linspace(0.0, 1.2, 60)\n else:\n assert 0\n\n\n\n system, host_coords, box, topology = builders.build_water_system(4.0)\n\n r_host = Recipe.from_openmm(system)\n r_final = r_host.combine(r_combined)\n\n # minimize coordinates of host + ligand A\n ha_coords = np.concatenate([\n host_coords,\n get_romol_conf(benzene)\n ])\n\n\n pool = Pool(args.num_gpus)\n\n # we need to run this in a subprocess since the cuda runtime\n # must not be initialized in the master thread due to lack of\n # fork safety\n r_minimize = minimize_setup(r_host, r_benzene)\n ha_coords = pool.map(minimize, [(r_minimize.bound_potentials, r_minimize.masses, ha_coords, box)], chunksize=1)\n # this is a list\n ha_coords = ha_coords[0]\n pool.close()\n\n pool = Pool(args.num_gpus)\n\n x0 = np.concatenate([\n ha_coords,\n get_romol_conf(phenol)\n ])\n\n masses = np.concatenate([r_host.masses, r_benzene.masses, r_phenol.masses])\n\n seed = np.random.randint(np.iinfo(np.int32).max)\n\n intg = LangevinIntegrator(\n 300.0,\n 1.5e-3,\n 1.0,\n masses,\n seed\n )\n\n # production run at various values of lambda\n for epoch in range(10):\n avg_du_dls = []\n\n run_args = []\n for lamb_idx, lamb in enumerate(lambda_schedule):\n run_args.append((\n lamb,\n intg,\n r_final.bound_potentials,\n r_final.masses,\n x0,\n box,\n lamb_idx % args.num_gpus,\n stage))\n\n avg_du_dls = pool.map(run, run_args, chunksize=1)\n\n print(\"stage\", stage, \"epoch\", epoch, \"dG\", np.trapz(avg_du_dls, lambda_schedule))\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(\n description=\"RBFE testing\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n\n parser.add_argument(\n \"--num_gpus\",\n type=int,\n help=\"number of gpus\"\n )\n\n args = parser.parse_args()\n\n main(args, 0)", "meta": {"hexsha": "78d7dda331d7cc02f929770296d979b72a9504e9", "size": 6770, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/dual_topology.py", "max_stars_repo_name": "schmolly/timemachine", "max_stars_repo_head_hexsha": "7d13a0406dc2d09ac67892988641ba4965bfb206", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/dual_topology.py", "max_issues_repo_name": "schmolly/timemachine", "max_issues_repo_head_hexsha": "7d13a0406dc2d09ac67892988641ba4965bfb206", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/dual_topology.py", "max_forks_repo_name": "schmolly/timemachine", "max_forks_repo_head_hexsha": "7d13a0406dc2d09ac67892988641ba4965bfb206", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7414448669, "max_line_length": 115, "alphanum_fraction": 0.6228951256, "include": true, "reason": "import numpy", "num_tokens": 1926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.2751297238231752, "lm_q1q2_score": 0.1450804494448172}} {"text": "import copy\nimport os\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom common.buffers import OfflineBuffer\nfrom utils.train_tools import soft_target_update, evaluate\nfrom utils import log_tools\nfrom common.networks import MLPSquashedReparamGaussianPolicy, CVAE, MLPQsaNet\n\n\nclass BEAR_Agent:\n \"\"\"\n Implementation of Bootstrapping Error Accumulation Reduction (BEAR)\n https://arxiv.org/abs/1906.00949\n BEAR's MMD Loss's weight alpha_prime is tuned automatically by default.\n\n Actor Loss: alpha_prime * MMD Loss + -minQ(s,a)\n Critic Loss: Like BCQ\n Alpha_prime Loss: -(alpha_prime * (MMD Loss - threshold))\n \"\"\"\n def __init__(self,\n env,\n data_buffer: OfflineBuffer,\n policy_net: MLPSquashedReparamGaussianPolicy, # actor\n q_net1: MLPQsaNet, # critic\n q_net2: MLPQsaNet,\n cvae_net: CVAE,\n policy_lr=1e-4,\n qf_lr=3e-4,\n cvae_lr=3e-4,\n gamma=0.99,\n tau=0.05,\n\n # BEAR\n lmbda=0.75, # used for double clipped double q-learning\n mmd_sigma=20.0, # the sigma used in mmd kernel\n kernel_type='gaussian', # the type of mmd kernel(gaussian or laplacian)\n lagrange_thresh=0.05, # the hyper-parameter used in automatic tuning alpha in cql loss\n n_action_samples=100, # the number of action samples to compute the best action when choose action\n n_target_samples=10, # the number of action samples to compute BCQ-like target value\n n_mmd_action_samples=4, # the number of action samples to compute MMD.\n warmup_step=40000, # do support matching with a warm start before policy(actor) train\n\n max_train_step=1000000,\n log_interval=1000,\n eval_freq=5000,\n train_id=\"bear_hopper-medium-v2_test\",\n resume=False, # if True, train from last checkpoint\n device='cpu',\n ):\n\n self.env = env\n self.data_buffer = data_buffer\n\n self.device = torch.device(device)\n\n # the network and optimizers\n self.policy_net = policy_net.to(self.device)\n self.q_net1 = q_net1.to(self.device)\n self.q_net2 = q_net2.to(self.device)\n self.target_q_net1 = copy.deepcopy(self.q_net1).to(self.device)\n self.target_q_net2 = copy.deepcopy(self.q_net2).to(self.device)\n self.cvae_net = cvae_net.to(self.device)\n self.policy_optimizer = torch.optim.Adam(self.policy_net.parameters(), lr=policy_lr)\n self.q_optimizer1 = torch.optim.Adam(self.q_net1.parameters(), lr=qf_lr)\n self.q_optimizer2 = torch.optim.Adam(self.q_net2.parameters(), lr=qf_lr)\n self.cvae_optimizer = torch.optim.Adam(self.cvae_net.parameters(), lr=cvae_lr)\n\n self.gamma = gamma\n self.tau = tau\n\n self.max_train_step = max_train_step\n self.eval_freq = eval_freq\n self.train_step = 0\n\n self.resume = resume # whether load checkpoint start train from last time\n\n # BEAR\n self.lmbda = lmbda\n self.mmd_sigma = mmd_sigma\n self.kernel_type = kernel_type\n self.lagrange_thresh = lagrange_thresh\n self.n_action_samples = n_action_samples\n self.n_target_samples = n_target_samples\n self.n_mmd_action_samples = n_mmd_action_samples\n self.warmup_step = warmup_step\n\n # mmd loss's temperature\n self.log_alpha_prime = torch.zeros(1, requires_grad=True, device=self.device)\n self.alpha_prime_optimizer = torch.optim.Adam([self.log_alpha_prime], lr=1e-3)\n\n # log dir and interval\n self.log_interval = log_interval\n self.result_dir = os.path.join(log_tools.ROOT_DIR, \"run/results\", train_id)\n log_tools.make_dir(self.result_dir)\n self.checkpoint_path = os.path.join(self.result_dir, \"checkpoint.pth\")\n self.tensorboard_writer = log_tools.TensorboardLogger(self.result_dir)\n\n def choose_action(self, obs, eval=False):\n with torch.no_grad():\n obs = torch.FloatTensor(obs).reshape(1, -1).repeat(self.n_action_samples, 1).to(self.device)\n action, _, _ = self.policy_net(obs)\n q1 = self.q_net1(obs, action)\n ind = q1.argmax(dim=0)\n return action[ind].cpu().numpy().flatten()\n\n def mmd_loss_laplacian(self, samples1, samples2, sigma=0.2):\n \"\"\"MMD constraint with Laplacian kernel for support matching\"\"\"\n # sigma is set to 10.0 for hopper, cheetah and 20 for walker/ant\n diff_x_x = samples1.unsqueeze(2) - samples1.unsqueeze(1) # B x N x N x d\n diff_x_x = torch.mean((-(diff_x_x.abs()).sum(-1)/(2.0 * sigma)).exp(), dim=(1, 2))\n\n diff_x_y = samples1.unsqueeze(2) - samples2.unsqueeze(1)\n diff_x_y = torch.mean((-(diff_x_y.abs()).sum(-1)/(2.0 * sigma)).exp(), dim=(1, 2))\n\n diff_y_y = samples2.unsqueeze(2) - samples2.unsqueeze(1) # B x N x N x d\n diff_y_y = torch.mean((-(diff_y_y.abs()).sum(-1)/(2.0 * sigma)).exp(), dim=(1, 2))\n\n overall_loss = (diff_x_x + diff_y_y - 2.0 * diff_x_y + 1e-6).sqrt()\n return overall_loss\n\n def mmd_loss_gaussian(self, samples1, samples2, sigma=0.2):\n \"\"\"MMD constraint with Gaussian Kernel support matching\"\"\"\n # sigma is set to 10.0 for hopper, cheetah and 20 for walker/ant\n diff_x_x = samples1.unsqueeze(2) - samples1.unsqueeze(1) # B x N x N x d\n diff_x_x = torch.mean((-(diff_x_x.pow(2)).sum(-1)/(2.0 * sigma)).exp(), dim=(1, 2))\n\n diff_x_y = samples1.unsqueeze(2) - samples2.unsqueeze(1)\n diff_x_y = torch.mean((-(diff_x_y.pow(2)).sum(-1)/(2.0 * sigma)).exp(), dim=(1, 2))\n\n diff_y_y = samples2.unsqueeze(2) - samples2.unsqueeze(1) # B x N x N x d\n diff_y_y = torch.mean((-(diff_y_y.pow(2)).sum(-1)/(2.0 * sigma)).exp(), dim=(1, 2))\n\n overall_loss = (diff_x_x + diff_y_y - 2.0 * diff_x_y + 1e-6).sqrt()\n return overall_loss\n\n def train(self):\n # Sample\n batch = self.data_buffer.sample()\n obs = batch[\"obs\"].to(self.device)\n acts = batch[\"acts\"].to(self.device)\n rews = batch[\"rews\"].to(self.device)\n next_obs = batch[\"next_obs\"].to(self.device)\n done = batch[\"done\"].to(self.device)\n\n \"\"\"\n Train the Behaviour cloning policy to be able to take more than 1 sample for MMD.\n Conditional VAE is used as Behaviour cloning policy in BEAR.\n \"\"\"\n recon_action, mu, log_std = self.cvae_net(obs, acts)\n cvae_loss = self.cvae_net.loss_function(recon_action, acts, mu, log_std)\n\n self.cvae_optimizer.zero_grad()\n cvae_loss.backward()\n self.cvae_optimizer.step()\n\n \"\"\"\n Critic Training\n \"\"\"\n with torch.no_grad():\n # generate 10 actions for every next_obs(Same as BCQ)\n next_obs = torch.repeat_interleave(next_obs, repeats=self.n_target_samples, dim=0).to(self.device)\n # compute target Q value of generated action\n target_q1 = self.target_q_net1(next_obs, self.policy_net(next_obs)[0])\n target_q2 = self.target_q_net2(next_obs, self.policy_net(next_obs)[0])\n # soft clipped double q-learning\n target_q = self.lmbda * torch.min(target_q1, target_q2) + (1. - self.lmbda) * torch.max(target_q1, target_q2)\n # take max over each action sampled from the generation and perturbation model\n target_q = target_q.reshape(obs.shape[0], self.n_target_samples, 1).max(1)[0].squeeze(1)\n target_q = rews + self.gamma * (1. - done) * target_q\n\n # compute current Q\n current_q1 = self.q_net1(obs, acts).squeeze(1)\n current_q2 = self.q_net2(obs, acts).squeeze(1)\n # compute critic loss\n critic_loss1 = F.mse_loss(current_q1, target_q)\n critic_loss2 = F.mse_loss(current_q2, target_q)\n\n self.q_optimizer1.zero_grad()\n critic_loss1.backward()\n self.q_optimizer1.step()\n\n self.q_optimizer2.zero_grad()\n critic_loss2.backward()\n self.q_optimizer2.step()\n\n # MMD Loss\n # sample actions from dataset and current policy(B x N x D)\n raw_sampled_actions = self.cvae_net.decode_multiple_without_squash(obs, decode_num=self.n_mmd_action_samples,\n z_device=self.device)\n raw_actor_actions = self.policy_net.sample_multiple_without_squash(obs, sample_num=self.n_mmd_action_samples)\n if self.kernel_type == 'gaussian':\n mmd_loss = self.mmd_loss_gaussian(raw_sampled_actions, raw_actor_actions, sigma=self.mmd_sigma)\n else:\n mmd_loss = self.mmd_loss_laplacian(raw_sampled_actions, raw_actor_actions, sigma=self.mmd_sigma)\n\n \"\"\"\n Alpha prime training(lagrangian parameter update for MMD loss weight)\n \"\"\"\n alpha_prime_loss = -(self.log_alpha_prime.exp() * (mmd_loss - self.lagrange_thresh)).mean()\n self.alpha_prime_optimizer.zero_grad()\n alpha_prime_loss.backward(retain_graph=True)\n self.alpha_prime_optimizer.step()\n\n self.log_alpha_prime.data.clamp_(min=-5.0, max=10.0) # clip for stability\n\n \"\"\"\n Actor Training\n Actor Loss = alpha_prime * MMD Loss + -minQ(s,a)\n \"\"\"\n a, log_prob, _ = self.policy_net(obs)\n min_q = torch.min(self.q_net1(obs, a), self.q_net2(obs, a)).squeeze(1)\n # policy_loss = (self.alpha * log_prob - min_q).mean() # SAC Type\n policy_loss = - (min_q.mean())\n\n # BEAR Actor Loss\n actor_loss = (self.log_alpha_prime.exp() * mmd_loss).mean()\n if self.train_step > self.warmup_step:\n actor_loss = policy_loss + actor_loss\n self.policy_optimizer.zero_grad()\n actor_loss.backward() # the mmd_loss will backward again in alpha_prime_loss.\n self.policy_optimizer.step()\n\n soft_target_update(self.q_net1, self.target_q_net1, tau=self.tau)\n soft_target_update(self.q_net2, self.target_q_net2, tau=self.tau)\n\n self.train_step += 1\n\n return critic_loss1.cpu().item(), critic_loss2.cpu().item(), policy_loss.cpu().item(), alpha_prime_loss.cpu().item()\n\n def learn(self):\n if self.resume:\n self.load_agent_checkpoint()\n else:\n # delete tensorboard log file\n log_tools.del_all_files_in_dir(self.result_dir)\n\n while self.train_step < (int(self.max_train_step)):\n # train\n q_loss1, q_loss2, policy_loss, alpha_prime_loss = self.train()\n\n if self.train_step % self.eval_freq == 0:\n avg_reward, avg_length = evaluate(agent=self, episode_num=5)\n self.tensorboard_writer.log_eval_data({\"eval_episode_length\": avg_length,\n \"eval_episode_reward\": avg_reward}, self.train_step)\n\n if self.train_step % self.log_interval == 0:\n self.store_agent_checkpoint()\n self.tensorboard_writer.log_train_data({\"q_loss_1\": q_loss1,\n \"q_loss_2\": q_loss2,\n \"policy_loss\": policy_loss,\n \"alpha_prime_loss\": alpha_prime_loss}, self.train_step)\n\n def store_agent_checkpoint(self):\n checkpoint = {\n \"q_net1\": self.q_net1.state_dict(),\n \"q_net2\": self.q_net2.state_dict(),\n \"policy_net\": self.policy_net.state_dict(),\n \"q_optimizer1\": self.q_optimizer1.state_dict(),\n \"q_optimizer2\": self.q_optimizer2.state_dict(),\n \"policy_optimizer\": self.policy_optimizer.state_dict(),\n \"log_alpha_prime\": self.log_alpha_prime,\n \"alpha_prime_optimizer\": self.alpha_prime_optimizer.state_dict(),\n \"train_step\": self.train_step,\n }\n\n torch.save(checkpoint, self.checkpoint_path)\n\n def load_agent_checkpoint(self):\n checkpoint = torch.load(self.checkpoint_path, map_location=self.device) # can load gpu's data on cpu machine\n self.q_net1.load_state_dict(checkpoint[\"q_net1\"])\n self.q_net2.load_state_dict(checkpoint[\"q_net2\"])\n self.policy_net.load_state_dict(checkpoint[\"policy_net\"])\n self.q_optimizer1.load_state_dict(checkpoint[\"q_optimizer1\"])\n self.q_optimizer2.load_state_dict(checkpoint[\"q_optimizer2\"])\n self.policy_optimizer.load_state_dict(checkpoint[\"policy_optimizer\"])\n self.log_alpha_prime = checkpoint[\"log_alpha_prime\"]\n self.alpha_prime_optimizer.load_state_dict(checkpoint[\"alpha_prime_optimizer\"])\n self.train_step = checkpoint[\"train_step\"]\n\n print(\"load checkpoint from \\\"\" + self.checkpoint_path +\n \"\\\" at \" + str(self.train_step) + \" time step\")\n", "meta": {"hexsha": "3059a3e3d69fcfc949148f70131e864640db9b77", "size": 13060, "ext": "py", "lang": "Python", "max_stars_repo_path": "algos/offline/bear.py", "max_stars_repo_name": "dragon-wang/RL_Algorithms", "max_stars_repo_head_hexsha": "00af9008e870c8832f7ad1cbffe5d55997ddf62c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-04-17T12:11:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T07:23:47.000Z", "max_issues_repo_path": "algos/offline/bear.py", "max_issues_repo_name": "dragon-wang/RL_Algorithms", "max_issues_repo_head_hexsha": "00af9008e870c8832f7ad1cbffe5d55997ddf62c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-24T08:06:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-29T11:59:46.000Z", "max_forks_repo_path": "algos/offline/bear.py", "max_forks_repo_name": "dragon-wang/RL_Algorithms", "max_forks_repo_head_hexsha": "00af9008e870c8832f7ad1cbffe5d55997ddf62c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-11-22T12:59:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T07:23:50.000Z", "avg_line_length": 45.985915493, "max_line_length": 124, "alphanum_fraction": 0.6270290965, "include": true, "reason": "import numpy", "num_tokens": 3136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337582, "lm_q2_score": 0.2598256322295121, "lm_q1q2_score": 0.14506766811300875}} {"text": "#! /usr/bin/env python\n\nimport mdtraj as md\nimport argparse\nimport numpy as np\nfrom LLC_Membranes.llclib import physical, topology\nfrom LLC_Membranes.analysis import p2p\nimport matplotlib.pyplot as plt\nimport tqdm\nimport matplotlib as mpl\nimport os.path as path\n\n\ndef initialize():\n\n parser = argparse.ArgumentParser(description='Calculate the number density of selected groups along axis')\n\n parser.add_argument('-g', '--gro', default='wiggle.gro', help='Name of coordinate file')\n parser.add_argument('-t', '--traj', default='traj_whole.xtc', help='Trajectory file (.trr, .xtc should work)')\n parser.add_argument('-b', '--begin', default=0, type=int, help='Frame to begin calculations')\n parser.add_argument('-c', '--components', nargs='+', help=\"Region(s) or atoms to include in calculation. Special\"\n \"groups include 'head groups' and 'tails'\")\n parser.add_argument('-m', '--monomer', default='NaGA3C11', help='Name of monomer (no file extension)')\n parser.add_argument('-e', '--end', default=-1, type=int, help='Frame to stop doing calculations')\n parser.add_argument('-bins', default=100, type=int, help='Number of bins to use')\n parser.add_argument('-s', '--solvate', action=\"store_true\",\n help='If the system is solvated, plot the number density of water as well')\n parser.add_argument('-l', '--load', help='Name of compressed .npz to load')\n\n args = parser.parse_args()\n\n return args\n\n\ndef grps(name):\n \"\"\" Return names of atoms making up specialized groups. This is specifically for NaGA3C11.\n\n TODO: incorporate these groups as annotations (maybe)\n\n :param name: specialized group names. Valid options are 'head groups' and 'tails'\n\n :type name: str\n\n :return: atom names that constitute specialized groups\n \"\"\"\n\n if name == 'head groups':\n\n return ['C', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'O3', 'O4']\n\n elif name == 'tails':\n\n return ['C7', 'C8', 'C9', 'C10', 'C11', 'C12', 'C13', 'C14', 'C15', 'C16', 'C17', 'C18', 'C19', 'C20', 'C21',\n 'C22', 'C23', 'C24', 'C25', 'C26', 'C27', 'C28', 'C29', 'C30', 'C31', 'C32', 'C33', 'C34', 'C35',\n 'C36', 'C37', 'C38', 'C39', 'C40', 'C41', 'C42', 'C43', 'C44', 'C45', 'C46', 'C47', 'C48']\n\n\nclass Region(object):\n\n def __init__(self, traj, gro, components, monomer, begin=0, end=-1):\n \"\"\" Determine the density of components. Similar to a radial density, but instead of center of mass, the radial\n density of each atom in the region is averaged together.\n\n :param traj: name of trajectory to analyze (.xtc or .trr)\n :param gro: name of GROMACS coordinate file with same topology as traj\n :param component: list of atoms or name of groups of atoms\n :param begin: first frame to analyze\n :param end: last grame to analyze\n\n :type traj: str\n :type gro: str\n :type component: list\n :type begin: int\n :type end: int\n \"\"\"\n\n special_groups = ['head groups', 'tails']\n\n if components[0].lower() in special_groups:\n self.components = grps(components[0].lower())\n else:\n self.components = components\n\n print('Loading trajectory...', end=\"\")\n self.t = md.load('%s' % traj, top='%s' % gro)[begin:end]\n print('done')\n\n self.monomer = topology.LC('%s.gro' % monomer)\n\n self.r = None\n self.density = None\n\n def component_density(self, bins=50, spline=True, progress=True, npts_spline=10):\n\n self.r = np.zeros([bins])\n self.density = np.zeros([self.t.n_frames, bins])\n\n pore_defining_atoms = [a.index for a in self.t.topology.atoms if a.name in self.monomer.pore_defining_atoms\n and a.residue.name in self.monomer.residues]\n\n pore_centers = physical.avg_pore_loc(4, self.t.xyz[:, pore_defining_atoms, :], self.t.unitcell_vectors,\n spline=spline, progress=progress, npts=npts_spline)\n\n print('Calculating component density')\n self.r, self.density = physical.compdensity(self.com, pore_centers, self.t.unitcell_vectors,\n nbins=bins, spline=spline, cut=cut)\n\n\ndef duplicate(pos, box):\n \"\"\"\n Duplicate a set of positions periodically once in the +/- xy directions\n :param pos: xyz positions of a set of coordinates to be duplicated periodically\n :param box: box vectors in mdtraj format (t.unitcell_vectors : [nframes, 3, 3]) for every frame\n :return: Periodically duplicated system\n \"\"\"\n\n n = pos.shape[1] # number atoms in original unit cell\n\n p = np.zeros([pos.shape[0], n*9, 3]) # will hold periodically duplicated system\n p[:, :n, :] = pos\n\n # x-direction\n for t in range(pos.shape[0]):\n p[t, n:2*n, :] = pos[t, :, :] + box[t, 0, :]\n p[t, 2*n:3*n, :] = pos[t, :, :] - box[t, 0, :]\n\n # y-direction\n n *= 3\n for t in range(pos.shape[0]):\n p[t, n:2*n, :] = p[t, :n, :] + box[t, 1, :]\n p[t, 2*n:3*n, :] = p[t, :n, :] - box[t, 1, :]\n\n return p\n\n\ndef compdensity(component, pore_centers, start, box, cut=1.5, pores=4, nbins=50, rmax=3.5, buffer=0.0):\n \"\"\" Measure the density of a component as a function of the distance from the pore centers\n\n :param component: the coordinates of the component(s) which you want a radial distribution of at each frame\n :param pore_centers: a numpy array of the locations of each pore center at each trajectory frame\n :param start: the frame number at which to start calculations (should be after equilibration)\n :param cut: cutoff distance for distance calculations. Will not count anything further than cut from the pore center\n :param pores: number of pores (int) default=4\n :param rmax: maximum distance from pore center to calculate density for, default = 3.5 nm\n :param buffer: percentage used to define the location of z planes between which component density will be computed,\n float, default = 0 (i.e. no buffer). Should be between 0 and 1. e.g. for 1 percent, use 0.01 as the buffer\n\n :type component: numpy.ndarray\n :type pore_centers: numpy.ndarray\n :type start: int\n :type cut: float\n :type pores: int\n :type rmax: float\n :type buffer: float\n\n :return: the density of \"component\" as a function the distance from the pore center. Also\n returns the calculated bin width for plotting\n \"\"\"\n\n # Extract basic system information. It's important to follow the format of the component array to get it right\n\n tot_atoms = component.shape[1] # the total number of components in a single frame\n n_ppore = tot_atoms // pores # the total number of components in each pore\n\n nT = component.shape[0]\n zbox = np.mean(box[:, 2, 2])\n # Find the approximate max and minimum z values of the components based on the last frame\n\n zmax = np.max(component[-1, :, 2])\n zmin = np.min(component[-1, :, 2])\n thickness = zmax - zmin # approximate membrane thickness\n\n # now find the maximum and minimum permissible z dimensions based on the buffer\n zmax_buff = zmax - thickness * buffer # Could use buffer/2 depending on how you interpret what buffer % means\n zmin_buff = zmin + thickness * buffer\n\n density = np.zeros([nbins]) # number / nm^3\n for t in tqdm.tqdm(range(start, nT)):\n for p in range(pores):\n # narrow down the positions to those that are within 'cut' of at least one pore\n distances = np.linalg.norm(component[t, :, :2] - pore_centers[t, p, :], axis=1)\n d_sorted = np.sort(distances)\n # find where the distances exceed the cutoff\n stop = 0\n while d_sorted[stop] < cut:\n stop += 1\n\n hist, bin_edges = np.histogram(d_sorted[:stop], bins=nbins, range=(0, cut)) # the range option is necessary\n # to make sure we have equal sized bins on every iteration\n\n density += hist\n\n density /= zbox * (nT - start) # take average\n bin_width = cut / nbins\n\n # normalize based on area of anulus where bin is located\n r = np.zeros([nbins])\n normalization = []\n for i in range(nbins):\n normalization.append(np.pi * (bin_edges[i + 1] ** 2 - bin_edges[i] ** 2))\n density[i] /= np.pi * (bin_edges[i + 1] ** 2 - bin_edges[i] ** 2)\n r[i] = (bin_edges[i + 1] + bin_edges[i]) / 2\n\n return density, r, bin_width\n\n\nif __name__ == \"__main__\":\n \n args = initialize() # parse the args\n\n # run : regional_density.py - m offset_disordered_regional_density.npz offset_regional_density.npz\n # layered_disordered_regional_density.npz layered_regional_density.npz solvated_regional_density.npz\n\n # mpl.style.use('seaborn')\n\n # regions = ['Tails', 'Head Groups', 'Sodium']\n regions = ['Tails', 'Head Groups', 'Sodium']\n\n # if args.multi:\n if False:\n\n # colors = ['blue', 'red', 'green', 'xkcd:orange']\n # colors = ['xkcd:red', 'xkcd:green', 'blue', 'xkcd:yellow']\n colors = ['xkcd:blue', 'xkcd:olive', 'xkcd:orangered', 'xkcd:magenta', 'xkcd:gold']\n names = ['Ordered Parallel Displaced', 'Ordered Sandwiched', 'Disordered Sandwiched',\n 'Disordered Parallel Displaced', 'Solvated Parallel Displaced']\n\n # import pylab\n #\n # fig = pylab.figure()\n # figlegend = pylab.figure(figsize=(7.75, 0.6))\n # ax = fig.add_subplot(111)\n # for i in range(5):\n # ax.plot(range(10), pylab.randn(10), color=colors[i], label=names[i])\n #\n # #lines = ax.plot(range(10), pylab.randn(10), range(10), pylab.randn(10),range(10), pylab.randn(10), range(10), pylab.randn(10), range(10), pylab.randn(10))\n # figlegend.legend(*ax.get_legend_handles_labels(), 'best', ncol=3)\n # fig.show()\n # figlegend.show()\n # fig.tight_layout()\n # figlegend.savefig('legend.pdf')\n #\n # plt.show()\n # exit()\n\n # names = ['Parallel Displaced (d=3.7)', 'Sandwiched (d=3.7)', 'Sandwiched (d=5.0)', 'Parallel Displaced (d=5.0)',\n # 'Solvated Parallel Displaced']\n # names = ['Dry', 'Solvated']\n # colors = ['xkcd:orange', 'xkcd:blue', 'xkcd:orange']\n\n n = len(args.multi)\n system = np.load(args.multi[0])\n\n # It is assumed that all of the data uses the same number of bins with the same bin width\n r = system['r']\n bin_width = system['bw']\n\n results = np.zeros([n, len(regions), len(r)])\n # results = np.zeros([n, 4, len(r)])\n\n # results[0, :3, :] = system['results']\n\n for i in range(n - 1):\n system = np.load(args.multi[i])\n results[i, :, :] = system['results']\n\n system = np.load(args.multi[-1])\n results[-1, :, :] = system['results'][:3, :]\n\n outline = np.zeros([4, n, r.shape[0]*2 + 2, 2])\n for i in range(len(regions)):\n print(i)\n fig = plt.figure(i)\n for j in range(n):\n #plt.bar(r, results[j, i, :], bin_width, color=colors[j], alpha=1, label=names[j])\n\n half_width = bin_width / 2\n # outline = np.zeros([r.shape[0]*2 + 2, 2])\n outline[i, j, 0, 0] = r[0] - half_width\n outline[i, j, -1, 0] = r[-1] + half_width\n outline[i, j, 1:-1:2, 0] = r - half_width\n outline[i, j, 2:-1:2, 0] = r + half_width\n outline[i, j, 1:-1:2, 1] = results[j, i, :]\n outline[i, j, 2:-1:2, 1] = results[j, i, :]\n if i == 0:\n plt.plot(outline[i, j, :-1, 0], outline[i, j, :-1, 1], color=colors[j], linewidth=2, label=names[j])\n else:\n plt.plot(outline[i, j, 1:, 0], outline[i, j, 1:, 1], color=colors[j], linewidth=2,\n label=names[j])\n # plt.title(regions[i], fontsize=14)\n\n #plt.legend()#fontsize=12)\n\n plt.ylabel('Component Number Density \\n (number/nm$^3$)', fontsize=18)\n plt.xlabel('Distance from pore center, r (nm)', fontsize=18)\n plt.axes().tick_params(labelsize=14)\n # plt.ylim([0, 0.6])\n plt.tight_layout()\n plt.savefig(\"%s_density.pdf\" % regions[i])\n\n plt.show()\n\n if args.solvate:\n colors = ['xkcd:red', 'xkcd:green', 'blue', 'xkcd:yellow']\n else:\n colors = ['red', 'green', 'blue']\n\n if not args.load:\n\n R = Region(args.traj, args.gro, args.components, begin=args.begin, end=args.end)\n\n print('Loading trajectory...', end=\"\")\n t = md.load('%s' % args.traj, top='%s' % args.gro)[args.begin:args.end]\n print('done')\n\n box = t.unitcell_vectors\n nT = t.n_frames\n npores = 4\n r_max = 0\n\n if args.solvate:\n results = np.zeros([len(regions) + 1, args.bins])\n else:\n results = np.zeros([len(regions), args.bins])\n\n #keep = [a.index for a in t.topology.atoms if a.residue.name != 'HOH'] # everything kept if system not solvated\n components = ['C', 'C1', 'C2', 'C3', 'C4', 'C5']\n comp = [a.index for a in t.topology.atoms if a.name in components]\n\n p_centers = physical.avg_pore_loc(npores, t.xyz[:, comp, :], box)\n\n for i, reg in enumerate(regions):\n\n print('Calculating number density of %s region' % reg)\n\n pos = p2p.restrict_atoms(t, reg) # restrict trajectory to region\n\n p = duplicate(pos, t.unitcell_vectors) # duplicate things periodically\n\n equil = 0\n density, r, bin_width = compdensity(pos, p_centers, equil, box, pores=npores, nbins=args.bins)\n\n results[i, :] = density\n\n plt.bar(r, density, bin_width, color=colors[i], alpha=0.6, label=reg)\n\n np.savez_compressed(\"regional_density\", results=results, r=r, bw=bin_width, box=t.unitcell_vectors)\n print('Arrays saved as regional_density.npz')\n\n if args.solvate:\n\n print('Calculating number density of solvent')\n keep = [a.index for a in t.topology.atoms if a.residue.name == 'HOH' and a.name == 'O']\n pos = t.xyz[:, keep, :]\n p = duplicate(pos, t.unitcell_vectors)\n equil = 0\n density, r, bin_width = Structure_char.compdensity(pos, p_centers, equil, t.unitcell_vectors, pores=npores, buffer=0, nbins=args.bins)\n results[-1, :] = density\n plt.bar(r, density, bin_width, color='xkcd:gold', alpha=0.75, label='Water')\n\n else:\n\n d = np.load(args.load)\n\n bw = d['bw']\n r = d['r']\n results = d['results']\n box = d['box']\n\n if args.solvate:\n regions.append('Water')\n\n for i in range(results.shape[0]):\n plt.bar(r, results[i, :], bw, color=colors[i], alpha=0.75, label=regions[i])\n\n un_normalize = np.zeros_like(results)\n\n annulus_area = []\n dr = r[-1] - r[-2] # width of annulus\n # r from above is calculated as the average of the edges of the bins. So I need to reverse that here\n for i in r:\n inner_r = i - (dr/2)\n outer_r = i + (dr/2)\n annulus_area.append(np.pi*(outer_r**2 - inner_r**2))\n\n for i in range(results.shape[0]):\n un_normalize[i, :] = results[i, :] * annulus_area\n\n r_cut = 0.6\n cut_index = 0\n while r[cut_index] < r_cut:\n cut_index += 1\n\n print('Percentage of sodium within %s nm of pore center: %2.2f %%' % (r_cut, 100*(sum(un_normalize[2, :cut_index])/sum(un_normalize[2, :]))))\n\n r_cut = 0.6\n cut_index = len(r) - 1\n while r[cut_index] > r_cut:\n cut_index -= 1\n\n print('Percentage of tails within %s nm of pore center: %2.2f %%' % (r_cut, 100*(sum(un_normalize[0, :cut_index])/sum(un_normalize[0, :]))))\n\n r_cut_pore = r_cut\n pore_cut_index = cut_index\n\n r_cut = 1\n cut_index = len(r) - 1\n while r[cut_index] > r_cut:\n cut_index -= 1\n\n print('Percentage of tails between %s and %s nm of pore center: %2.2f %%' % (r_cut_pore, r_cut,\n 100*(sum(un_normalize[0, pore_cut_index:cut_index])/sum(un_normalize[0, :]))))\n\n print('Maximum of Head group region: r = %s' % r[np.argmax(results[1, :])])\n\n plt.legend(prop={'size':14}, loc=1)\n plt.ylabel('Component number density (count/nm$^3$)', fontsize=14)\n plt.xlabel('Distance from pore center (nm)', fontsize=14)\n plt.axes().tick_params(labelsize=14)\n plt.xlim(0, 1.5)\n plt.tight_layout()\n plt.savefig(\"regional_density.png\")\n plt.show()\n", "meta": {"hexsha": "853880a4e996f3348cf80ddc8265f0046916024c", "size": 16679, "ext": "py", "lang": "Python", "max_stars_repo_path": "LLC_Membranes/analysis/regional_density.py", "max_stars_repo_name": "shirtsgroup/LLC_Membranes", "max_stars_repo_head_hexsha": "e94694f298909352d7e9d912625314a1e46aa5b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-06-18T15:26:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-11T18:57:39.000Z", "max_issues_repo_path": "LLC_Membranes/analysis/regional_density.py", "max_issues_repo_name": "shirtsgroup/LLC_Membranes", "max_issues_repo_head_hexsha": "e94694f298909352d7e9d912625314a1e46aa5b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-08-22T20:11:46.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T22:35:17.000Z", "max_forks_repo_path": "LLC_Membranes/analysis/regional_density.py", "max_forks_repo_name": "shirtsgroup/LLC_Membranes", "max_forks_repo_head_hexsha": "e94694f298909352d7e9d912625314a1e46aa5b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-07-06T15:41:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-27T17:59:13.000Z", "avg_line_length": 39.3372641509, "max_line_length": 165, "alphanum_fraction": 0.5913424066, "include": true, "reason": "import numpy", "num_tokens": 4609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.28776782797747225, "lm_q1q2_score": 0.14500798419759922}} {"text": "\"\"\"Sequential Monte Carlo sampler also known as\nAdaptive Transitional Marcov Chain Monte Carlo sampler.\n\nRuns on any pymc3 model.\n\nCreated on March, 2016\n\nVarious significant updates July, August 2016\n\nMade pymc3 compatible November 2016\nRenamed to SMC and further improvements March 2017\n\n@author: Hannes Vasyura-Bathke\n\"\"\"\nimport numpy as np\nimport pymc3 as pm\nfrom tqdm import tqdm\n\nimport theano\nimport copy\nimport warnings\n\nfrom ..model import modelcontext\nfrom ..vartypes import discrete_types\nfrom ..theanof import inputvars, make_shared_replacements, join_nonshared_inputs\nimport numpy.random as nr\n\nfrom .arraystep import metrop_select\nfrom ..backends import smc_text as atext\n\n__all__ = ['SMC', 'ATMIP_sample']\n\nEXPERIMENTAL_WARNING = \"Warning: SMC is an experimental step method, and not yet\"\\\n \" recommended for use in PyMC3!\"\n\n\nclass Proposal(object):\n \"\"\"Proposal distributions modified from pymc3 to initially create all the\n Proposal steps without repeated execution of the RNG - significant speedup!\n\n Parameters\n ----------\n s : :class:`numpy.ndarray`\n \"\"\"\n def __init__(self, s):\n self.s = np.atleast_1d(s)\n\n\nclass MultivariateNormalProposal(Proposal):\n def __call__(self, num_draws=None):\n return np.random.multivariate_normal(\n mean=np.zeros(self.s.shape[0]), cov=self.s, size=num_draws)\n\n\nproposal_dists = {\n 'MultivariateNormal': MultivariateNormalProposal,\n }\n\n\ndef choose_proposal(proposal_name, scale=1.):\n \"\"\"Initialise and select proposal distribution.\n\n Parameters\n ----------\n proposal_name : string\n Name of the proposal distribution to initialise\n scale : float or :class:`numpy.ndarray`\n\n Returns\n -------\n class:`pymc3.Proposal` Object\n \"\"\"\n return proposal_dists[proposal_name](scale)\n\n\nclass SMC(atext.ArrayStepSharedLLK):\n \"\"\"Adaptive Transitional Markov-Chain Monte-Carlo sampler class.\n\n Creates initial samples and framework around the (C)ATMIP parameters\n\n Parameters\n ----------\n vars : list\n List of variables for sampler\n out_vars : list\n List of output variables for trace recording. If empty unobserved_RVs\n are taken.\n n_chains : int\n Number of chains per stage has to be a large number\n of number of n_jobs (processors to be used) on the machine.\n scaling : float\n Factor applied to the proposal distribution i.e. the step size of the\n Markov Chain\n covariance : :class:`numpy.ndarray`\n (n_chains x n_chains)\n Initial Covariance matrix for proposal distribution,\n if None - identity matrix taken\n likelihood_name : string\n name of the :class:`pymc3.determinsitic` variable that contains the\n model likelihood - defaults to 'like'\n proposal_name :\n Type of proposal distribution, see\n smc.proposal_dists.keys() for options\n tune : boolean\n Flag for adaptive scaling based on the acceptance rate\n tune_interval : int\n Number of steps to tune for\n coef_variation : scalar, float\n Coefficient of variation, determines the change of beta\n from stage to stage, i.e.indirectly the number of stages,\n low coef_variation --> slow beta change,\n results in many stages and vice verca (default: 1.)\n check_bound : boolean\n Check if current sample lies outside of variable definition\n speeds up computation as the forward model wont be executed\n default: True\n model : :class:`pymc3.Model`\n Optional model for sampling step.\n Defaults to None (taken from context).\n random_seed : int\n Optional to set the random seed. Necessary for initial population.\n\n References\n ----------\n .. [Ching2007] Ching, J. and Chen, Y. (2007).\n Transitional Markov Chain Monte Carlo Method for Bayesian Model\n Updating, Model Class Selection, and Model Averaging.\n J. Eng. Mech., 10.1061/(ASCE)0733-9399(2007)133:7(816), 816-832.\n `link `__\n \"\"\"\n default_blocked = True\n\n def __init__(self, vars=None, out_vars=None, n_chains=100, scaling=1., covariance=None,\n likelihood_name='like', proposal_name='MultivariateNormal', tune=True,\n tune_interval=100, coef_variation=1., check_bound=True, model=None,\n random_seed=-1):\n warnings.warn(EXPERIMENTAL_WARNING)\n if random_seed != -1:\n nr.seed(random_seed)\n\n model = modelcontext(model)\n\n if vars is None:\n vars = model.vars\n\n vars = inputvars(vars)\n\n if out_vars is None:\n out_vars = model.unobserved_RVs\n\n out_varnames = [out_var.name for out_var in out_vars]\n\n if covariance is None and proposal_name == 'MultivariateNormal':\n self.covariance = np.eye(sum(v.dsize for v in vars))\n scale = self.covariance\n elif covariance is None:\n scale = np.ones(sum(v.dsize for v in vars))\n else:\n scale = covariance\n\n self.proposal_name = proposal_name\n self.proposal_dist = choose_proposal(self.proposal_name, scale=scale)\n\n self.scaling = np.atleast_1d(scaling)\n self.tune = tune\n self.check_bnd = check_bound\n self.tune_interval = tune_interval\n self.steps_until_tune = tune_interval\n\n self.proposal_samples_array = self.proposal_dist(n_chains)\n\n self.stage_sample = 0\n self.accepted = 0\n\n self.beta = 0\n self.stage = 0\n self.chain_index = 0\n self.resampling_indexes = np.arange(n_chains)\n\n self.coef_variation = coef_variation\n self.n_chains = n_chains\n self.likelihoods = np.zeros(n_chains)\n\n self.likelihood_name = likelihood_name\n self._llk_index = out_varnames.index(likelihood_name)\n self.discrete = np.concatenate([[v.dtype in discrete_types] * (v.dsize or 1) for v in vars])\n self.any_discrete = self.discrete.any()\n self.all_discrete = self.discrete.all()\n\n # create initial population\n self.population = []\n self.array_population = np.zeros(n_chains)\n for _ in range(self.n_chains):\n self.population.append(pm.Point({v.name: v.random() for v in vars}, model=model))\n\n self.chain_previous_lpoint = copy.deepcopy(self.population)\n\n shared = make_shared_replacements(vars, model)\n self.logp_forw = logp_forw(out_vars, vars, shared)\n self.check_bnd = logp_forw([model.varlogpt], vars, shared)\n\n super(SMC, self).__init__(vars, out_vars, shared)\n\n def astep(self, q0):\n if self.stage == 0:\n l_new = self.logp_forw(q0)\n q_new = q0\n\n else:\n if not self.stage_sample:\n self.proposal_samples_array = self.proposal_dist(self.n_steps)\n\n if not self.steps_until_tune and self.tune:\n # Tune scaling parameter\n self.scaling = tune(self.accepted / float(self.tune_interval))\n # Reset counter\n self.steps_until_tune = self.tune_interval\n self.accepted = 0\n\n delta = self.proposal_samples_array[self.stage_sample, :] * self.scaling\n\n if self.any_discrete:\n if self.all_discrete:\n delta = np.round(delta, 0)\n q0 = q0.astype(int)\n q = (q0 + delta).astype(int)\n else:\n delta[self.discrete] = np.round(delta[self.discrete], 0).astype(int)\n q = q0 + delta\n q = q[self.discrete].astype(int)\n else:\n q = q0 + delta\n\n l0 = self.chain_previous_lpoint[self.chain_index]\n\n if self.check_bnd:\n varlogp = self.check_bnd(q)\n\n if np.isfinite(varlogp):\n logp = self.logp_forw(q)\n q_new, accepted = metrop_select(\n self.beta * (logp[self._llk_index] - l0[self._llk_index]), q, q0)\n\n if accepted:\n self.accepted += 1\n l_new = logp\n self.chain_previous_lpoint[self.chain_index] = l_new\n else:\n l_new = l0\n else:\n q_new = q0\n l_new = l0\n\n else:\n logp = self.logp_forw(q)\n q_new, accepted = metrop_select(\n self.beta * (logp[self._llk_index] - l0[self._llk_index]), q, q0)\n\n if accepted:\n self.accepted += 1\n l_new = logp\n self.chain_previous_lpoint[self.chain_index] = l_new\n else:\n l_new = l0\n\n self.steps_until_tune -= 1\n self.stage_sample += 1\n\n # reset sample counter\n if self.stage_sample == self.n_steps:\n self.stage_sample = 0\n\n return q_new, l_new\n\n def calc_beta(self):\n \"\"\"Calculate next tempering beta and importance weights based on\n current beta and sample likelihoods.\n\n Returns\n -------\n beta(m+1) : scalar, float\n tempering parameter of the next stage\n beta(m) : scalar, float\n tempering parameter of the current stage\n weights : :class:`numpy.ndarray`\n Importance weights (floats)\n \"\"\"\n low_beta = self.beta\n up_beta = 2.\n old_beta = self.beta\n\n while up_beta - low_beta > 1e-6:\n current_beta = (low_beta + up_beta) / 2.\n temp = np.exp((current_beta - self.beta) * (self.likelihoods - self.likelihoods.max()))\n cov_temp = np.std(temp) / np.mean(temp)\n if cov_temp > self.coef_variation:\n up_beta = current_beta\n else:\n low_beta = current_beta\n\n beta = current_beta\n weights = temp / np.sum(temp)\n return beta, old_beta, weights\n\n def calc_covariance(self):\n \"\"\"Calculate trace covariance matrix based on importance weights.\n\n Returns\n -------\n cov : :class:`numpy.ndarray`\n weighted covariances (NumPy > 1.10. required)\n \"\"\"\n cov = np.cov(self.array_population, aweights=self.weights.ravel(), bias=False, rowvar=0)\n if np.isnan(cov).any() or np.isinf(cov).any():\n raise ValueError('Sample covariances not valid! Likely \"n_chains\" is too small!')\n return np.atleast_2d(cov)\n\n def select_end_points(self, mtrace):\n \"\"\"Read trace results (variables and model likelihood) and take end points\n for each chain and set as start population for the next stage.\n\n Parameters\n ----------\n mtrace : :class:`.base.MultiTrace`\n\n Returns\n -------\n population : list\n of :func:`pymc3.Point` dictionaries\n array_population : :class:`numpy.ndarray`\n Array of trace end-points\n likelihoods : :class:`numpy.ndarray`\n Array of likelihoods of the trace end-points\n \"\"\"\n array_population = np.zeros((self.n_chains, self.ordering.dimensions))\n n_steps = len(mtrace)\n\n # collect end points of each chain and put into array\n for var, slc, shp, _ in self.ordering.vmap:\n slc_population = mtrace.get_values(varname=var, burn=n_steps - 1, combine=True)\n if len(shp) == 0:\n array_population[:, slc] = np.atleast_2d(slc_population).T\n else:\n array_population[:, slc] = slc_population\n # get likelihoods\n likelihoods = mtrace.get_values(varname=self.likelihood_name,\n burn=n_steps - 1,\n combine=True)\n\n # map end array_endpoints to dict points\n population = [self.bij.rmap(row) for row in array_population]\n\n return population, array_population, likelihoods\n\n def get_chain_previous_lpoint(self, mtrace):\n \"\"\"Read trace results and take end points for each chain and set as\n previous chain result for comparison of metropolis select.\n\n Parameters\n ----------\n mtrace : :class:`.base.MultiTrace`\n\n Returns\n -------\n chain_previous_lpoint : list\n all unobservedRV values, including dataset likelihoods\n \"\"\"\n array_population = np.zeros((self.n_chains, self.lordering.dimensions))\n n_steps = len(mtrace)\n for var, (_, slc, shp, _) in zip(mtrace.varnames, self.lordering.vmap):\n slc_population = mtrace.get_values(varname=var, burn=n_steps - 1, combine=True)\n if len(shp) == 0:\n array_population[:, slc] = np.atleast_2d(slc_population).T\n else:\n array_population[:, slc] = slc_population\n\n return [self.lij.rmap(row) for row in array_population[self.resampling_indexes, :]]\n\n def mean_end_points(self):\n \"\"\"Calculate mean of the end-points and return point.\n\n Returns\n -------\n Dictionary of trace variables\n \"\"\"\n return self.bij.rmap(self.array_population.mean(axis=0))\n\n def resample(self):\n \"\"\"Resample pdf based on importance weights.\n based on Kitagawas deterministic resampling algorithm.\n\n Returns\n -------\n outindex : :class:`numpy.ndarray`\n Array of resampled trace indexes\n \"\"\"\n parents = np.arange(self.n_chains)\n N_childs = np.zeros(self.n_chains, dtype=int)\n\n cum_dist = np.cumsum(self.weights)\n u = (parents + np.random.rand()) / self.n_chains\n j = 0\n for i in parents:\n while u[i] > cum_dist[j]:\n j += 1\n\n N_childs[j] += 1\n\n indx = 0\n outindx = np.zeros(self.n_chains, dtype=int)\n for i in parents:\n if N_childs[i] > 0:\n for j in range(indx, (indx + N_childs[i])):\n outindx[j] = parents[i]\n\n indx += N_childs[i]\n\n return outindx\n\n\ndef ATMIP_sample(n_steps, step=None, start=None, homepath=None, chain=0, stage=0, n_jobs=1,\n tune=None, progressbar=False, model=None, random_seed=-1, rm_flag=False):\n \"\"\"(C)ATMIP sampling algorithm (Cascading - (C) not always relevant)\n\n Samples the solution space with n_chains of Metropolis chains, where each\n chain has n_steps iterations. Once finished, the sampled traces are\n evaluated:\n\n (1) Based on the likelihoods of the final samples, chains are weighted\n (2) the weighted covariance of the ensemble is calculated and set as new\n proposal distribution\n (3) the variation in the ensemble is calculated and the next tempering\n parameter (beta) calculated\n (4) New n_chains Metropolis chains are seeded on the traces with high\n weight for n_steps iterations\n (5) Repeat until beta > 1.\n\n Parameters\n ----------\n n_steps : int\n The number of samples to draw for each Markov-chain per stage\n step : :class:`SMC`\n SMC initialisation object\n start : List of dictionaries\n with length of (n_chains)\n Starting points in parameter space (or partial point)\n Defaults to random draws from variables (defaults to empty dict)\n homepath : string\n Result_folder for storing stages, will be created if not existing.\n chain : int\n Chain number used to store sample in backend. If `n_jobs` is\n greater than one, chain numbers will start here.\n stage : int\n Stage where to start or continue the calculation. It is possible to\n continue after completed stages (stage should be the number of the\n completed stage + 1). If None the start will be at stage = 0.\n n_jobs : int\n The number of cores to be used in parallel. Be aware that theano has\n internal parallelisation. Sometimes this is more efficient especially\n for simple models.\n step.n_chains / n_jobs has to be an integer number!\n tune : int\n Number of iterations to tune, if applicable (defaults to None)\n progressbar : bool\n Flag for displaying a progress bar\n model : :class:`pymc3.Model`\n (optional if in `with` context) has to contain deterministic\n variable name defined under step.likelihood_name' that contains the\n model likelihood\n random_seed : int or list of ints\n A list is accepted, more if `n_jobs` is greater than one.\n rm_flag : bool\n If True existing stage result folders are being deleted prior to\n sampling.\n\n References\n ----------\n .. [Minson2013] Minson, S. E. and Simons, M. and Beck, J. L., (2013),\n Bayesian inversion for finite fault earthquake source models\n I- Theory and algorithm. Geophysical Journal International, 2013,\n 194(3), pp.1701-1726,\n `link `__\n \"\"\"\n warnings.warn(EXPERIMENTAL_WARNING)\n\n model = modelcontext(model)\n step.n_steps = int(n_steps)\n if random_seed != -1:\n nr.seed(random_seed)\n\n if step is None:\n raise TypeError('Argument `step` has to be a SMC step object.')\n\n if homepath is None:\n raise TypeError('Argument `homepath` should be path to result_directory.')\n\n if n_jobs > 1:\n if not (step.n_chains / float(n_jobs)).is_integer():\n raise TypeError('n_chains / n_jobs has to be a whole number!')\n\n if start is not None:\n if len(start) != step.n_chains:\n raise TypeError('Argument `start` should have dicts equal the '\n 'number of chains (`step.n_chains`)')\n else:\n step.population = start\n\n if not any(step.likelihood_name in var.name for var in model.deterministics):\n raise TypeError('Model (deterministic) variables need to contain a variable %s '\n 'as defined in `step`.' % step.likelihood_name)\n\n stage_handler = atext.TextStage(homepath)\n\n if progressbar and n_jobs > 1:\n progressbar = False\n\n if stage == 0:\n # continue or start initial stage\n step.stage = stage\n draws = 1\n else:\n step = stage_handler.load_atmip_params(stage)\n draws = step.n_steps\n\n stage_handler.clean_directory(stage, None, rm_flag)\n with model:\n chains = stage_handler.recover_existing_results(stage, draws, step, n_jobs)\n if chains is not None:\n rest = len(chains) % n_jobs\n if rest > 0:\n pm._log.info('Fixing %i chains ...' % rest)\n chains, rest_chains = chains[:-rest], chains[-rest:]\n # process traces that are not a multiple of n_jobs\n sample_args = {\n 'draws': draws,\n 'step': step,\n 'stage_path': stage_handler.stage_path(stage),\n 'progressbar': progressbar,\n 'model': model,\n 'n_jobs': rest,\n 'chains': rest_chains}\n\n _iter_parallel_chains(**sample_args)\n pm._log.info('Back to normal!')\n\n with model:\n while step.beta < 1:\n if step.stage == 0:\n # Initial stage\n pm._log.info('Sample initial stage: ...')\n draws = 1\n else:\n draws = n_steps\n\n pm._log.info('Beta: %f Stage: %i' % (step.beta, step.stage))\n\n # Metropolis sampling intermediate stages\n chains = stage_handler.clean_directory(stage, chains, rm_flag)\n sample_args = {\n 'draws': draws,\n 'step': step,\n 'stage_path': stage_handler.stage_path(step.stage),\n 'progressbar': progressbar,\n 'model': model,\n 'n_jobs': n_jobs,\n 'chains': chains}\n\n _iter_parallel_chains(**sample_args)\n\n mtrace = stage_handler.load_multitrace(step.stage)\n\n step.population, step.array_population, step.likelihoods = step.select_end_points(\n mtrace)\n step.beta, step.old_beta, step.weights = step.calc_beta()\n\n if step.beta > 1.:\n pm._log.info('Beta > 1.: %f' % step.beta)\n step.beta = 1.\n stage_handler.dump_atmip_params(step)\n if stage == -1:\n chains = []\n else:\n chains = None\n else:\n step.covariance = step.calc_covariance()\n step.proposal_dist = choose_proposal(step.proposal_name, scale=step.covariance)\n step.resampling_indexes = step.resample()\n step.chain_previous_lpoint = step.get_chain_previous_lpoint(mtrace)\n\n stage_handler.dump_atmip_params(step)\n\n step.stage += 1\n del(mtrace)\n\n # Metropolis sampling final stage\n pm._log.info('Sample final stage')\n step.stage = -1\n temp = np.exp((1 - step.old_beta) * (step.likelihoods - step.likelihoods.max()))\n step.weights = temp / np.sum(temp)\n step.covariance = step.calc_covariance()\n step.proposal_dist = choose_proposal(step.proposal_name, scale=step.covariance)\n step.resampling_indexes = step.resample()\n step.chain_previous_lpoint = step.get_chain_previous_lpoint(mtrace)\n\n sample_args['step'] = step\n sample_args['stage_path'] = stage_handler.stage_path(step.stage)\n sample_args['chains'] = chains\n _iter_parallel_chains(**sample_args)\n\n stage_handler.dump_atmip_params(step)\n return stage_handler.load_multitrace(step.stage, model=model)\n\n\ndef _sample(draws, step=None, start=None, trace=None, chain=0, tune=None,\n progressbar=True, model=None, random_seed=-1):\n\n sampling = _iter_sample(draws, step, start, trace, chain,\n tune, model, random_seed)\n\n if progressbar:\n sampling = tqdm(sampling, total=draws)\n\n try:\n for strace in sampling:\n pass\n\n except KeyboardInterrupt:\n pass\n\n return chain\n\n\ndef _iter_sample(draws, step, start=None, trace=None, chain=0, tune=None,\n model=None, random_seed=-1):\n \"\"\"Modified from :func:`pymc3.sampling._iter_sample` to be more efficient with SMC algorithm.\"\"\"\n model = modelcontext(model)\n draws = int(draws)\n if draws < 1:\n raise ValueError('Argument `draws` should be above 0.')\n\n if start is None:\n start = {}\n\n if random_seed != -1:\n nr.seed(random_seed)\n\n try:\n step = pm.step_methods.CompoundStep(step)\n except TypeError:\n pass\n\n point = pm.Point(start, model=model)\n step.chain_index = chain\n trace.setup(draws, chain)\n for i in range(draws):\n if i == tune:\n step = pm.sampling.stop_tuning(step)\n\n point, out_list = step.step(point)\n trace.record(out_list)\n yield trace\n\n\ndef _work_chain(work):\n \"\"\"Wrapper function for parallel execution of _sample i.e. the Markov Chains.\n\n Parameters\n ----------\n work : List\n Containing all the information that is unique for each Markov Chain\n i.e. [:class:'SMC', chain_number(int),\n sampling index(int), start_point(dictionary)]\n\n Returns\n -------\n chain : int\n Index of chain that has been sampled\n \"\"\"\n return _sample(*work)\n\n\ndef _iter_parallel_chains(draws, step, stage_path, progressbar, model, n_jobs, chains=None):\n \"\"\"Do Metropolis sampling over all the chains with each chain being\n sampled 'draws' times. Parallel execution according to n_jobs.\n \"\"\"\n if chains is None:\n chains = range(step.n_chains)\n\n pm._log.info('Initialising chain traces ...')\n\n max_int = np.iinfo(np.int32).max\n random_seeds = nr.randint(1, max_int, size=len(chains))\n\n pm._log.info('Sampling ...')\n work = [(draws,\n step,\n step.population[step.resampling_indexes[chain]],\n atext.TextChain(stage_path, model=model),\n chain,\n None,\n False,\n model,\n rseed) for chain, rseed in\n zip(chains, random_seeds)]\n\n if draws < 10:\n chunksize = n_jobs\n else:\n chunksize = 1\n\n p = atext.paripool(_work_chain, work, chunksize=chunksize, nprocs=n_jobs)\n\n if n_jobs == 1 and progressbar:\n p = tqdm(p, total=len(chains))\n\n for _ in p:\n pass\n\n\ndef tune(acc_rate):\n \"\"\"Tune adaptively based on the acceptance rate.\n\n Parameters\n ----------\n acc_rate: scalar, float\n Acceptance rate of the Metropolis sampling\n\n Returns\n -------\n scaling: scalar float\n \"\"\"\n # a and b after Muto & Beck 2008 .\n a = 1. / 9\n b = 8. / 9\n return np.power((a + (b * acc_rate)), 2)\n\n\ndef logp_forw(out_vars, vars, shared):\n \"\"\"Compile Theano function of the model and the input and output variables.\n\n Parameters\n ----------\n out_vars : List\n containing :class:`pymc3.Distribution` for the output variables\n vars : List\n containing :class:`pymc3.Distribution` for the input variables\n shared : List\n containing :class:`theano.tensor.Tensor` for dependend shared data\n \"\"\"\n out_list, inarray0 = join_nonshared_inputs(out_vars, vars, shared)\n f = theano.function([inarray0], out_list)\n f.trust_input = True\n return f\n", "meta": {"hexsha": "13b8e10fd8c77f7b75f75f0cd381b38ba6640434", "size": 25765, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymc3/step_methods/smc.py", "max_stars_repo_name": "JWarmenhoven/pymc3", "max_stars_repo_head_hexsha": "d953028b9cd7f38eb760c49555565c54b1a80c15", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-07-09T19:50:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-14T10:50:24.000Z", "max_issues_repo_path": "pymc3/step_methods/smc.py", "max_issues_repo_name": "JWarmenhoven/pymc3", "max_issues_repo_head_hexsha": "d953028b9cd7f38eb760c49555565c54b1a80c15", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-08-17T06:58:38.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-17T06:58:38.000Z", "max_forks_repo_path": "pymc3/step_methods/smc.py", "max_forks_repo_name": "rsumner31/pymc3-23", "max_forks_repo_head_hexsha": "539c0fc04c196679a1cdcbf4bc2dbea4dee10080", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-07-07T01:45:08.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-24T10:11:22.000Z", "avg_line_length": 34.1258278146, "max_line_length": 100, "alphanum_fraction": 0.6032214244, "include": true, "reason": "import numpy,import theano,import pymc3,from pymc3", "num_tokens": 5908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.28776781576105315, "lm_q1q2_score": 0.14500797804167026}} {"text": "'''Copyright (c) 2021 James Gayvert\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.'''\n\nimport numpy as np\nfrom numpy import linalg as LA\nimport warnings\n\n# https://physics.nist.gov/cgi-bin/cuu/Value?hrev\nau2eV = 27.211386245988\n\n\ndef _delete_indices(H0, W, exclude_states):\n exclude_states = np.unique(exclude_states)\n exclude_states = sorted(exclude_states, reverse=True)\n for i in exclude_states:\n H0 = np.delete(H0, i, axis=0)\n H0 = np.delete(H0, i, axis=1)\n W = np.delete(W, i, axis=0)\n W = np.delete(W, i, axis=1)\n return H0, W\n\n\nclass Root():\n '''\n Root obtained from diagonalizing CAP Hamiltonian at given value of eta.\n \n Attributes\n ----------\n eta: float\n CAP strength parameter\n energy: float\n Total energy of state\n eigvc: list of float\n Eigenvector for state\n '''\n def __init__(self, energy, eta, eigvc):\n '''\n Initializes root object.\n \n Parameters\n ----------\n eta: float\n CAP strength parameter\n energy: float\n Total energy of state\n eigvc: list of float\n Eigenvector for state\n '''\n self.eta = eta\n self.energy = energy\n self.eigvc = eigvc\n\n\nclass EigenvalueTrajectory():\n '''\n Eigenvalue trajectory generated by repeated diagonalizations of CAP Hamiltonian over range of eta values. \n\n States are tracked using either eigenvector overlap or energy criterion. Corrected energies(U) are obtained as:\n U = E - eta*dE/deta.\n \n Attributes\n ----------\n states: list of :class:`~pyopencap.analysis.Root`\n List of states in trajectory.\n uncorrected_energies: list of float\n List of uncorrected energies in trajectory.\n corrected_energies: list of float\n List of corrected energies in trajectory.\n etas: list of float\n List of CAP strengths in trajectory.\n '''\n def __init__(self, state_idx, init_roots, tracking=\"overlap\"):\n '''\n Initializes EigenvalueTrajectory object, which tracks a state starting from the first diagonalization at eta = 0.\n \n Parameters\n ----------\n state_idx: int\n Index of state to track\n init_roots: list of :class:`~pyopencap.analysis.Root`\n Initial set of roots generated by diagonalization at eta = 0\n tracking: str, default=\"overlap\"\n Method to use to track the state\n '''\n self._last = init_roots[state_idx]\n self.states = [self._last]\n self.uncorrected_energies = [self._last.energy]\n self.corrected_energies = []\n self.etas = [0.0]\n if tracking == \"overlap\":\n self._add_state = self._overlap_tracking\n elif tracking == \"energy\":\n self._add_state = self._energy_tracking\n else:\n raise RuntimeError(\n \"Invalid choice of tracking. Choose either overlap or energy.\")\n\n def _overlap_tracking(self, states):\n maxo = 0.0\n state_idx = -1\n for st in states:\n ov = np.abs(np.dot(st.eigvc, self._last.eigvc))\n if ov > maxo:\n maxo = ov\n cur = st\n self._last = cur\n self.states.append(cur)\n self.uncorrected_energies.append(cur.energy)\n self.etas.append(cur.eta)\n\n def _energy_tracking(self, states):\n min = float(\"inf\")\n cur = -1\n for st in states:\n if np.absolute(st.energy - self._last.energy) < min or cur == -1:\n cur = st\n min = np.absolute(st.energy - self._last.energy)\n self._last = cur\n self.states.append(cur)\n self.uncorrected_energies.append(cur.energy)\n self.etas.append(cur.eta)\n\n def _calculate_corrected_energies(self):\n derivs = list(\n np.gradient(self.uncorrected_energies) / np.gradient(self.etas))\n # E_cor = E_uc - eta * dE/deta\n for i in range(0, len(self.states)):\n self.corrected_energies.append(self.uncorrected_energies[i] -\n self.etas[i] * derivs[i])\n\n def find_eta_opt(self,\n corrected=False,\n start_idx=1,\n end_idx=-1,\n ref_energy=0.0,\n units=\"au\"):\n '''\n Finds optimal cap strength parameter for eigenvalue trajectory, as defined by eta_opt = min|eta*dE/deta|.\n \n The range of self.etas[start_idx:end_idx] (in python slice notation) is searched for the optimal value of CAP strength parameter.\n \n Parameters\n ----------\n corrected: bool, default=False\n Set to true if searching for stationary point on corrected trajectory\n start_idx: int, default=1\n Starting slice index\n end_idx: int, default=1\n Ending slice index\n ref_energy: float, default=0.0\n Reference energy to define excitation energy.\n units: str, default=\"au\"\n Options are \"au\" or \"eV\"\n \n Returns\n -------\n E_res: complex float\n Complex energy at optimal value of eta\n eta_opt: float\n Optimal value of eta\n\n '''\n if units == \"au\":\n scaling_factor = 1.0\n elif units == \"eV\":\n scaling_factor = au2eV\n else:\n raise RuntimeError(\"Units should be either au or eV.\")\n if corrected:\n derivs = np.array(self.etas) * np.absolute(\n np.gradient(self.corrected_energies) / np.gradient(self.etas))\n min_val = np.min(derivs[start_idx:end_idx])\n opt_idx = list(derivs).index(min_val)\n E = self.corrected_energies[opt_idx]\n E = (E - ref_energy) * scaling_factor\n return E, self.etas[opt_idx]\n else:\n derivs = np.array(self.etas) * np.absolute(\n np.gradient(self.uncorrected_energies) /\n np.gradient(self.etas))\n min_val = np.min(derivs[start_idx:end_idx])\n opt_idx = list(derivs).index(min_val)\n E = self.uncorrected_energies[opt_idx]\n E = (E - ref_energy) * scaling_factor\n return E, self.etas[opt_idx]\n\n def energies_ev(self, ref_energy, corrected=False):\n '''\n Returns excitation energies of all states in trajectory in eV with respect to specified reference energy.\n \n Parameters\n ----------\n ref_energy: float\n Reference energy\n corrected: bool, default=False\n Set to true if analyzing corrected trajectory\n \n Returns\n -------\n E_eV: list of floats\n Excitation energies in eV with respect to specified reference energy.\n '''\n E_eV = []\n if corrected:\n E_hartree = self.corrected_energies\n else:\n E_hartree = self.uncorrected_energies\n for E in E_hartree:\n E_eV.append((E - ref_energy) * au2eV)\n return E_eV\n\n def get_energy(self, eta, corrected=False, ref_energy=0.0, units=\"au\"):\n '''\n Returns total energy at given value of eta. \n \n Note that if the eta provided is not in self.etas, the nearest value will be used.\n\n Parameters\n ----------\n eta: float\n Value of CAP strength parameter\n corrected: bool, default=False\n Set to true if analyzing corrected trajectory\n ref_energy: float, default=0.0\n Reference energy to define excitation energy.\n units: str, default=\"au\"\n Options are \"au\" or \"eV\"\n \n Returns\n -------\n E: float\n Energy at given value of eta\n '''\n if units == \"au\":\n scaling_factor = 1.0\n elif units == \"eV\":\n scaling_factor = au2eV\n else:\n raise RuntimeError(\"Invalid unit. Options are au or eV.\")\n if eta in self.etas:\n idx = self.etas.index(eta)\n else:\n idx = np.nanargmin(np.abs(np.asarray(self.etas) - eta))\n warnings.warn(\"Warning: \"+str(eta) + \" is not in the list of values for this trajectory.\" \\\n +\" Defaulting to nearest value of \" + str(self.etas[idx]))\n if corrected:\n return (self.corrected_energies[idx] - ref_energy) * scaling_factor\n else:\n return (self.uncorrected_energies[idx] -\n ref_energy) * scaling_factor\n\n def get_logarithmic_velocities(self, corrected=False):\n '''\n Returns eta*dE/deta for each point on eigenvalue trajectory. \n\n Useful for plotting when dealing with multiple potential stationary points. \n \n Parameters\n ----------\n corrected: bool, default=False\n Set to true if analyzing corrected trajectory\n\n Returns\n -------\n derivs: np.array of float\n eta*dE/deta for each point on eigenvalue trajectory\n '''\n if corrected:\n energies = self.corrected_energies\n else:\n energies = self.uncorrected_energies\n return np.array(self.etas) * np.absolute(\n np.gradient(energies) / np.gradient(self.etas))\n\n\nclass CAPHamiltonian():\n '''\n Projected CAP Hamiltonian handler for generating eigenvalue trajectories. \n\n The instance variables H0,W etc. are only set after `run_trajectory` is executed. The original matrices \n passed/parsed when the object is constructed are stored in _H0, _W, etc. This makes it easy to run multiple \n trajectories with different states included in the projection scheme without having to construct a new object.\n \n Attributes\n ----------\n H0: np.ndarray of float: default=None\n Zeroth order Hamiltonian in state basis\n W: np.ndarray of float: default=None\n CAP matrix in state basis. -1 prefactor is assumed.\n nstates: int\n Number of states \n total_energies: list of float\n Energies of all states found by repeated diagonalization of CAP Hamiltonian\n etas: list of float\n List of CAP strengths in trajectory.\n cap_lambda: float\n Real CAP strength used for continuum remover CAP. Set to 0.0 by default.\n '''\n def _init_from_matrices(self, H0, W):\n H0 = np.array(H0)\n W = np.array(W)\n assert H0.shape == W.shape\n self._H0 = H0\n self._W = W\n self._nstates = len(H0)\n\n def __init__(self,\n pc=None,\n H0=None,\n W=None,\n output=None,\n irrep=\"\",\n onset=\"\"):\n '''\n Initializes CAPHamiltonian object from H0 and W matrix in state basis.\n\n Object can be initialized in one of two ways. The user can pass H0 and W directly \n as numpy matrices, or they can specify a path to a properly formatted output file \n (either OpenCAP or Q-Chem) which contains these two matrices. \n\n W matrix is assumed to already have a -1 prefactor, as that is how OpenCAP output is formatted.\n \n Parameters\n ----------\n pc: :class:`~pyopencap.CAP`: default=None\n PyOpenCAP CAP object\n H0: np.ndarray of float: default=None\n Zeroth order Hamiltonian in state basis\n W: np.ndarray of float: default=None\n CAP matrix in state basis. -1 prefactor is assumed.\n output: str: default=None\n Path to Q-Chem or OpenCAP output file.\n irrep: str: default=None\n Title of irreducible representation of state of interest. Only compatible with Q-Chem projected CAP-EOM-CC outputs. Set to 'all' to include all symmetries in CAP projection.\n onset: str: default=None\n Title of CAP onset. Only compatible with Q-Chem projected CAP-ADC outputs.\n\n '''\n if pc is not None:\n self._init_from_matrices(pc.get_H(), pc.get_projected_cap())\n elif H0 is not None and W is not None:\n self._init_from_matrices(H0, W)\n elif output is not None:\n with open(output, 'r') as file:\n filedata = file.readlines()\n for l in filedata:\n if \"Welcome to OpenCAP\" in l:\n self._init_from_opencap_output(output)\n return\n elif \"Welcome to Q-Chem\" in l:\n self._init_from_qchem_output(output, irrep, onset)\n return\n raise RuntimeError(\n \"Only Q-Chem and OpenCAP outputs are supported.\")\n else:\n raise RuntimeError(\n \"Error: Either pass a CAP object, H0 and W as matrices, or specify a path to an OpenCAP/Q-Chem output file.\"\n )\n\n def _init_from_qchem_eomcc_old(self, output_file, irrep):\n with open(output_file, 'r') as file:\n filedata = file.readlines()\n cur_idx = -1\n nstates = 0\n for i in range(0, len(filedata)):\n if \"Performing Projected CAP-EOM calculation for \" + str(\n irrep) in filedata[i]:\n cur_idx = i + 1\n break\n if cur_idx == -1:\n if not irrep == \"\":\n raise RuntimeError(\"Error: could not find matrices for \" +\n str(irrep) + \" states in \" + output_file)\n else:\n raise RuntimeError(\"Error: could not find matrices in \" +\n output_file)\n nstates = int(filedata[cur_idx].split()[-2])\n while \"zeroth order hamiltonian\" not in filedata[cur_idx].lower(\n ) and cur_idx < len(filedata):\n cur_idx += 1\n cur_idx += 1\n H0 = []\n for i in range(0, nstates):\n l1 = filedata[cur_idx].split()\n l1 = [float(x) for x in l1]\n H0 += l1\n cur_idx += 1\n H0 = np.reshape(H0, (nstates, nstates))\n cur_idx += 1\n W = []\n for i in range(0, nstates):\n l1 = filedata[cur_idx].split()\n l1 = [float(x) for x in l1]\n W += l1\n cur_idx += 1\n W = np.reshape(W, (nstates, nstates))\n assert H0.shape == W.shape\n self._H0 = H0\n self._W = W\n self._nstates = len(H0)\n\n def _init_from_qchem_eomcc(self, output_file, irrep):\n try:\n self._init_from_qchem_eomcc_new(output_file, irrep)\n except ValueError as e:\n self._init_from_qchem_eomcc_old(output_file, irrep)\n\n def _init_from_qchem_eomcc_new(self, output_file, irrep):\n with open(output_file, 'r') as file:\n filedata = file.readlines()\n cur_idx = -1\n nstates = 0\n if irrep==\"all\":\n for i in range(0, len(filedata)):\n if \"Total Projected CAP Hamiltonian\" in filedata[i]:\n cur_idx = i + 1\n break\n else:\n for i in range(0, len(filedata)):\n if \"Performing Projected CAP-EOM calculation for \" + str(\n irrep) in filedata[i]:\n cur_idx = i + 1\n break\n if cur_idx == -1:\n if not irrep == \"\":\n raise RuntimeError(\"Error: could not find matrices for \" +\n str(irrep) + \" states in \" + output_file)\n else:\n raise RuntimeError(\"Error: could not find matrices in \" +\n output_file)\n nstates = int(filedata[cur_idx].split()[-1])\n cur_idx +=2\n H0 = []\n for i in range(0, nstates):\n l1 = filedata[cur_idx].split()\n l1 = [float(x) for x in l1]\n H0 += l1\n cur_idx += 1\n H0 = np.reshape(H0, (nstates, nstates))\n cur_idx += 1\n W = []\n for i in range(0, nstates):\n l1 = filedata[cur_idx].split()\n l1 = [float(x) for x in l1]\n W += l1\n cur_idx += 1\n W = np.reshape(W, (nstates, nstates))\n assert H0.shape == W.shape\n self._H0 = H0\n self._W = W\n self._nstates = len(H0)\n\n def _init_from_qchem_adc(self, output_file, onset):\n with open(output_file, 'r') as file:\n filedata = file.readlines()\n cur_idx = -1\n found = False\n for i in range(0, len(filedata)):\n if \"Hamiltonian subspace matrix\" in filedata[i]:\n cur_idx = i + 2\n found = True\n break\n if not found:\n raise RuntimeError(\"Error: could not find matrices in \" +\n output_file)\n H0 = []\n done = False\n nstates = 0\n while cur_idx < len(filedata) and not done:\n l1 = filedata[cur_idx].split()\n try:\n l1 = [float(x) for x in l1]\n if len(l1) > 0:\n H0 += l1\n cur_idx += 1\n nstates += 1\n else:\n done = True\n except:\n done = True\n H0 = np.reshape(H0, (nstates, nstates))\n found = False\n for i in range(0, len(filedata)):\n if \"The imaginary part of the CAP subspace matrix, onset=\" + str(\n onset) in filedata[i]:\n cur_idx = i + 2\n found = True\n break\n if not found:\n raise RuntimeError(\"Error: could not find matrices in \" +\n output_file)\n W = []\n done = False\n nstates = 0\n while cur_idx < len(filedata) and not done:\n l1 = filedata[cur_idx].split()\n try:\n l1 = [float(x) for x in l1]\n if len(l1) > 0:\n W += l1\n cur_idx += 1\n nstates += 1\n else:\n done = True\n except:\n done = True\n W = np.reshape(W, (nstates, nstates))\n assert H0.shape == W.shape\n self._H0 = H0\n self._W = W\n self._nstates = len(H0)\n\n def _init_from_qchem_output(self, output_file, irrep, onset):\n with open(output_file, 'r') as file:\n filedata = file.readlines()\n method = \"\"\n for i in range(0, len(filedata)):\n if \"Performing Projected CAP-EOM calculation for \" in filedata[i]:\n method = \"eomcc\"\n break\n elif \"The imaginary part of the CAP subspace matrix, onset=\" in filedata[\n i]:\n method = \"adc\"\n break\n if method == \"eomcc\":\n self._init_from_qchem_eomcc(output_file, irrep)\n elif method == \"adc\":\n self._init_from_qchem_adc(output_file, onset)\n else:\n raise RuntimeError(\"Error: Incompatible Q-Chem output.\")\n\n def _init_from_opencap_output(self, output_file):\n with open(output_file, 'r') as file:\n filedata = file.readlines()\n cur_idx = -1\n nstates = 0\n for i in range(0, len(filedata)):\n if \"Number of states\" in filedata[i]:\n cur_idx = i\n nstates = int(filedata[cur_idx].split()[-1])\n break\n if nstates == 0:\n raise RuntimeError(\"Error: incompatible output. 0 states found.\")\n cur_idx += 2\n # zeroth order hamiltonian first\n H0 = []\n for i in range(0, nstates):\n l1 = filedata[cur_idx].split()\n l1 = [float(x) for x in l1]\n H0 += l1\n cur_idx += 1\n H0 = np.reshape(H0, (nstates, nstates))\n cur_idx += 1\n # now CAP matrix\n W = []\n for i in range(0, nstates):\n l1 = filedata[cur_idx].split()\n l1 = [float(x) for x in l1]\n W += l1\n cur_idx += 1\n W = np.reshape(W, (nstates, nstates))\n assert H0.shape == W.shape\n self._H0 = H0\n self._W = W\n self._nstates = len(H0)\n\n def run_trajectory(self,\n eta_list,\n cap_lambda=0.0,\n exclude_states=None,\n include_states=None):\n '''\n Diagonalizes CAP Hamiltonian over range of eta values.\n\n CAP Hamiltonian is defined as H^CAP = H0 + i*eta*W - cap_lambda * W.\n W matrix is assumed to already have a -1 prefactor, as that is how OpenCAP output is formatted.\n Recommended range for eta_list is between 1E-5 and 1E-2, though this can vary widely based on system and CAP shape.\n \n Parameters\n ----------\n eta_list: iterable object\n List of eta values to use \n cap_lambda: float, default=0.0\n Real CAP strength to use for continuum remover CAP\n exclude_states: list of int, default=None\n List of states to exclude from subspace projection. Not compatible with include_states parameter.\n include_states: list of int, default=None\n List of states to include in subspace projection. Not compatible with exclude_states parameter.\n\n '''\n if exclude_states is not None and include_states is not None:\n raise RuntimeError(\n \"Error: exclude_states and include_states keyword arguments are incompatible.\"\n )\n if exclude_states is not None:\n self.H0, self.W = _delete_indices(self._H0, self._W,\n exclude_states)\n self.nstates = len(self.H0)\n elif include_states is not None:\n all_states = [i for i in range(0, self._nstates)]\n exclude_states = [\n item for item in all_states if item not in include_states\n ]\n self.H0, self.W = _delete_indices(self._H0, self._W,\n exclude_states)\n self.nstates = len(self.H0)\n else:\n self.H0 = self._H0\n self.W = self._W\n self.nstates = self._nstates\n self._all_roots = []\n self.total_energies = []\n self.cap_lambda = cap_lambda\n self.etas = []\n for i in range(0, len(eta_list)):\n eta = eta_list[i]\n self.etas.append(eta)\n roots = []\n CAPH = self.H0 + 1.0j * eta * self.W - cap_lambda * self.W\n eigv, eigvc = LA.eig(CAPH)\n for j, eig in enumerate(eigv):\n roots.append(Root(eigv[j], eta, eigvc[:, j]))\n self.total_energies.append(eigv[j])\n self._all_roots.append(roots)\n\n def track_state(self, state_idx, tracking=\"overlap\"):\n '''\n Diagonalizes CAP Hamiltonian over range of eta values.\n\n CAP Hamiltonian is defined as H^CAP = H0 + i*eta*W - cap_lambda * W. \n CAP matrix W is assumed to already have a -1 prefactor.\n \n Parameters\n ----------\n state_idx: int\n Index of state to track\n tracking: str, default=\"overlap\"\n Method to use to track the state. Options are \"overlap\", which tracks based on eigenvector overlap, and \"energy\" which \n tracks based on energy.\n\n Returns\n -------\n traj: :class:`~pyopencap.analysis.EigenvalueTrajectory`\n Eigenvalue trajectory for further analysis.\n '''\n if len(self._all_roots) == 0:\n raise RuntimeError(\n \"Nothing to track. Execute `run_trajectory` first.\")\n traj = EigenvalueTrajectory(state_idx,\n self._all_roots[0],\n tracking=tracking)\n for i in range(1, len(self._all_roots)):\n traj._add_state(self._all_roots[i])\n traj._calculate_corrected_energies()\n return traj\n\n def energies_ev(self, ref_energy):\n '''\n Returns excitation energies of all calculated states in eV with respect to specified reference energy.\n \n Parameters\n ----------\n ref_energy: float\n Reference energy\n \n Returns\n -------\n E_eV: list of floats\n Excitation energies in eV with respect to specified reference energy.\n '''\n E_eV = []\n for E in self.total_energies:\n E_eV.append((E - ref_energy) * au2eV)\n return E_eV\n\n def export(self, finame):\n '''\n Exports Zeroth order Hamiltonian and CAP matrix to an OpenCAP formatted output file for further analysis. \n Useful for saving the results of an expensive electronic structure calculation performed in a python environment.\n\n Parameters\n ----------\n finame: str\n File handle to export data.\n '''\n from datetime import datetime\n from pandas import DataFrame\n now = datetime.now()\n dt_string = now.strftime(\"%m/%d/%Y %H:%M:%S\")\n with open(finame, 'w') as f:\n f.write(\n \"Welcome to OpenCAP: An open-source program for studying resonances in molecules.\\n\"\n )\n f.write(\"OpenCAP output file generated on: \" + dt_string + \"\\n\")\n f.write(\n \"Printing out matrices required for Projected CAP calculation.\\n\"\n )\n f.write(\"Number of states: \" + str(self._nstates) + \"\\n\")\n f.write(\"Zeroth order Hamiltonian\\n\")\n f.write(DataFrame(self._H0).to_string(index=False, header=False,float_format='%.15g'))\n f.write(\"\\nCAP Matrix\\n\")\n f.write(DataFrame(self._W).to_string(index=False, header=False,float_format='%.15g'))\n\n def __str__(self):\n ''' Returns formatted matrices.\n '''\n from pandas import DataFrame\n import pandas\n pandas.set_option(\"display.precision\", 15)\n my_str = \"Zeroth order Hamiltonian\\n\"\n my_str += DataFrame(self._H0).to_string(index=False, header=False,float_format='%.15g')\n my_str+= \"\\nCAP Matrix\\n\"\n my_str+= DataFrame(self._W).to_string(index=False, header=False,float_format='%.15g')\n return my_str\n\n\n", "meta": {"hexsha": "1eaded66bcd8bc714efadefdc25a3a17e76a2895", "size": 27411, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyopencap/analysis/CAPTrajectory.py", "max_stars_repo_name": "gayverjr/opencap", "max_stars_repo_head_hexsha": "b481c88a1f84f7e219677d9cda1d1132605744d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2020-08-24T15:06:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T20:51:26.000Z", "max_issues_repo_path": "pyopencap/analysis/CAPTrajectory.py", "max_issues_repo_name": "gayverjr/opencap", "max_issues_repo_head_hexsha": "b481c88a1f84f7e219677d9cda1d1132605744d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2020-08-04T07:03:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T22:37:39.000Z", "max_forks_repo_path": "pyopencap/analysis/CAPTrajectory.py", "max_forks_repo_name": "gayverjr/opencap", "max_forks_repo_head_hexsha": "b481c88a1f84f7e219677d9cda1d1132605744d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-09-15T20:38:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T18:54:52.000Z", "avg_line_length": 37.3446866485, "max_line_length": 185, "alphanum_fraction": 0.5556893218, "include": true, "reason": "import numpy,from numpy", "num_tokens": 6275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.14500797804167023}} {"text": "\"\"\"\nTool to calculate accuracy for loadgen accuracy output found in mlperf_log_accuracy.json\nWe assume that loadgen's query index is in the same order as\nthe images in coco's annotations/instances_val2017.json.\n\"\"\"\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport argparse\nimport json\nimport os\n\nimport numpy as np\n\nfrom pycocotools.coco import COCO\nfrom pycocotools.cocoeval import COCOeval\n\n# pylint: disable=missing-docstring\n\ndef get_args():\n \"\"\"Parse commandline.\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--mlperf-accuracy-file\", required=True, help=\"path to mlperf_log_accuracy.json\")\n parser.add_argument(\"--coco-dir\", required=True, help=\"coco directory\")\n parser.add_argument(\"--verbose\", action=\"store_true\", help=\"verbose messages\")\n args = parser.parse_args()\n return args\n\n\ndef main():\n args = get_args()\n\n cocoGt = COCO(os.path.join(args.coco_dir, \"annotations/instances_val2017.json\"))\n\n with open(args.mlperf_accuracy_file, \"r\") as f:\n results = json.load(f)\n\n detections = []\n image_ids = set()\n seen = set()\n image_map = cocoGt.dataset[\"images\"]\n\n for j in results:\n idx = j['qsl_idx']\n # de-dupe in case loadgen sends the same image multiple times\n if idx in seen:\n continue\n seen.add(idx)\n\n # reconstruct from mlperf accuracy log\n # what is written by the benchmark is an array of float32's:\n # id, box[0], box[1], box[2], box[3], score, detection_class\n # note that id is a index into instances_val2017.json, not the actual image_id\n data = np.frombuffer(bytes.fromhex(j['data']), np.float32)\n for i in range(0, len(data), 7):\n image_idx, ymin, xmin, ymax, xmax, score, label = data[i:i + 7]\n image_idx = int(image_idx)\n image = image_map[image_idx]\n image_id = image[\"id\"]\n height, width = image[\"height\"], image[\"width\"]\n ymin *= height\n xmin *= width\n ymax *= height\n xmax *= width\n loc = os.path.join(args.coco_dir, \"val2017\", image[\"file_name\"])\n # pycoco wants {imageID,x1,y1,w,h,score,class}\n detections.append({\n \"image_id\": image_id,\n \"image_loc\": loc,\n \"category_id\": int(label),\n \"bbox\": [float(xmin), float(ymin), float(xmax - xmin), float(ymax - ymin)],\n \"score\": float(score)})\n image_ids.add(image_id)\n\n with open(\"coco-results.json\", \"w\") as fp:\n json.dump(detections, fp, sort_keys=True, indent=4)\n\n cocoDt = cocoGt.loadRes(detections)\n cocoEval = COCOeval(cocoGt, cocoDt, iouType='bbox')\n cocoEval.params.imgIds = list(image_ids)\n cocoEval.evaluate()\n cocoEval.accumulate()\n cocoEval.summarize()\n\n print(\"mAP={:.3f}%\".format(100. * cocoEval.stats[0]))\n if args.verbose:\n print(\"found and ignored {} dupes\".format(len(results) - len(seen)))\n\n\nif __name__ == \"__main__\":\n main()\n", "meta": {"hexsha": "37dc7858746edcc75eff4c778f9c30afb1a45301", "size": 3101, "ext": "py", "lang": "Python", "max_stars_repo_path": "v0.5/classification_and_detection/tools/accuracy-coco.py", "max_stars_repo_name": "goldgeisser/inference", "max_stars_repo_head_hexsha": "42c68883f6f60bf6e0d0253c1bb797a285e2d5f2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "v0.5/classification_and_detection/tools/accuracy-coco.py", "max_issues_repo_name": "goldgeisser/inference", "max_issues_repo_head_hexsha": "42c68883f6f60bf6e0d0253c1bb797a285e2d5f2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "v0.5/classification_and_detection/tools/accuracy-coco.py", "max_forks_repo_name": "goldgeisser/inference", "max_forks_repo_head_hexsha": "42c68883f6f60bf6e0d0253c1bb797a285e2d5f2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-20T16:59:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-20T16:59:07.000Z", "avg_line_length": 32.9893617021, "max_line_length": 105, "alphanum_fraction": 0.6323766527, "include": true, "reason": "import numpy", "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.14500797804167023}} {"text": "\"\"\"\nCreate an image combination algroithm that chooses between a minimum\nor median image based up bad pixel identification.\n\n:Authors: Christopher Hanley\n\n:License: :doc:`LICENSE`\n\n\"\"\"\n# PROGRAM: numcombine.py\n# AUTHOR: Christopher Hanley (based upon original code of Anton Koekemoer)\n# DATE: February 11, 2004\n# PURPOSE: Create an image combination algroithm that chooses between\n# a minimum or median image based up bad pixel identification.\n# HISTORY:\n# Version 0.1.0: Initial Development -- CJH -- 02/11/04\n# Version 0.1.1: Cast boxsize as type int. This should always be the case\n# anyways but this protects against errors in the\n# MDRIZTAB -- CJH/WJH -- 07/08/04\n# Version 0.1.2: Improve error message handing in the case where\n# the boxcar convolution step fails. --CJH -- 10/13/04\n# Version 0.2.0: The creation of the median image will now more closesly\n# replicate the IRAF IMCOMBINE behavior of nkeep = 1 and nhigh = 1.\n# -- CJH -- 03/29/05\n# Version 0.3.0: Rewritten to optimize the code and to bring\n# code up to modern standards.-- Mihai Cara -- 02/19/2018\nimport warnings\nimport numpy as np\nfrom scipy import signal\nfrom stsci.image.numcombine import numCombine, num_combine\nfrom .version import *\n\nclass minmed:\n \"\"\" **DEPRECATED** Create a median array, rejecting the highest pixel and\n computing the lowest valid pixel after mask application\n\n # In this case we want to calculate two things:\n # 1) the median array, rejecting the highest pixel (thus running\n # imcombine with nlow=0, nhigh=1, nkeep=1, using the masks)\n # 2) the lowest valid pixel after applying the masks (thus running\n # imcombine with nlow=0, nhigh=3, nkeep=1, using the masks)\n #\n # We also calculate the sum of the weight files (to produce the total\n # effective exposure time for each pixel).\n #\n # The total effective background in the final image is calculated as follows:\n # - convert background for each input image to counts/s (divide by exptime)\n # - multiply this value by the weight image, to obtain the effective background\n # counts (in DN) for each pixel, for each image\n # - Add these images together, to obtain the total effective background\n # for the combined image.\n #\n # Once we've made these two files, then calculate the SNR based on the\n # median-pixel image, and compare with the minimum.\n\n In this version of the mimmed algorithm we assume that the units of all\n input data is electons.\n \"\"\"\n def __init__(self,\n imageList, # list of input data to be combined.\n weightImageList, # list of input data weight images to be combined.\n readnoiseList, # list of readnoise values to use for the input images.\n exposureTimeList, # list of exposure times to use for the input images.\n backgroundValueList, # list of image background values to use for the input images\n weightMaskList= None, # list of imput data weight masks to use for pixel rejection.\n combine_grow = 1, # Radius (pixels) for neighbor rejection\n combine_nsigma1 = 4, # Significance for accepting minimum instead of median\n combine_nsigma2 = 3, # Significance for accepting minimum instead of median\n fillval = False # Turn on use of imedian/imean\n\n ):\n\n warnings.warn(\"The 'minmed' class is deprecated and may be removed\"\n \" in a future version. Use 'min_med()' instead.\",\n DeprecationWarning)\n\n # Define input variables\n self._imageList = imageList\n self._weightImageList = weightImageList\n self._weightMaskList = weightMaskList\n self._exposureTimeList = exposureTimeList\n self._readnoiseList = readnoiseList\n self._backgroundValueList = backgroundValueList\n self._numberOfImages = len( self._imageList)\n self._combine_grow = combine_grow\n self._combine_nsigma1 = combine_nsigma1\n self._combine_nsigma2 = combine_nsigma2\n\n if fillval:\n combtype_mean = 'imean'\n combtype_median = 'imedian'\n else:\n combtype_mean = 'mean'\n combtype_median = 'median'\n\n\n # Create a different median image based upon the number of images in the input list.\n median_file = np.zeros(self._imageList[0].shape,dtype=self._imageList[0].dtype)\n if (self._numberOfImages == 2):\n tmp = numCombine(self._imageList,numarrayMaskList=self._weightMaskList,\n combinationType=combtype_mean,nlow=0,nhigh=0,\n nkeep=1,upper=None,lower=None)\n median_file = tmp.combArrObj\n else:\n # The value of NHIGH=1 will cause problems when there is only 1 valid\n # unmasked input image for that pixel due to a difference in behavior\n # between 'numcombine' and 'iraf.imcombine'.\n # This value may need to be adjusted on the fly based on the number of\n # inputs and the number of masked values/pixel.\n #\n tmp = numCombine(self._imageList,numarrayMaskList=self._weightMaskList,\n combinationType=combtype_median,nlow=0,nhigh=1,\n nkeep=1,upper=None,lower=None)\n median_file = tmp.combArrObj\n\n if self._weightMaskList in [None,[]]:\n self._weightMaskList = [np.zeros(self._imageList[0].shape,dtype=self._imageList[0].dtype)]*len(self._imageList)\n # The following section of code will address the problem caused by having\n # a value of nhigh = 1. This will behave in a way similar to the way the\n # IRAF task IMCOMBINE behaves. In order to accomplish this, the following\n # procedure will be followed:\n # 1) The input masks will be summed.\n # 2) The science data will be summed.\n # 3) In the locations of the summed mask where the sum is 1 less than the\n # the total number of images, the value of that location in the summed\n # sceince image will be used to replace the existing value in the\n # existing median_file.\n #\n # This procuedure is being used to prevent too much data from being thrown\n # out of the image. Take for example the case of 3 input images. In two\n # of the images the pixel locations have been masked out. Now, if nhigh\n # is applied there will be no value to use for that position. However,\n # if this new procedure is used that value in the resulting images will\n # be the value that was rejected by the nhigh rejection step.\n #\n\n # We need to make certain that \"bad\" pixels in the sci data are set to 0. That way,\n # when the sci images are summed, the value of the sum will only come from the \"good\"\n # pixels.\n tmpList = []\n for image in range(len(self._imageList)):\n tmp =np.where(self._weightMaskList[image] == 1, 0, self._imageList[image])\n tmpList.append(tmp)\n\n # Sum the mask files\n maskSum = self._sumImages(self._weightMaskList)\n # Sum the science images\n sciSum = self._sumImages(tmpList)\n del(tmpList)\n # Use the summed sci image values in locations where the maskSum indicates\n # that there is only 1 good pixel to use. The value will be used in the\n # median_file image\n median_file = np.where(maskSum == self._numberOfImages-1,sciSum,median_file)\n\n if self._weightMaskList in [None,[]]:\n self._weightMaskList = [np.zeros(self._imageList[0].shape,dtype=self._imageList[0].dtype)]*len(self._imageList)\n # Sum the weightMaskList elements\n maskSum = self._sumImages(self._weightMaskList)\n\n # Create the minimum image from the stack of input images.\n # Find the maximum pixel value for the image stack.\n maxValue = -1e+9\n for image in self._imageList:\n newMax = image.max()\n if (newMax > maxValue):\n maxValue = newMax\n\n # For each image, set pixels masked as \"bad\" to the \"super-maximum\" value.\n for image in range(len(self._imageList)):\n self._imageList[image] = np.where(self._weightMaskList[image] == 1,maxValue+1,self._imageList[image])\n\n # Call numcombine throwing out the highest N - 1 pixels.\n tmp = numCombine(self._imageList,numarrayMaskList=None,\n combinationType=combtype_median,nlow=0,nhigh=self._numberOfImages-1,\n nkeep=1,upper=None,lower=None)\n minimum_file = tmp.combArrObj\n # Reset any pixl at maxValue + 1 to 0.\n minimum_file = np.where(maskSum == self._numberOfImages, 0, minimum_file)\n\n # Scale the weight images by the background values and add them to the bk\n backgroundFileList = []\n for image in range(len(self._weightImageList)):\n tmp = self._weightImageList[image] * (self._backgroundValueList[image]/(self._exposureTimeList[image]))\n backgroundFileList.append(tmp)\n\n # Create an image of the total effective background (in DN) per pixel:\n # (which is the sum of all the background-scaled weight files)\n #\n bkgd_file = self._sumImages(backgroundFileList)\n del(backgroundFileList)\n\n #\n # Scale the weight mask images by the square of the readnoise values\n #\n readnoiseFileList = []\n for image in range(len(self._weightMaskList)):\n tmp = (np.logical_not(self._weightMaskList[image]) *\n (self._readnoiseList[image] * self._readnoiseList[image]))\n readnoiseFileList.append(tmp)\n\n # Create an image of the total readnoise**2 per pixel:\n # (which is the sum of all the input readnoise values)\n #\n readnoise_file = self._sumImages(readnoiseFileList)\n del(readnoiseFileList)\n\n # Create an image of the total effective exposure time per pixel:\n # (which is simply the sum of all the drizzle output weight files)\n #\n weight_file = self._sumImages(self._weightImageList)\n\n\n # Scale up both the median and minimum arrays by the total effective exposure time\n # per pixel.\n #\n minimum_file_weighted = minimum_file * weight_file\n median_file_weighted = median_file * weight_file\n del(weight_file)\n\n # Calculate the 1-sigma r.m.s.:\n # variance = median_electrons + bkgd_electrons + readnoise**2\n # rms = sqrt(variance)\n # This image has units of electrons.\n #\n # make this the abs value so that negative numbers dont throw an exception?\n rms_file2 = np.fmax(\n median_file_weighted + bkgd_file + readnoise_file,\n np.zeros_like(median_file_weighted)\n )\n rms_file = np.sqrt(rms_file2)\n\n del bkgd_file\n del readnoise_file\n # For the median array, calculate the n-sigma lower threshold to the array\n # and incorporate that into the pixel values.\n #\n median_rms_file = median_file_weighted - (rms_file * self._combine_nsigma1)\n\n if self._combine_grow != 0:\n #\n # Do a more sophisticated rejection: For all cases where the minimum pixel will\n # be accepted instead of the median, set a lower threshold for that pixel and the\n # ones around it (ie become less conservative in rejecting the median). This is\n # because in cases of triple-incidence cosmic rays, quite often the low-lying\n # outliers of the CRs can influence the median for the initial relatively high\n # value of sigma, so a lower threshold must be used to mnake sure that the minimum\n # is selected.\n #\n # This is done as follows:\n # 1) make an image which is zero everywhere except where the minimum will be accepted\n # 2) box-car smooth this image, to make these regions grow.\n # 3) In the file \"median_rms_file_electrons\", replace these pixels\n # by median - combine_nsigma2 * rms\n #\n # Then use this image in the final replacement, in the same way as for the\n # case where this option is not selected.\n\n minimum_flag_file = np.where(np.less(minimum_file_weighted,median_rms_file), 1, 0)\n\n # The box size value must be an integer. This is not a problem since __combine_grow should always\n # be an integer type. The combine_grow column in the MDRIZTAB should also be an integer type.\n boxsize = int(2 * self._combine_grow + 1)\n boxshape = (boxsize, boxsize)\n minimum_grow_file = np.zeros(self._imageList[0].shape,dtype=self._imageList[0].dtype)\n\n\n # If the boxcar convolution has failed it is potentially for two reasons:\n # 1) The kernel size for the boxcar is bigger than the actual image.\n # 2) The grow parameter was specified with a value < 0. This would result\n # in an illegal boxshape kernel. The dimensions of the kernel box *MUST*\n # be integer and greater than zero.\n #\n # If the boxcar convolution has failed, try to give a meaningfull explanation\n # as to why based upon the conditionals described above.\n\n if (boxsize <= 0):\n errormsg1 = \"############################################################\\n\"\n errormsg1 += \"# The boxcar convolution in minmed has failed. The 'grow' #\\n\"\n errormsg1 += \"# parameter must be greater than or equal to zero. You #\\n\"\n errormsg1 += \"# specified an input value for the 'grow' parameter of: #\\n\"\n errormsg1 += \" combine_grow: \" + str(self._combine_grow)+'\\n'\n errormsg1 += \"############################################################\\n\"\n raise ValueError(errormsg1)\n if (boxsize > self._imageList[0].shape[0]):\n errormsg2 = \"############################################################\\n\"\n errormsg2 += \"# The boxcar convolution in minmed has failed. The 'grow' #\\n\"\n errormsg2 += \"# parameter specified has resulted in a boxcar kernel that #\\n\"\n errormsg2 += \"# has dimensions larger than the actual image. You #\\n\"\n errormsg2 += \"# specified an input value for the 'grow' parameter of: #\\n\"\n errormsg2 += \" combine_grow: \" +str(self._combine_grow)+'\\n'\n errormsg2 += \"############################################################\\n\"\n print(self._imageList[0].shape)\n raise ValueError(errormsg2)\n\n # Attempt the boxcar convolution using the boxshape based upon the user input value of \"grow\"\n ker = np.ones(boxshape) / float(boxsize**2)\n minimum_grow_file = signal.convolve2d(minimum_flag_file, ker,\n boundary='fill', mode='same')\n\n del(minimum_flag_file)\n\n temp1 = (median_file_weighted - (rms_file * self._combine_nsigma1))\n temp2 = (median_file_weighted - (rms_file * self._combine_nsigma2))\n median_rms2_file = np.where(np.equal(minimum_grow_file, 0), temp1, temp2)\n del(temp1)\n del(temp2)\n del(rms_file)\n del(minimum_grow_file)\n\n # Finally decide whether to use the minimim or the median (in counts/s),\n # based on whether the median is more than 3 sigma above the minimum.\n #\n self.combArrObj = np.where(\n np.less(minimum_file_weighted, median_rms2_file),\n minimum_file,\n median_file\n )\n\n else:\n # Finally decide whether to use the minimim or the median (in counts/s),\n # based on whether the median is more than 3 sigma above the minimum.\n #\n self.combArrObj = np.where(\n np.less(minimum_file_weighted, median_rms_file),\n minimum_file,\n median_file\n )\n\n # Set fill regions to a pixel value of 0.\n self.combArrObj = np.where(maskSum == self._numberOfImages, 0, self.combArrObj)\n\n# self.out_file1 = median_rms2_file.copy()\n# self.out_file2 = minimum_file_weighted.copy()\n\n\n def _sumImages(self,numarrayObjectList):\n \"\"\" Sum a list of numarray objects. \"\"\"\n if numarrayObjectList in [None, []]:\n return None\n\n tsum = np.zeros(numarrayObjectList[0].shape, dtype=numarrayObjectList[0].dtype)\n\n for image in numarrayObjectList:\n tsum += image\n\n return tsum\n\n\ndef min_med(images, weight_images, readnoise_list, exptime_list,\n background_values, weight_masks=None, combine_grow=1,\n combine_nsigma1=4, combine_nsigma2=3, fillval=False):\n \"\"\" Create a median array, rejecting the highest pixel and\n computing the lowest valid pixel after mask application.\n\n .. note::\n In this version of the mimmed algorithm we assume that the units of\n all input data is electons.\n\n Parameters\n ----------\n images : list of numpy.ndarray\n List of input data to be combined.\n\n weight_images : list of numpy.ndarray\n List of input data weight images to be combined.\n\n readnoise_list : list\n List of readnoise values to use for the input images.\n\n exptime_list : list\n List of exposure times to use for the input images.\n\n background_values : list\n List of image background values to use for the input images.\n\n weight_masks : list of numpy.ndarray, None\n List of imput data weight masks to use for pixel rejection.\n (Default: `None`)\n\n combine_grow : int\n Radius (pixels) for neighbor rejection. (Default: 1)\n\n combine_nsigma1 : float\n Significance for accepting minimum instead of median. (Default: 4)\n\n combine_nsigma2 : float\n Significance for accepting minimum instead of median. (Default: 3)\n\n fillval : bool\n Turn on use of imedian/imean. (Default: `False`)\n\n Returns\n -------\n combined_array : numpy.ndarray\n Combined array.\n\n \"\"\"\n # In this case we want to calculate two things:\n # 1) the median array, rejecting the highest pixel (thus running\n # imcombine with nlow=0, nhigh=1, nkeep=1, using the masks)\n # 2) the lowest valid pixel after applying the masks (thus running\n # imcombine with nlow=0, nhigh=3, nkeep=1, using the masks)\n #\n # We also calculate the sum of the weight files (to produce the total\n # effective exposure time for each pixel).\n #\n # The total effective background in the final image is calculated as\n # follows:\n # - convert background for each input image to counts/s\n # (divide by exptime)\n # - multiply this value by the weight image, to obtain the effective\n # background counts (in DN) for each pixel, for each image\n # - Add these images together, to obtain the total effective background\n # for the combined image.\n #\n # Once we've made these two files, then calculate the SNR based on the\n # median-pixel image, and compare with the minimum.\n\n nimages = len(images)\n combtype_median = 'imedian' if fillval else 'median'\n images = np.asarray(images)\n weight_images = np.asarray(weight_images)\n\n if weight_masks == [] or weight_masks is None:\n weight_masks = None\n mask_sum = np.zeros(images.shape[1:], dtype=np.int16)\n all_bad_idx = np.array([], dtype=np.int)\n all_bad_idy = np.array([], dtype=np.int)\n else:\n weight_masks = np.asarray(weight_masks, dtype=np.bool)\n mask_sum = np.sum(weight_masks, axis=0, dtype=np.int16)\n all_bad_idx, all_bad_idy = np.where(mask_sum == nimages)\n\n # Create a different median image based upon the number of images in the\n # input list.\n if nimages == 2:\n median_file = num_combine(\n images,\n masks=weight_masks,\n combination_type='imean' if fillval else 'mean',\n nlow=0, nhigh=0, lower=None, upper=None\n )\n\n else:\n # The value of NHIGH=1 will cause problems when there is only 1 valid\n # unmasked input image for that pixel due to a difference in behavior\n # between 'num_combine' and 'iraf.imcombine'.\n # This value may need to be adjusted on the fly based on the number of\n # inputs and the number of masked values/pixel.\n #\n median_file = num_combine(\n images,\n masks=weight_masks,\n combination_type=combtype_median,\n nlow=0, nhigh=1, lower=None, upper=None\n )\n\n # The following section of code will address the problem caused by\n # having a value of nhigh = 1. This will behave in a way similar to\n # the way the IRAF task IMCOMBINE behaves. In order to accomplish\n # this, the following procedure will be followed:\n # 1) The input masks will be summed.\n # 2) The science data will be summed.\n # 3) In the locations of the summed mask where the sum is 1 less than\n # the total number of images, the value of that location in the\n # summed science image will be used to replace the existing value\n # in the existing median_file.\n #\n # This procedure is being used to prevent too much data from being\n # thrown out of the image. Take for example the case of 3 input images.\n # In two of the images the pixel locations have been masked out.\n # Now, if nhigh is applied there will be no value to use for that\n # position. However, if this new procedure is used that value in\n # the resulting images will be the value that was rejected by the\n # nhigh rejection step.\n\n # We need to make certain that \"bad\" pixels in the sci data are set to\n # 0. That way, when the sci images are summed, the value of the sum\n # will only come from the \"good\" pixels.\n if weight_masks is None:\n sci_sum = np.sum(images, axis=0)\n if nimages == 1:\n median_file = sci_sum\n\n else:\n sci_sum = np.sum(images * np.logical_not(weight_masks), axis=0)\n # Use the summed sci image values in locations where the mask_sum\n # indicates that there is only 1 good pixel to use. The value will\n # be used in the median_file image\n idx = np.where(mask_sum == (nimages - 1))\n median_file[idx] = sci_sum[idx]\n\n # Create the minimum image from the stack of input images.\n if weight_masks is not None:\n # make a copy of images to avoid side-effect of modifying input\n # argument:\n images = images.copy()\n images[weight_masks] = np.nan\n images[:, all_bad_idx, all_bad_idy] = 0\n minimum_file = np.nanmin(images, axis=0)\n else:\n minimum_file = np.amin(images, axis=0)\n\n # Scale the weight images by the background values and add them to the bk\n # Create an image of the total effective background (in DN) per pixel:\n # (which is the sum of all the background-scaled weight files)\n s = np.asarray([bv / et for bv, et in\n zip(background_values, exptime_list)])\n bkgd_file = np.sum(weight_images * s[:, None, None], axis=0)\n\n # Scale the weight mask images by the square of the readnoise values.\n # Create an image of the total readnoise**2 per pixel\n # (which is the sum of all the input readnoise values).\n if weight_masks is None:\n rdn2 = sum((r**2 for r in readnoise_list))\n readnoise_file = rdn2 * np.ones_like(images[0])\n\n else:\n readnoise_file = np.sum(\n np.logical_not(weight_masks) *\n (np.asarray(readnoise_list)**2)[:, None, None],\n axis=0\n )\n\n # Create an image of the total effective exposure time per pixel:\n # (which is simply the sum of all the drizzle output weight files)\n weight_file = np.sum(weight_images, axis=0)\n\n # Scale up both the median and minimum arrays by the total effective\n # exposure time per pixel.\n minimum_file_weighted = minimum_file * weight_file\n median_file_weighted = median_file * weight_file\n del weight_file\n\n # Calculate the 1-sigma r.m.s.:\n # variance = median_electrons + bkgd_electrons + readnoise**2\n # rms = sqrt(variance)\n # This image has units of electrons.\n #\n # make this the abs value so that negative numbers dont throw an exception?\n rms_file2 = np.fmax(\n median_file_weighted + bkgd_file + readnoise_file,\n np.zeros_like(median_file_weighted)\n )\n rms_file = np.sqrt(rms_file2)\n del bkgd_file, readnoise_file\n\n # For the median array, calculate the n-sigma lower threshold to the array\n # and incorporate that into the pixel values.\n median_rms_file = median_file_weighted - rms_file * combine_nsigma1\n\n if combine_grow != 0:\n # Do a more sophisticated rejection: For all cases where the minimum\n # pixel will be accepted instead of the median, set a lower threshold\n # for that pixel and the ones around it (ie become less conservative\n # in rejecting the median). This is because in cases of\n # triple-incidence cosmic rays, quite often the low-lying outliers\n # of the CRs can influence the median for the initial relatively high\n # value of sigma, so a lower threshold must be used to mnake sure that\n # the minimum is selected.\n #\n # This is done as follows:\n # 1) make an image which is zero everywhere except where the minimum\n # will be accepted\n # 2) box-car smooth this image, to make these regions grow.\n # 3) In the file \"median_rms_file_electrons\", replace these pixels\n # by median - combine_nsigma2 * rms\n #\n # Then use this image in the final replacement, in the same way as for\n # the case where this option is not selected.\n minimum_flag_file = np.less(minimum_file_weighted,\n median_rms_file).astype(np.float64)\n\n # The box size value must be an integer. This is not a problem since\n # __combine_grow should always be an integer type. The combine_grow\n # column in the MDRIZTAB should also be an integer type.\n boxsize = int(2 * combine_grow + 1)\n boxshape = (boxsize, boxsize)\n minimum_grow_file = np.zeros_like(images[0])\n\n # If the boxcar convolution has failed it is potentially for\n # two reasons:\n # 1) The kernel size for the boxcar is bigger than the actual image.\n # 2) The grow parameter was specified with a value < 0. This would\n # result in an illegal boxshape kernel. The dimensions of the\n # kernel box *MUST* be integer and greater than zero.\n #\n # If the boxcar convolution has failed, try to give a meaningfull\n # explanation as to why based upon the conditionals described above.\n if boxsize <= 0:\n errormsg1 = \"############################################################\\n\"\n errormsg1 += \"# The boxcar convolution in minmed has failed. The 'grow' #\\n\"\n errormsg1 += \"# parameter must be greater than or equal to zero. You #\\n\"\n errormsg1 += \"# specified an input value for the 'grow' parameter of: #\\n\"\n errormsg1 += \" combine_grow: \" + str(combine_grow)+'\\n'\n errormsg1 += \"############################################################\\n\"\n raise ValueError(errormsg1)\n\n if boxsize > images.shape[1]:\n errormsg2 = \"############################################################\\n\"\n errormsg2 += \"# The boxcar convolution in minmed has failed. The 'grow' #\\n\"\n errormsg2 += \"# parameter specified has resulted in a boxcar kernel that #\\n\"\n errormsg2 += \"# has dimensions larger than the actual image. You #\\n\"\n errormsg2 += \"# specified an input value for the 'grow' parameter of: #\\n\"\n errormsg2 += \" combine_grow: \" + str(combine_grow) + '\\n'\n errormsg2 += \"############################################################\\n\"\n print(images.shape[1:])\n raise ValueError(errormsg2)\n\n # Attempt the boxcar convolution using the boxshape based upon the user\n # input value of \"grow\"\n ker = np.ones((boxsize, boxsize)) / float(boxsize**2)\n minimum_grow_file = signal.convolve2d(minimum_flag_file, ker,\n boundary='fill', mode='same')\n\n median_rms_file = np.where(\n np.equal(minimum_grow_file, 0),\n median_file_weighted - rms_file * combine_nsigma1,\n median_file_weighted - rms_file * combine_nsigma2\n )\n del rms_file, minimum_grow_file\n\n # Finally decide whether to use the minimim or the median (in counts/s),\n # based on whether the median is more than 3 sigma above the minimum.\n combined_array = np.where(\n np.less(minimum_file_weighted, median_rms_file),\n minimum_file,\n median_file\n )\n # Set fill regions to a pixel value of 0.\n combined_array[all_bad_idx, all_bad_idy] = 0\n\n return combined_array\n", "meta": {"hexsha": "0406424db44a624ae4bf00fe33a60bb97983f54b", "size": 30069, "ext": "py", "lang": "Python", "max_stars_repo_path": "drizzlepac/minmed.py", "max_stars_repo_name": "jhunkeler/drizzlepac", "max_stars_repo_head_hexsha": "09ca153b8e4f4e03dd155c61243d722e1c40caee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-02-10T16:15:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-24T20:08:03.000Z", "max_issues_repo_path": "drizzlepac/minmed.py", "max_issues_repo_name": "jhunkeler/drizzlepac", "max_issues_repo_head_hexsha": "09ca153b8e4f4e03dd155c61243d722e1c40caee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "drizzlepac/minmed.py", "max_forks_repo_name": "jhunkeler/drizzlepac", "max_forks_repo_head_hexsha": "09ca153b8e4f4e03dd155c61243d722e1c40caee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-02T18:08:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-02T18:08:39.000Z", "avg_line_length": 47.427444795, "max_line_length": 127, "alphanum_fraction": 0.6172802554, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.2782567996876011, "lm_q1q2_score": 0.14456034041586122}} {"text": "#!/usr/bin/env python\n\n\"\"\"\n.. module:: nllFast\n :synopsis: This module provides methods to access the nllfast grid and\n compute k-factors (when available) to SUSY pair \n production cross sections.\n\n.. moduleauthor:: Suchita Kulkarni \n.. moduleauthor:: Andre Lessa \n\n\"\"\"\n#\ntry:\n import commands as executor\nexcept ImportError:\n import subprocess as executor\nimport os\nfrom smodels.tools import toolBox\nimport pyslha\nfrom smodels.tools.physicsUnits import TeV\nimport numpy\nimport operator\n\nfrom smodels import installation\nfrom smodels.tools.smodelsLogging import logger\n\nsquarks = [1000001,\n 2000001,\n 1000002,\n 2000002,\n 1000003,\n 2000003,\n 1000004,\n 2000004]\nantisquarks = map(operator.neg, squarks)\nthird = [1000005,\n 2000005,\n 1000006,\n 2000006]\ngluinos = [1000021]\n\ndef getKfactorsFor(pIDs, sqrts, slhafile, pdf='cteq'):\n \"\"\"\n Read the NLLfast grid and returns a pair of k-factors (NLO and NLL) for the\n pair.\n\n :returns: k-factors = None, if NLLfast does not contain the process; uses\n the slhafile to obtain the SUSY spectrum.\n \n \"\"\"\n if not os.path.isfile(slhafile):\n logger.error(\"SLHA file %s not found\", slhafile)\n return False\n\n # Get process name (in NLLfast notation)\n process = getProcessName(pIDs)\n if not process:\n # Return k-factors = None, if NLLfast does not have the process\n return (None, None)\n\n # Obtain relevant masses\n readfile = pyslha.readSLHAFile(slhafile)\n masses=readfile.blocks['MASS']\n check_pids=squarks+gluinos+third\n for check in check_pids:\n if not check in masses.entries:\n logger.error ( \"cannot compute k factor for pdgid %d: \" \\\n \" no particle mass given. will set mass to inf.\" % check )\n masses.entries[check]=1.e10\n\n gluinomass = abs(masses.entries[1000021])\n squarkmass = sum([abs(masses.entries[pid])\n for pid in squarks]) / 8.\n pid1, pid2 = sorted(pIDs)\n if pid1 in antisquarks and pid2 in squarks:\n squarkmass = (abs(masses.entries[abs(pid1)]) +\n abs(masses.entries[pid2])) / 2.\n elif pid1 in squarks and pid2 in squarks:\n squarkmass = (abs(masses.entries[pid1]) + abs(masses.entries[pid2])) / 2.\n elif abs(pid1) == pid2 and pid2 in third:\n squarkmass = abs(masses.entries[abs(pid1)])\n\n # Set up NLLfast run, the old way\n sqrtS = float(sqrts/TeV)\n energy = str(int(sqrtS)) + 'TeV'\n toolname = \"nllfast%d\" % int(sqrtS)\n box = toolBox.ToolBox()\n tool = box.get(toolname)\n if tool == None:\n logger.warning(\"No NLLfast data for sqrts = \" + str(sqrts))\n return (None, None)\n nllpath = tool.installDirectory()\n tool.pathOfExecutable()\n tool.checkInstallation()\n if process == \"st\":\n nll_run = \"./nllfast_\" + energy + \" %s %s %s\" % \\\n (process, pdf, squarkmass)\n else:\n nll_run = \"./nllfast_\" + energy + \" %s %s %s %s\" % \\\n (process, pdf, squarkmass, gluinomass)\n\n # Run NLLfast\n nll_output = runNLLfast(nll_run, nllpath)\n\n # If run was successful, return k-factors:\n if \"K_NLO\" in nll_output:\n # NLLfast ran ok, try to get the k-factors\n kFacs = getKfactorsFrom(nll_output)\n if not kFacs or min(kFacs) <= 0.:\n logger.warning(\"Error obtaining k-factors\")\n return (None, None)\n else:\n return kFacs\n # If run was not successful, check for decoupling error messages:\n elif not \"too low/high\" in nll_output.lower():\n logger.warning(\"Error running NLLfast\")\n return (None, None)\n\n # Check for decoupling cases with a decoupling grid (only for sb and gg)\n doDecoupling = False\n if \"too low/high gluino\" in nll_output.lower(): \n if gluinomass > 500. and process == 'sb': \n doDecoupling = True\n dcpl_mass = gluinomass\n elif \"too low/high squark\" in nll_output.lower():\n if squarkmass > 500. and process == 'gg':\n doDecoupling = True\n dcpl_mass = squarkmass\n\n # If process do not have decoupled grids, return None:\n if not doDecoupling:\n logger.warning(\"Masses out of NLLfast grid for \" + process)\n return (None, None)\n\n # Obtain k-factors from the NLLfast decoupled grid\n kfacs = getDecoupledKfactors(nllpath,process,energy,pdf,min(gluinomass,squarkmass))\n # Decoupling limit is satisfied, do not interpolate\n if not kfacs:\n logger.warning(\"Error obtaining k-factors from the NLLfast decoupled grid for \" + process)\n return (None, None)\n elif dcpl_mass/min(gluinomass,squarkmass) > 10.: \n return kfacs\n # Interpolate between the non-decoupled and decoupled grids\n else:\n kFacsVector = [[10.*min(gluinomass,squarkmass),kfacs]] #First point for interpolation (decoupled grid)\n kfacs = None \n while not kfacs and dcpl_mass > 500.:\n dcpl_mass -= 100. # Reduce decoupled mass, until NLLfast produces results\n if process == 'sb': nllinput = (process, pdf, squarkmass, dcpl_mass)\n else: nllinput = (process, pdf, dcpl_mass, gluinomass)\n nll_run = \"./nllfast_\" + energy + \" %s %s %s %s\" % nllinput\n nll_output = runNLLfast(nll_run, nllpath)\n kfacs = getKfactorsFrom(nll_output) \n kFacsVector.append([dcpl_mass, kfacs]) #Second point for interpolation (non-decoupled grid)\n\n if len(kFacsVector) < 2:\n logger.warning(\"Not enough points for interpolation in the decoupling \"\n \"limit\")\n return (None, None)\n else:\n # Interpolate k-factors\n kFacs = interpolateKfactors(kFacsVector,\n max(squarkmass, gluinomass))\n return kFacs\n\n\n\ndef getProcessName(pIDs):\n \"\"\"\n Return the process name (in NLLfast notation) for the pair production of\n pIDs.\n \n :returns: None, if the particle ID pair is not contained in NLLfast\n \n \"\"\"\n pid1, pid2 = sorted(pIDs)\n process = None\n\n # Obtain the type of process:\n # - gluino-gluino production = gg\n # - squark-antisquark = sb\n # - squark-squark = ss\n # - squark-gluino = sg\n # - antistop-stop\n # - antisbottom-sbottom = st\n if pid1 in antisquarks and pid2 in squarks:\n process = 'sb'\n elif abs(pid1) in squarks and abs(pid2) in squarks:\n process = 'ss'\n elif pid1 == pid2 and pid1 in gluinos:\n process = 'gg'\n elif abs(pid1) in squarks and pid2 == 1000021 or \\\n abs(pid2) in squarks and pid1 == 1000021:\n process = 'sg'\n elif abs(pid1) == pid2 and pid2 in third:\n process = 'st'\n\n return process\n\n\ndef runNLLfast(nll_run, nllpath):\n \"\"\"\n Execute NLLfast with command nll_run at nllpath.\n \n :returns: NLLfast output as a string\n \n \"\"\"\n current_dir = os.getcwd()\n os.chdir(nllpath)\n nll_output = executor.getoutput(nll_run)\n # nll_output = subprocess.check_output ( nll_run, shell=True, universal_newlines=True )\n os.chdir(current_dir)\n return nll_output\n\n\ndef getKfactorsFrom(output):\n \"\"\"\n Read NLLfast output and return the k-factors.\n \n \"\"\"\n if not output:\n return False\n else:\n lines = output.split('\\n')\n il = 0\n line = lines[il]\n process = False\n while not \"K_NLO\" in line and il < len(lines) - 2:\n if \"process\" in line:\n process = line[line.find(\"process:\") + 8:].replace(\" \", \"\")\n il += 1\n line = lines[il]\n if not process:\n return False\n # Line with header\n line = lines[il]\n # Count number of mass entries\n nmass = line.count('GeV')\n # Line with values\n line = lines[il + 2]\n data = [eval(x) for x in line.split()]\n if len(data) != nmass + 11:\n return False\n else:\n kFacs = data[9 + nmass:]\n\n return kFacs\n\n\ndef interpolateKfactors(kFacsVector, xval):\n \"\"\"\n Interpolate a list of k-factor values from\n kFacsVector = [[x0,[k1,k2,..]], [x1,[k1,k2,..],...].\n \n :returns: list of interpolated k-factor values at x-value xval\n \n \"\"\"\n kFacs = []\n\n xpts = [x[0] for x in kFacsVector]\n ypts = [x[1] for x in kFacsVector]\n coeffs = numpy.matrix.transpose(numpy.polyfit(xpts, ypts, len(xpts) - 1))\n for ik in range(len(ypts[0])):\n kfac = 0.\n for ip, coeff in enumerate(coeffs[ik]):\n kfac += coeff * xval ** (len(xpts) - 1 - ip)\n if kfac <= 0.:\n kfac = 1.\n kFacs.append(kfac)\n\n return kFacs\n\ndef getDecoupledKfactors(nllpath,process,energy,pdf,mass):\n \"\"\"\n Compute k-factors in the decoupled (squark or gluino) regime for the process.\n If a decoupled grid does not exist for the process, return None\n \"\"\"\n \n if process != 'sb' and process != 'gg': return None\n elif process == 'sb': process_dcpl = 'sdcpl'\n elif process == 'gg': process_dcpl = 'gdcpl' \n nll_run = \"./nllfast_\" + energy + \" %s %s %s\" % \\\n (process_dcpl, pdf, mass)\n nll_output = runNLLfast(nll_run, nllpath)\n if \"K_NLO\" in nll_output:\n return getKfactorsFrom(nll_output)\n else: return None\n\n\n\nif __name__ == \"__main__\":\n \"\"\"\n Calculate k factors for a pid pair.\n \n \"\"\"\n slhaF = installation.installDirectory() + \"inputFiles/slha/T1.slha\"\n kNLO, kNLL = getKfactorsFor((1000021, 1000021), 13.*TeV, slhaF)\n print(\"nlo, nll = \" + str(kNLO) + \", \" + str(kNLL))\n", "meta": {"hexsha": "37ace8732b8c113a68e791da679d69f560828bb2", "size": 9732, "ext": "py", "lang": "Python", "max_stars_repo_path": "Externals/micromegas_4.3.5/Packages/smodels-v1.1.0patch1/smodels/tools/nllFast.py", "max_stars_repo_name": "yuanfangtardis/vscode_project", "max_stars_repo_head_hexsha": "2d78a85413cc85789cc4fee8ec991eb2a0563ef8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Externals/micromegas_4.3.5/Packages/smodels-v1.1.0patch1/smodels/tools/nllFast.py", "max_issues_repo_name": "yuanfangtardis/vscode_project", "max_issues_repo_head_hexsha": "2d78a85413cc85789cc4fee8ec991eb2a0563ef8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Externals/micromegas_4.3.5/Packages/smodels-v1.1.0patch1/smodels/tools/nllFast.py", "max_forks_repo_name": "yuanfangtardis/vscode_project", "max_forks_repo_head_hexsha": "2d78a85413cc85789cc4fee8ec991eb2a0563ef8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-15T12:22:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T12:22:30.000Z", "avg_line_length": 32.44, "max_line_length": 111, "alphanum_fraction": 0.6043978627, "include": true, "reason": "import numpy", "num_tokens": 2787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.2782567937024021, "lm_q1q2_score": 0.14456033730642276}} {"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\nimport numpy as np\nfrom astropy.utils import lazyproperty\nimport astropy.units as u\nfrom ..utils.fitting import Fit, Parameters\nfrom ..stats import cash\nfrom ..maps import Map, MapAxis\n\n__all__ = [\"MapEvaluator\", \"MapDataset\"]\n\n\nclass MapDataset:\n \"\"\"Perform sky model likelihood fit on maps.\n\n Parameters\n ----------\n model : `~gammapy.cube.models.SkyModel`\n Fit model\n counts : `~gammapy.maps.WcsNDMap`\n Counts cube\n exposure : `~gammapy.maps.WcsNDMap`\n Exposure cube\n mask : `~gammapy.maps.WcsNDMap`\n Mask to apply to the likelihood.\n psf : `~gammapy.cube.PSFKernel`\n PSF kernel\n edisp : `~gammapy.irf.EnergyDispersion`\n Energy dispersion\n background_model: `~gammapy.cube.models.BackgroundModel`\n Background model to use for the fit.\n likelihood : {\"cash\"}\n\t Likelihood function to use for the fit.\n \"\"\"\n\n def __init__(\n self,\n model,\n counts=None,\n exposure=None,\n mask=None,\n psf=None,\n edisp=None,\n background_model=None,\n ):\n if mask is not None and mask.data.dtype != np.dtype(\"bool\"):\n raise ValueError(\"mask data must have dtype bool\")\n\n self.model = model\n self.counts = counts\n self.exposure = exposure\n self.mask = mask\n self.psf = psf\n self.edisp = edisp\n self.background_model = background_model\n if background_model:\n self.parameters = Parameters(\n self.model.parameters.parameters +\n self.background_model.parameters.parameters\n )\n else:\n self.parameters = Parameters(self.model.parameters.parameters)\n\n self.evaluator = MapEvaluator(\n model=self.model, exposure=exposure, psf=self.psf, edisp=self.edisp\n )\n\n @property\n def data_shape(self):\n \"\"\"Shape of the counts data\"\"\"\n return self.counts.data.shape\n\n def npred(self):\n \"\"\"Returns npred map (model + background)\"\"\"\n model_npred = self.evaluator.compute_npred()\n back_npred = self.background_model.evaluate()\n total_npred = model_npred.data + back_npred.data\n return back_npred.copy(data=total_npred)\n # TODO: return model_npred + back_npred\n # There is some bug: edisp.e_reco.unit is dimensionless\n # thus map arithmetic does not work.\n\n def likelihood_per_bin(self):\n \"\"\"Likelihood per bin given the current model parameters\"\"\"\n return cash(n_on=self.counts.data, mu_on=self.npred().data)\n\n def likelihood(self, parameters, mask=None):\n \"\"\"Total likelihood given the current model parameters.\n\n Parameters\n ----------\n mask : `~numpy.ndarray`\n Mask to be combined with the dataset mask.\n \"\"\"\n if self.mask is None and mask is None:\n stat = self.likelihood_per_bin()\n elif self.mask is None:\n stat = self.likelihood_per_bin()[mask]\n elif mask is None:\n stat = self.likelihood_per_bin()[self.mask.data]\n else:\n stat = self.likelihood_per_bin()[mask & self.mask.data]\n return np.sum(stat, dtype=np.float64)\n\n\nclass MapEvaluator:\n \"\"\"Sky model evaluation on maps.\n\n This evaluates a sky model on a 3D map and convolves with the IRFs,\n and returns a map of the predicted counts.\n Note that background counts are not added.\n\n For now, we only make it work for 3D WCS maps with an energy axis.\n No HPX, no other axes, those can be added later here or via new\n separate model evaluator classes.\n\n\n Parameters\n ----------\n model : `~gammapy.cube.models.SkyModel`\n Sky model\n exposure : `~gammapy.maps.Map`\n Exposure map\n background : `~gammapy.maps.Map`\n Background map\n psf : `~gammapy.cube.PSFKernel`\n PSF kernel\n edisp : `~gammapy.irf.EnergyDispersion`\n Energy dispersion\n \"\"\"\n\n def __init__(self, model=None, exposure=None, psf=None, edisp=None):\n self.model = model\n self.exposure = exposure\n self.psf = psf\n self.edisp = edisp\n\n self.parameters = Parameters(self.model.parameters.parameters)\n\n @lazyproperty\n def geom(self):\n \"\"\"This will give the energy axes in e_true\"\"\"\n return self.exposure.geom\n\n @lazyproperty\n def geom_image(self):\n return self.geom.to_image()\n\n @lazyproperty\n def energy_center(self):\n \"\"\"True energy axis bin centers (`~astropy.units.Quantity`)\"\"\"\n energy_axis = self.geom.get_axis_by_name(\"energy\")\n energy = energy_axis.center * energy_axis.unit\n return energy[:, np.newaxis, np.newaxis]\n\n @lazyproperty\n def energy_edges(self):\n \"\"\"Energy axis bin edges (`~astropy.units.Quantity`)\"\"\"\n energy_axis = self.geom.get_axis_by_name(\"energy\")\n energy = energy_axis.edges * energy_axis.unit\n return energy[:, np.newaxis, np.newaxis]\n\n @lazyproperty\n def energy_bin_width(self):\n \"\"\"Energy axis bin widths (`astropy.units.Quantity`)\"\"\"\n return np.diff(self.energy_edges, axis=0)\n\n @lazyproperty\n def lon_lat(self):\n \"\"\"Spatial coordinate pixel centers.\n\n Returns ``lon, lat`` tuple of `~astropy.units.Quantity`.\n \"\"\"\n lon, lat = self.geom_image.get_coord()\n return (u.Quantity(lon, \"deg\", copy=False), u.Quantity(lat, \"deg\", copy=False))\n\n @lazyproperty\n def lon(self):\n return self.lon_lat[0]\n\n @lazyproperty\n def lat(self):\n return self.lon_lat[1]\n\n @lazyproperty\n def solid_angle(self):\n \"\"\"Solid angle per pixel\"\"\"\n return self.geom.solid_angle()\n\n @lazyproperty\n def bin_volume(self):\n \"\"\"Map pixel bin volume (solid angle times energy bin width).\"\"\"\n omega = self.solid_angle\n de = self.energy_bin_width\n return omega * de\n\n def compute_dnde(self):\n \"\"\"Compute model differential flux at map pixel centers.\n\n Returns\n -------\n model_map : `~gammapy.maps.Map`\n Sky cube with data filled with evaluated model values.\n Units: ``cm-2 s-1 TeV-1 deg-2``\n \"\"\"\n coord = (self.lon, self.lat, self.energy_center)\n dnde = self.model.evaluate(*coord)\n return dnde\n\n def compute_flux(self):\n \"\"\"Compute model integral flux over map pixel volumes.\n\n For now, we simply multiply dnde with bin volume.\n \"\"\"\n dnde = self.compute_dnde()\n volume = self.bin_volume\n flux = dnde * volume\n return flux\n\n def apply_exposure(self, flux):\n \"\"\"Compute npred cube\n\n For now just divide flux cube by exposure\n \"\"\"\n npred = (flux * self.exposure.quantity).to_value(\"\")\n return self.exposure.copy(data=npred)\n\n def apply_psf(self, npred):\n \"\"\"Convolve npred cube with PSF\"\"\"\n return npred.convolve(self.psf)\n\n def apply_edisp(self, npred):\n \"\"\"Convolve map data with energy dispersion.\n\n Parameters\n ----------\n npred : `~gammapy.maps.Map`\n Predicted counts in true energy bins\n\n Returns\n ---------\n npred_reco : `~gammapy.maps.Map`\n Predicted counts in reco energy bins\n \"\"\"\n loc = npred.geom.get_axis_index_by_name(\"energy\")\n data = np.rollaxis(npred.data, loc, len(npred.data.shape))\n data = np.dot(data, self.edisp.pdf_matrix)\n data = np.rollaxis(data, -1, loc)\n e_reco_axis = MapAxis.from_edges(\n self.edisp.e_reco.bins, unit=self.edisp.e_reco.unit, name=\"energy\"\n )\n geom_ereco = self.exposure.geom.to_image().to_cube(axes=[e_reco_axis])\n npred = Map.from_geom(geom_ereco, unit=\"\")\n npred.data = data\n return npred\n\n def compute_npred(self):\n \"\"\"\n Evaluate model predicted counts.\n\n Returns\n -------\n npred : `~gammapy.maps.Map`\n Predicted counts on the map (in reco energy bins)\n \"\"\"\n flux = self.compute_flux()\n npred = self.apply_exposure(flux)\n if self.psf is not None:\n npred = self.apply_psf(npred)\n if self.edisp is not None:\n npred = self.apply_edisp(npred)\n return npred\n", "meta": {"hexsha": "212bd69edeeffb6fb210354a5ed1979fd707cd41", "size": 8384, "ext": "py", "lang": "Python", "max_stars_repo_path": "gammapy/cube/fit.py", "max_stars_repo_name": "watsonjj/gammapy", "max_stars_repo_head_hexsha": "8d2498c8f63f73d1fbe4ba81ab02d9e72552df67", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gammapy/cube/fit.py", "max_issues_repo_name": "watsonjj/gammapy", "max_issues_repo_head_hexsha": "8d2498c8f63f73d1fbe4ba81ab02d9e72552df67", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gammapy/cube/fit.py", "max_forks_repo_name": "watsonjj/gammapy", "max_forks_repo_head_hexsha": "8d2498c8f63f73d1fbe4ba81ab02d9e72552df67", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8235294118, "max_line_length": 87, "alphanum_fraction": 0.6105677481, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 1944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.2782567877172032, "lm_q1q2_score": 0.1445603341969843}} {"text": "# This file is part of QuTiP: Quantum Toolbox in Python.\n#\n# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names\n# of its contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n###############################################################################\nimport warnings\nfrom copy import deepcopy\n\nimport numpy as np\n\nfrom qutip import (tensor, identity, destroy, sigmax, sigmaz, basis, Qobj,\n QobjEvo)\nfrom ..circuit import QubitCircuit\nfrom ..operations import Gate\nfrom .processor import Processor\nfrom .modelprocessor import ModelProcessor\nfrom ..operations import expand_operator\nfrom ..pulse import Pulse\nfrom ..compiler import (GateCompiler, CavityQEDCompiler)\n\n\n\n__all__ = ['DispersiveCavityQED']\n\n\nclass DispersiveCavityQED(ModelProcessor):\n \"\"\"\n The processor based on the physical implementation of\n a dispersive cavity QED system.\n The available Hamiltonian of the system is predefined.\n For a given pulse amplitude matrix, the processor can\n calculate the state evolution under the given control pulse,\n either analytically or numerically.\n (Only additional attributes are documented here, for others please\n refer to the parent class :class:`.ModelProcessor`)\n\n Parameters\n ----------\n num_qubits: int\n The number of qubits in the system.\n\n correct_global_phase: float, optional\n Save the global phase, the analytical solution\n will track the global phase.\n It has no effect on the numerical solution.\n\n num_levels: int, optional\n The number of energy levels in the resonator.\n\n t1: list or float, optional\n Characterize the decoherence of amplitude damping for\n each qubit. A list of size `num_qubits` or a float for all qubits.\n\n t2: list of float, optional\n Characterize the decoherence of dephasing for\n each qubit. A list of size `num_qubits` or a float for all qubits.\n\n **params:\n Keyword argument for hardware parameters, in the unit of GHz.\n Qubit parameters can either be a float or a list of the length\n ``num_qubits``.\n\n - ``deltamax``: the pulse strength of sigma-x control, default ``1.0``\n - ``epsmax``: the pulse strength of sigma-z control, default ``9.5``\n - ``eps``: the bare transition frequency for each of the qubits,\n default ``9.5``\n - ``delta``: the coupling between qubit states, default ``0.0``\n - ``g``: the coupling strength between the resonator and the qubit,\n default ``1.0``\n - ``w0``: the bare frequency of the resonator. Should only be a float,\n default ``0.01``\n\n The dressed qubit frequency is `wq` is computed by\n :math:`w_q=\\sqrt{\\epsilon^2+\\delta^2}`\n\n Attributes\n ----------\n wq: list of float\n The frequency of the qubits calculated from\n eps and delta for each qubit.\n\n Delta: list of float\n The detuning with respect to w0 calculated\n from wq and w0 for each qubit.\n \"\"\"\n\n def __init__(self, num_qubits, correct_global_phase=True,\n num_levels=10, t1=None, t2=None, **params):\n super(DispersiveCavityQED, self).__init__(\n num_qubits, correct_global_phase=correct_global_phase,\n t1=t1, t2=t2)\n self.correct_global_phase = correct_global_phase\n self.spline_kind = \"step_func\"\n self.num_levels = num_levels\n self.params = { # default parameters\n \"deltamax\": 1.0,\n \"epsmax\": 9.5,\n \"w0\": 10,\n \"eps\": 9.5,\n \"delta\": 0.0,\n \"g\": 0.01,\n }\n if params is not None:\n self.params.update(params)\n for key, value in self.params.items():\n if key != \"w0\":\n # if float, make it an array\n self.params[key] = self.to_array(value, self.num_qubits)\n self.set_up_params()\n self.set_up_ops(num_qubits)\n self.dims = [num_levels] + [2] * num_qubits\n self.pulse_dict = self.get_pulse_dict()\n self.native_gates = [\"SQRTISWAP\", \"ISWAP\", \"RX\", \"RZ\"]\n\n def set_up_ops(self, num_qubits):\n \"\"\"\n Generate the Hamiltonians for the spinchain model and save them in the\n attribute `ctrls`.\n\n Parameters\n ----------\n num_qubits: int\n The number of qubits in the system.\n \"\"\"\n # single qubit terms\n for m in range(num_qubits):\n self.add_control(2*np.pi*sigmax(), [m+1], label=\"sx\" + str(m))\n for m in range(num_qubits):\n self.add_control(2*np.pi*sigmaz(), [m+1], label=\"sz\" + str(m))\n # coupling terms\n a = tensor(\n [destroy(self.num_levels)] +\n [identity(2) for n in range(num_qubits)])\n for n in range(num_qubits):\n sm = tensor([identity(self.num_levels)] +\n [destroy(2) if m == n else identity(2)\n for m in range(num_qubits)])\n self.add_control(\n 2*np.pi * a.dag() * sm + 2*np.pi * a * sm.dag(),\n list(range(num_qubits+1)), label=\"g\" + str(n)\n )\n\n def set_up_params(self):\n \"\"\"\n Compute the qubit frequency and detune.\n \"\"\"\n # backward compatibility\n self.params[\"sz\"] = self.params[\"epsmax\"]\n self.params[\"sx\"] = self.params[\"deltamax\"]\n eps = self.params[\"eps\"]\n delta = self.params[\"delta\"]\n w0 = self.params[\"w0\"]\n g = self.params[\"g\"]\n # computed\n self.wq = np.sqrt(eps**2 + delta**2)\n self.Delta = self.wq - w0\n\n # rwa/dispersive regime tests\n if any(g / (w0 - self.wq) > 0.05):\n warnings.warn(\"Not in the dispersive regime\")\n\n if any((w0 - self.wq)/(w0 + self.wq) > 0.05):\n warnings.warn(\n \"The rotating-wave approximation might not be valid.\")\n print(self.params)\n\n @property\n def sx_ops(self):\n \"\"\"\n list: A list of sigmax Hamiltonians for each qubit.\n \"\"\"\n return self.ctrls[0: self.num_qubits]\n\n @property\n def sz_ops(self):\n \"\"\"\n list: A list of sigmaz Hamiltonians for each qubit.\n \"\"\"\n return self.ctrls[self.num_qubits: 2*self.num_qubits]\n\n @property\n def cavityqubit_ops(self):\n \"\"\"\n list: A list of interacting Hamiltonians between cavity and each qubit.\n \"\"\"\n return self.ctrls[2*self.num_qubits: 3*self.num_qubits]\n\n @property\n def sx_u(self):\n \"\"\"array-like: Pulse matrix for sigmax Hamiltonians.\"\"\"\n return self.coeffs[: self.num_qubits]\n\n @property\n def sz_u(self):\n \"\"\"array-like: Pulse matrix for sigmaz Hamiltonians.\"\"\"\n return self.coeffs[self.num_qubits: 2*self.num_qubits]\n\n @property\n def g_u(self):\n \"\"\"\n array-like: Pulse matrix for interacting Hamiltonians\n between cavity and each qubit.\n \"\"\"\n return self.coeffs[2*self.num_qubits: 3*self.num_qubits]\n\n def get_operators_labels(self):\n \"\"\"\n Get the labels for each Hamiltonian.\n It is used in the method method :meth:`.Processor.plot_pulses`.\n It is a 2-d nested list, in the plot,\n a different color will be used for each sublist.\n \"\"\"\n return ([[r\"$\\sigma_x^%d$\" % n for n in range(self.num_qubits)],\n [r\"$\\sigma_z^%d$\" % n for n in range(self.num_qubits)],\n [r\"$g_{%d}$\" % (n) for n in range(self.num_qubits)]])\n\n def eliminate_auxillary_modes(self, U):\n \"\"\"\n Eliminate the auxillary modes like the cavity modes in cqed.\n \"\"\"\n psi_proj = tensor(\n [basis(self.num_levels, 0)] +\n [identity(2) for n in range(self.num_qubits)])\n return psi_proj.dag() * U * psi_proj\n\n def load_circuit(\n self, qc, schedule_mode=\"ASAP\", compiler=None):\n if compiler is None:\n compiler = CavityQEDCompiler(\n self.num_qubits, self.params, global_phase=0.)\n tlist, coeff = super().load_circuit(\n qc, schedule_mode=schedule_mode, compiler=compiler)\n self.global_phase = compiler.global_phase\n return tlist, coeff\n", "meta": {"hexsha": "51eda1c1add86150a88c4e20de52b6c3ddc04911", "size": 9810, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/qutip_qip/device/cavityqed.py", "max_stars_repo_name": "jakelishman/qutip-qip", "max_stars_repo_head_hexsha": "fa1cb1b139bb294861b21698f721f5421c4386ab", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-07T00:18:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T10:46:06.000Z", "max_issues_repo_path": "src/qutip_qip/device/cavityqed.py", "max_issues_repo_name": "jakelishman/qutip-qip", "max_issues_repo_head_hexsha": "fa1cb1b139bb294861b21698f721f5421c4386ab", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/qutip_qip/device/cavityqed.py", "max_forks_repo_name": "jakelishman/qutip-qip", "max_forks_repo_head_hexsha": "fa1cb1b139bb294861b21698f721f5421c4386ab", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4427480916, "max_line_length": 79, "alphanum_fraction": 0.6175331295, "include": true, "reason": "import numpy", "num_tokens": 2347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.1445110712303212}} {"text": "import warnings\n\nimport astropy.units as u\nimport numpy as np\nfrom astropy.time import Time\n\nfrom sora.config.decorators import deprecated_function, deprecated_alias\nfrom sora.prediction import occ_params, PredictionTable\nfrom .fitting import fit_ellipse as ellipse_fitting\n\n__all__ = ['Occultation']\nwarnings.simplefilter('always', UserWarning)\n\n\nclass Occultation:\n \"\"\"Instantiates the Occultation object and performs the reduction of the\n occultation.\n\n Attributes\n ----------\n star : `sora.Star`, `str`, required\n the coordinate of the star in the same reference frame as the ephemeris.\n It must be a Star object or a string with the coordinates of the object\n to search on Vizier.\n\n body : `sora.Body`, `str`\n Object that will occult the star. It must be a Body object or its name\n to search in the Small Body Database.\n\n ephem : `sora.Ephem`, `list`\n Object ephemeris. It must be an Ephemeris object or a list.\n\n time : `str`, `astropy.time.Time`, required\n Reference time of the occultation. Time does not need to be exact, but\n needs to be within approximately 50 minutes of the occultation closest\n approach to calculate occultation parameters.\n\n reference_center : `str`, `sora.Observer`, `sora.Spacecraft`\n A SORA observer object or a string 'geocenter'.\n The occultation parameters will be calculated in respect\n to this reference as center of projection.\n\n\n Important\n ---------\n When instantiating with \"body\" and \"ephem\", the user may define the\n Occultation in 3 ways:\n\n 1. With `body` and `ephem`.\n\n 2. With only \"body\". In this case, the \"body\" parameter must be a Body\n object and have an ephemeris associated (see Body documentation).\n\n 3. With only `ephem`. In this case, the `ephem` parameter must be one of the\n Ephem Classes and have a name (see Ephem documentation) to search for the\n body in the Small Body Database.\n\n \"\"\"\n def __init__(self, star, body=None, ephem=None, time=None, reference_center='geocenter'):\n\n from sora.body import Body\n from sora.star import Star\n from .chordlist import ChordList\n\n if body is None and ephem is None:\n raise ValueError('\"body\" and/or \"ephem\" must be given.')\n if time is None:\n raise ValueError('\"time\" parameter must be given.')\n if isinstance(star, str):\n star = Star(coord=star)\n elif not isinstance(star, Star):\n raise ValueError('\"star\" must be a Star object or a string with coordinates of the star')\n self._star = star\n if body is not None:\n if not isinstance(body, (str, Body)):\n raise ValueError('\"body\" must be a string with the name of the object or a Body object')\n if isinstance(body, str):\n body = Body(name=body)\n self._body = body\n if ephem is not None:\n if body is not None:\n self.body.ephem = ephem\n else:\n if hasattr(ephem, 'name'):\n self._body = Body(name=ephem.name, ephem=ephem)\n else:\n raise ValueError('When only \"ephem\" is given, \"ephem\" must have a name for search.')\n try:\n ephem = self.body.ephem\n except AttributeError:\n raise ValueError('An Ephem object must be defined in Body object.')\n self._reference_center = reference_center\n\n tca, ca, pa, vel, dist = occ_params(self.star, ephem, time, reference_center=reference_center)\n self.ca = ca # Closest Approach distance\n self.pa = pa # Position Angle at CA\n self.vel = vel # Shadow velocity at CA\n self.dist = dist # object distance at CA\n self.tca = tca # Instant of CA\n self.star_diam = self.star.apparent_diameter(self.dist, verbose=False)\n\n meta = {\n 'name': self.body.name, 'radius': self.body.radius.to(u.km).value,\n 'error_ra': self.body.ephem.error_ra.to(u.mas).value, 'error_dec': self.body.ephem.error_dec.to(u.mas).value}\n self.predict = PredictionTable(\n time=[tca], coord_star=[self.star.get_position(tca, observer=reference_center)],\n coord_obj=[self.body.ephem.get_position(tca, observer=reference_center)],\n ca=[ca.value], pa=[pa.value], vel=[vel.value], dist=[dist.value],\n mag=[self.star.mag['G']], source=[self.star.code], meta=meta)\n\n self.__observations = []\n self._chords = ChordList(star=self.star, body=self._body, time=self.tca)\n self._chords._shared_with['occultation'] = {\"vel\": np.absolute(self.vel), \"dist\": float(self.dist.AU),\n \"star_diam\": float(self.star_diam.km)}\n\n @property\n def star(self):\n return self._star\n\n @property\n def body(self):\n return self._body\n\n @property\n def chords(self):\n return self._chords\n\n # remove this block for v1.0\n @deprecated_function(message=\"Please use chords.add_chord to add new observations.\")\n def add_observation(self, obs, lightcurve):\n \"\"\"Adds observations to the Occultation object.\n\n Parameters\n ----------\n obs : `sora.Observer`\n The Observer object to be added.\n\n lightcurve : `sora.LightCurve`\n The LightCurve object to be added.\n \"\"\"\n self.chords.add_chord(name=lightcurve.name, observer=obs, lightcurve=lightcurve)\n\n @deprecated_function(message=\"Please use chords.remove_chord to remove observations.\")\n def remove_observation(self, key, key_lc=None):\n \"\"\"Removes an observation from the Occultation object.\n\n Parameters\n ----------\n key : `str`\n The name given to `Observer` or `LightCurve` to remove from the list.\n\n key_lc : `str`\n In the case where repeated names are present for different\n observations, `key_lc` must be given for the name of the `LightCurve`\n and key will be used for the name of the `Observer`.\n \"\"\"\n try:\n self.chords.remove_chord(name=key)\n except KeyError:\n rm_list = []\n for name, chord in self.chords.items():\n if chord.observer.name == key and (key_lc is None or chord.lightcurve.name == key_lc):\n rm_list.append(name)\n if len(rm_list) != 1:\n if len(rm_list) == 0:\n err_mes = \"No observation was identified with given keys.\"\n else:\n err_mes = \"More than one chord was identified. Please provide unique keys.\"\n raise ValueError(err_mes)\n else:\n self.chords.remove_chord(name=rm_list[0])\n\n @deprecated_function(message=\"Please use chords.\")\n def observations(self):\n \"\"\" Print all the observations added to the Occultation object\n Pair (`Observer`, `LightCurve`)\n \"\"\"\n print(self.chords.__repr__())\n\n # end of block removal\n\n def fit_ellipse(self, **kwargs):\n chisquare = ellipse_fitting(self, **kwargs)\n return chisquare\n\n fit_ellipse.__doc__ = ellipse_fitting.__doc__\n\n # remove this block for v1.0\n @property\n @deprecated_function(message=\"Please use chords.summary()\")\n def positions(self):\n \"\"\" Calculates the position and velocity for all chords.\n Saves it into an `_PositionDict` object.\n \"\"\"\n from functools import partial\n from .meta import _PositionDict\n\n if not hasattr(self, '_position'):\n self._position = _PositionDict()\n position = self._position\n if len(self.chords) == 0:\n raise ValueError('There is no observation defined for this occultation')\n\n pair = []\n for name, chord in self.chords.items():\n obs = chord.observer\n obs_name = obs.name\n if obs_name == '':\n obs_name = '{}_obs'.format(chord.name)\n lc = chord.lightcurve\n lc_name = lc.name\n if lc_name == '':\n lc_name = '{}_lc'.format(chord.name)\n pair.append((obs_name, lc_name))\n\n coord = [obs.lon, obs.lat, obs.height]\n if obs.name not in position.keys():\n position['_occ_'+obs_name] = _PositionDict(lon=obs.lon, lat=obs.lat, height=obs.height)\n position[obs_name]['_occ_lon'] = obs.lon\n position[obs_name]['_occ_lat'] = obs.lat\n position[obs_name]['_occ_height'] = obs.height\n pos_obs = position[obs_name]\n coord2 = [pos_obs['lon'], pos_obs['lat'], pos_obs['height']]\n if obs.lon != pos_obs['lon']:\n position[obs_name]['_occ_lon'] = obs.lon\n if obs.lat != pos_obs['lat']:\n position[obs_name]['_occ_lat'] = obs.lat\n if obs.height != pos_obs['height']:\n position[obs_name]['_occ_height'] = obs.height\n samecoord = (coord == coord2)\n\n if lc_name not in pos_obs.keys():\n pos_obs['_occ_'+lc_name] = _PositionDict()\n pos_lc = pos_obs[lc_name]\n\n pos_lc['_occ_status'] = chord.status()\n\n if hasattr(lc, 'immersion'):\n if 'immersion' not in pos_lc.keys():\n pos_lc['_occ_immersion'] = _PositionDict(on=chord.is_able['immersion'],\n enable=partial(chord.enable, time='immersion'),\n disable=partial(chord.disable, time='immersion'))\n obs_im = pos_lc['immersion']\n obs_im['_occ_on'] = chord.is_able['immersion']\n do_err = False\n if samecoord and 'time' in obs_im.keys() and obs_im['time'] == lc.immersion:\n pass\n else:\n do_err = True\n f1, g1, vf1, vg1 = chord.get_fg(time='immersion', vel=True)\n obs_im['_occ_time'] = lc.immersion\n obs_im['_occ_value'] = (round(f1, 3), round(g1, 3))\n obs_im['_occ_vel'] = (round(vf1, 3), round(vg1, 3))\n if not do_err and 'time_err' in obs_im.keys() and obs_im['time_err'] == lc.immersion_err:\n pass\n else:\n fe1, ge1 = chord.get_fg(time=lc.immersion-lc.immersion_err*u.s)\n fe2, ge2 = chord.get_fg(time=lc.immersion+lc.immersion_err*u.s)\n obs_im['_occ_time_err'] = lc.immersion_err\n obs_im['_occ_error'] = ((round(fe1, 3), round(ge1, 3)), (round(fe2, 3), round(ge2, 3)))\n\n if hasattr(lc, 'emersion'):\n pos_lc['_occ_emersion'] = _PositionDict(on=chord.is_able['emersion'],\n enable=partial(chord.enable, time='emersion'),\n disable=partial(chord.disable, time='emersion'))\n obs_em = pos_lc['emersion']\n do_err = False\n if samecoord and 'time' in obs_em.keys() and obs_em['time'] == lc.emersion:\n pass\n else:\n do_err = True\n f1, g1, vf1, vg1 = chord.get_fg(time='emersion', vel=True)\n obs_em['_occ_time'] = lc.emersion\n obs_em['_occ_value'] = (round(f1, 3), round(g1, 3))\n obs_em['_occ_vel'] = (round(vf1, 3), round(vg1, 3))\n if not do_err and 'time_err' in obs_em.keys() and obs_em['time_err'] == lc.emersion_err:\n pass\n else:\n fe1, ge1 = chord.get_fg(time=lc.emersion-lc.emersion_err*u.s)\n fe2, ge2 = chord.get_fg(time=lc.emersion+lc.emersion_err*u.s)\n obs_em['_occ_time_err'] = lc.emersion_err\n obs_em['_occ_error'] = ((round(fe1, 3), round(ge1, 3)), (round(fe2, 3), round(ge2, 3)))\n\n if pos_lc['status'] == 'negative':\n if 'start_obs' not in pos_lc.keys():\n pos_lc['_occ_start_obs'] = _PositionDict()\n obs_start = pos_lc['start_obs']\n if samecoord and 'time' in obs_start.keys() and obs_start['time'] == lc.initial_time:\n pass\n else:\n f, g, vf, vg = chord.get_fg(time='start', vel=True)\n obs_start['_occ_time'] = lc.initial_time\n obs_start['_occ_value'] = (round(f, 3), round(g, 3))\n obs_start['_occ_vel'] = (round(vf, 3), round(vg, 3))\n if 'end_obs' not in pos_lc.keys():\n pos_lc['_occ_end_obs'] = _PositionDict()\n obs_end = pos_lc['end_obs']\n if samecoord and 'time' in obs_end.keys() and obs_end['time'] == lc.end_time:\n pass\n else:\n f, g, vf, vg = chord.get_fg(time='end', vel=True)\n obs_end['_occ_time'] = lc.end_time\n obs_end['_occ_value'] = (round(f, 3), round(g, 3))\n obs_end['_occ_vel'] = (round(vf, 3), round(vg, 3))\n\n for key in list(position):\n n = 0\n for key_lc in list(position[key]):\n if type(position[key][key_lc]) != _PositionDict:\n continue\n if (key, key_lc) not in pair:\n del position[key][key_lc]\n else:\n n += 1\n if n == 0:\n del position[key]\n\n return self._position\n\n @positions.setter\n def positions(self, value):\n \"\"\"\n Note\n ----\n If the users tries to set a value to position, it must be ``'on'`` or\n ``'off'``, and it will be assigned to all chords.\n \"\"\"\n if value not in ['on', 'off']:\n raise ValueError(\"Value must be 'on' or 'off' only.\")\n pos = self.positions\n for key in pos.keys():\n pos[key] = value\n\n # end of block removal\n\n def check_velocities(self):\n \"\"\"Prints the current velocity used by the LightCurves and its radial velocity.\n \"\"\"\n if hasattr(self, 'fitted_params'):\n center = np.array([self.fitted_params['center_f'][0], self.fitted_params['center_g'][0]])\n else:\n center = np.array([0, 0])\n for name, chord in self.chords.items():\n im = getattr(chord.lightcurve, 'immersion', None)\n em = getattr(chord.lightcurve, 'emersion', None)\n if im is None and em is None:\n continue\n print('{} - Velocity used: {:.3f}'.format(name, chord.lightcurve.vel))\n if im is not None:\n vals = chord.get_fg(time=im, vel=True)\n delta = np.array(vals[0:2]) - center\n print(' Immersion Radial Velocity: {:.3f}'.\n format(np.abs(np.dot(np.array(vals[2:]), delta)/np.linalg.norm(delta))))\n if em is not None:\n vals = chord.get_fg(time=em, vel=True)\n delta = np.array(vals[0:2]) - center\n print(' Emersion Radial Velocity: {:.3f}'.\n format(np.abs(np.dot(np.array(vals[2:]), delta)/np.linalg.norm(delta))))\n\n @deprecated_alias(log='verbose') # remove this line in v1.0\n def new_astrometric_position(self, time=None, offset=None, error=None, verbose=True, observer=None):\n \"\"\"Calculates the new astrometric position for the object given fitted parameters.\n\n Parameters\n ----------\n time : `str`, `astropy.time.Time`\n Reference time to calculate the position. If not given, it uses the\n instant of the occultation Closest Approach. It can be a string\n in the ISO format (yyyy-mm-dd hh:mm:ss.s) or an astropy Time object.\n\n offset : `list`\n Offset to apply to the position. If not given, uses the parameters\n from the fitted ellipse.\n\n Note\n ----\n Must be a list of 3 values being [X, Y, 'unit']. 'unit' must be\n Angular or Distance unit.\n\n If Distance units for X and Y:\n Ex: [100, -200, 'km'], [0.001, 0.002, 'AU']\n\n If Angular units fox X [d*a*cos(dec)] and Y [d*dec]:\n Ex: [30.6, 20, 'mas'], or [-15, 2, 'arcsec']\n\n error : `list`\n Error bar of the given offset. If not given, it uses the 1-sigma\n value of the fitted ellipse.\n\n Note\n ----\n Error must be a list of 3 values being [dX, dY, 'unit'], similar to\n offset. It does not need to be in the same unit as offset.\n\n verbose : `bool`\n If true, it Prints text, else it Returns text.\n\n observer : `str`, `sora.Observer`, `sora.Spacecraft`\n IAU code of the observer (must be present in given list of kernels),\n a SORA observer object or a string: ['geocenter', 'barycenter']\n \"\"\"\n from astropy.coordinates import SkyCoord, SkyOffsetFrame\n\n if time is not None:\n time = Time(time)\n else:\n time = self.tca\n\n tca_diff = np.absolute(time-self.tca)\n if tca_diff > 1*u.day:\n warnings.warn('The difference between the given time and the closest approach instant is {:.1f} days. '\n 'This position could not have a physical meaning.'.format(tca_diff.jd))\n\n if offset is not None:\n off_ra = offset[0]*u.Unit(offset[2])\n off_dec = offset[1]*u.Unit(offset[2])\n if off_ra.unit.physical_type == 'length':\n dist = True\n elif off_ra.unit.physical_type == 'angle':\n dist = False\n else:\n raise ValueError('Offset unit must be a distance or angular value.')\n elif hasattr(self, 'fitted_params'):\n off_ra = self.fitted_params['center_f'][0]*u.km\n off_dec = self.fitted_params['center_g'][0]*u.km\n dist = True\n else:\n warnings.warn('No offset given or found. Using 0.0 instead.')\n off_ra = 0.0*u.mas\n off_dec = 0.0*u.mas\n dist = False\n\n if error is not None:\n e_off_ra = error[0]*u.Unit(error[2])\n e_off_dec = error[1]*u.Unit(error[2])\n if e_off_ra.unit.physical_type == 'length':\n e_dist = True\n elif e_off_ra.unit.physical_type == 'angle':\n e_dist = False\n else:\n raise ValueError('Error unit must be a distance or angular value.')\n elif hasattr(self, 'fitted_params'):\n e_off_ra = self.fitted_params['center_f'][1]*u.km\n e_off_dec = self.fitted_params['center_g'][1]*u.km\n e_dist = True\n else:\n warnings.warn('No error given or found. Using 0.0 instead.')\n e_off_ra = 0.0*u.mas\n e_off_dec = 0.0*u.mas\n e_dist = False\n\n if observer is None:\n observer = self._reference_center\n\n coord = self.body.ephem.get_position(time, observer=observer)\n distance = coord.distance.to(u.km)\n coord_frame = SkyOffsetFrame(origin=coord)\n if dist:\n off_ra = np.arctan2(off_ra, distance)\n off_dec = np.arctan2(off_dec, distance)\n if e_dist:\n e_off_ra = np.arctan2(e_off_ra, distance)\n e_off_dec = np.arctan2(e_off_dec, distance)\n new_pos = SkyCoord(lon=off_ra, lat=off_dec, frame=coord_frame)\n new_pos = new_pos.icrs\n\n error_star = self.star.error_at(self.tca)\n error_ra = np.sqrt(error_star[0]**2 + e_off_ra**2)\n error_dec = np.sqrt(error_star[1]**2 + e_off_dec**2)\n\n out = 'Ephemeris offset (km): X = {:.1f} +/- {:.1f}; Y = {:.1f} +/- {:.1f}\\n'.format(\n distance*np.sin(off_ra.to(u.mas)).value, distance*np.sin(e_off_ra.to(u.mas)).value,\n distance*np.sin(off_dec.to(u.mas)).value, distance*np.sin(e_off_dec.to(u.mas)).value)\n out += 'Ephemeris offset (mas): da_cos_dec = {:.3f} +/- {:.3f}; d_dec = {:.3f} +/- {:.3f}\\n'.format(\n off_ra.to(u.mas).value, e_off_ra.to(u.mas).value, off_dec.to(u.mas).value, e_off_dec.to(u.mas).value)\n out += '\\nAstrometric object position at time {} for reference {}\\n'.format(time.iso, observer.__repr__())\n out += 'RA = {} +/- {:.3f} mas; DEC = {} +/- {:.3f} mas'.format(\n new_pos.ra.to_string(u.hourangle, precision=7, sep=' '), error_ra.to(u.mas).value,\n new_pos.dec.to_string(u.deg, precision=6, sep=' '), error_dec.to(u.mas).value)\n\n if verbose:\n print(out)\n else:\n return out\n\n # remove this block for v1.0\n @deprecated_function(message=\"Please use chords.plot_chords to have a better control of the plots\")\n def plot_chords(self, all_chords=True, positive_color='blue', negative_color='green', error_color='red',\n ax=None, lw=2):\n \"\"\"Plots the chords of the occultation.\n\n Parameters\n ----------\n all_chords : `bool`, default=True\n If True, it plots all the chords. If False, it sees what was\n deactivated in self.positions and ignores them.\n\n positive_color : `str`, default='blue'\n Color for the positive chords.\n\n negative_color : `str`, default='green'\n Color for the negative chords.\n\n error_color : `str`, default='red'\n Color for the error bars of the chords.\n\n ax : `maptlotlib.pyplot.Axes`, default=None\n Axis where to plot chords (default: Uses matplotlib pool).\n\n lw : `int`, `float`, default=2\n Linewidth of the chords.\n\n \"\"\"\n self.chords.plot_chords(segment='positive', only_able=not all_chords, color=positive_color, lw=lw, ax=ax)\n self.chords.plot_chords(segment='error', only_able=not all_chords, color=error_color, lw=lw, ax=ax)\n self.chords.plot_chords(segment='negative', color=negative_color, lw=lw, ax=ax, linestyle='--')\n\n # end of block removal\n\n def get_map_sites(self):\n \"\"\"Returns Dictionary with sites in the format required by plot_occ_map function.\n\n Returns\n -------\n sites : `dict`\n Dictionary with the sites in the format required by `plot_occ_map`\n function.\n \"\"\"\n sites = {}\n color = {'positive': 'blue', 'negative': 'red'}\n for name, chord in self.chords.items():\n obs = chord.observer\n sites[name] = [obs.lon.deg, obs.lat.deg, 10, 10, color[chord.status()]]\n return sites\n\n def plot_occ_map(self, **kwargs):\n if 'radius' not in kwargs and hasattr(self, 'fitted_params'):\n r_equa = self.fitted_params['equatorial_radius'][0]\n obla = self.fitted_params['oblateness'][0]\n pos_ang = self.fitted_params['position_angle'][0]\n theta = np.linspace(-np.pi, np.pi, 1800)\n map_pa = self.predict['P/A'][0]\n circle_x = r_equa*np.cos(theta)\n circle_y = r_equa*(1.0-obla)*np.sin(theta)\n ellipse_y = -circle_x*np.sin((pos_ang-map_pa)*u.deg) + circle_y*np.cos((pos_ang-map_pa)*u.deg)\n kwargs['radius'] = ellipse_y.max()\n print('Projected shadow radius = {:.1f} km'.format(kwargs['radius']))\n kwargs['sites'] = kwargs.get('sites', self.get_map_sites())\n if 'offset' not in kwargs and hasattr(self, 'fitted_params'):\n off_ra = self.fitted_params['center_f'][0]*u.km\n off_dec = self.fitted_params['center_g'][0]*u.km\n off_ra = np.arctan2(off_ra, self.dist)\n off_dec = np.arctan2(off_dec, self.dist)\n kwargs['offset'] = [off_ra, off_dec]\n self.predict.plot_occ_map(**kwargs)\n\n plot_occ_map.__doc__ = PredictionTable.plot_occ_map.__doc__\n\n def to_log(self, namefile=None):\n \"\"\"Saves the occultation log to a file.\n\n Parameters\n ----------\n namefile : `str`\n Filename to save the log.\n \"\"\"\n if namefile is None:\n namefile = 'occ_{}_{}.log'.format(self.body.shortname.replace(' ', '_'), self.tca.isot[:16])\n f = open(namefile, 'w')\n f.write(self.__str__())\n f.close()\n\n def check_time_shift(self, time_interval=30, time_resolution=0.001, verbose=False, plot=False, use_error=True, delta_plot=100,\n ignore_chords=None):\n \"\"\"Check the needed time offset, so all chords have their center aligned.\n\n Parameters\n ----------\n time_interval : `int`, `float`\n Time interval to check, default is 30 seconds.\n\n time_resolution : `int`, `float`\n Time resolution of the search, default is 0.001 seconds.\n\n verbose : `bool`\n If True, it prints text, default is False.\n\n plot : `bool`, default=False\n If True, it plots figures as a visual aid.\n\n use_error : `bool`, default=True\n if True, the linear fit considers the time uncertainty.\n\n delta_plot : `int`, `float`, default=100\n Value to be added to increase the plot limit, in km.\n\n ignore_chords : `str`, list, default=None\n Names of the chords to be ignored in the linear fit.\n\n Returns\n -------\n time_shift : `dict`\n Dictionary with needed time offset to align the chords, each key is\n the name of the chord.\n \"\"\"\n import matplotlib.pyplot as plt\n fm = np.array([])\n gm = np.array([])\n dfm = np.array([])\n dgm = np.array([])\n vfm = np.array([])\n vgm = np.array([])\n chord_name = np.array([])\n ignore_chords = np.array(ignore_chords, ndmin=1)\n use_chords = np.array([], dtype=bool)\n out_dic = {}\n\n chords = range(len(self.chords))\n for i in chords:\n chord = self.chords[i]\n if chord.status() == 'positive':\n ffm, ggm, vffm, vggm = chord.get_fg(time=chord.lightcurve.time_mean, vel=True)\n df1, dg1, df2, dg2 = chord.path(segment='error')\n dfm = np.append(dfm, np.sqrt(((df1.max() - df1.min())/2)**2 + ((df2.max() - df2.min())/2)**2))\n dgm = np.append(dgm, np.sqrt(((dg1.max() - dg1.min())/2)**2 + ((dg2.max() - dg2.min())/2)**2))\n fm = np.append(fm, ffm)\n gm = np.append(gm, ggm)\n vfm = np.append(vfm, vffm)\n vgm = np.append(vgm, vggm)\n chord_name = np.append(chord_name, chord.name)\n if chord.name in ignore_chords:\n use_chords = np.append(use_chords, False)\n else:\n use_chords = np.append(use_chords, True)\n if len(fm[use_chords]) < 2:\n raise ValueError('The number of fitted chords should be higher than two')\n out = self.__linear_fit_error(x=fm[use_chords], y=gm[use_chords], sx=dfm[use_chords], sy=dgm[use_chords],\n verbose=verbose, use_error=use_error)\n fm_fit = np.arange(-delta_plot+np.min([fm.min(), gm.min()]), delta_plot+np.max([fm.max(), gm.max()]),\n time_resolution*np.absolute(self.vel.value))\n gm_fit = self.__func_line_decalage(out.beta, fm_fit)\n\n previous_dt = np.array([])\n fm_decalage = np.array([])\n gm_decalage = np.array([])\n time_decalage = np.array([])\n\n for i, j in enumerate(chord_name):\n previous_dt = np.append(previous_dt, self.chords[j].lightcurve.dt)\n dist_min = np.array([])\n dtt = np.arange(-time_interval, +time_interval, time_resolution)\n for dt in dtt:\n fm_new = fm[i] + dt*vfm[i]\n gm_new = gm[i] + dt*vgm[i]\n dist = np.sqrt((fm_new - fm_fit)**2 + (gm_new - gm_fit)**2)\n dist_min = np.append(dist_min, dist.min())\n print('dt = {:+6.3f} seconds; chord = {}'.format(previous_dt[i] + dtt[dist_min.argmin()], chord_name[i]))\n fm_decalage = np.append(fm_decalage, fm[i] + dtt[dist_min.argmin()]*vfm[i])\n gm_decalage = np.append(gm_decalage, gm[i] + dtt[dist_min.argmin()]*vgm[i])\n time_decalage = np.append(time_decalage, dtt[dist_min.argmin()])\n\n for i in range(len(chord_name)):\n out_dic[chord_name[i]] = time_decalage[i]\n if plot:\n plt.figure(figsize=(5, 5))\n plt.title('Before', fontsize=15)\n self.chords.plot_chords(color='blue')\n self.chords.plot_chords(color='red', segment='error')\n plt.plot(fm[use_chords], gm[use_chords], linestyle='None', marker='o', color='k')\n plt.plot(fm[np.invert(use_chords)], gm[np.invert(use_chords)], linestyle='None', marker='x', color='r')\n plt.plot(fm_fit, gm_fit, 'k-')\n plt.xlim(-delta_plot + np.min([fm.min(), gm.min()]), delta_plot + np.max([fm.max(), gm.max()]))\n plt.ylim(-delta_plot + np.min([fm.min(), gm.min()]), delta_plot + np.max([fm.max(), gm.max()]))\n plt.show()\n for i, j in enumerate(chord_name):\n self.chords[j].lightcurve.dt = previous_dt[i] + time_decalage[i]\n plt.figure(figsize=(5, 5))\n plt.title('After', fontsize=15)\n self.chords.plot_chords(color='blue')\n self.chords.plot_chords(color='red', segment='error')\n plt.plot(fm_decalage[use_chords], gm_decalage[use_chords], linestyle='None', marker='o', color='k')\n plt.plot(fm_decalage[np.invert(use_chords)], gm_decalage[np.invert(use_chords)], linestyle='None', marker='x',\n color='r')\n plt.plot(fm_fit, gm_fit, 'k-')\n plt.xlim(-delta_plot + np.min([fm.min(), gm.min()]), delta_plot + np.max([fm.max(), gm.max()]))\n plt.ylim(-delta_plot + np.min([fm.min(), gm.min()]), delta_plot + np.max([fm.max(), gm.max()]))\n plt.show()\n for i, j in enumerate(chord_name):\n self.chords[j].lightcurve.dt = previous_dt[i]\n return out_dic\n\n def to_file(self):\n \"\"\"Saves the occultation data to a file.\n\n Three files are saved containing the positions and velocities for the\n observations. They are for the positive, negative and error bars positions.\n\n The format of the files are: positions in f and g, velocities in f and\n g, the Julian Date of the observation, light curve name of the\n corresponding position.\n \"\"\"\n pos = []\n neg = []\n err = []\n for name, chord in self.chords.items():\n status = chord.status()\n l_name = name.replace(' ', '_')\n if status == 'positive':\n im = chord.lightcurve.immersion\n ime = chord.lightcurve.immersion_err\n f, g, vf, vg = chord.get_fg(time=im, vel=True)\n f1, g1 = chord.get_fg(time=im-ime*u.s)\n f2, g2 = chord.get_fg(time=im+ime*u.s)\n pos.append([f, g, vf, vg, im.jd, l_name+'_immersion'])\n err.append([f1, g1, vf, vg, (im-ime*u.s).jd, l_name+'_immersion_err-'])\n err.append([f2, g2, vf, vg, (im+ime*u.s).jd, l_name+'_immersion_err+'])\n\n em = chord.lightcurve.emersion\n eme = chord.lightcurve.emersion_err\n f, g, vf, vg = chord.get_fg(time=em, vel=True)\n f1, g1 = chord.get_fg(time=em-eme*u.s)\n f2, g2 = chord.get_fg(time=em+eme*u.s)\n pos.append([f, g, vf, vg, em.jd, l_name+'_emersion'])\n err.append([f1, g1, vf, vg, (em-eme*u.s).jd, l_name+'_emersion_err-'])\n err.append([f2, g2, vf, vg, (em+eme*u.s).jd, l_name+'_emersion_err+'])\n\n if status == 'negative':\n ini = chord.lightcurve.initial_time\n f, g, vf, vg = chord.get_fg(time=ini, vel=True)\n neg.append([f, g, vf, vg, ini.jd, l_name+'_start'])\n\n end = chord.lightcurve.end_time\n f, g, vf, vg = chord.get_fg(time=end, vel=True)\n neg.append([f, g, vf, vg, end.jd, l_name+'_end'])\n if len(pos) > 0:\n f = open('occ_{}_pos.txt'.format(self.body.shortname.replace(' ', '_')), 'w')\n for line in pos:\n f.write('{:10.3f} {:10.3f} {:-6.2f} {:-6.2f} {:16.8f} {}\\n'.format(*line))\n f.close()\n f = open('occ_{}_err.txt'.format(self.body.shortname.replace(' ', '_')), 'w')\n for line in err:\n f.write('{:10.3f} {:10.3f} {:-6.2f} {:-6.2f} {:16.8f} {}\\n'.format(*line))\n f.close()\n if len(neg) > 0:\n f = open('occ_{}_neg.txt'.format(self.body.shortname.replace(' ', '_')), 'w')\n for line in neg:\n f.write('{:10.3f} {:10.3f} {:-6.2f} {:-6.2f} {:16.8f} {}\\n'.format(*line))\n f.close()\n\n def __str__(self):\n \"\"\" String representation of the Occultation class\n \"\"\"\n out = ('Stellar occultation of star {} {} by {}.\\n\\n'\n 'Geocentric Closest Approach: {:.3f}\\n'\n 'Instant of CA: {}\\n'\n 'Position Angle: {:.2f}\\n'\n 'Geocentric shadow velocity: {:.2f}\\n'\n 'Sun-Geocenter-Target angle: {:.2f} deg\\n'\n 'Moon-Geocenter-Target angle: {:.2f} deg\\n\\n\\n'.format(\n self.star._catalogue, self.star.code, self.body.name, self.ca, self.tca.iso,\n self.pa, self.vel, self.predict['S-G-T'].data[0], self.predict['M-G-T'].data[0])\n )\n\n count = {'positive': 0, 'negative': 0, 'visual': 0}\n string = {'positive': '', 'negative': '', 'visual': ''}\n if len(self.chords) > 0:\n for chord in self.chords.values():\n status = chord.status()\n string[status] += chord.__str__() + '\\n'\n count[status] += 1\n\n if len(self.chords) == 0:\n out += 'No observations reported'\n else:\n out += '\\n'.join(['{} {} observations'.format(count[k], k) for k in string.keys() if count[k] > 0])\n\n out += '\\n\\n'\n\n out += '#'*79 + '\\n{:^79s}\\n'.format('STAR') + '#'*79 + '\\n'\n out += self.star.__str__() + '\\n\\n'\n\n coord = self.star.get_position(self.tca, observer=self._reference_center)\n try:\n error_star = self.star.error_at(self.tca)\n except:\n error_star = [0, 0]*u.mas\n out += 'Geocentric star coordinate at occultation Epoch ({}):\\n'.format(self.tca.iso)\n out += 'RA={} +/- {:.4f}, DEC={} +/- {:.4f}\\n\\n'.format(\n coord.ra.to_string(u.hourangle, sep='hms', precision=5), error_star[0],\n coord.dec.to_string(u.deg, sep='dms', precision=4), error_star[1])\n\n out += self.body.__str__() + '\\n'\n\n for status in string.keys():\n if count[status] == 0:\n continue\n out += ('#'*79 + '\\n{:^79s}\\n'.format(status.upper() + ' OBSERVATIONS') + '#'*79)\n out += '\\n\\n'\n out += string[status]\n\n if hasattr(self, 'fitted_params'):\n out += '#'*79 + '\\n{:^79s}\\n'.format('RESULTS') + '#'*79 + '\\n\\n'\n out += 'Fitted Ellipse:\\n'\n out += '\\n'.join(['{}: {:.3f} +/- {:.3f}'.format(k, *self.fitted_params[k])\n for k in self.fitted_params.keys()]) + '\\n'\n polar_radius = self.fitted_params['equatorial_radius'][0]*(1.0-self.fitted_params['oblateness'][0])\n equivalent_radius = np.sqrt(self.fitted_params['equatorial_radius'][0]*polar_radius)\n out += 'polar_radius: {:.3f} km \\n'.format(polar_radius)\n out += 'equivalent_radius: {:.3f} km \\n'.format(equivalent_radius)\n if not np.isnan(self.body.H):\n H_sun = -26.74\n geometric_albedo = (10**(0.4*(H_sun - self.body.H.value))) * ((u.au.to('km')/equivalent_radius)**2)\n out += 'geometric albedo (V): {:.3f} ({:.1%}) \\n'.format(geometric_albedo, geometric_albedo)\n else:\n out += 'geometric albedo (V): not calculated, absolute magnitude (H) is unknown \\n'\n out += '\\nMinimum chi-square: {:.3f}\\n'.format(self.chi2_params['chi2_min'])\n out += 'Number of fitted points: {}\\n'.format(self.chi2_params['npts'])\n out += 'Number of fitted parameters: {}\\n'.format(self.chi2_params['nparam'])\n out += 'Minimum chi-square per degree of freedom: {:.3f}\\n'.format(\n self.chi2_params['chi2_min']/(self.chi2_params['npts'] - self.chi2_params['nparam']))\n out += 'Radial dispersion: {:.3f} +/- {:.3f} km\\n'.format(\n self.chi2_params['radial_dispersion'].mean(), self.chi2_params['radial_dispersion'].std(ddof=1))\n out += 'Radial error: {:.3f} +/- {:.3f} km\\n'.format(\n self.chi2_params['radial_error'].mean(), self.chi2_params['radial_error'].std(ddof=1))\n\n out += '\\n' + self.new_astrometric_position(verbose=False)\n\n return out\n\n def __func_line_decalage(self, p, x):\n \"\"\" Private function returns a linear function, intended for fitting inside the self.check_decalage().\n \"\"\"\n a, b = p\n return a*x + b\n\n def __linear_fit_error(self, x, y, sx, sy, verbose=False, use_error=True):\n \"\"\" Private function returns a linear fit, intended for fitting inside the self.check_decalage().\n \"\"\"\n import scipy.odr as odr\n\n model = odr.Model(self.__func_line_decalage)\n if use_error:\n data = odr.RealData(x=x, y=y, sx=sx, sy=sy)\n else:\n data = odr.RealData(x=x, y=y)\n fit = odr.ODR(data, model, beta0=[0., 1.])\n out = fit.run()\n if verbose:\n print('Linear fit procedure')\n out.pprint()\n print('\\n')\n return out\n", "meta": {"hexsha": "fb7d995c32f18291b2166bc1b79de340b636418a", "size": 38265, "ext": "py", "lang": "Python", "max_stars_repo_path": "sora/occultation/core.py", "max_stars_repo_name": "Bmorgado19/SORA", "max_stars_repo_head_hexsha": "6b9bbb9238f521d8b93cd8b9d332f36d66b7a138", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sora/occultation/core.py", "max_issues_repo_name": "Bmorgado19/SORA", "max_issues_repo_head_hexsha": "6b9bbb9238f521d8b93cd8b9d332f36d66b7a138", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sora/occultation/core.py", "max_forks_repo_name": "Bmorgado19/SORA", "max_forks_repo_head_hexsha": "6b9bbb9238f521d8b93cd8b9d332f36d66b7a138", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.8593200469, "max_line_length": 130, "alphanum_fraction": 0.5525937541, "include": true, "reason": "import numpy,import scipy,import astropy,from astropy", "num_tokens": 9479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2845760042165267, "lm_q1q2_score": 0.14451107123032117}} {"text": "#! /usr/bin/env python\n\nfrom sys import argv\nimport numpy as np\nfrom ase.io import read, write\nfrom ase.build.surface import fcc111\n\nif argv[1] == \"-h\" or argv[1] == \"--help\":\n print(\"\"\"\nPython script that generates a molecular junction for transport computation\nusing DFTB+.\n\nAuthor: Alessandro Pirrotta\nMIT Licence\n\nExample 1:\n$ python generate_molecular_junction.py molecule.xyz c r 0 1\n\nusing molecule 'molecule.xyz' as device region\nit generates a cluster type molecular junction (c) with no pbc,\nremoves terminal hydrogen (r) on the end atoms 0 and 1.\n\nExample 2:\n$ python generate_molecular_junction.py molecule.xyz s nr\n\ngenerate a supercell type molecular junction with pbc (s),\ndoes not removes terminal hydrogen (nr) and automatically looks for\nsulphur atoms as end atoms.\n\"\"\")\n exit()\n\n\ndef find_nearest(atom, atoms):\n # create empty list\n dists = []\n # define coordinates for atom\n coord = atom.position\n # loop over atoms and append distance to list\n for a in atoms:\n if a.symbol == 'H':\n v = a.position - coord\n dist = np.sqrt(v[0]**2+v[1]**2+v[2]**2)\n dists.append(dist)\n continue\n dists.append(1.7)\n # make list to np.array\n dists = np.array(dists)\n # find index with shortest distance using argmin\n index = np.argmin(dists)\n if dists[index] > 1.7: # atom closer than C\n print 'found no H bonded to S, deleted something, consider revising'\n return index\n\n\nif len(argv) > 4:\n # print(\"reading end atoms from input\")\n endatom1 = int(argv[4])\n endatom2 = int(argv[5])\n\n# create gold electrode\na = 4\npbc = bool(True)\n\nb = a\nc = 6\nlelectrode = fcc111('Au', size=(a, b, c), vacuum=5.0, orthogonal=True)\n\n# Au-S 2.72AA / Au-Au 2.88AA\n# distance between two adjacent gold layers\n# deltag 2.35558909829\n# perpendicular distance between endatom and electrode surface\n# delta s_g 2.14441090171\n\n# read the molecule file\n# molecule = read('mol.xyz')\nmolecule = read(argv[1])\n# place electrode close to the origin of axis\nn = (lelectrode[0].position)\nn = - n # put atom 1 at the origin of axis\nlelectrode.translate(n)\nnatoms = len(molecule)\n\ntry:\n endatom1\nexcept NameError:\n endatom1 = -1\n for atom in molecule:\n # if your endatoms are S atoms and there are only 2 in the molecule\n if atom.symbol == 'S':\n if endatom1 < 0:\n endatom1 = atom.index\n else:\n endatom2 = atom.index\n\n# remove terminal hydrogens\nif len(argv) > 3 and argv[3] == 'r':\n list = []\n for atom in molecule:\n if atom.symbol == 'S':\n list.append(atom.index)\n del molecule[find_nearest(molecule[list[1]], molecule)]\n del molecule[find_nearest(molecule[list[0]], molecule)]\n natoms = len(molecule)\n\n# align the sulphur atoms along the z axis\npo = (molecule[endatom1].position)\nlo = (molecule[endatom2].position)\nv = lo-po\nz = [0, 0, 1]\nmolecule.rotate(v, z)\nmolecule.rotate('z', np.pi+np.pi/4.0)\n\n# place the molecule on top of a hollow fcc site for axa face\nif a == 6:\n q = (lo + [0, 0, 4.5] - lelectrode[(b*a*2)+(6*4)].position)\nif a == 3:\n q = (lo + [0, 0, 4.5] - lelectrode[(a*b*2)+(4)].position)\nif a == 4:\n q = (lo + [0, 0, 4.5] - lelectrode[(b*a*2)+(9)].position)\nq = - q\nmolecule.translate(q)\n\n# define distance betweet gold layers\ndeltag = abs(lelectrode[0].position[2] - lelectrode[(a*b)+1].position[2])\n# define end to end distance\nv = molecule[endatom2].position - molecule[endatom1].position\nlenght_molecule = np.sqrt(v[0]**2+v[1]**2+v[2]**2)\nmolecule.translate([0, 0, -(deltag)])\nmolecule.extend(lelectrode)\n# make a list of indexes relative to gold atoms\nau_list = []\nfor atom in molecule:\n if atom.symbol == 'Au':\n au_list.append(atom.index)\n\n# number of gold atoms on a single layer\nng = int(a*b)\n# distance along the z axis between one layer and the adjacent one:\ndeltag = abs(lelectrode[0].position[2] - lelectrode[(a*b)+1].position[2])\nv = molecule[endatom2].position-molecule[natoms+2].position\ndeltas_g = abs(v[2])\n\nfor x in range(c):\n ly = []\n ly = au_list[(x*a*b):(a*b*(x+1))]\n layer = molecule[ly]\n layer.translate([0, 0,\n -(abs(lenght_molecule)+abs(deltas_g*2)+abs(deltag*(2*x)))])\n molecule.extend(layer)\n\nif argv[2] == \"s\" or argv[2] == \"S\":\n molecule.set_pbc(True)\nif argv[2] == \"c\" or argv[2] == \"C\":\n molecule.set_pbc(False)\nn = (molecule[natoms+a*b*c-a*b].position)\nn = -n\nmolecule.translate(n)\n\nif argv[2] == \"s\" or argv[2] == \"S\":\n lele = fcc111('Au',\n size=(a, b, 18),\n vacuum=deltas_g+lenght_molecule,\n orthogonal=True)\n cell = lele.get_cell()\n molecule.set_cell([cell[0],\n cell[1],\n [0., 0., molecule[len(molecule)-1].position[2]-20.0]])\n molecule.set_pbc((True, True, True))\n write('moljunct_S.gen', molecule)\n\nwrite('moljunct_C.gen', molecule)\n\n\n# printing device, source and drain atom indeces\nprint 1, natoms\nprint natoms+1, natoms+a*b*6\nprint natoms+a*b*6+1, len(molecule)\n\nexit()\n", "meta": {"hexsha": "cd56c93f35d5d30034f46663ce51487c3092e50d", "size": 5136, "ext": "py", "lang": "Python", "max_stars_repo_path": "generate_molecular_junction.py", "max_stars_repo_name": "alessap/sturdy-meme", "max_stars_repo_head_hexsha": "0dff0307e786728f1cb2875b9504de4630f28727", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "generate_molecular_junction.py", "max_issues_repo_name": "alessap/sturdy-meme", "max_issues_repo_head_hexsha": "0dff0307e786728f1cb2875b9504de4630f28727", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "generate_molecular_junction.py", "max_forks_repo_name": "alessap/sturdy-meme", "max_forks_repo_head_hexsha": "0dff0307e786728f1cb2875b9504de4630f28727", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5333333333, "max_line_length": 79, "alphanum_fraction": 0.6339563863, "include": true, "reason": "import numpy", "num_tokens": 1543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2845759981489974, "lm_q1q2_score": 0.14451106814915782}} {"text": "#!/usr/local/sci/bin/python2.7\n#*****************************\n#\n# convert 3 hourly data to pentads\n#\n#\n#************************************************************************\n'''\nAuthor: Robert Dunn\nCreated: March 2016\nLast update: 12 April 2016\nLocation: /project/hadobs2/hadisdh/marine/PROGS/Build\n\n-----------------------\nCODE PURPOSE AND OUTPUT\n-----------------------\nTakes 3 hourly data and creates pentads. First summing across the 5 days and then the 8 timestamps\n\n-----------------------\nLIST OF MODULES\n-----------------------\nutils.py\n\n-----------------------\nDATA\n-----------------------\nInput data and output data stored in:\n/project/hadobs2/hadisdh/marine/ICOADS.2.5.1/GRIDS2/\n\nRequires 3hrly grids.\n\n-----------------------\nHOW TO RUN THE CODE\n-----------------------\npython2.7 3hrlies_to_pentads.py --suffix relax --period day --start_year YYYY --end_year YYYY\n\npython2.7 3hrlies_to_pentads.py --help \nwill show all options\n\n-----------------------\nOUTPUT\n-----------------------\n/project/hadobs2/hadisdh/marine/ICOADS.2.5.1/GRIDS2/\n\nPlots to appear in \n/project/hadobs2/hadisdh/marine/ICOADS.2.5.1/PLOTS2/\n\n-----------------------\nVERSION/RELEASE NOTES\n-----------------------\n\nVersion 1 (release date)\n---------\n \nEnhancements\n \nChanges\n \nBug fixes\n \n\n-----------------------\nOTHER INFORMATION\n-----------------------\n'''\n\nimport os\nimport datetime as dt\nimport numpy as np\nimport sys\nimport argparse\nimport matplotlib\nmatplotlib.use('Agg') \n\nimport calendar\nimport netCDF4 as ncdf\nimport gc\n\nimport utils\nimport set_paths_and_vars\ndefaults = set_paths_and_vars.set()\n\nOBS_ORDER = utils.make_MetVars(defaults.mdi, multiplier = False)\n\n# what size grid (lat/lon)\nDELTA_LAT = 1\nDELTA_LON = 1\nDELTA_HOUR = 3\n\n# set up the grid\ngrid_lats = np.arange(-90 + DELTA_LAT, 90 + DELTA_LAT, DELTA_LAT)\ngrid_lons = np.arange(-180 + DELTA_LAT, 180 + DELTA_LON, DELTA_LON)\n\n\n#************************************************************************\ndef read_data(settings, suffix, name, year, grid_lats, grid_lons, period, N_OBS_PER_DAY):\n '''\n Read in the data from the netCDF files\n\n :param Settings settings: object to hold all filepaths etc.\n :param str suffix: used to determine whether using strict or relaxed criteria\n :param str name: variable name\n :param int year: year to read\n :param array grid_lats: latitudes\n :param array grid_lons: longitudes\n :param str period: which period (day/night/all)\n :param int N_OBS_PER_DAY: number of observation times per day\n\n :returns: var_3hrlys - array of 3hrly data for single variable\n '''\n\n if suffix == \"relax\":\n N_OBS_OVER_DAYS = 1\n N_OBS_OVER_PENTAD = 2\n\n elif suffix == \"strict\":\n N_OBS_OVER_DAYS = 2\n N_OBS_OVER_PENTAD = 4 \n\n\n # set up empty data array\n var_3hrlys = np.ma.zeros([utils.days_in_year(year)*N_OBS_PER_DAY, len(grid_lats), len(grid_lons)])\n var_3hrlys.mask = np.zeros([utils.days_in_year(year)*N_OBS_PER_DAY, len(grid_lats), len(grid_lons)])\n var_3hrlys.fill_value = settings.mdi\n \n year_start = dt.datetime(year, 1, 1, 0, 0)\n \n for month in np.arange(12) + 1:\n print year, month\n \n month_start = utils.day_of_year(year, month)\n month_end = month_start + calendar.monthrange(year, month)[1]\n \n filename = \"{}/{}_1x1_3hr_{}{:02d}_{}_{}.nc\".format(settings.DATA_LOCATION, settings.OUTROOT, year, month, period, suffix)\n \n ncdf_file = ncdf.Dataset(filename,'r', format='NETCDF4')\n \n if month == 12:\n # run to end of year if december\n var_3hrlys[month_start*N_OBS_PER_DAY:, :, :] = ncdf_file.variables[name][:]\n else:\n var_3hrlys[month_start*N_OBS_PER_DAY:month_end*N_OBS_PER_DAY, :, :] = ncdf_file.variables[name][:]\n\n return var_3hrlys # read_data\n\n#************************************************************************\ndef process_february(var_3hrlys, doMask = True):\n '''\n Process the set of 3hly obs that fall on 29th Feb.\n\n Store them, then remove from the main array.\n\n :param array var_3hrlys: array for 3hrly data for one variable\n :param bool doMask: process the mask (for data yes, for n_obs no)\n\n :returns: var_3hrlys, incl_feb29th - updated data and the Feb 29th obs.\n '''\n\n\n assert var_3hrlys.shape[0] == 366\n \n # extract 6-day pentad\n incl_feb29th = var_3hrlys[55:61, :, :, :]\n \n if doMask:\n # remove the data of Feb 29th from array\n # np.ma.delete doesn't exist, so have to copy mask separately\n mask = var_3hrlys.mask\n \n var_3hrlys = np.delete(var_3hrlys, 59, 0) \n\n if doMask:\n mask = np.delete(mask, 59, 0)\n var_3hrlys = np.ma.array(var_3hrlys, mask = mask)\n del mask\n \n return var_3hrlys, incl_feb29th # process_february\n\n\n\n#************************************************************************\ndef do_conversion(suffix = \"relax\", start_year = defaults.START_YEAR, end_year = defaults.END_YEAR, period = \"all\", doQC = False, doBC = False):\n '''\n Convert 3 hrlies to pentads 1x1\n\n First get pentad average of 3hrly values (so values at 0, 3, 6, ... averaged over 5 days)\n Then get average over the pentad.\n\n :param str suffix: \"relax\" or \"strict\" criteria\n :param int start_year: start year to process\n :param int end_year: end year to process\n :param str period: which period to do day/night/all?\n :param bool doQC: incorporate the QC flags or not\n :param bool doBC: work on the bias corrected data\n\n :returns:\n '''\n settings = set_paths_and_vars.set(doBC = doBC, doQC = doQC)\n\n\n # KW Added SUFFIX variable because all hourlies/dailies/monthlies now have suffix 'strict' (4/2 per daily/day-night) \n # or 'relax' (2/1 per daily/day-night)\n if suffix == \"relax\":\n N_OBS_OVER_DAYS = 1 # at least 1 obs at this 3 hr timestamp from 5 days in pentad\n N_OBS_OVER_PENTAD = 2\n\n elif suffix == \"strict\":\n N_OBS_OVER_DAYS = 2\n N_OBS_OVER_PENTAD = 4 # at least 4 timestamps (of 8) in pentad, could be 2 for local 'relax' setting\n\n\n N_OBS_PER_DAY = 24/DELTA_HOUR\n\n for year in np.arange(start_year, end_year + 1): \n\n all_pentads = np.ma.zeros([len(OBS_ORDER), 73, len(grid_lats), len(grid_lons)])\n all_pentads.mask = np.zeros([len(OBS_ORDER), 73, len(grid_lats), len(grid_lons)])\n\n # read in a years worth of 3hrly data\n for v, var in enumerate(OBS_ORDER):\n # arrays too massive to process all variables at once.\n print var.name\n \n var_3hrlys = read_data(settings, suffix, var.name, year, grid_lats, grid_lons, period, N_OBS_PER_DAY)\n\n # reshape to days x 3hrly obs (365(366),8,180,360)\n var_3hrlys = var_3hrlys.reshape(-1, N_OBS_PER_DAY, var_3hrlys.shape[1], var_3hrlys.shape[2])\n\n # process the leap-year if appropriate\n if calendar.isleap(year):\n var_3hrlys, incl_feb29th = process_february(var_3hrlys, doMask = True)\n else:\n assert var_3hrlys.shape[0] == 365\n\n # get pentadly values for each timestep (73,5,8,180,360)\n shape = var_3hrlys.shape\n var_3hrlys = var_3hrlys.reshape(-1, 5, shape[-3], shape[-2], shape[-1]) # n_pentads x days x hrs x lat x lon\n\n n_days_per_timestamp = np.ma.count(var_3hrlys, axis = 1) # n_pentads x hrs x lat x lon\n\n # get average at each timestamp across the pentad - so have N_OBS_PER_DAY averaged values per pentad\n if settings.doMedian:\n pentad_3hrly_grid = utils.bn_median(var_3hrlys, axis = 1) # n_pentads x hrs x lat x lon\n else:\n pentad_3hrly_grid = np.ma.mean(var_3hrlys, axis = 1) # n_pentads x hrs x lat x lon\n\n pentad_3hrly_grid.mask[n_days_per_timestamp < N_OBS_OVER_DAYS] = True # mask where fewer than N_OBS_OVER_DAYS days have values\n \n # clear up memory\n del var_3hrlys\n gc.collect()\n\n # the pentad containing feb 29th is the 11th in the year (KW actually its the 12th, so the 11 in array speak which is what you have done)\n if calendar.isleap(year):\n # overwrite this with the me(di)an of a 6-day pentad\n if settings.doMedian:\n pentad_3hrly_grid[11, :, :, :] = utils.bn_median(incl_feb29th, axis = 0)\n else:\n pentad_3hrly_grid[11, :, :, :] = np.ma.mean(incl_feb29th, axis = 0)\n\n feb_n_days_per_timestamp = np.ma.count(incl_feb29th, axis = 0)\n pentad_3hrly_grid.mask[11, :, :, :][feb_n_days_per_timestamp < N_OBS_OVER_DAYS] = True\n n_days_per_timestamp[11, :, :, :] = feb_n_days_per_timestamp\n\n print \"processed Feb 29th\"\n\n if settings.plots and v == 0:\n import matplotlib.pyplot as plt\n plt.clf()\n plt.hist(n_days_per_timestamp.reshape(-1), bins = np.arange(-1,7), align = \"left\", log = True, rwidth=0.5)\n plt.axvline(x = N_OBS_OVER_DAYS-0.5, color = \"r\") \n plt.title(\"Number of days with obs at each 3hrly timestamp (over entire year)\")\n plt.xlabel(\"Number of days (max = 5)\")\n plt.ylabel(\"Frequency (log scale)\")\n plt.savefig(settings.PLOT_LOCATION + \"pentads_n_days_{}_{}_{}.png\".format(year, period, suffix))\n\n # get single pentad values\n n_hrs_per_pentad = np.ma.count(pentad_3hrly_grid, axis = 1) # get the number of pentad-hours present in each pentad\n n_grids_per_pentad = np.sum(n_days_per_timestamp, axis = 1) # get the number of 3hrly 1x1 grids included per pentad 1x1\n\n # get average at each timestamp across the pentad - so have N_OBS_PER_DAY values per pentad\n if settings.doMedian:\n pentad_grid = utils.bn_median(pentad_3hrly_grid, axis = 1)\n else:\n pentad_grid = np.ma.mean(pentad_3hrly_grid, axis = 1)\n\n if period == \"all\":\n# KW are you sure this should be n_hrs_per_pentad and not n_grids_per_pentad here? I think it should\n pentad_grid.mask[n_hrs_per_pentad < N_OBS_OVER_PENTAD] = True # mask where fewer than N_OBS_OVER_PENTAD hours have values\n else:\n# KW are you sure this should be n_hrs_per_pentad and not n_grids_per_pentad here? I think it should\n pentad_grid.mask[n_hrs_per_pentad < (N_OBS_OVER_PENTAD/2.)] = True # mask where fewer than N_OBS_OVER_PENTAD hours have values\n \n all_pentads[v, :, :, :] = pentad_grid\n\n # diagnostics plots of obs/grids per pentad\n if settings.plots and v == 0:\n plt.clf()\n plt.hist(n_hrs_per_pentad.reshape(-1), bins = np.arange(-1,10), align = \"left\", log = True, rwidth=0.5)\n if period == \"all\":\n plt.axvline(x = N_OBS_OVER_PENTAD-0.5, color = \"r\") \n else:\n plt.axvline(x = (N_OBS_OVER_PENTAD/2.)-0.5, color = \"r\") \n plt.title(\"Number of hrs with obs in each pentad (over entire year)\")\n plt.xlabel(\"Number of days (max = 8)\")\n plt.ylabel(\"Frequency (log scale)\")\n plt.savefig(settings.PLOT_LOCATION + \"pentads_n_hrs_{}_{}_{}.png\".format(year, period, suffix))\n\n # clear up memory\n del pentad_3hrly_grid\n del pentad_grid\n gc.collect()\n\n # done all main variables. Now for number of observations\n print \"n_obs\"\n n_obs = read_data(settings, suffix, \"n_obs\", year, grid_lats, grid_lons, period, N_OBS_PER_DAY)\n\t# KW so we've gone from 8*365hrs,lats,lons to 365,8,lats,lons\n n_obs = n_obs.reshape(-1, N_OBS_PER_DAY, n_obs.shape[1], n_obs.shape[2])\n if calendar.isleap(year):\n n_obs, incl_feb29th = process_february(n_obs, doMask = True)\n else:\n assert n_obs.shape[0] == 365 \n\n shape = n_obs.shape\n\t# KW so we're now at pentads, 5days, 8hours, lats, lons\n n_obs = n_obs.reshape(-1, 5, shape[-3], shape[-2], shape[-1]) # pentads x days x hours x lat x lon\n \n\t# KW This should sum over the 5days leaving pentads, 8hrs, lats, lons\n\t# n_obs has -1 as missing data!!! So sum will not work properly\n\t# set up fill_value as -1\n\tn_obs.fill_value = -1\n n_obs_per_3hrly_pentad = np.ma.sum(n_obs, axis = 1)\n n_obs_per_3hrly_pentad.fill_value = -1\n\n if calendar.isleap(year):\n n_obs_per_3hrly_pentad[11, :, :, :] = np.ma.sum(incl_feb29th, axis = 0)\n\n n_obs_per_pentad = np.ma.sum(n_obs_per_3hrly_pentad, axis = 1)\n\n # and write out\n times = utils.TimeVar(\"time\", \"time since 1/1/{} in hours\".format(year), \"hours\", \"time\")\n times.data = np.arange(0, all_pentads.shape[1]) * 5 * 24\n\n out_filename = settings.DATA_LOCATION + settings.OUTROOT + \"_1x1_pentad_from_3hrly_{}_{}_{}.nc\".format(year, period, suffix)\n \n utils.netcdf_write(out_filename, all_pentads, n_grids_per_pentad, n_obs_per_pentad, OBS_ORDER, grid_lats, grid_lons, times, frequency = \"P\")\n\n\n return # do_conversion\n \n#************************************************************************\nif __name__==\"__main__\":\n\n import argparse\n\n # set up keyword arguments\n parser = argparse.ArgumentParser()\n parser.add_argument('--suffix', dest='suffix', action='store', default = \"relax\",\n help='\"relax\" or \"strict\" completeness, default = relax')\n parser.add_argument('--start_year', dest='start_year', action='store', default = defaults.START_YEAR,\n help='which year to start run, default = 1973')\n parser.add_argument('--end_year', dest='end_year', action='store', default = defaults.END_YEAR,\n help='which year to end run, default = present')\n parser.add_argument('--period', dest='period', action='store', default = \"all\",\n help='which period to run for (day/night/all), default = \"all\"')\n parser.add_argument('--doQC', dest='doQC', action='store_true', default = False,\n help='process the QC information, default = False')\n parser.add_argument('--doBC', dest='doBC', action='store_true', default = False,\n help='process the bias corrected data, default = False')\n args = parser.parse_args()\n\n\n do_conversion(suffix = str(args.suffix), start_year = int(args.start_year), end_year = int(args.end_year), period = str(args.period), doQC = args.doQC, doBC = args.doBC)\n\n# END\n# ************************************************************************\n", "meta": {"hexsha": "701971f83af2545e365091354c8ab5b6a5a168c8", "size": 14757, "ext": "py", "lang": "Python", "max_stars_repo_path": "EUSTACE_SST_MAT/3hrlies_to_pentads.py", "max_stars_repo_name": "Kate-Willett/HadISDH_Marine_Build", "max_stars_repo_head_hexsha": "293b4c89dc6e04e47d3f6e3645cf0f610beca2f2", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EUSTACE_SST_MAT/3hrlies_to_pentads.py", "max_issues_repo_name": "Kate-Willett/HadISDH_Marine_Build", "max_issues_repo_head_hexsha": "293b4c89dc6e04e47d3f6e3645cf0f610beca2f2", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EUSTACE_SST_MAT/3hrlies_to_pentads.py", "max_forks_repo_name": "Kate-Willett/HadISDH_Marine_Build", "max_forks_repo_head_hexsha": "293b4c89dc6e04e47d3f6e3645cf0f610beca2f2", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1432360743, "max_line_length": 173, "alphanum_fraction": 0.6041200786, "include": true, "reason": "import numpy", "num_tokens": 3974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2845759920814681, "lm_q1q2_score": 0.14451106506799444}} {"text": "#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\nSample for Multi Pixel Gibbs MCMC.\n\"\"\"\n\nfrom collections import OrderedDict\n# import pprint\nimport json\nimport numpy as np\n\nimport fsps\n\nfrom astropy.utils.console import ProgressBar\nfrom astropy.table import Table, hstack, Column\n\nfrom sedbot.photconv import micro_jy_to_luminosity\nfrom sedbot.chain import MultiPixelChain\n\n\nMODEL = None\n\n\nclass MultiPixelGibbsBgSampler(object):\n \"\"\"MH-in-Gibbs sampler for three level hierarchical models of\n pixel parameters, global parameters, and a linearly sampled background\n parameter.\n\n Parameters\n ----------\n model_initializer : function\n Function that, when called, creates a model instance.\n This is done to enable multi-processing.\n n_cpu : int\n Number of CPUs to run on.\n \"\"\"\n def __init__(self, model_initializer,\n n_cpu=1):\n super(MultiPixelGibbsBgSampler, self).__init__()\n self._n_cpu = n_cpu\n self._model_initializer = model_initializer\n\n # Set up a local model instance\n self._model = self._model_initializer()\n\n # Set up a pixel compute pool\n self._map = self._init_pixel_compute_pool()\n\n def _init_pixel_compute_pool(self):\n \"\"\"Initialize an ipython.parallel pool for processing pixels.\"\"\"\n # Put the model in the global namespace for parallel processing\n global MODEL\n MODEL = self._model_initializer()\n\n # Setup up the pool\n if self._n_cpu == 1:\n map_fcn = map # single processing\n else:\n map_fcn = None # TODO\n return map_fcn\n\n def sample(self, n_iter,\n theta_prop=None,\n phi_prop=None,\n theta0=None,\n phi0=None,\n B0=None,\n chain=None,\n use_bkg_sample_errors=False):\n \"\"\"Sample for `n_iter` Gibbs steps.\n\n Parameters\n ----------\n n_iter : int\n Number of Gibbs steps (number of full iterations over all\n parameters)\n theta_prop : ndarray\n Standard deviations of Gaussian proposal distribtions for\n theta (pixel) parameters. If any individual proposal sigma is\n zero then that parameter will not be sampled (but instead kept\n constant in the chain).\n phi_prop : ndarray\n Standard deviations of Gaussian proposal distributions for\n phi (global) parameters. Leave as ``None`` to use the model's\n defaults. If any individual proposal sigma is\n zero then that parameter will not be sampled (but instead kept\n constant in the chain).\n theta0 : ndarray\n Initial values for the theta parameters, a ``(n_pix, n_theta)``\n array.\n phi0 : ndarray\n Initial values for the phi parameters, a ``(n_phi)`` array.\n B0 : ndarray\n Initial values for the background, a ``(n_band)`` array.\n Background is in units of flux per arcsec^2.\n chain : :class:`sedbot.chain.MultiPixelChain`\n A previously-built chain, whose last sample will be used\n as the starting points for this sampling (in liue of setting\n `theta0`, `phi0` and `B0` manually).\n use_bkg_sample_errors : bool\n Use sample standard deviation when updating the background.\n \"\"\"\n global MODEL\n\n # Keep these for storage in the HDF5 file later\n self._theta_prop = theta_prop\n self._phi_prop = phi_prop\n\n if chain is not None:\n theta0 = np.empty((self._model.n_pix, self._model.n_theta),\n dtype=np.float)\n for i, n in enumerate(self._model.theta_params):\n theta0[:, i] = chain[n][-1]\n\n phi0 = np.empty(self._model.n_phi, dtype=np.float)\n for i, n in enumerate(self._model.phi_params):\n phi0[i] = chain[n][-1]\n\n B0 = np.empty(self._model.n_bands, dtype=np.float)\n for i, (n, instr) in enumerate(zip(self._model.observed_bands,\n self._model.instruments)):\n name = \"B__{0}__{1}\".format(instr, n)\n B0[i] = chain[name][-1]\n else:\n assert theta0 is not None\n assert phi0 is not None\n assert B0 is not None\n\n # initialize memory\n i0 = self._init_chains(n_iter, theta0, phi0, B0)\n\n with ProgressBar(n_iter) as bar:\n for i in xrange(i0, i0 + n_iter):\n # Sample for all pixels\n args = []\n for ipix in xrange(self._model.n_pix):\n _post0 = self.pix_lnpost[i - 1, ipix]\n _theta0 = self.theta[i - 1, ipix, :]\n _phi0 = self.phi[i - 1, :]\n _B0 = self.B[i - 1, :]\n args.append((ipix, _post0, _theta0, _phi0, _B0,\n theta_prop))\n results = self._map(pixel_mh_sampler, args)\n for ipix, result in enumerate(results):\n lnpost, theta, blob, theta_accept = result\n self.pix_lnpost[i, ipix] = lnpost\n self.theta[i, ipix, :] = theta\n if blob is not None:\n for k, v in blob.iteritems():\n self.blobs[i][k][ipix] = v\n else:\n # repeat previous blob values\n for k in self.blobs.dtype.fields:\n self.blobs[i][k][ipix] = self.blobs[i - 1][k][ipix]\n self._theta_n_accept[ipix, :] += theta_accept\n\n # Update the background\n model_seds = self.blobs[i]['model_sed']\n B_new, global_lnp, pixel_lnp, pixel_blobs \\\n = self._model.update_background(\n self.theta[i, :, :],\n self.phi[i - 1, :],\n model_seds,\n sample_errors=use_bkg_sample_errors)\n self.B[i, :] = B_new\n\n # Sample the global parameters\n phi_new, global_lnp, pixel_lnps, pixel_blobs, n_accept \\\n = self._global_mh(i,\n global_lnp,\n self.phi[i - 1, :],\n self.theta[i, :, :],\n self.B[i, :],\n phi_prop)\n # fill in new values to chain.\n self.phi[i, :] = phi_new\n self.lnpost[i] = global_lnp\n self._phi_n_accept += n_accept\n # Update ln post and blob data for all pixels too\n # it was done for the pixel-only step, but these values have\n # changed given the new background, etc.\n if pixel_lnps is not None:\n for ipix, lnp in enumerate(pixel_lnps):\n self.pix_lnpost[i, ipix] = lnp\n if pixel_blobs is not None:\n for ipix, blobs in enumerate(pixel_blobs):\n for k, v in blobs.iteritems():\n self.blobs[i][k][ipix] = v\n\n bar.update()\n\n def _global_mh(self, i, lnpost0, phi, theta, B, phi_prop):\n \"\"\"Perform MH-in-Gibbs at the global level.\"\"\"\n phi = np.copy(phi)\n lnpost = lnpost0\n lnpost_pixel = None\n blobs = None\n n_accept = np.zeros(phi.shape[0], dtype=np.int)\n for j in xrange(phi.shape[0]):\n # Gaussian proposal for parameter j, only\n # Skip parameter advancement if proposal sigma is zero.\n if phi_prop[j] > 0.:\n phi_new = np.copy(phi)\n phi_new[j] += phi_prop[j] * np.random.randn()\n global_lnp, pixel_lnp, pixel_blobs \\\n = self._model.sample_global(theta,\n phi_new,\n B)\n ln_r = global_lnp - lnpost0\n reject = True\n if ~np.isfinite(ln_r):\n pass\n elif ln_r >= 0.:\n reject = False\n else:\n x = np.random.random_sample()\n if x < np.exp(ln_r):\n reject = False\n if not reject:\n # adopt new point\n phi = phi_new\n lnpost = global_lnp\n lnpost_pixel = pixel_lnp\n blobs = pixel_blobs\n n_accept[j] = 1\n return phi, lnpost, lnpost_pixel, blobs, n_accept\n\n def _init_chains(self, n_iter, theta0, phi0, B0):\n \"\"\"Initialize memory\n\n Note this could be adapted to extend existing chains.\n \"\"\"\n # Make parameter chains\n self.theta = np.empty((n_iter + 1,\n self._model.n_pix,\n self._model.n_theta),\n dtype=np.float)\n self.theta.fill(np.nan)\n self.theta[0, :, :] = theta0\n\n self.phi = np.empty((n_iter + 1,\n self._model.n_phi),\n dtype=np.float)\n self.phi.fill(np.nan)\n self.phi[0, :] = phi0\n\n self.B = np.empty((n_iter + 1,\n self._model.n_bands),\n dtype=np.float)\n self.B.fill(np.nan)\n self.B[0, :] = B0\n\n self.lnpost = np.empty(n_iter + 1, dtype=np.float)\n self.lnpost.fill(np.nan)\n\n self.pix_lnpost = np.empty((n_iter + 1, self._model.n_pix),\n dtype=np.float)\n self.pix_lnpost.fill(np.nan)\n\n # Make a structured array for the complex blob data\n self.blobs = np.empty(n_iter + 1, dtype=self._model.blob_dtype)\n self.blobs.fill(np.nan)\n\n # Initialize the starting point of the chains\n global_lnp, pixel_lnp, pixel_blobs \\\n = self._model.sample_global(theta0, phi0, B0)\n self.lnpost[0] = global_lnp\n for ipix, lnp in enumerate(pixel_lnp):\n self.pix_lnpost[0, ipix] = lnp\n for ipix, blobs in enumerate(pixel_blobs):\n for k, v in blobs.iteritems():\n self.blobs[0][k][ipix] = v\n\n # Track acceptance of individual parameters for each pixel\n self._theta_n_accept = np.zeros((self._model.n_pix,\n self._model.n_theta),\n dtype=np.int)\n self._phi_n_accept = np.zeros(self._model.n_phi, dtype=np.int)\n\n return 1\n\n @property\n def median_theta_faccept(self):\n \"\"\"Median acceptance fraction across all pixels for each parameter\"\"\"\n n_samples = float(self.theta.shape[0])\n faccept = np.median(self._theta_n_accept / n_samples, axis=0)\n return faccept\n\n @property\n def phi_faccept(self):\n \"\"\"Acceptance fraction of phi parameters.\"\"\"\n n_samples = float(self.theta.shape[0])\n return self._phi_n_accept / n_samples\n\n def print_faccept(self):\n \"\"\"Printed report of the acceptance fraction statistics\"\"\"\n faccept = self.median_theta_faccept\n d = OrderedDict(zip(self._model.theta_params, faccept))\n # pp = pprint.PrettyPrinter(indent=4)\n # pp.pprint(d)\n print(\"theta\")\n print(json.dumps(d, indent=4))\n print(\"phi\")\n d = OrderedDict(zip(self._model.phi_params, self.phi_faccept))\n print(json.dumps(d, indent=4))\n\n @property\n def table(self):\n \"\"\"An :class:`astropy.table.Table` with the chain.\"\"\"\n msuns = np.array([fsps.get_filter(n).msun_ab\n for n in self._model.computed_bands])\n theta_f_accept = json.dumps(dict(zip(self._model.theta_params,\n self.median_theta_faccept)))\n phi_f_accept = json.dumps(dict(zip(self._model.phi_params,\n self.phi_faccept)))\n meta = OrderedDict((\n ('theta_f_accept', theta_f_accept),\n ('phi_f_accept', phi_f_accept),\n ('observed_bands', self._model.observed_bands),\n ('instruments', self._model.instruments),\n ('computed_bands', self._model.computed_bands),\n ('msun_ab', msuns),\n ('band_indices', self._model.band_indices),\n ('theta_params', self._model.theta_params),\n ('phi_params', self._model.phi_params),\n ('theta_proposal_sigma', self._theta_prop),\n ('phi_proposal_sigma', self._theta_prop),\n ('sed', self._model._seds),\n ('sed_err', self._model._errs),\n ('pixels', self._model.pixel_metadata),\n ('area', self._model._areas)))\n # Make tables for individual chains; stack later\n # FIXME should axis order be changed for theta throughout the sampler?\n # or I can just continue to swarp aces here\n theta_table = Table(np.swapaxes(self.theta, 1, 2),\n names=self._model.theta_params,\n meta=meta)\n phi_table = Table(self.phi, names=self._model.phi_params)\n background_names = [\"B__{0}__{1}\".format(n, b)\n for n, b in zip(self._model.instruments,\n self._model.observed_bands)]\n B_table = Table(self.B, names=background_names)\n blob_table = Table(self.blobs)\n tbl = MultiPixelChain(hstack((theta_table,\n phi_table,\n B_table,\n blob_table)))\n\n # Add M/L computations for each computed band.\n for i, (band_name, msun) in enumerate(zip(self._model.computed_bands,\n msuns)):\n logLsol = micro_jy_to_luminosity(tbl['model_sed'][:, :, i],\n msun,\n np.atleast_2d(tbl['d']).T)\n ml = tbl['logMstar'] - logLsol\n colname = \"logML_{0}\".format(band_name)\n tbl.add_column(Column(name=colname, data=ml))\n\n return tbl\n\n\ndef pixel_mh_sampler(args):\n \"\"\"Execute MH-in-Gibbs sampling for a single pixel.\n\n This function is design to be called by a ``map`` function, hence all\n arguments are wrapped in a single tuple, ``args``.\n\n Parameters\n ----------\n ipix : int\n Pixel index\n post0 : float\n Ln Posterior probability *for the pixel* given initial values of\n theta0 and phi0.\n theta0 : ndarray\n Initial values of theta parameters.\n phi0 : ndarray\n Initial values of the phi parameters.\n B0 : ndarray\n Initial values of the B, background, parameters.\n theta_prop : ndarray\n Array of Gaussian proposal standard deviations. If an individual\n proposal sigma is zero then that value will not be sampled,\n and kept constant.\n\n Returns\n -------\n post : float\n Final posterior probability *for this pixel*.\n theta : ndarray\n Theta parameters from this Gibbs step.\n blob : dict\n Stellar population metadata for this pixel given the updated `theta`\n parameters.\n n_accept : ndarray\n Array of length ``n_theta`` whose values are 1 for parameters\n that were updated, and zeros for values that remain constant from\n the previous iteration.\n \"\"\"\n global MODEL\n ipix, post0, theta0, phi0, B0, theta_prop = args\n theta = np.copy(theta0)\n post = post0\n # MH on each parameter\n blob = None\n n_accept = np.zeros(theta.shape[0], dtype=np.int)\n for i in xrange(theta0.shape[0]):\n # Gaussian proposal for parameter i, only\n if theta_prop[i] > 0.:\n theta_new = theta.copy()\n theta_new[i] += theta_prop[i] * np.random.randn()\n lnpost_new, blob_new = MODEL.sample_pixel(theta_new,\n phi0, B0, ipix)\n ln_r = lnpost_new - post\n # print \"pix {0:d} param {1:d} ln_r {2:.2f}\".format(ipix, i, ln_r),\n reject = True\n if ~np.isfinite(ln_r):\n # print \" reject ln_r not finite\"\n pass\n elif ln_r >= 0.:\n # print \" accepted\".format(ipix, i)\n reject = False\n else:\n x = np.random.random_sample()\n if x < np.exp(ln_r):\n # print \" accept {0:.2f} < r\".format(x)\n reject = False\n # else:\n # print \" reject {0:.2f} > r\".format(x)\n if not reject:\n # adopt new point\n theta = theta_new\n blob = blob_new\n post = lnpost_new\n n_accept[i] = 1\n return post, theta, blob, n_accept\n", "meta": {"hexsha": "eb43f60fae57ab303880e1bb45a5e33c18236af3", "size": 17235, "ext": "py", "lang": "Python", "max_stars_repo_path": "sedbot/multipix/sampler.py", "max_stars_repo_name": "jonathansick/sedbot", "max_stars_repo_head_hexsha": "3114ebb36a8618800b3b556fe1a63372b4b5e054", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sedbot/multipix/sampler.py", "max_issues_repo_name": "jonathansick/sedbot", "max_issues_repo_head_hexsha": "3114ebb36a8618800b3b556fe1a63372b4b5e054", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sedbot/multipix/sampler.py", "max_forks_repo_name": "jonathansick/sedbot", "max_forks_repo_head_hexsha": "3114ebb36a8618800b3b556fe1a63372b4b5e054", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4393592677, "max_line_length": 79, "alphanum_fraction": 0.5266028431, "include": true, "reason": "import numpy,from astropy", "num_tokens": 3745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.2720245628973633, "lm_q1q2_score": 0.1445019975989783}} {"text": "\"\"\"\n(c) RIKEN 2015. All rights reserved. \nAuthor: Keitaro Yamashita\n\nThis software is released under the new BSD License; see LICENSE.\n\"\"\"\nimport numpy\nimport itertools\nfrom yamtbx.dataproc.xds import get_xdsinp_keyword\nfrom yamtbx.util import safe_float\n\nclass XPARM:\n def __init__(self, xparm_file=None):\n if xparm_file is not None:\n self.parse_xparm_file(xparm_file)\n else:\n self.starting_frame = 1\n self.starting_angle = 0.\n self.osc_range = -1.\n self.rotation_axis = numpy.array((1.,0.,0.))\n self.wavelength = -1.\n self.incident_beam = numpy.array((0.,0.,1.))\n self.nx, self.ny = 0, 0\n self.qx, self.qy = 0., 0.\n self.distance = 0.\n self.origin = numpy.array((0., 0.))\n self.X_axis = numpy.array((1., 0., 0.))\n self.Y_axis = numpy.array((0., 1., 0.))\n self.Z_axis = numpy.array((0., 0., 1.))\n self.spacegroup = 1\n self.unit_cell = numpy.array((100., 100., 100., 90., 90., 90.))\n self.a_axis = numpy.array((100., 0., 0.))\n self.b_axis = numpy.array((0., 100., 0.))\n self.c_axis = numpy.array((0., 0., 100.))\n # __init__()\n\n def space_group_info(self):\n from cctbx import sgtbx\n g = sgtbx.space_group_info(self.spacegroup).group()\n return g.info()\n\n def parse_xparm_file(self, xparm_file):\n lines = open(xparm_file).readlines()\n\n is_new_format = \"XPARM.XDS\" in lines[0]\n\n if not is_new_format:\n starting_frame, starting_angle, osc_range, rotx, roty, rotz = lines[0].split()\n wavelength, ibeamx, ibeamy, ibeamz = lines[1].split()\n nx, ny, qx, qy = lines[2].split()\n distance, orgx, orgy = lines[3].split()\n Xx, Xy, Xz = lines[4].split()\n Yx, Yy, Yz = lines[5].split()\n Zx, Zy, Zz = lines[6].split()\n spacegroup, a, b, c, alpha, beta, gamma = lines[7].split()\n ax, ay, az = lines[8].split()\n bx, by, bz = lines[9].split()\n cx, cy, cz = lines[10].split()\n else:\n starting_frame, starting_angle, osc_range, rotx, roty, rotz = lines[1].split()\n wavelength, ibeamx, ibeamy, ibeamz = lines[2].split()\n spacegroup, a, b, c, alpha, beta, gamma = lines[3].split()\n ax, ay, az = lines[4][:15], lines[4][15:30], lines[4][30:45]\n bx, by, bz = lines[5][:15], lines[5][15:30], lines[5][30:45]\n cx, cy, cz = lines[6][:15], lines[6][15:30], lines[6][30:45]\n nseg, nx, ny, qx, qy = lines[7].split()\n orgx, orgy, distance = lines[8].split()\n Xx, Xy, Xz = lines[9].split()\n Yx, Yy, Yz = lines[10].split()\n Zx, Zy, Zz = lines[11].split()\n\n self.starting_frame = int(starting_frame)\n self.starting_angle = float(starting_angle)\n self.osc_range = float(osc_range)\n self.rotation_axis = numpy.array((float(rotx), float(roty), float(rotz)))\n self.wavelength = float(wavelength)\n self.incident_beam = numpy.array((float(ibeamx), float(ibeamy), float(ibeamz)))\n self.nx = float(nx)\n self.ny = float(ny)\n self.qx = float(qx)\n self.qy = float(qy)\n self.distance = float(distance)\n self.origin = numpy.array((float(orgx), float(orgy)))\n self.X_axis = numpy.array((float(Xx), float(Xy), float(Xz)))\n self.Y_axis = numpy.array((float(Yx), float(Yy), float(Yz)))\n self.Z_axis = numpy.array((float(Zx), float(Zy), float(Zz)))\n self.spacegroup = int(spacegroup)\n self.unit_cell = numpy.array((float(a), float(b), float(c), float(alpha), float(beta), float(gamma)))\n self.a_axis = numpy.array(map(safe_float, (ax, ay, az)))\n self.b_axis = numpy.array(map(safe_float, (bx, by, bz)))\n self.c_axis = numpy.array(map(safe_float, (cx, cy, cz)))\n # parse_xparm_file()\n\n def set_info_from_xdsinp(self, xdsinp):\n # XXX x, y, z axes\n\n table = [(\"STARTING_FRAME\", \"starting_frame\", lambda x: int(x)),\n (\"STARTING_ANGLE\", \"starting_angle\", lambda x: float(x)),\n (\"OSCILLATION_RANGE\", \"osc_range\", lambda x: float(x)),\n (\"ROTATION_AXIS\", \"rotation_axis\", lambda x: numpy.array(map(lambda y:float(y), x.split()))),\n (\"X-RAY_WAVELENGTH\", \"wavelength\", lambda x: float(x)),\n (\"INCIDENT_BEAM_DIRECTION\", \"incident_beam\", lambda x: numpy.array(map(lambda y:float(y), x.split()))),\n (\"NX\", \"nx\", lambda x: int(x)),\n (\"NY\", \"ny\", lambda x: int(x)),\n (\"QX\", \"qx\", lambda x: float(x)),\n (\"QY\", \"qy\", lambda x: float(x)),\n (\"DETECTOR_DISTANCE\", \"distance\", lambda x: float(x)),\n (\"SPACE_GROUP_NUMBER\", \"spacegroup\", lambda x: int(x)),\n (\"UNIT_CELL_CONSTANTS\", \"unit_cell\", lambda x: numpy.array(map(lambda y:float(y), x.split()))),\n (\"UNIT_CELL_A-AXIS\", \"a_axis\", lambda x: numpy.array(map(lambda y:float(y), x.split()))),\n (\"UNIT_CELL_B-AXIS\", \"b_axis\", lambda x: numpy.array(map(lambda y:float(y), x.split()))),\n (\"UNIT_CELL_C-AXIS\", \"c_axis\", lambda x: numpy.array(map(lambda y:float(y), x.split())))\n ]\n inp = dict(get_xdsinp_keyword(xdsinp)) # I believe dict() removes duplicated parameters and keeps last.\n\n for k, at, f in table:\n if k in inp and inp[k].strip() != \"\":\n setattr(self, at, f(inp[k]))\n if \"ORGX\" in inp:\n self.origin[0] = float(inp[\"ORGX\"])\n if \"ORGY\" in inp:\n self.origin[1] = float(inp[\"ORGY\"])\n # set_info_from_xdsinp()\n\n def xparm_str(self, old_format=False):\n assert not old_format # Currently, only new format is supported!\n xparm_str = \"\"\" XPARM.XDS VERSION March 30, 2013\n%6d%14.4f%10.4f%10.6f%10.6f%10.6f\n%15.6f%15.6f%15.6f%15.6f\n%6d%12.6f%12.6f%12.6f%8.3f%8.3f%8.3f\n%15.6f%15.6f%15.6f\n%15.6f%15.6f%15.6f\n%15.6f%15.6f%15.6f\n%10d%10d%10d%12.6f%12.6f\n%15.6f%15.6f%15.6f\n%15.6f%15.6f%15.6f\n%15.6f%15.6f%15.6f\n%15.6f%15.6f%15.6f\n%10d%10d%10d%10d%10d\n%8.2f%8.2f%8.2f%9.5f%9.5f%9.5f%9.5f%9.5f%9.5f\n\"\"\" % (self.starting_frame, self.starting_angle, self.osc_range, self.rotation_axis[0], self.rotation_axis[1], self.rotation_axis[2], \n self.wavelength, self.incident_beam[0], self.incident_beam[1], self.incident_beam[2], \n self.spacegroup, self.unit_cell[0], self.unit_cell[1], self.unit_cell[2], self.unit_cell[3], self.unit_cell[4], self.unit_cell[5],\n self.a_axis[0], self.a_axis[1], self.a_axis[2], \n self.b_axis[0], self.b_axis[1], self.b_axis[2], \n self.c_axis[0], self.c_axis[1], self.c_axis[2],\n 1, self.nx, self.ny, self.qx, self.qy,\n self.origin[0], self.origin[1], self.distance, \n self.X_axis[0], self.X_axis[1], self.X_axis[2], \n self.Y_axis[0], self.Y_axis[1], self.Y_axis[2], \n self.Z_axis[0], self.Z_axis[1], self.Z_axis[2], \n 1, 1, self.nx, 1, self.ny,\n 0., 0., 0., 1., 0., 0., 0., 1., 0.,\n )\n return xparm_str\n # xparm_str()\n\n def crystal_symmetry(self):\n from cctbx import crystal\n return crystal.symmetry(tuple(self.unit_cell),\n self.spacegroup)\n # crystal_symmetry()\n\n def update_cell_based_on_axes(self):\n from yamtbx.util.maths import vectors_angle\n\n a, b, c = map(lambda x: numpy.linalg.norm(x), (self.a_axis, self.b_axis, self.c_axis))\n al = vectors_angle(self.b_axis, self.c_axis)\n be = vectors_angle(self.c_axis, self.a_axis)\n ga = vectors_angle(self.a_axis, self.b_axis)\n al, be, ga = map(lambda x: numpy.rad2deg(x), (al, be, ga))\n \n self.unit_cell = numpy.array((a,b,c,al,be,ga))\n print \n# class XPARM\n\n\ndef get_xparm_from_integrate_lp(lpfile, frame):\n assert 0 < frame\n\n keys = {\"beam direction\": \"DIRECT BEAM COORDINATES (REC. ANGSTROEM)\",\n \"beam center\": \"DETECTOR ORIGIN (PIXELS) AT\",\n \"distance\": \"CRYSTAL TO DETECTOR DISTANCE (mm)\",\n \"rotation axis\": \"LAB COORDINATES OF ROTATION AXIS\",\n \"a axis\": \"COORDINATES OF UNIT CELL A-AXIS\",\n \"b axis\": \"COORDINATES OF UNIT CELL B-AXIS\",\n \"c axis\": \"COORDINATES OF UNIT CELL C-AXIS\",\n \"cell\": \"UNIT CELL PARAMETERS\",\n \"spacegroup\": \"SPACE GROUP NUMBER\"\n }\n data = {}\n \n flag_read = False\n for l in open(lpfile):\n if \"PROCESSING OF IMAGES\" in l:\n flag_read = False\n l = l.strip()\n first, last = map(lambda x:int(x.strip()), l[l.index(\"PROCESSING OF IMAGES\")+len(\"PROCESSING OF IMAGES\"):].split(\"...\"))\n if first <= frame <= last:\n flag_read = True\n\n if flag_read:\n for key, s in keys.items():\n if s in l:\n l = l.strip()\n val = map(lambda x:float(x.strip()), l[l.index(s)+len(s):].split())\n data[key] = val\n\n beam = data[\"beam direction\"]\n rotaxis = data[\"rotation axis\"]\n distance = data[\"distance\"][0]\n orgx, orgy = data[\"beam center\"]\n spacegroup = data[\"spacegroup\"][0]\n a, b, c, alpha, beta, gamma = data[\"cell\"]\n aaxis = data[\"a axis\"]\n baxis = data[\"b axis\"]\n caxis = data[\"c axis\"]\n\n xp = XPARM(\"XPARM.XDS\")\n\n xp.rotation_axis = numpy.array(rotaxis)\n xp.incident_beam = numpy.array(beam)\n xp.spacegroup = spacegroup\n xp.unit_cell = numpy.array((a, b, c, alpha, beta, gamma))\n xp.a_axis = numpy.array(aaxis)\n xp.b_axis = numpy.array(baxis)\n xp.c_axis = numpy.array(caxis)\n xp.origin = numpy.array((orgx, orgy))\n xp.distance = distance\n\n return xp.xparm_str()\n# get_xparm_from_integrate_lp()\n\n\ndef find_best_ucaxes_transform(xparm1, xparm2):\n \"\"\"\n Reference: matrix iteration method in whirligig in CrystFEL-0.6.0 src/whirligig.c: gatinator()\n\n calculates the matrix m, which gives the best result; axes1 and m * axes2\n returns m, axes1, axes2, rms\n \"\"\"\n\n a1, b1, c1 = xparm1.a_axis, xparm1.b_axis, xparm1.c_axis\n a2, b2, c2 = xparm2.a_axis, xparm2.b_axis, xparm2.c_axis\n\n P = numpy.vstack([a2, b2, c2])\n Q = numpy.vstack([a1, b1, c1])\n\n min_score = numpy.inf\n best_mat = None\n\n for x in itertools.product(xrange(-1,2), repeat=9):\n #if x != (1,0,0,0,1,0,0,0,1): continue\n m = numpy.array(x).reshape(3,3)\n if numpy.linalg.det(m) != 1: continue\n #print \"Trying\"\n #print m\n\n score = numpy.sum((numpy.dot(m, Q) - P)**2)\n #if x == (1,0,0,0,1,0,0,0,1): print score\n if score < min_score:\n min_score = score\n best_mat = m\n\n return best_mat, Q, P, numpy.sqrt(min_score/3.)\n# find_best_ucaxes_transform()\n", "meta": {"hexsha": "e23f74093977d7c7393f496c843f56d425742f78", "size": 10940, "ext": "py", "lang": "Python", "max_stars_repo_path": "yamtbx/dataproc/xds/xparm.py", "max_stars_repo_name": "harumome/kamo", "max_stars_repo_head_hexsha": "060e6fbd9c5a30f86065cec7807ad3449027607e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "yamtbx/dataproc/xds/xparm.py", "max_issues_repo_name": "harumome/kamo", "max_issues_repo_head_hexsha": "060e6fbd9c5a30f86065cec7807ad3449027607e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "yamtbx/dataproc/xds/xparm.py", "max_forks_repo_name": "harumome/kamo", "max_forks_repo_head_hexsha": "060e6fbd9c5a30f86065cec7807ad3449027607e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9737827715, "max_line_length": 137, "alphanum_fraction": 0.5696526508, "include": true, "reason": "import numpy", "num_tokens": 3324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.2720245510940225, "lm_q1q2_score": 0.14450199536662195}} {"text": "# coding=utf-8\n# Copyright 2021 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\n\"\"\"Functions related to sampling from a model.\"\"\"\n\nimport jax\nimport jax.nn\nimport jax.numpy as jnp\nfrom absl import logging\nfrom flax.training import common_utils\nfrom jax import lax, random\n\nLARGE_NEGATIVE = -1e12\n\n\ndef multinomial(rng, logits):\n \"\"\"Draws samples from a multinomial distribution.\n\n Args:\n rng: A jax.random.PRNGKey.\n logits: An array of shape (..., num_categories) containing unnormalized\n log-probabilities.\n\n Returns:\n An array of shape (...) containing sampled category indices.\n \"\"\"\n probs = jax.nn.softmax(logits)\n probs = jnp.cumsum(probs, axis=-1)\n a = jax.random.uniform(rng, logits.shape[:-1] + (1,))\n out = jnp.argmin(a > probs, axis=-1)\n return out\n\n\ndef apply_repetition_penalty(\n sequences,\n logits,\n i,\n repetition_penalty,\n repetition_window,\n repetition_penalty_normalize,\n):\n \"\"\"Apply repetition penalty.\n\n Repetition penalty is introduced in Section 4.1. of the\n [CTRL paper](https://einstein.ai/presentations/ctrl.pdf).\n\n It involves reducing the logits corresponding to previously generated tokens.\n Given a list of generated tokens g, the next token probability is given by:\n\n p_{i + 1} propto exp(logit_i / (T * I_i))\n\n where I_i = repetition_penalty, if i in g,\n 1, otherwise.\n\n Args:\n sequences: An array of shape (batch_size, max_seq_len) with the sequences.\n logits: An array of shape (batch_size, vocab_size) with next token logits.\n i: An array of shape () with the current sequence positions.\n repetition_penalty: A float indicating the repetition penalty.\n repetition_window: An int indicating the window size for repetition penalty.\n We reduce the probability of tokens that have been generated within\n repetition_window tokens prior to the token to be generated.\n repetition_penalty_normalize: A bool indicating whether to normalize\n the logits (log_softmax) before applying the repetition penalty. This\n ensures that all logits have the same sign.\n\n Returns:\n An array of shape (batch_size, vocab_size) with updated next token logits.\n \"\"\"\n max_i = i # We are currently generating a token for position i + 1.\n min_i = i - repetition_window + 1\n batch_size, vocab_size = logits.shape\n positions = jnp.arange(sequences.shape[1])\n positions = jnp.tile(\n positions[jnp.newaxis, :, jnp.newaxis], [batch_size, 1, vocab_size]\n )\n sequences_onehot = jnp.eye(vocab_size)[sequences]\n sequences_onehot = jnp.where(\n (positions >= min_i) * (positions <= max_i),\n sequences_onehot,\n jnp.zeros_like(sequences_onehot),\n )\n # Compute the indicator that a token appeared at least once in the\n # repetition window. Output shape: (batch_size, vocab_size).\n indicator = jnp.max(sequences_onehot, axis=1)\n # Compute a penalty tensor. The logits are divided by the penalty tensor.\n penalty_tensor = jnp.where(\n indicator, jnp.ones_like(logits) * repetition_penalty, jnp.ones_like(logits)\n )\n if repetition_penalty_normalize:\n logits = jax.nn.log_softmax(logits)\n # Dividing a negative logit by the penalty tensor actually increases the\n # resulting probability. Take the inverse for negative logits.\n penalty_tensor = jnp.where(logits > 0, penalty_tensor, 1 / penalty_tensor)\n\n logits = logits / penalty_tensor\n return logits\n\n\ndef temperature_sample(\n prompt,\n init_cache,\n tokens_to_logits,\n temperature=1.0,\n top_k=None,\n repetition_penalty=1,\n repetition_window=4,\n repetition_penalty_normalize=False,\n max_decode_len=512,\n rng=None,\n eos_token=None,\n pad_token=None,\n masked_tokens=None,\n use_lax_while_loop=True,\n):\n \"\"\"Temperature sampling for sequence models.\n\n Args:\n prompt: An array of shape (batch_size, prompt_length) containing the input\n prompt (the model consumes these tokens and starts generation after). For\n generic sampling, the prompt must be a single BOS token.\n init_cache: A flax.nn.attention.Cache object.\n tokens_to_logits: A fast autoregressive decoder function taking single token\n slices and the cache and returning next-token logits and updated cache.\n temperature: A float with the sampling temperature factor. As it approaches\n zero this sampling procedure becomes equivalent to greedy sampling.\n top_k: An int with the number of high probability tokens to keep for\n sampling. If None, keep all.\n repetition_penalty: A float with the repetition penalty. Values smaller\n (greater) than 1 encourage (discourage) repetition; 1 disables penalties.\n repetition_window: An int indicating the window size for repetition penalty.\n We reduce the probability of tokens that have been generated within\n repetition_window tokens prior to the token to be generated.\n repetition_penalty_normalize: A bool indicating whether to normalize the\n logits (log_softmax) before applying the repetition penalty. This ensures\n that all logits have the same sign.\n max_decode_len: An int indicating the maximum sequence length.\n rng: A jax.random.PRNGKey.\n eos_token: An int token id. If not None, we stop decoding a sequence after\n the first instance.\n pad_token: An int token used to pad sequences after the eos token. If none,\n we set pad_token to eos_token.\n masked_tokens: A list of int token id. If not None, we mask these token\n before sampling.\n use_lax_while_loop: A bool; whether to use a lax while loop or python loop.\n\n Returns:\n An array of shape (batch_size, max_decode_len) containing sequences. If\n variable-length, the sequences are right-padded with the EOS token.\n \"\"\"\n batch_size = prompt.shape[0]\n eos_token = eos_token if eos_token is not None else -1\n if pad_token is None:\n logging.warn(\"Pad token is not provided. Using the EOS token.\")\n pad_token = pad_token if pad_token is not None else eos_token\n end_marker = jnp.array(eos_token)\n temperature = jnp.array(temperature)\n\n # Initialize sampling loop state.\n rng0 = rng if rng is not None else random.PRNGKey(0)\n i0 = jnp.array(0)\n ended0 = jnp.zeros((batch_size, 1)).astype(jnp.bool_)\n\n # Initialize sequences with the prompt followed by the out_of_prompt_marker to\n # indicate when we can start generation.\n out_of_prompt_marker = jnp.array(-2)\n pad = (\n jnp.ones((batch_size, max_decode_len - prompt.shape[1]), dtype=jnp.int32)\n * out_of_prompt_marker\n )\n sequences0 = jnp.concatenate([prompt, pad], axis=1)\n token0 = sequences0[:, 0:1]\n\n # Sampling loop state is stored in a simple tuple.\n tokens_to_logits_state = None\n\n sampling_loop_init_state = (\n i0,\n sequences0,\n init_cache,\n token0,\n ended0,\n rng0,\n tokens_to_logits_state,\n )\n\n def sampling_loop_cond_fn(state):\n \"\"\"Sampling loop termination condition.\"\"\"\n (i, _, _, _, ended, _, _) = state\n # Have we reached max decoding length?\n not_at_end = i <= max_decode_len\n # Have all sampled sequences reached an end marker?\n all_sequences_ended = jnp.all(ended)\n return not_at_end & (~all_sequences_ended)\n\n def sampling_loop_body_fn(state):\n \"\"\"Sampling loop state update.\"\"\"\n i, sequences, cache, cur_token, ended, rng, tokens_to_logits_state = state\n\n # Split RNG for sampling.\n rng1, rng2 = random.split(rng)\n\n # Call fast-decoder model on current tokens to get raw next-position logits.\n logits, new_cache, new_tokens_to_logits_state = tokens_to_logits(\n cur_token, cache, internal_state=tokens_to_logits_state\n )\n logits = logits / temperature\n\n # Mask out the BOS token.\n if masked_tokens is not None:\n mask = common_utils.onehot(\n jnp.array(masked_tokens),\n num_classes=logits.shape[-1],\n on_value=LARGE_NEGATIVE,\n )\n mask = jnp.sum(mask, axis=0)[None, :] # Combine multiple masks together\n logits = logits + mask\n\n # Apply the repetition penalty.\n if repetition_penalty != 1:\n logits = apply_repetition_penalty(\n sequences,\n logits,\n i,\n repetition_penalty=repetition_penalty,\n repetition_window=repetition_window,\n repetition_penalty_normalize=repetition_penalty_normalize,\n )\n\n # Mask out everything but the top-k entries.\n if top_k is not None:\n # Compute top_k_index and top_k_threshold with shapes (batch_size, 1).\n top_k_index = jnp.argsort(logits, axis=-1)[:, ::-1][:, top_k - 1 : top_k]\n top_k_threshold = jnp.take_along_axis(logits, top_k_index, axis=-1)\n logits = jnp.where(\n logits < top_k_threshold, jnp.full_like(logits, LARGE_NEGATIVE), logits\n )\n # Sample next token from logits.\n sample = multinomial(rng1, logits)\n next_token = sample.astype(jnp.int32)\n # Only use sampled tokens if we have past the out_of_prompt_marker.\n out_of_prompt = sequences[:, i + 1] == out_of_prompt_marker\n next_token = next_token * out_of_prompt + sequences[:, i + 1] * ~out_of_prompt\n # If end-marker reached for batch item, only emit padding tokens.\n next_token = next_token[:, None]\n next_token_or_endpad = jnp.where(\n ended, jnp.full_like(next_token, pad_token), next_token\n )\n ended |= next_token_or_endpad == end_marker\n # Add current sampled tokens to recorded sequences.\n new_sequences = lax.dynamic_update_slice(\n sequences, next_token_or_endpad, (0, i + 1)\n )\n return (\n i + 1,\n new_sequences,\n new_cache,\n next_token_or_endpad,\n ended,\n rng2,\n new_tokens_to_logits_state,\n )\n\n # Run sampling loop and collect final state.\n if use_lax_while_loop:\n final_state = lax.while_loop(\n sampling_loop_cond_fn, sampling_loop_body_fn, sampling_loop_init_state\n )\n else:\n final_state = sampling_loop_init_state\n while sampling_loop_cond_fn(final_state):\n final_state = sampling_loop_body_fn(final_state)\n\n final_sequences = final_state[1]\n # If generation ended early (all sampled sequences reached an end marker)\n # replace all remaining out_of_prompt_marker instances with the pad_token.\n final_sequences = jnp.where(\n final_sequences == out_of_prompt_marker,\n jnp.full_like(final_sequences, pad_token),\n final_sequences,\n )\n return final_sequences\n", "meta": {"hexsha": "38fa121517333f927c7b6d7a6bae01ee90a26cc0", "size": 11540, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sampling.py", "max_stars_repo_name": "SauravMaheshkar/Protein-Modeling", "max_stars_repo_head_hexsha": "cf64b4c41fa959f5357f2f997d2dfe0ed0bb88a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-16T08:40:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T08:40:17.000Z", "max_issues_repo_path": "src/sampling.py", "max_issues_repo_name": "SauravMaheshkar/Protein-Modeling", "max_issues_repo_head_hexsha": "cf64b4c41fa959f5357f2f997d2dfe0ed0bb88a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-01-16T10:00:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T11:34:01.000Z", "max_forks_repo_path": "src/sampling.py", "max_forks_repo_name": "SauravMaheshkar/Protein-Modeling", "max_forks_repo_head_hexsha": "cf64b4c41fa959f5357f2f997d2dfe0ed0bb88a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9864864865, "max_line_length": 87, "alphanum_fraction": 0.67694974, "include": true, "reason": "import jax,from jax", "num_tokens": 2573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.2720245569956929, "lm_q1q2_score": 0.14450199446395567}} {"text": "#! /usr/bin/env python3\n#\n# Copyright 2018 California Institute of Technology\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# ISOFIT: Imaging Spectrometer Optimal FITting\n# Author: David R Thompson, david.r.thompson@jpl.nasa.gov\n#\n\nfrom sys import platform\nimport json\nimport os\nimport re\nimport scipy as s\nfrom common import json_load_ascii, combos, VectorInterpolator\nfrom common import recursive_replace\nfrom copy import deepcopy\nfrom scipy.stats import norm as normal\nfrom scipy.interpolate import interp1d\nfrom rt_lut import TabularRT, FileExistsError\n\neps = 1e-5 # used for finite difference derivative calculations\n\n\nclass ModtranRT(TabularRT):\n \"\"\"A model of photon transport including the atmosphere.\"\"\"\n\n def __init__(self, config, instrument):\n\n TabularRT.__init__(self, config, instrument)\n\n self.modtran_dir = self.find_basedir(config)\n self.filtpath = os.path.join(self.lut_dir, 'wavelengths.flt')\n self.template = deepcopy(json_load_ascii(\n config['modtran_template_file'])['MODTRAN'])\n\n # Insert aerosol templates, if specified\n if 'aerosol_template_file' in config:\n self.template[0]['MODTRANINPUT']['AEROSOLS'] = \\\n deepcopy(json_load_ascii(config['aerosol_template_file']))\n\n # Insert aerosol data, if specified\n if 'aerosol_model_file' in config:\n aer_data = s.loadtxt(config['aerosol_model_file'])\n self.aer_wl = aer_data[:, 0]\n aer_data = aer_data[:, 1:].T\n self.naer = int(len(aer_data)/3)\n aer_absc, aer_extc, aer_asym = [], [], []\n for i in range(self.naer):\n aer_extc.append(aer_data[i*3])\n aer_absc.append(aer_data[i*3+1])\n aer_asym.append(aer_data[i*3+2])\n self.aer_absc = s.array(aer_absc)\n self.aer_extc = s.array(aer_extc)\n self.aer_asym = s.array(aer_asym)\n\n # Build the lookup table\n self.build_lut(instrument)\n\n def find_basedir(self, config):\n '''Seek out a modtran base directory'''\n\n try:\n return config['modtran_directory']\n except KeyError:\n pass # fall back to environment variable\n try:\n return os.getenv('MODTRAN_DIR')\n except KeyError:\n raise KeyError('I could not find the MODTRAN base directory')\n\n def load_tp6(self, infile):\n '''Load a .tp6 file. This contains the solar geometry. We \n Return cosine of mean solar zenith'''\n\n with open(infile, 'r') as f:\n ts, te = -1, -1 # start and end indices\n lines = []\n while len(lines) == 0 or len(lines[-1]) > 0:\n try:\n lines.append(f.readline())\n except UnicodeDecodeError:\n pass\n #lines = f.readlines()\n for i, line in enumerate(lines):\n if \"SINGLE SCATTER SOLAR\" in line:\n ts = i+5\n if ts >= 0 and len(line) < 5:\n te = i\n break\n if ts < 0:\n raise ValueError('Could not find solar geometry in .tp6 file')\n szen = s.array([float(lines[i].split()[3])\n for i in range(ts, te)]).mean()\n return szen\n\n def load_chn(self, infile, coszen):\n \"\"\"Load a .chn output file and parse critical coefficient vectors. \n These are:\n wl - wavelength vector\n sol_irr - solar irradiance\n sphalb - spherical sky albedo at surface\n transm - diffuse and direct irradiance along the \n sun-ground-sensor path\n transup - transmission along the ground-sensor path only \n We parse them one wavelength at a time.\"\"\"\n\n with open(infile) as f:\n sols, transms, sphalbs, wls, rhoatms, transups = [], [], [], [], [], []\n lines = f.readlines()\n for i, line in enumerate(lines):\n if i < 5:\n continue\n toks = line.strip().split(' ')\n toks = re.findall(r\"[\\S]+\", line.strip())\n wl, wid = float(toks[0]), float(toks[8]) # nm\n solar_irr = float(toks[18]) * 1e6 * \\\n s.pi / wid / coszen # uW/nm/sr/cm2\n rdnatm = float(toks[4]) * 1e6 # uW/nm/sr/cm2\n rhoatm = rdnatm * s.pi / (solar_irr * coszen)\n sphalb = float(toks[23])\n transm = float(toks[22]) + float(toks[21])\n transup = float(toks[24])\n sols.append(solar_irr)\n transms.append(transm)\n sphalbs.append(sphalb)\n rhoatms.append(rhoatm)\n transups.append(rhoatm)\n wls.append(wl)\n params = [s.array(i) for i in\n [wls, sols, rhoatms, transms, sphalbs, transups]]\n return tuple(params)\n\n def ext550_to_vis(self, ext550):\n return s.log(50.0) / (ext550 + 0.01159)\n\n def modtran_driver(self, overrides):\n \"\"\"Write a MODTRAN 6.0 input file\"\"\"\n\n param = deepcopy(self.template)\n\n if hasattr(self, 'aer_absc'):\n fracs = s.zeros((self.naer))\n\n # Perform overrides\n for key, val in overrides.items():\n recursive_replace(param, key, val)\n\n if key.startswith('AER'):\n i = int(key.split('_')[-1])\n fracs[i] = val\n\n elif key == 'EXT550' or key == 'AOT550' or key == 'AOD550':\n # MODTRAN 6.0 convention treats negative visibility as AOT550\n recursive_replace(param, 'VIS', -val)\n\n elif key == 'FILTNM':\n param[0]['MODTRANINPUT']['SPECTRAL']['FILTNM'] = val\n\n elif key in ['ITYPE', 'H1ALT', 'IDAY', 'IPARM', 'PARM1',\n 'PARM2', 'GMTIME', 'TRUEAZ', 'OBSZEN']:\n param[0]['MODTRANINPUT']['GEOMETRY'][key] = val\n\n # For custom aerosols, specify final extinction and absorption\n # MODTRAN 6.0 convention treats negative visibility as AOT550\n if hasattr(self, 'aer_absc'):\n total_aot = fracs.sum()\n recursive_replace(param, 'VIS', -total_aot)\n total_extc = self.aer_extc.T.dot(fracs)\n total_absc = self.aer_absc.T.dot(fracs)\n norm_fracs = fracs/(fracs.sum())\n total_asym = self.aer_asym.T.dot(norm_fracs)\n\n # Normalize to 550 nm\n total_extc550 = interp1d(self.aer_wl, total_extc)(0.55)\n lvl0 = param[0]['MODTRANINPUT']['AEROSOLS']['IREGSPC'][0]\n lvl0['NARSPC'] = len(self.aer_wl)\n lvl0['VARSPC'] = [float(v) for v in self.aer_wl]\n lvl0['ASYM'] = [float(v) for v in total_asym]\n lvl0['EXTC'] = [float(v) / total_extc550 for v in total_extc]\n lvl0['ABSC'] = [float(v) / total_extc550 for v in total_absc]\n\n return json.dumps({\"MODTRAN\": param})\n\n def build_lut(self, instrument, rebuild=False):\n \"\"\" Each LUT is associated with a source directory. We build a \n lookup table by: \n (1) defining the LUT dimensions, state vector names, and the grid \n of values; \n (2) running modtran if needed, with each MODTRAN run defining a \n different point in the LUT; and \n (3) loading the LUTs, one per key atmospheric coefficient vector,\n into memory as VectorInterpolator objects.\"\"\"\n\n # Regenerate MODTRAN input wavelength file\n if not os.path.exists(self.filtpath):\n self.wl2flt(instrument.wl, instrument.fwhm, self.filtpath)\n\n TabularRT.build_lut(self, instrument, rebuild)\n\n def rebuild_cmd(self, point, fn):\n\n vals = dict([(n, v) for n, v in zip(self.lut_names, point)])\n vals['DISALB'] = True\n vals['NAME'] = fn\n vals['FILTNM'] = os.path.normpath(self.filtpath)\n modtran_config_str = self.modtran_driver(dict(vals))\n\n # Check rebuild conditions: LUT is missing or from a different config\n infilename = 'LUT_'+fn+'.json'\n infilepath = os.path.join(self.lut_dir, infilename)\n outchnname = fn+'.chn'\n outchnpath = os.path.join(self.lut_dir, outchnname)\n if not os.path.exists(infilepath) or\\\n not os.path.exists(outchnpath):\n rebuild = True\n else:\n with open(infilepath, 'r') as f:\n current = f.read()\n rebuild = (modtran_config_str.strip() != current.strip())\n\n if not rebuild:\n raise FileExistsError('File exists')\n\n # write_config_file\n with open(infilepath, 'w') as f:\n f.write(modtran_config_str)\n\n # Specify location of the proper MODTRAN 6.0 binary for this OS\n xdir = {'linux': 'linux', 'darwin': 'macos', 'windows': 'windows'}\n cmd = self.modtran_dir+'/bin/'+xdir[platform]+'/mod6c_cons '+infilename\n return cmd\n\n def load_rt(self, point, fn):\n tp6file = self.lut_dir+'/'+fn+'.tp6'\n solzen = self.load_tp6(tp6file)\n coszen = s.cos(solzen * s.pi / 180.0)\n chnfile = self.lut_dir+'/'+fn+'.chn'\n wl, sol, rhoatm, transm, sphalb, transup = self.load_chn(\n chnfile, coszen)\n return wl, sol, solzen, rhoatm, transm, sphalb, transup\n\n def wl2flt(self, wls, fwhms, outfile):\n \"\"\" helper function to generate Gaussian distributions around the center \n wavelengths \"\"\"\n I = None\n sigmas = fwhms/2.355\n span = 2.0 * (wls[1]-wls[0]) # nm\n steps = 101\n\n with open(outfile, 'w') as fout:\n\n fout.write('Nanometer data for sensor\\n')\n for wl, fwhm, sigma in zip(wls, fwhms, sigmas):\n\n ws = wl + s.linspace(-span, span, steps)\n vs = normal.pdf(ws, wl, sigma)\n vs = vs/vs[int(steps/2)]\n wns = 10000.0/(ws/1000.0)\n\n fout.write('CENTER: %6.2f NM FWHM: %4.2f NM\\n' %\n (wl, fwhm))\n\n for w, v, wn in zip(ws, vs, wns):\n fout.write(' %9.4f %9.7f %9.2f\\n' % (w, v, wn))\n", "meta": {"hexsha": "6a06b75710f9d8803d074519873b706610ff1227", "size": 10797, "ext": "py", "lang": "Python", "max_stars_repo_path": "isofit/rt_modtran.py", "max_stars_repo_name": "cfranken/isofit", "max_stars_repo_head_hexsha": "a67a26fe59fe0eb3fd5fe3503736294e17172f82", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "isofit/rt_modtran.py", "max_issues_repo_name": "cfranken/isofit", "max_issues_repo_head_hexsha": "a67a26fe59fe0eb3fd5fe3503736294e17172f82", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "isofit/rt_modtran.py", "max_forks_repo_name": "cfranken/isofit", "max_forks_repo_head_hexsha": "a67a26fe59fe0eb3fd5fe3503736294e17172f82", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-25T05:36:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-25T05:36:49.000Z", "avg_line_length": 38.9783393502, "max_line_length": 83, "alphanum_fraction": 0.565434843, "include": true, "reason": "import scipy,from scipy", "num_tokens": 2764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.2568319970758679, "lm_q1q2_score": 0.14438491343162296}} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nSimEVLA.py: This module simulates the slewing motion of the EVLA for use in \ndetermining optimized schedules. Based largely on the equivalent code created\nby NRAO SSS for use in the Observation Planning Tool. Small modifications have\nbeen implemented to make it more scriptable.\n\"\"\"\n\n__author__ = \"Seth Bruzewski\"\n__email__ = \"bruzewskis@unm.edu\"\n__license__ = \"GPL\"\n\n# Built in Modules\nimport logging\n\n# Third Party Modules\nimport numpy as np\nfrom astropy.coordinates import SkyCoord, Angle, EarthLocation\nimport astropy.units as u\n\nclass MotionSimulator(object):\n '''\n A pythonic class simulator of the EVLA slewing system, for implementation \n in scheduling codes.\n '''\n \n # Generate a logger\n __logger = logging.getLogger(__name__)\n \n # Motion Ranges\n __MIN_AZ = Angle(-85.0, unit='deg')\n __MAX_AZ = Angle(445.0, unit='deg')\n __MIN_EL = Angle(8.0, unit='deg')\n __MAX_EL = Angle(125.0, unit='deg')\n \n # Velocity and acceleration rates\n __VEL_AZ = 40.0/60 * u.Unit('deg/s')\n __VEL_EL = 20.0/60 * u.Unit('deg/s')\n __ACC_AZ = 1000 * u.Unit('deg/s^2')\n __ACC_EL = 1000 * u.Unit('deg/s^2')\n \n # Setup and Settling Time\n __MIN_SETUP_TIME = 0 * u.s\n __SETTLING_TIME = 7.0 * u.s\n \n # Default currentAz/El to midpoint of their ranges.\n __currentAz = Angle(225.0, unit='deg')\n __currentEl = Angle(35.0, unit='deg')\n\n # These variables keep track of what the new Az/El will be set to during\n # the moveTime calculation\n __newAz = None\n __newEl = None\n \n # Keep track of error codes generated during moveTo\n __errors = []\n \n def __init__(self, startaz=None, startel=None, wrap=None):\n '''\n Creates a EvlaTelescopeMotionSimulator with an initial position of \n `startAz` and `startEl` that is on wrap `wrap`.\n \n Args\n =======\n startaz (Angle) - Azimuth to initialize the telescope with as an\n Astropy Angle object. If not provided, telescope is initialized\n to default Azimuth, which is 225 degrees.\n startel (Angle) - Elevation to initialize the telescope with as an\n Astropy Angle object. If not provided, telescope is initialized\n to default Elevation, which is 35 degrees.\n wrap (string) - Preferred wrap of the telescope, may be CLOCKWISE,\n COUNTERCLOCKWISE, or NO_PREFERENCE\n \n Returns\n =======\n None\n \n Raises\n =======\n TypeError - Raised by class functions setCurrentAntennaAzimuth or \n setCurrentAntennaElevation when inputs are not the correct type\n ValueError - Raised by class functions setCurrentAntennaAzimuth or \n setCurrentAntennaElevation when inputs are outside of range\n '''\n \n self.setCurrentAntennaAzimuth(startaz, wrap)\n self.setCurrentAntennaElevation(startel)\n \n def moveTo(self, azEnd, elEnd, wrap=None, goOverTheTop=False):\n '''\n Returns the estimated move time from our current saved position to \n `az`, `el`. For the very first calculation, a starting position \n due south at 65 degrees elevation is assumed. The method takes into \n account antenna wrap by calculating 4 different move times and \n returning the smallest valid move time. The 4 cases are as follows:\n\n 1) The position we're moving to is on the COUNTERCLOCKWISE (left) \n wrap. We simple rotate the antenna to that position and see how long \n it takes. This is a valid option only if `wrap` is not CLOCKWISE \n and `goOverTheTop` is false.\n\n 2) The position is on the CLOCKWISE (right) wrap. Again, we calculate \n how long it will take to rotate the antenna to that position on that \n wrap. This is a valid option only if {@code wrap} is not \n COUNTERCLOCKWISE and `goOverTheTop` is false.\n\n 3) We rotate the antenna 180 degrees and then go over the top to get \n to our target position. (i.e. we're subtracting 180 degrees from the \n AZ in case 1 above.) This is only valid if `goOverTheTop' is \n true and the elevation is greater than 55 degrees (180 - MAX_EL).\n\n 4) The same as 3 above, but we add 180 to the az instead of \n subtracting.\n\n This method also clears and refills the list of errors encountered \n while attempting this move.\n \n Args\n =======\n azEnd (Angle) - Target azimuth to slew to as an Astropy Angle. Will\n be checked against telescope motion ranges.\n elEnd (Angle) - Target elevation to slew to as an Astropy Angle. Will\n be checked against telescope motion ranges.\n wrap (string) - Preferred wrap of the telescope, may be CLOCKWISE,\n COUNTERCLOCKWISE, or NO_PREFERENCE\n goOverTheTop (bool) - Whether or not to allow the telescope to \n traverse in elevation beyond the zenith. For standard observing \n this is not advised.\n \n Returns\n =======\n tmin (Quantity) - The total slew time expressed as an Astropy Quantity\n object with units of time. \n \n Raises\n =======\n None\n '''\n \n # Check type of inputs\n if not isinstance(azEnd, Angle) or not isinstance(elEnd, Angle):\n self.__errors.append('IMPROPER_INPUT_TYPE')\n self.__logger.error('azEnd or elEnd are not Astropy Angles')\n return np.nan\n \n # Start up stuff\n azStart = self.__currentAz.copy()\n elStart = self.__currentEl.copy()\n \n # Keeping track of things\n self.__newAz = None\n self.__newEl = None\n self.__errors = []\n \n # Initialize min to something large\n tmin = 10 * u.day\n \n # Initialize wrap to a default if it was None\n w = 'NO_PREFERENCE' if wrap is None else wrap\n \n toAz = azStart\n toAzEnd = azEnd\n \n # Put the toAz on the left or COUNTERCLOCKWISE wrap.\n if toAz > self.__MIN_AZ + 360*u.deg: \n toAz -= 360*u.deg\n \n # Make sure the end position is on the same wrap! This is checked \n # separately from the above because we aren't guaranteed that just \n # because we need to subtract 360 from the start pos that we need to \n # do so to the end as well. This is mainly a concern for scans that \n # cross the 0d/360d boundary.\n if toAzEnd > self.__MIN_AZ + 360*u.deg: \n toAzEnd -= 360*u.deg\n \n toEl = elStart\n toElEnd = elEnd\n \n # Debug stuff\n coords = [toAz,toEl,toAzEnd,toElEnd]\n logstr = \"Moving : ({0:.2f},{1:.2f}) --> ({2:.2f},{3:.2f})\"\n self.__logger.debug(logstr.format(*[a.deg for a in coords]))\n \n # Whereas Longitude is always gaurunteed to be in bounds of our \n # motion, Latitude (elevation) is not, so we have to check that here \n # before going any further. We only check the min, because the max a \n # Latitude can hold is 90 and our MAX_EL is 125 or so.\n if toEl < self.__MIN_EL:\n self.__errors.append('ELEVATION_OUT_OF_RANGE')\n toEl = self.__MIN_EL.copy()\n \n # We need to do the same check for the elevation END position too!\n if toElEnd < self.__MIN_EL:\n self.__errors.append('SCAN_END_ELEVATION_OUT_OF_RANGE')\n toElEnd = self.__MIN_EL.copy()\n \n # This checks to make sure that the if the user selected a CLOCKWISE \n # preference, but the source is in the region where the wraps do NOT \n # overlap, we still get a valid calculation. The reason this comes \n # up is because for much of the logic below we're considering a wrap \n # to be a full 360 degrees when it is only actually 265. So, a \n # source could be in the CLOCKWISE wrap (180 - 445 degrees) but be \n # missed in the logic below if it's position is less than 275 degrees. \n # (which is within the range (-85, -85 + 360))\n if w=='CLOCKWISE' and toAz > 85*u.deg:\n w = 'NO_PREFERENCE'\n \n # tmp variables for calculations\n tmpAz = toAz.copy()\n tmpAzEnd = toAzEnd.copy()\n tmpEl = toEl.copy()\n tmpElEnd = toElEnd.copy()\n \n # Counterclockwise or No Pref\n if w!='CLOCKWISE':\n # Case 3:\n if goOverTheTop:\n print('case3')\n tmpAz = toAz - 180*u.deg\n tmpAzEnd = toAzEnd - 180*u.deg\n tmpEl = 180*u.deg - toEl\n tmpElEnd = 180*u.deg - toElEnd\n \n if (tmpAz >= self.__MIN_AZ and tmpEl <= self.__MAX_EL):\n tmin, updateBool = self.__updateMin(tmin,tmpAzEnd,tmpElEnd)\n if updateBool:\n self.__newAz = tmpAzEnd\n self.__newEl = tmpElEnd\n \n time_str = tmin.to('s').value\n case_str = \"Case 3 min = {0:.2f} s\"\n self.__logger.debug(case_str.format(time_str))\n\n # Case 1:\n else:\n tmin, updateBool = self.__updateMin(tmin, tmpAzEnd, tmpElEnd)\n if updateBool:\n self.__newAz = tmpAzEnd\n self.__newEl = tmpElEnd\n \n time_str = tmin.to('s').value\n case_str = \"Case 1 min = {0:.2f} s\"\n self.__logger.debug(case_str.format(time_str))\n \n # Clockwise or No Pref\n if w!='COUNTERCLOCKWISE':\n # Case 4\n if goOverTheTop:\n print('case4')\n tmpAz = toAz + 180*u.deg\n tmpEl = 180*u.deg - toEl\n tmpAzEnd = toAzEnd + 180.0*u.deg\n tmpElEnd = 180*u.deg - toElEnd\n \n if tmpAz <= self.__MAX_AZ and tmpEl <= self.__MAX_EL:\n tmin, updateBool = self.__updateMin(tmin,tmpAzEnd,tmpElEnd)\n if updateBool:\n self.__newAz = tmpAzEnd\n self.__newEl = tmpElEnd\n \n time_str = tmin.to('s').value\n case_str = \"Case 4 min = {0:.2f} s\"\n self.__logger.debug(case_str.format(time_str))\n \n # Case 2\n else:\n tmpAz = toAz + 360*u.deg\n tmpAzEnd = toAzEnd + 360*u.deg\n tmpEl = toEl.copy()\n tmpElEnd = toElEnd.copy()\n if tmpAz < self.__MAX_AZ:\n tmin, updateBool = self.__updateMin(tmin,tmpAzEnd,tmpElEnd)\n if updateBool:\n self.__newAz = tmpAzEnd\n self.__newEl = tmpElEnd\n \n time_str = tmin.to('s').value\n case_str = \"Case 2 min = {0:.2f} s\"\n self.__logger.debug(case_str.format(time_str))\n \n if self.__newAz is None or self.__newEl is None:\n self.__errors.append('MOVE_NOT_POSSIBLE')\n else:\n # Azimuth checks\n if self.__MIN_AZ > self.__newAz:\n self.__logger.error(\"newAz < min: \" + self.__newAz.to_string())\n self.__errors.append('SCAN_END_AZIMUTH_OUT_OF_RANGE')\n self.__currentAz = self.__MIN_AZ.copy()\n elif self.__MAX_AZ < self.__newAz:\n self.__logger.error(\"newAz > max: \" + self.__newAz.to_string())\n self.__errors.append('SCAN_END_AZIMUTH_OUT_OF_RANGE')\n self.__currentAz = self.__MAX_AZ.copy()\n else:\n self.__currentAz = self.__newAz\n \n # Elevation checks\n if self.__MIN_EL > self.__newEl:\n self.__logger.error(\"newEl < min: \" + self.__newEl.to_string())\n self.__errors.append('SCAN_END_ELEVATION_OUT_OF_RANGE')\n self.__currentEl = self.__MIN_EL.copy()\n elif self.__MAX_EL < self.__newEl:\n self.__logger.error(\"newEl > max: \" + self.__newEl.to_string())\n self.__errors.append('SCAN_END_ELEVATION_OUT_OF_RANGE')\n self.__currentEl = self.__MAX_EL.copy()\n else:\n self.__currentEl = self.__newEl\n \n # Add any settling time necessary.\n tmin += self.__SETTLING_TIME\n \n # If the slew took less time than the min. time it takes to \n # prepare the antenna for observing, use that min. instead.\n if tmin < self.__MIN_SETUP_TIME:\n tmin = self.__MIN_SETUP_TIME.copy()\n \n # Decompose units just to be safe\n tmin = tmin.decompose()\n \n return tmin\n \n def getErrors(self):\n '''\n Returns a list of any errrors that may have occured during the lastest \n call to the moveTo method. These errors are stored as simple strings\n for the user to parse or use as they see fit.\n \n Args\n =======\n None\n \n Returns\n =======\n self.__errors.copy() (list) - List of errors generated by moveTo\n \n Raises\n =======\n None\n '''\n \n return self.__errors.copy()\n \n def getCurrentAntennaWrap(self):\n '''\n Returns which AntennaWrap this simulator is currently on using the \n following rules. If the currentAz is greater than 275 degrees (MIN_AZ \n + 360) then we're in the CLOCKWISE (right) wrap. Otherwise we're in \n the COUNTERCLOCKWISE (left) wrap. Note: This could be changed to split \n the range in half: greater than 180 degrees is CLOCKWISE, the rest is \n COUNTERCLOCKWISE. As it is now, you are only in the CLOCKWISE wrap if \n you are in the overlapping region.\n \n Args\n =======\n None\n \n Returns\n =======\n wrap (string) - The current antenna wrap expressed as a string.\n \n Raises\n =======\n None\n '''\n \n if self.__currentAz > 180*u.deg:\n return 'CLOCKWISE' #AntennaWrap.CLOCKWISE\n else:\n return 'COUNTERCLOCKWISE' #AntennaWrap.COUNTERCLOCKWISE\n \n def getCurrentAntennaAzimuth(self):\n '''\n Returns a copy of the current antenna azimuth. This value should be\n in the range -85 to 445 degrees.\n \n Args\n =======\n None\n \n Returns\n =======\n self.__currentAz.copy() (Angle) - The current antenna azimuth\n expressed as an Astropy Angle object.\n \n Raises\n =======\n None\n '''\n \n return self.__currentAz.copy()\n \n def setCurrentAntennaAzimuth(self, a, w=None):\n '''\n Sets the current Antenna Az to a clone of Angle equivalent to \n `a` at wrap `w` if `a` is within range.\n \n Args\n =======\n None\n \n Returns\n =======\n self.__currentAz.copy() (Angle) - The current antenna azimuth\n expressed as an Astropy Angle object.\n \n Raises\n =======\n TypeError - Raised when inputs are not the correct type\n ValueError - Raised when inputs are outside of range\n '''\n \n # Check input type\n if not a is None:\n if not isinstance(a, Angle):\n raise TypeError('Initializing Azimuth is not Astropy Angle')\n \n # Check that input is in range\n if w is None:\n if a is not None and self.__MIN_AZ < a < self.__MAX_AZ:\n self.__currentAz = a.copy()\n elif a is None:\n pass\n else:\n raise ValueError('Invalid Antenna Azimuth: '+str(a.deg))\n else:\n self.setCurrentAntennaAzimuth(self.toAntennaAzimuth(a, w))\n \n def getCurrentAntennaElevation(self):\n '''\n Returns a copy of the current antenna elevation. This value should be\n in the range 8 to 125 degrees.\n \n Args\n =======\n None\n \n Returns\n =======\n self.__currentEl.copy() (Angle) - The current antenna elevation\n expressed as an Astropy Angle object.\n \n Raises\n =======\n None\n '''\n \n return self.__currentEl.copy()\n \n def setCurrentAntennaElevation(self, a):\n '''\n Sets the current Antenna El to a clone of `a` if a is within \n range.\n \n Args\n =======\n None\n \n Returns\n =======\n self.__currentEl.copy() (Angle) - The current antenna azimuth\n expressed as an Astropy Angle object.\n \n Raises\n =======\n TypeError - Raised when inputs are not the correct type\n ValueError - Raised when inputs are outside of range\n '''\n \n # Check input type\n if not a is None:\n if not isinstance(a, Angle):\n raise TypeError('Initializing Elevation is not Astropy Angle')\n \n # Check that input is in range\n if a is not None and self.__MIN_EL < a < self.__MAX_EL:\n self.__currentEl = a.copy()\n elif a is None:\n pass\n else:\n raise ValueError('Invalid Antenna Elevation: '+str(a.deg))\n \n def toAntennaAzimuth(self, az, w):\n '''\n Returns an Angle in degrees between -85 and 445 degrees that \n represents `az` at AntennaWrap `w`.\n \n Args\n =======\n az (Angle) - Initial azimuth to be converted\n w (string) - Current wrap of the antenna\n \n Returns\n =======\n antennaAz (Angle) - Proper azimuth inside the antenna wrap\n \n Raises\n =======\n None\n '''\n \n antennaAz = None\n \n if az is not None:\n # az is 0 - 360 degrees\n if w=='CLOCKWISE':\n # 180 to 445 degrees\n if az < self.__MAX_AZ-360*u.deg:\n az += 360*u.deg\n elif w=='COUNTERCLOCKWISE':\n # -85 to 180 degrees\n if az > self.__MIN_AZ+360*u.deg:\n az -= 360*u.deg\n \n antennaAz = az\n \n return antennaAz\n \n def getAzimuthMinimum(self):\n '''\n Returns the minimum azimuth value for EVLA antenna pointings.\n \n Args\n =======\n None\n \n Returns\n =======\n self.__MIN_AZ.copy (Angle) - Telescope minimum azmiuth\n \n Raises\n =======\n None\n '''\n \n return self.__MIN_AZ.copy()\n \n def getAzimuthMaximum(self):\n '''\n Returns the maximum azimuth value for EVLA antenna pointings.\n \n Args\n =======\n None\n \n Returns\n =======\n self.__MAX_AZ.copy (Angle) - Telescope maximum azmiuth\n \n Raises\n =======\n None\n '''\n return self.__MAX_AZ.copy()\n \n def getAzimuthDefault(self):\n '''\n Returns the default azimuth value for EVLA antenna pointings.\n \n Args\n =======\n None\n \n Returns\n =======\n DEF_AZ (Angle) - Telescope default azimuth\n \n Raises\n =======\n None\n '''\n return Angle(225, unit='deg')\n \n def getElevationMinimum(self):\n '''\n Returns the minimum elevation value for EVLA antenna pointings.\n \n Args\n =======\n None\n \n Returns\n =======\n self.__MIN_EL.copy (Angle) - Telescope minimum elevation\n \n Raises\n =======\n None\n '''\n return self.__MIN_EL.copy()\n \n def getElevationMaximum(self):\n '''\n Returns the maximum elevation value for EVLA antenna pointings.\n \n Args\n =======\n None\n \n Returns\n =======\n self.__MAX_AZ.copy (Angle) - Telescope maximum elevation\n \n Raises\n =======\n None\n '''\n return self.__MIN_EL.copy()\n \n def getElevationDefault(self):\n '''\n Returns the default elevation value for EVLA antenna pointings.\n \n Args\n =======\n None\n \n Returns\n =======\n DEF_EL (Angle) - Telescope default elevation\n \n Raises\n =======\n None\n '''\n return Angle(35, unit='deg')\n \n def __updateMin(self, currentMin, az, el):\n '''\n This method updates the passed in `currentMin` variable with \n the minimum value of 'tmin' in the moveTo function, the time it takes \n to move from currentAz to az, and the time it takes to move from \n currentEl to el. If the currentMin is changed, we return true.\n \n Args\n =======\n currentMin (Quantity) - The current slew time minimum expressed as an\n Astropy Quantity object with units of time.\n az (Angle) - Target azimuth to slew to.\n el (Angle) - Target elevation to slew to.\n \n Returns\n =======\n newCurrentMin (Quantity) - The new current slew time minimum expressed \n as an Astropy Quantity object with units of time.\n update (bool) - Whether or not `tmin` will have been changed\n \n Raises\n =======\n None\n '''\n taz = self.__calcAzMoveTime(self.__currentAz, az)\n tel = self.__calcElMoveTime(self.__currentEl, el)\n \n # t is the larger of taz and tel\n t = max([taz,tel])\n \n if currentMin > t:\n return t, True\n else:\n return currentMin, False\n \n def __calcAzMoveTime(self, f, t):\n '''\n Calculates the move time from angle `f` to angle `t` in Azimuth.\n \n Args\n =======\n f (Angle) - Initial azimuth angle\n t (Angle) - Final azimuth angle\n \n Returns\n =======\n telSlewAz (Quantity) - Slew time, accounting for factors like the\n telescope slew acceleration, expressed as an Astropy Quantity\n with units of time.\n \n Raises\n =======\n None\n '''\n azd = abs(f-t)\n \n # Time it takes to reach full speed\n # Accounts for both acceleration & decceleration.\n timeAccAz = 2 * self.__VEL_AZ / self.__ACC_AZ\n \n # Distance it takes to reach full speed\n distAccAz = (self.__VEL_AZ * self.__VEL_AZ) / self.__ACC_AZ\n \n # If the antenna never reaches full speed, use this equation.\n if azd < distAccAz:\n telSlewAz = 2 * np.sqrt(azd / self.__ACC_AZ)\n # otherwise, use this equation.\n else:\n telSlewAz = timeAccAz + (azd - distAccAz) / self.__VEL_AZ\n\n return telSlewAz\n \n def __calcElMoveTime(self, f, t):\n '''\n Calculates the move time from angle `f` to angle `t` in Elevation.\n \n Args\n =======\n f (Angle) - Initial elevation angle\n t (Angle) - Final elevation angle\n \n Returns\n =======\n telSlewEl (Quantity) - Slew time, accounting for factors like the\n telescope slew acceleration, expressed as an Astropy Quantity\n with units of time.\n \n Raises\n =======\n None\n '''\n eld = abs(f-t)\n \n # Time it takes to reach full speed\n # Accounts for both acceleration & decceleration.\n timeAccEl = 2 * self.__VEL_EL / self.__ACC_EL\n\n # Distance it takes to reach full speed\n distAccEl = (self.__VEL_EL * self.__VEL_EL) / self.__ACC_EL\n\n \n if eld < distAccEl:\n # If the antenna never reaches full speed, use this equation.\n telSlewEl = 2 * np.sqrt(eld / self.__ACC_EL)\n else:\n # otherwise, use this equation.\n telSlewEl = timeAccEl + (eld - distAccEl) / self.__VEL_EL\n \n return telSlewEl\n \ndef EquitorialToHorizontal(ra, dec, lst):\n '''\n This function converts Equitorial coordinates (RA/DEC) to a horizontal\n coordinate system local to the VLA (AZ/EL). Ideally utilizes astropy \n Angles, but will convert where possible. Also requires a specific time \n given in LST. Note that Azimuth here is measured clockwise from the North.\n \n Args\n =======\n ra (various) - Either an Astropy Angle class, or a string/number in\n hourangle units. The latter will be converted to an Astropy Angle.\n dec (various) - Either an Astropy Angle class, or a string/number in\n degree units. The latter will be converted to an Astropy Angle.\n lst (string) - The local sidereal time at the VLA to be converted for,\n ideally in format HH:MM:SS.SS. This will be converted into hourangle.\n \n Returns\n =======\n Az (Angle) - The resulting Azimuth generated from the inputs. Measured\n clockwise from due North.\n Alt (Angle) - The resulting Altitude/Elevation generated from the inputs.\n Measured from the horizon.\n \n Raises\n =======\n UnitTypeError - Raised if the inputs cannot be coerced into Astropy Angles\n '''\n \n # Check type of inputs for safety\n if not isinstance(ra, Angle):\n ra = Angle(ra, unit=u.hourangle)\n if not isinstance(dec, Angle):\n dec = Angle(dec, unit=u.deg)\n if not isinstance(lst, Angle):\n dec = Angle(lst, unit=u.hourangle)\n \n # Let's just assume we're at the VLA\n vla = EarthLocation.of_site('VLA')\n ha = lst - ra\n lat = vla.lat\n \n # Do Trigonometry\n cosAlt_sinAz = -np.cos(dec)*np.sin(ha)\n cosAlt_cosAz = np.sin(dec)*np.cos(lat) - np.cos(dec)*np.cos(ha)*np.sin(lat)\n sinAlt = np.sin(dec)*np.sin(lat) + np.cos(dec)*np.cos(ha)*np.cos(lat)\n \n Az = Angle(np.arctan2(cosAlt_sinAz,cosAlt_cosAz)).wrap_at('360d')\n Alt = Angle(np.arcsin(sinAlt))\n \n return Az, Alt\n\ndef PointToPointTime(start_sc, end_sc, lst):\n '''\n Calculate the time to slew between two coordinates on the sky. Note that\n this function will not check if the slew is possible, instead allowing\n MotionSimulator to throw errors where it likes. This is largely useful\n for diagnostic checking.\n \n Args\n =======\n start_sc (SkyCoord) - The coordinates of the first point on the sky, where\n the telescope will begin its slew. Must be an Astropy SkyCoord object\n end_sc (SkyCoord) - The coordinates of the second point on the sky, where\n the telescope will end its slew. Must be an Astropy SkyCoord object\n lst (string) - The local sidereal time at the VLA to be converted for,\n ideally in format HH:MM:SS.SS. This will be converted into hourangle.\n \n Returns\n =======\n slewtime (Quantity) - The time it takes to slew between the input points.\n This is returned as an Astropy Quantity with units of time, that way it\n can be easily worked with.\n \n Raises\n =======\n TypeError - Raised when start_sc or end_sc are not SkyCoords\n '''\n # Check type of inputs\n if not isinstance(start_sc, SkyCoord):\n raise TypeError('param \\'start_sc\\' is not a Astropy SkyCoord')\n if not isinstance(end_sc, SkyCoord):\n raise TypeError('param \\'end_sc\\' is not a Astropy SkyCoord')\n \n # Basic logging\n mlogger = logging.getLogger(__name__)\n \n # Translate Start Point\n start_az, start_el = EquitorialToHorizontal(start_sc.ra,start_sc.dec,lst)\n \n # Translate End Point\n end_az, end_el = EquitorialToHorizontal(end_sc.ra,end_sc.dec,lst)\n \n # Nice Debug\n coo_fmt = '(ra:{0:.2f},dec:{1:.2f}) --> (az:{2:.2f},el:{3:.2f})'\n coo1 = [start_sc.ra.deg, start_sc.dec.deg, start_az.deg, start_el.deg]\n coo2 = [end_sc.ra.deg, end_sc.dec.deg, end_az.deg, end_el.deg]\n mlogger.debug('Converting : '+coo_fmt.format(*coo1))\n mlogger.debug('Converting : '+coo_fmt.format(*coo2)) \n \n # Generate Simulator\n sim = MotionSimulator(start_az, start_el)\n slewtime = sim.moveTo(end_az, end_el)\n mlogger.debug('Took {0:.2f} seconds to slew'.format(slewtime.value))\n \n # Errors\n err = sim.getErrors()\n mlogger.debug('Found {:d} errors'.format(len(err)))\n for e in err:\n mlogger.error(e)\n \n return slewtime\n \n \nif __name__=='__main__':\n '''\n Psuedomain function for simple tests to give some idea how this works\n \n Args\n =======\n None\n \n Returns\n =======\n None\n \n Raises\n =======\n None\n '''\n \n # Test 1\n print('Test 1:')\n s1 = SkyCoord(21.915*u.hourangle, -30*u.deg)\n s2 = SkyCoord(21.915*u.hourangle, 30*u.deg)\n sc2str = lambda sc : sc.to_string('hmsdms')\n print('Slewing from {0:s} to {1:s}'.format(sc2str(s1), sc2str(s2)))\n \n lst0 = Angle('21:54:55', unit='hourangle')\n st = PointToPointTime(s1, s2, lst0)\n st_sec = st.to('s').value\n st_dst = s1.separation(s2).deg\n fmt_str = 'Took {0:.2f} seconds to slew {1:.2f} degrees'\n print(fmt_str.format(st_sec, st_dst))\n \n # Test 2\n print('\\nTest 2:')\n sim = MotionSimulator()\n totaltime = 0*u.s\n for _ in range(10):\n new_az = Angle(np.random.uniform(0,360) * u.deg)\n new_el = Angle(np.random.uniform(10,90) * u.deg)\n slewt = sim.moveTo(new_az, new_el)\n totaltime += slewt\n \n t2_st = totaltime.to('s').value\n print('Slewed to 10 points over {0:.2f} seconds'.format(t2_st))", "meta": {"hexsha": "7adbf0441c015751abfb7b72b778ffda374f2fbe", "size": 30110, "ext": "py", "lang": "Python", "max_stars_repo_path": "beta/SimEVLA.py", "max_stars_repo_name": "bruzewskis/grote", "max_stars_repo_head_hexsha": "80b2e150f8e2d0027397732369c3cfeadfb742e5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "beta/SimEVLA.py", "max_issues_repo_name": "bruzewskis/grote", "max_issues_repo_head_hexsha": "80b2e150f8e2d0027397732369c3cfeadfb742e5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "beta/SimEVLA.py", "max_forks_repo_name": "bruzewskis/grote", "max_forks_repo_head_hexsha": "80b2e150f8e2d0027397732369c3cfeadfb742e5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7556053812, "max_line_length": 80, "alphanum_fraction": 0.5571238791, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 7157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.2568319970758679, "lm_q1q2_score": 0.14438491343162294}} {"text": "# The MIT License (MIT)\n#\n# Copyright (c) 2016-2018 Albert Kottke\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport numpy as np\nimport numba\n\nfrom scipy.optimize import minimize\n\nfrom .site import Location, Layer, Profile\nfrom .motion import WaveField, GRAVITY\n\n\nclass AbstractCalculator(object):\n def __init__(self):\n self._loc_input = None\n self._motion = None\n self._profile = None\n\n def __call__(self, motion, profile, loc_input):\n self._motion = motion\n self._profile = profile\n self._loc_input = loc_input\n\n @property\n def motion(self):\n return self._motion\n\n @property\n def profile(self):\n return self._profile\n\n @property\n def loc_input(self):\n return self._loc_input\n\n def calc_accel_tf(self, lin, lout):\n raise NotImplementedError\n\n def calc_stress_tf(self, lin, lout, damped):\n raise NotImplementedError\n\n def calc_strain_tf(self, lin, lout):\n raise NotImplementedError\n\n\n@numba.jit\ndef my_trapz(thickness, property, depth_max):\n total = 0\n depth = 0\n\n for t, p in zip(thickness, property):\n depth += t\n if depth_max < depth:\n # Partial layer\n total += (t - (depth - depth_max)) * p\n break\n total += t * p\n else:\n # Final infinite layer\n total += (depth_max - depth) * p\n\n return total / depth_max\n\n\nclass QuarterWaveLenCalculator(AbstractCalculator):\n \"\"\"Compute quarter-wave length site amplification.\n\n No consideration for nolninearity is made by this calculator.\n \"\"\"\n\n def __init__(self, site_atten=None):\n super().__init__()\n self._site_atten = site_atten\n\n def __call__(self, motion, profile, loc_input):\n \"\"\"Perform the wave propagation.\n\n Parameters\n ----------\n motion: :class:`~.base.motion.Motion`\n Input motion.\n\n profile: :class:`~.base.site.Profile`\n Site profile.\n\n loc_input: :class:`~.base.site.Location`\n Location of the input motion.\n \"\"\"\n super().__call__(motion, profile, loc_input)\n\n self._crustal_amp, self._site_term = self._calc_amp(\n profile.density, profile.thickness, profile.slowness)\n\n @property\n def crustal_amp(self):\n return self._crustal_amp\n\n @property\n def site_term(self):\n return self._site_term\n\n @property\n def site_atten(self):\n return self._site_atten\n\n def _calc_amp(self, density, thickness, slowness):\n freqs = self.motion.freqs\n # 1/4 wavelength depth -- estimated for mean slowness\n qwl_depth = 1 / (4 * np.mean(slowness) * freqs)\n\n def qwl_average(param):\n return np.array(\n [my_trapz(thickness, param, qd) for qd in qwl_depth])\n\n for _ in range(20):\n qwl_slowness = qwl_average(slowness)\n prev_qwl_depth = qwl_depth\n qwl_depth = 1 / (4 * qwl_slowness * freqs)\n\n if np.allclose(prev_qwl_depth, qwl_depth, rtol=0.005):\n break\n\n # FIXME return an error if not converged?\n\n qwl_density = qwl_average(density)\n crustal_amp = np.sqrt(\n (density[-1] / slowness[-1]) / (qwl_density / qwl_slowness))\n site_term = np.array(crustal_amp)\n if self._site_atten:\n site_term *= np.exp(-np.pi * self.site_atten * freqs)\n\n return crustal_amp, site_term\n\n def fit(self,\n target_type,\n target,\n adjust_thickness=False,\n adjust_site_atten=False,\n adjust_source_vel=False):\n \"\"\"\n Fit to a target crustal amplification or site term.\n\n The fitting process adjusts the velocity, site attenuation, and layer\n thickness (if enabled) to fit a target values. The frequency range is\n specified by the input motion.\n\n Parameters\n ----------\n target_type: str\n Options are 'crustal_amp' to only fit to the crustal amplification,\n or 'site_term' to fit both the velocity and the site attenuation\n parameter.\n target: `array_like`\n Target values.\n adjust_thickness: bool (optional)\n If the thickness of the layers is adjusted as well, default: False.\n adjust_site_atten: bool (optional)\n If the site attenuation is adjusted as well, default: False.\n adjust_source_vel: bool (optional)\n If the source velocity should be adjusted, default: False.\n Returns\n -------\n profile: `pyrsa.site.Profile`\n profile optimized to fit a target amplification.\n \"\"\"\n density = self.profile.density\n\n nl = len(density)\n\n # Slowness bounds\n slowness = self.profile.slowness\n thickness = self.profile.thickness\n site_atten = self._site_atten\n\n # Slowness\n initial = slowness\n bounds = 1 / np.tile((4000, 100), (nl, 1))\n if not adjust_source_vel:\n bounds[-1] = (initial[-1], initial[-1])\n\n # Thickness bounds\n if adjust_thickness:\n bounds = np.r_[bounds, [[t / 2, 2 * t] for t in thickness]]\n initial = np.r_[initial, thickness]\n\n # Site attenuation bounds\n if adjust_site_atten:\n bounds = np.r_[bounds, [[0.0001, 0.200]]]\n initial = np.r_[initial, self.site_atten]\n\n def calc_rmse(this, that):\n return np.mean(((this - that) / that) ** 2)\n\n def err(x):\n _slowness = x[0:nl]\n if adjust_thickness:\n _thickness = x[nl:(2 * nl)]\n else:\n _thickness = thickness\n if adjust_site_atten:\n self._site_atten = x[-1]\n\n crustal_amp, site_term = self._calc_amp(density, _thickness,\n _slowness)\n\n calc = crustal_amp if target_type == 'crustal_amp' else site_term\n\n err = 10 * calc_rmse(target, calc)\n # Prefer the original values so add the difference to the error\n err += calc_rmse(slowness, _slowness)\n if adjust_thickness:\n err += calc_rmse(thickness, _thickness)\n if adjust_site_atten:\n err += calc_rmse(self._site_atten, site_atten)\n return err\n\n res = minimize(err, initial, method='L-BFGS-B', bounds=bounds)\n\n slowness = res.x[0:nl]\n if adjust_thickness:\n thickness = res.x[nl:(2 * nl)]\n\n profile = Profile([\n Layer(l.soil_type, t, 1 / s)\n for l, t, s in zip(self.profile, thickness, slowness)\n ], self.profile.wt_depth)\n # Update the calculated amplificaiton\n self(self.motion, profile, self.loc_input)\n\n\nclass LinearElasticCalculator(AbstractCalculator):\n \"\"\"Class for performing linear elastic site response.\"\"\"\n\n def __init__(self):\n super().__init__()\n\n self._waves_a = np.array([])\n self._waves_b = np.array([])\n self._wave_nums = np.array([])\n\n def __call__(self, motion, profile, loc_input):\n \"\"\"Perform the wave propagation.\n\n Parameters\n ----------\n motion: :class:`~.base.motion.Motion`\n Input motion.\n\n profile: :class:`~.base.site.Profile`\n Site profile.\n\n loc_input: :class:`~.base.site.Location`\n Location of the input motion.\n \"\"\"\n super().__call__(motion, profile, loc_input)\n\n # Set initial properties\n for l in profile:\n l.reset()\n if l.strain is None:\n l.strain = 0.\n\n self._calc_waves(motion.angular_freqs, profile)\n\n def _calc_waves(self, angular_freqs, profile):\n \"\"\"Compute the wave numbers and amplitudes (up- and down-going).\n\n Parameters\n ----------\n angular_freqs: :class:`numpy.ndarray`\n Angular frequency at which the waves are computed.\n\n profile: :class:`~.base.site.Profile`\n Site profile.\n \"\"\"\n\n # Compute the complex wave numbers of the system\n wave_nums = np.empty((len(profile), len(angular_freqs)), np.complex)\n for i, l in enumerate(profile):\n wave_nums[i, :] = angular_freqs / l.comp_shear_vel\n\n # Compute the waves. In the top surface layer, the up-going and\n # down-going waves have an amplitude of 1 as they are completely\n # reflected at the surface.\n waves_a = np.ones_like(wave_nums, np.complex)\n waves_b = np.ones_like(wave_nums, np.complex)\n for i, l in enumerate(profile[:-1]):\n # Complex impedance -- wave number can be zero which causes an\n # error.\n with np.errstate(invalid='ignore'):\n cimped = ((wave_nums[i] * l.comp_shear_mod) /\n (wave_nums[i + 1] * profile[i + 1].comp_shear_mod))\n\n # Complex term to simplify equations -- uses full layer height\n cterm = 1j * wave_nums[i, :] * l.thickness\n\n waves_a[i + 1, :] = (\n 0.5 * waves_a[i] *\n (1 + cimped) * np.exp(cterm) + 0.5 * waves_b[i] *\n (1 - cimped) * np.exp(-cterm))\n waves_b[i + 1, :] = (\n 0.5 * waves_a[i] *\n (1 - cimped) * np.exp(cterm) + 0.5 * waves_b[i] *\n (1 + cimped) * np.exp(-cterm))\n\n # Set wave amplitudes with zero frequency to 1\n mask = ~np.isfinite(cimped)\n waves_a[i + 1, mask] = 1.\n waves_b[i + 1, mask] = 1.\n\n # fixme: Better way to handle this?\n # Set wave amplitudes to 1 at frequencies near 0\n mask = np.isclose(angular_freqs, 0)\n waves_a[-1, mask] = 1.\n waves_b[-1, mask] = 1.\n\n self._waves_a = waves_a\n self._waves_b = waves_b\n self._wave_nums = wave_nums\n\n def wave_at_location(self, l):\n \"\"\"Compute the wave field at specific location.\n\n Parameters\n ----------\n l : site.Location\n :class:`site.Location` of the input\n\n Returns\n -------\n `np.ndarray`\n Amplitude and phase of waves\n \"\"\"\n cterm = 1j * self._wave_nums[l.index] * l.depth_within\n\n if l.wave_field == WaveField.within:\n return (self._waves_a[l.index] * np.exp(cterm) +\n self._waves_b[l.index] * np.exp(-cterm))\n elif l.wave_field == WaveField.outcrop:\n return 2 * self._waves_a[l.index] * np.exp(cterm)\n elif l.wave_field == WaveField.incoming_only:\n return self._waves_a[l.index] * np.exp(cterm)\n else:\n raise NotImplementedError\n\n def calc_accel_tf(self, lin, lout):\n \"\"\"Compute the acceleration transfer function.\n\n Parameters\n ----------\n lin : :class:`~site.Location`\n Location of input\n lout : :class:`~site.Location`\n Location of output. Note that this would typically be midheight\n of the layer.\n\n \"\"\"\n tf = self.wave_at_location(lout) / self.wave_at_location(lin)\n return tf\n\n def calc_stress_tf(self, lin, lout, damped):\n \"\"\"Compute the stress transfer function.\n\n Parameters\n ----------\n lin : :class:`~site.Location`\n Location of input\n lout : :class:`~site.Location`\n Location of output. Note that this would typically be midheight\n of the layer.\n\n \"\"\"\n tf = self.calc_strain_tf(lin, lout)\n if damped:\n # Scale by complex shear modulus to include the influence of\n # damping\n tf *= lout.layer.comp_shear_mod\n else:\n tf *= lout.layer.shear_mod\n\n return tf\n\n def calc_strain_tf(self, lin, lout):\n \"\"\"Compute the strain transfer function from `lout` to\n `location_in`.\n\n The strain transfer function from the acceleration at layer `n`\n (outcrop) to the mid-height of layer `m` (within) is defined as\n\n Parameters\n ----------\n lin : :class:`~site.Location`\n Location of input\n lout : :class:`~site.Location`\n Location of output. Note that this would typically be midheight\n of the layer.\n\n Returns\n -------\n strain_tf : :class:`numpy.ndarray`\n Transfer function to be applied to an acceleration FAS.\n \"\"\"\n # FIXME: Correct discussion for using acceleration FAS\n # Strain(angFreq, z=h_m/2)\n # ------------------------ =\n # accel_n(angFreq)\n #\n # i k*_m [ A_m exp(i k*_m h_m / 2) - B_m exp(-i k*_m h_m / 2)]\n # ------------------------------------------------------------\n # -angFreq^2 (2 * A_n)\n #\n assert lout.wave_field == WaveField.within\n\n ang_freqs = self.motion.angular_freqs\n # The numerator cannot be computed using wave_at_location() because\n # it is A - B.\n cterm = 1j * self._wave_nums[lout.index, :] * lout.depth_within\n numer = (1j * self._wave_nums[lout.index, :] *\n (self._waves_a[lout.index, :] * np.exp(cterm) -\n self._waves_b[lout.index, :] * np.exp(-cterm)))\n denom = -ang_freqs ** 2 * self.wave_at_location(lin)\n\n # Only compute transfer function for non-zero frequencies\n mask = ~np.isclose(ang_freqs, 0)\n tf = np.zeros_like(mask, dtype=np.complex)\n # Scale into units from gravity\n tf[mask] = GRAVITY * numer[mask] / denom[mask]\n\n return tf\n\n\nclass EquivalentLinearCalculator(LinearElasticCalculator):\n \"\"\"Class for performing equivalent-linear elastic site response.\"\"\"\n\n def __init__(self, strain_ratio=0.65, tolerance=0.01, max_iterations=15):\n \"\"\"Initialize the class.\n\n Parameters\n ----------\n strain_ratio: float, default=0.65\n Ratio between the maximum strain and effective strain used to\n compute strain compatible properties.\n\n tolerance: float, default=0.01\n Tolerance in the iterative properties, which would cause the\n iterative process to terminate.\n\n max_iterations: int, default=15\n Maximum number of iterations to perform.\n \"\"\"\n super().__init__()\n self._strain_ratio = strain_ratio\n self._tolerance = tolerance\n self._max_iterations = max_iterations\n\n def __call__(self, motion, profile, loc_input):\n \"\"\"Perform the wave propagation.\n\n Parameters\n ----------\n motion: :class:`~.base.motion.Motion`\n Input motion.\n\n profile: :class:`~.base.site.Profile`\n Site profile.\n\n loc_input: :class:`~.base.site.Location`\n Location of the input motion.\n \"\"\"\n super().__call__(motion, profile, loc_input)\n\n self._estimate_strains()\n\n iteration = 0\n while iteration < self.max_iterations:\n self._calc_waves(motion.angular_freqs, profile)\n for index, layer in enumerate(profile[:-1]):\n loc_layer = Location(index, layer, 'within',\n layer.thickness / 2)\n # Compute the representative strain(s) within the layer. FDM\n # will provide a vector of strains.\n layer.strain = self._calc_strain(loc_input, loc_layer, motion)\n # Maximum error (damping and shear modulus) over all layers\n max_error = max(l.max_error for l in profile)\n if max_error < self.tolerance:\n break\n iteration += 1\n\n # Compute the maximum strain within the profile.\n for index, layer in enumerate(profile[:-1]):\n loc_layer = Location(index, layer, 'within', layer.thickness / 2)\n layer.strain_max = self._calc_strain_max(loc_input, loc_layer,\n motion)\n\n def _estimate_strains(self):\n \"\"\"Compute an estimate of the strains.\"\"\"\n # Estimate the strain based on the PGV and shear-wave velocity\n for l in self._profile:\n l.reset()\n l.strain = self._motion.pgv / l.initial_shear_vel\n\n @property\n def strain_ratio(self):\n return self._strain_ratio\n\n @property\n def tolerance(self):\n return self._tolerance\n\n @property\n def max_iterations(self):\n return self._max_iterations\n\n @classmethod\n def calc_strain_ratio(cls, mag):\n \"\"\"Compute the effective strain ratio using Idriss and Sun (1992).\n\n Parameters\n ----------\n mag: float\n Magnitude of the input motion.\n\n Returns\n -------\n strain_ratio : float\n Effective strain ratio\n\n References\n ----------\n .. [1] Idriss, I. M., & Sun, J. I. (1992). SHAKE91: A computer program\n for conducting equivalent linear seismic response analyses of\n horizontally layered soil deposits. Center for Geotechnical\n Modeling, Department of Civil and Environmental Engineering,\n University of California, Davis, CA.\n \"\"\"\n return (mag - 1) / 10\n\n def _calc_strain(self, loc_input, loc_layer, motion, *args):\n \"\"\"Compute the strain used for iterations of material properties.\"\"\"\n strain_max = self._calc_strain_max(loc_input, loc_layer, motion, *args)\n return self.strain_ratio * strain_max\n\n def _calc_strain_max(self, loc_input, loc_layer, motion, *args):\n \"\"\"Compute the effective strain at the center of a layer.\"\"\"\n return motion.calc_peak(\n self.calc_strain_tf(loc_input, loc_layer))\n\n\nclass FrequencyDependentEqlCalculator(EquivalentLinearCalculator):\n \"\"\"Class for performing equivalent-linear elastic site response with\n frequency-dependent modulii and damping.\n\n Parameters\n ----------\n use_smooth_spectrum: bool, default=False\n Use the Kausel & Assimaki (2002) smooth spectrum for the strain.\n Otherwise, the complete Fourier amplitude spectrum is used.\n strain_ratio: float, default=1.00\n ratio between the maximum strain and effective strain used to compute\n strain compatible properties. There is not clear guidance the use of\n the effective strain ratio. However, given the nature of the method,\n it would make sense not to include the an effective strain ratio.\n tolerance: float, default=0.01\n tolerance in the iterative properties, which would cause the iterative\n process to terminate.\n max_iterations: int, default=15\n maximum number of iterations to perform.\n\n References\n ----------\n .. [1] Kausel, E., & Assimaki, D. (2002). Seismic simulation of inelastic\n soils via frequency-dependent moduli and damping. Journal of\n Engineering Mechanics, 128(1), 34-47.\n \"\"\"\n\n def __init__(self,\n use_smooth_spectrum=False,\n strain_ratio=1.0,\n tolerance=0.01,\n max_iterations=15):\n \"\"\"Initialize the class.\"\"\"\n super().__init__(strain_ratio, tolerance, max_iterations)\n\n # Use the smooth strain spectrum as proposed by Kausel and Assimaki\n self._use_smooth_spectrum = use_smooth_spectrum\n\n def _estimate_strains(self):\n \"\"\"Estimate the strains by running an EQL site response.\n\n This step was recommended in Section 8.3.1 of Zalachoris (2014).\n \"\"\"\n eql = EquivalentLinearCalculator()\n eql(self._motion, self._profile, self._loc_input)\n\n def _calc_strain(self, loc_input, loc_layer, motion, *args):\n freqs = np.array(motion.freqs)\n strain_tf = self.calc_strain_tf(loc_input, loc_layer)\n strain_fas = np.abs(strain_tf * motion.fourier_amps)\n # Maximum strain in the time domain modified by the effective strain\n # ratio\n strain_eff = self.strain_ratio * motion.calc_peak(strain_tf)\n\n if self._use_smooth_spectrum:\n # Equation (8)\n freq_avg = (np.trapz(freqs * strain_fas, x=freqs) /\n np.trapz(strain_fas, x=freqs))\n\n # Find the average strain at frequencies less than the average\n # frequency\n # Equation (8)\n mask = (freqs < freq_avg)\n strain_avg = np.trapz(strain_fas[mask], x=freqs[mask]) / freq_avg\n\n # Normalize the frequency and strain by the average values\n freqs /= freq_avg\n strain_fas /= strain_avg\n\n # Fit the smoothed model at frequencies greater than the average\n A = np.c_[-freqs[~mask], -np.log(freqs[~mask])]\n a, b = np.linalg.lstsq(A, np.log(strain_fas[~mask]))[0]\n # This is a modification of the published method that ensures a\n # smooth transition in the strain\n shape = np.minimum(1, np.exp(-a * freqs) / np.power(freqs, b))\n strains = strain_eff * shape\n else:\n strains = strain_eff * strain_fas / np.max(strain_fas)\n\n return strains\n", "meta": {"hexsha": "a40e6c39ae5a370948a69b876662f319d1906403", "size": 22290, "ext": "py", "lang": "Python", "max_stars_repo_path": "pysra/propagation.py", "max_stars_repo_name": "eng-tools/pysra", "max_stars_repo_head_hexsha": "aa4317eed85d7829fd862f85ec0f23fcc7723408", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-01-11T08:13:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-31T23:23:55.000Z", "max_issues_repo_path": "pysra/propagation.py", "max_issues_repo_name": "eng-tools/pysra", "max_issues_repo_head_hexsha": "aa4317eed85d7829fd862f85ec0f23fcc7723408", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pysra/propagation.py", "max_forks_repo_name": "eng-tools/pysra", "max_forks_repo_head_hexsha": "aa4317eed85d7829fd862f85ec0f23fcc7723408", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-11T08:13:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-11T08:13:06.000Z", "avg_line_length": 34.3981481481, "max_line_length": 79, "alphanum_fraction": 0.5924629879, "include": true, "reason": "import numpy,from scipy,import numba", "num_tokens": 5115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.2598256322295121, "lm_q1q2_score": 0.14406563911093456}} {"text": "#!/usr/bin/env python\n# coding: utf-8\n# This is a demo, given a LINEMOD image 0002.png and the mask-RCNN result(mask and 2D boundingbox), do 6D pose estimation for the lamp:\n# First based on RGB, then use depth map to refine the z-direction, finally refine both rotation and translation.\n#Prerequisite before generating the codebook:\n#ckpt: under workspace_path/experiments//checkpoints_lambda250/checkpoints/ckpt--1\n#Rendered imgs and edgemaps under reference rotations \\bar_R(Generated by render_codebook.py) under the path: path_embedding_data\n#image,depth map, mask\n#mesh.ply under the path: path_model\n\nimport cv2\nimport os\nimport numpy as np\nimport tensorflow as tf\nimport sonnet as snt\nimport open3d as o3d\nfrom pysixd_stuff.pysixd import inout\nfrom est_utils import est_tra_w_tz,rectify_rot,depth_refinement,rotation_error_icp\nobj_id=14\nnum_iterations=30000\nLATENT_SPACE_SIZE = 128\nNUM_FILTER = [128, 256, 512, 512]\nKERNEL_SIZE_ENCODER = 5\nSTRIDES =[2, 2, 2, 2]\nBATCH_NORM = False\nimage_size=128\nembedding_dim = 128\nnum_embeddings = 92232\nK_train =np.array([572.41140, 0, 325.26110, 0, 573.57043, 242.04899, 0, 0, 1]).reshape((3, 3))#Should be consistent with \\bar_R images\nRadius_render_train = 700\n\nK_test = np.array([572.4114, 0.0, 325.2611, 0.0, 573.57043, 242.04899, 0.0, 0.0, 1.0]).reshape(3,3)\nexperiment_name='linemod_{:02d}_softmax_edge'.format(obj_id)\npath_workspath='./ws/'\npath_embedding_data='./embedding92232s/{:02d}'.format(obj_id)\npath_model='./ws/meshes/obj_{:02d}.ply'.format(obj_id)\nmodel_ply = inout.load_ply(path_model)\nmodel_o3d = o3d.io.read_point_cloud(path_model)\n\n#### Step 0: Load pose estimation network\nclass Encoder(snt.AbstractModule):\n def __init__(self, latent_space_size, num_filters, kernel_size, strides, batch_norm, name='encoder'):\n super(Encoder, self).__init__(name=name)\n self._latent_space_size = latent_space_size\n self._num_filters = num_filters\n self._kernel_size = kernel_size\n self._strides = strides\n self._batch_normalization = batch_norm\n\n @property\n def latent_space_size(self):\n return self._latent_space_size\n\n @property\n def encoder_layers(self):\n layers = []\n x = self._input\n layers.append(x)\n for filters, stride in zip(self._num_filters, self._strides):\n padding = 'same'\n x = tf.layers.conv2d(\n inputs=x,\n filters=filters,\n kernel_size=self._kernel_size,\n strides=stride,\n padding=padding,\n kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(),\n activation=tf.nn.relu,\n )\n if self._batch_normalization:\n x = tf.layers.batch_normalization(x, training=self._is_training)\n layers.append(x)\n return layers\n\n @property\n def encoder_out(self):\n x = self.encoder_layers[-1]\n encoder_out = tf.contrib.layers.flatten(x)\n\n return encoder_out\n\n @property\n def z(self):\n x = self.encoder_out\n # construct data\n z = tf.layers.dense(\n x,\n self._latent_space_size,\n activation=None,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name=None\n )\n return z\n\n def _build(self, x, is_training=False):\n self._input = x\n self._is_training = is_training\n return self.z\n\n\nclass VectorQuantizer(snt.AbstractModule):\n def __init__(self, embedding_dim, num_embeddings, name='vq_center'):\n super(VectorQuantizer, self).__init__(name=name)\n self._embedding_dim = embedding_dim\n self._num_embeddings = num_embeddings\n\n with self._enter_variable_scope():\n initializer = tf.uniform_unit_scaling_initializer()\n self._w = tf.get_variable('embedding', [embedding_dim, num_embeddings], initializer=initializer, trainable=True)\n\n def _build(self, inputs):\n input_shape = tf.shape(inputs)\n with tf.control_dependencies([\n tf.Assert(tf.equal(input_shape[-1], self._embedding_dim),[input_shape])]):\n flat_inputs = tf.reshape(inputs, [-1, self._embedding_dim])\n w = self.embeddings.read_value()\n\n distances = -tf.matmul(tf.nn.l2_normalize(flat_inputs, axis=1), tf.nn.l2_normalize(w, axis=0))\n encoding_indices = tf.argmax(- distances, 1)\n encoding_indices = tf.reshape(encoding_indices, tf.shape(inputs)[:-1]) \n return {'encoding_indices': encoding_indices, }\n\n @property\n def embeddings(self):\n return self._w\n\n\n# Build modules.\ngraph_estpose=tf.Graph()\nwith graph_estpose.as_default():\n with tf.variable_scope(experiment_name): # .split('_')[0]+'_'+experiment_name.split('_')[1]):\n I_x = tf.placeholder(tf.float32, shape=(None, image_size, image_size, 4))\n with tf.variable_scope('encoder'):\n encoder = Encoder(latent_space_size=LATENT_SPACE_SIZE,num_filters=NUM_FILTER,kernel_size=KERNEL_SIZE_ENCODER,strides=STRIDES,batch_norm=BATCH_NORM)\n z = encoder(I_x)\n network_vars = tf.trainable_variables()\n print(network_vars)\n vq_codebook = VectorQuantizer(embedding_dim=embedding_dim,num_embeddings=num_embeddings)\n\n # For evaluation, make sure is_training=False!\n with tf.variable_scope('validation'):\n nn_item = vq_codebook(z)\n\n # Bounding box informations for foreground model in pose template repository\n codebook_obj_bbs = np.load(os.path.join(path_embedding_data,'obj_bbs.npy'))\n codebook_rotations = np.load(os.path.join(path_embedding_data,'rot_infos.npz'))['rots']\n\n saver = tf.train.Saver(network_vars, save_relative_paths=False)\n embedding = tf.placeholder(tf.float32, shape=[embedding_dim, num_embeddings])\n embedding_assign_op = tf.assign(vq_codebook.embeddings, embedding)\n\n\ngpu_options = tf.GPUOptions(allow_growth=True, per_process_gpu_memory_fraction=0.9)\nconfig = tf.ConfigProto(gpu_options=gpu_options)\nsess_estpose=tf.Session(graph=graph_estpose,config=config)\nprint('Step 0, Load Rotation Estimation Net')\nwith sess_estpose.as_default():\n with graph_estpose.as_default():\n saver.restore(sess_estpose, '{:s}/experiments/{:s}/checkpoints_lambda250/checkpoints/chkpt-{:d}'.format(path_workspath,experiment_name,num_iterations-1))\n arr_codebook = np.load(os.path.join(path_embedding_data,'edgeLambda250_codebook.npy'))\n sess_estpose.run(embedding_assign_op, {embedding: arr_codebook.T})\n\n\n\nprint('Step 0, Load RGB image')\nimage = cv2.imread('./demo_data/0002.png')\nimg_depth = inout.load_depth2('./demo_data/0002_depth.png')\ndepth_scale=1.0\nimg_depth=img_depth*depth_scale\n\nprint('Step 1, Load 2D detection and mask')\nimg_masks = np.load('./demo_data/0002_mask.npy')\nfor cc in range(3):\n image[:, :, cc] = np.where(img_masks[:, :, 0] == 1,image[:, :, cc], 0)\nimg_depth = np.where(img_masks[:, :, 0] == 1, img_depth, 0)\n\n\nobj_bb=np.array([326, 54, 103, 151])\n#obj_bb is the 2D bounding box on the image, with 4 elements: x,y,w,h; where (x,y) is the location of the left-top corner\n#Thus center 2D location is (x+w/2, h+w/2)\n\nverbose=False\nif verbose:\n image_vis=image.copy()\n cv2.rectangle(image_vis,(obj_bb[0],obj_bb[1]),(obj_bb[0]+obj_bb[2],obj_bb[1]+obj_bb[3]),(255,0,0),2)\n cv2.imshow('img',image_vis)\n cv2.waitKey()\n\nprint('Step 2, Pose estimation')\nwith sess_estpose.as_default():\n with graph_estpose.as_default():\n img_bgr=image.copy()\n\n x,y,w,h=obj_bb\n H,W,_=img_bgr.shape\n size = int(np.maximum(h, w) * 1.2)\n left = int(np.max([x + w / 2 - size / 2, 0]))\n right = int(np.min([x + w / 2 + size / 2, W]))\n top = int(np.max([y + h / 2 - size / 2, 0]))\n bottom = int(np.min([y + h / 2 + size / 2, H]))\n\n crop = img_bgr[top:bottom, left:right].copy()\n crop_depth=img_depth[top:bottom,left:right].copy()\n\n query_bgr = cv2.resize(crop, (image_size,image_size))\n query_edge = np.expand_dims(cv2.Canny(query_bgr, 50, 150),2)\n query = np.expand_dims((np.concatenate((query_bgr, query_edge), axis=-1) /255.),0)\n\n idx=sess_estpose.run([nn_item],feed_dict={I_x:query})\n idx=idx[0]['encoding_indices'][0]\n est_rot_cb= codebook_rotations[idx] #This should be a 3x3 matrix, which indicates an initial model-to-camera rotation estimation\n\n if verbose:\n #path='../Edge-Network/embedding92232s/{:02d}/imgs/{:05d}.png'.format(obj_id,idx)\n #est_bgr=cv2.imread(path)\n cv2.imshow('bbox',query_bgr)\n cv2.imshow('bbox_depth',crop_depth)\n #cv2.imshow('estimated rotation',est_bgr)\n cv2.waitKey()\n\n K00_ratio = K_test[0, 0] / K_train[0, 0]\n K11_ratio = K_test[1, 1] / K_train[1, 1]\n\n mean_K_ratio = np.mean([K00_ratio, K11_ratio])\n\n render_bb = codebook_obj_bbs[idx].squeeze()\n est_bb = obj_bb.copy() #Same as obj_bb, thus est_bb=[x,y,w,h], is the 2D bounding box detected, where (x,y) is the 2D location of left-top corner\n #Center of the 2D bbox is (x_c,y_c)=(est_bb[0]+est_bb[2]/2,est_bb[1]+est_bb[3]/2)\n diag_bb_ratio = np.linalg.norm(np.float32(render_bb[2:])) / np.linalg.norm(np.float32(est_bb[2:]))\n\n mm_tz = diag_bb_ratio * mean_K_ratio * Radius_render_train\n\n center_obj_x_train = render_bb[0] + render_bb[2] / 2. - K_train[0, 2]\n center_obj_y_train = render_bb[1] + render_bb[3] / 2. - K_train[1, 2]\n\n center_obj_x_test = est_bb[0] + est_bb[2] / 2 - K_test[0, 2]\n center_obj_y_test = est_bb[1] + est_bb[3] / 2 - K_test[1, 2]\n\n\n\n est_tra = est_tra_w_tz(mm_tz,Radius_render_train,K_test,center_obj_x_test,center_obj_y_test,K_train,center_obj_x_train,center_obj_y_train)\n est_rot=rectify_rot(est_rot_cb,est_tra)\n\n max_mean_dist_factor=2.0\n #Refine the z-direction only.\n mm_tz,max_mean_dist=depth_refinement(crop_depth, model_ply,est_rot.astype(np.float32),est_tra.flatten(), K_test, (W, H), max_mean_dist_factor=max_mean_dist_factor)#5.0)\n\n est_tra = est_tra_w_tz(mm_tz,Radius_render_train,K_test,center_obj_x_test,center_obj_y_test, K_train,center_obj_x_train,center_obj_y_train)\n est_rot=rectify_rot(est_rot_cb,est_tra)\n\n #Further icp refinement for rotation and translation\n if True:\n est_rot,est_tra,_= rotation_error_icp(img_depth, model_o3d, obj_bb, est_rot, est_tra.flatten(),K_test.copy(),\n width=W, height=H, max_mean_dist=max_mean_dist,\n max_mean_dist_factor=max_mean_dist_factor,\n regist_error_threshold=3.0, fitness_threshold=0.7)\n\n\nprint('Step 3: Write result')\nprint('Estimated rotation - model2cam, 3x3 rotation matrix:') ###3x3 rotation matrix\nprint(est_rot.astype(np.float32).reshape((3,3)))\nprint('Estimated translation - model2cam, in mm:') ###translation vector, with unit mm\nprint(est_tra.astype(np.float32).reshape((1,3)))\nprint('Detected 2D bounding box - on 2D image, (x_topleft,y_topleft,bbox_width,bbox_height:')\nprint(np.array(obj_bb).astype(np.int32).reshape((1,4))) ### 2D bounding box\n\n\npath_result='./result.txt'\nwith open(path_result, 'w') as f:\n line_tpl=', '.join(['{:.8f}'] * 9) + '\\n' + ', '.join(['{:.8f}'] * 3)\n Rt = est_rot.astype(np.float32).flatten().tolist() + est_tra.flatten().tolist()\n txt=line_tpl.format(*Rt)\n f.write(txt)\n\n'''\nExpected result:\nif refine for both rotation and translation:\nest_rot: [-0.20446137, 0.94286263, -0.26306966, 0.85182256, 0.03896938, -0.52237886, -0.48227987, -0.33089498, -0.81111938], \nest_tra: [90.49808699, -137.58854774, 849.52665827]\nif refine only z-direction\nest_rot: [-0.15618885, 0.96754020, -0.19867308, 0.86759037, 0.03824597, -0.49580660, -0.47211438, -0.24980631, -0.84540218], \nest_tra: [85.44441029, -146.03545470, 840.30747686]\n'''\n", "meta": {"hexsha": "7a26e331f60a94de3a14b93a25379357f56ae01d", "size": 12036, "ext": "py", "lang": "Python", "max_stars_repo_path": "single3_test_ICP.py", "max_stars_repo_name": "rxjia/EEGP-AAE", "max_stars_repo_head_hexsha": "aaca7185637f4a35907d0fbce9ea54acb9346ebd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2020-07-04T13:07:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T17:32:56.000Z", "max_issues_repo_path": "single3_test_ICP.py", "max_issues_repo_name": "rxjia/EEGP-AAE", "max_issues_repo_head_hexsha": "aaca7185637f4a35907d0fbce9ea54acb9346ebd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-12-04T07:23:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T05:02:12.000Z", "max_forks_repo_path": "single3_test_ICP.py", "max_forks_repo_name": "rxjia/EEGP-AAE", "max_forks_repo_head_hexsha": "aaca7185637f4a35907d0fbce9ea54acb9346ebd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-11T10:40:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-11T10:40:41.000Z", "avg_line_length": 42.3802816901, "max_line_length": 176, "alphanum_fraction": 0.6778830176, "include": true, "reason": "import numpy", "num_tokens": 3310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.27512972976675254, "lm_q1q2_score": 0.14400849915727015}} {"text": "\"\"\"Load transformations from URDF files.\n\nSee :doc:`transform_manager` for more information.\n\"\"\"\nimport os\nimport numpy as np\nfrom bs4 import BeautifulSoup\nfrom .transform_manager import TransformManager\nfrom .transformations import transform_from, concat\nfrom .rotations import (\n active_matrix_from_extrinsic_roll_pitch_yaw, matrix_from_axis_angle,\n norm_vector)\n\n\nclass UrdfTransformManager(TransformManager):\n \"\"\"Transformation manager that can load URDF files.\n\n URDF is the `Unified Robot Description Format `_.\n URDF allows to define joints between links that can be rotated about one\n axis. This transformation manager allows to set the joint angles after\n joints have been added or loaded from an URDF.\n\n .. warning::\n\n Note that this module requires the Python package beautifulsoup4.\n\n .. note::\n\n Joint angles must be given in radians.\n\n Parameters\n ----------\n strict_check : bool, optional (default: True)\n Raise a ValueError if the transformation matrix is not numerically\n close enough to a real transformation matrix. Otherwise we print a\n warning.\n\n check : bool, optional (default: True)\n Check if transformation matrices are valid and requested nodes exist,\n which might significantly slow down some operations.\n \"\"\"\n def __init__(self, strict_check=True, check=True):\n super(UrdfTransformManager, self).__init__(strict_check, check)\n self._joints = {}\n self.collision_objects = []\n self.visuals = []\n\n def add_joint(self, joint_name, from_frame, to_frame, child2parent, axis,\n limits=(float(\"-inf\"), float(\"inf\")), joint_type=\"revolute\"):\n \"\"\"Add joint.\n\n Parameters\n ----------\n joint_name : str\n Name of the joint\n\n from_frame : Hashable\n Child link of the joint\n\n to_frame : Hashable\n Parent link of the joint\n\n child2parent : array-like, shape (4, 4)\n Transformation from child to parent\n\n axis : array-like, shape (3,)\n Rotation axis of the joint (defined in the child frame)\n\n limits : pair of float, optional (default: (-inf, inf))\n Lower and upper joint angle limit\n\n joint_type : str, optional (default: 'revolute')\n Joint type: revolute or prismatic (continuous is the same as\n revolute)\n \"\"\"\n self.add_transform(from_frame, to_frame, child2parent)\n self._joints[joint_name] = (\n from_frame, to_frame, child2parent, norm_vector(axis), limits,\n joint_type)\n\n def set_joint(self, joint_name, value):\n \"\"\"Set joint position.\n\n Note that joint values are clipped to their limits.\n\n Parameters\n ----------\n joint_name : str\n Name of the joint\n\n value : float\n Joint angle in radians in case of revolute joints or position\n in case of prismatic joint.\n\n Raises\n ------\n KeyError\n If joint_name is unknown\n \"\"\"\n if joint_name not in self._joints:\n raise KeyError(\"Joint '%s' is not known\" % joint_name)\n from_frame, to_frame, child2parent, axis, limits, joint_type = \\\n self._joints[joint_name]\n # this is way faster than np.clip:\n value = min(max(value, limits[0]), limits[1])\n if joint_type == \"revolute\":\n joint_rotation = matrix_from_axis_angle(\n np.hstack((axis, (value,))))\n joint2A = transform_from(\n joint_rotation, np.zeros(3), strict_check=self.strict_check)\n else:\n assert joint_type == \"prismatic\"\n joint_offset = value * axis\n joint2A = transform_from(\n np.eye(3), joint_offset, strict_check=self.strict_check)\n self.add_transform(from_frame, to_frame, concat(\n joint2A, child2parent, strict_check=self.strict_check,\n check=self.check))\n\n def get_joint_limits(self, joint_name):\n \"\"\"Get limits of a joint.\n\n Parameters\n ----------\n joint_name : str\n Name of the joint\n\n Returns\n -------\n limits : pair of float\n Lower and upper joint angle limit\n\n Raises\n ------\n KeyError\n If joint_name is unknown\n \"\"\"\n if joint_name not in self._joints:\n raise KeyError(\"Joint '%s' is not known\" % joint_name)\n return self._joints[joint_name][4]\n\n def load_urdf(self, urdf_xml, mesh_path=None, package_dir=None):\n \"\"\"Load URDF file into transformation manager.\n\n Parameters\n ----------\n urdf_xml : str\n Robot definition in URDF\n\n mesh_path : str, optional (default: None)\n Path in which we search for meshes that are defined in the URDF.\n Meshes will be ignored if it is set to None and no 'package_dir'\n is given.\n\n package_dir : str, optional (default: None)\n Some URDFs start file names with 'package://' to refer to the ROS\n package in which these files (textures, meshes) are located. This\n variable defines to which path this prefix will be resolved.\n \"\"\"\n robot_name, links, joints = parse_urdf(\n urdf_xml, mesh_path, package_dir, self.strict_check)\n initialize_urdf_transform_manager(self, robot_name, links, joints)\n\n def plot_visuals(self, frame, ax=None, ax_s=1, wireframe=False,\n convex_hull_of_mesh=True, alpha=0.3): # pragma: no cover\n \"\"\"Plot all visuals in a given reference frame.\n\n Visuals can be boxes, spheres, cylinders, or meshes. Note that visuals\n that cannot be connected to the reference frame are omitted.\n\n Parameters\n ----------\n frame : Hashable\n Reference frame\n\n ax : Matplotlib 3d axis, optional (default: None)\n If the axis is None, a new 3d axis will be created\n\n ax_s : float, optional (default: 1)\n Scaling of the new matplotlib 3d axis\n\n wireframe : bool, optional (default: False)\n Plot wireframe (surface otherwise)\n\n convex_hull_of_mesh : bool, optional (default: True)\n Displays convex hull of meshes instead of the original mesh. This\n makes plotting a lot faster with complex meshes.\n\n alpha : float, optional (default: 0.3)\n Alpha value of the surface / wireframe that will be plotted\n\n Returns\n -------\n ax : Matplotlib 3d axis\n New or old axis\n \"\"\"\n return self._plot_objects(\n self.visuals, frame, ax, ax_s, wireframe, convex_hull_of_mesh,\n alpha)\n\n def plot_collision_objects(\n self, frame, ax=None, ax_s=1, wireframe=True,\n convex_hull_of_mesh=True, alpha=1.0): # pragma: no cover\n \"\"\"Plot all collision objects in a given reference frame.\n\n Collision objects can be boxes, spheres, cylinders, or meshes. Note\n that collision objects that cannot be connected to the reference frame\n are omitted.\n\n Parameters\n ----------\n frame : Hashable\n Reference frame\n\n ax : Matplotlib 3d axis, optional (default: None)\n If the axis is None, a new 3d axis will be created\n\n ax_s : float, optional (default: 1)\n Scaling of the new matplotlib 3d axis\n\n wireframe : bool, optional (default: True)\n Plot wireframe (surface otherwise)\n\n convex_hull_of_mesh : bool, optional (default: True)\n Displays convex hull of meshes instead of the original mesh. This\n makes plotting a lot faster with complex meshes.\n\n alpha : float, optional (default: 1)\n Alpha value of the surface / wireframe that will be plotted\n\n Returns\n -------\n ax : Matplotlib 3d axis\n New or old axis\n \"\"\"\n return self._plot_objects(\n self.collision_objects, frame, ax, ax_s, wireframe,\n convex_hull_of_mesh, alpha)\n\n def _plot_objects(self, objects, frame, ax=None, ax_s=1, wireframe=True,\n convex_hull_of_mesh=True, alpha=1.0): # pragma: no cover\n \"\"\"Plot all objects in a given reference frame.\n\n Objects can be boxes, spheres, cylinders, or meshes. Note that objects\n that cannot be connected to the reference frame are omitted.\n\n Parameters\n ----------\n objects : list\n Objects that will be plotted\n\n frame : Hashable\n Reference frame\n\n ax : Matplotlib 3d axis, optional (default: None)\n If the axis is None, a new 3d axis will be created\n\n ax_s : float, optional (default: 1)\n Scaling of the new matplotlib 3d axis\n\n wireframe : bool, optional (default: True)\n Plot wireframe (surface otherwise)\n\n convex_hull_of_mesh : bool, optional (default: True)\n Displays convex hull of meshes instead of the original mesh. This\n makes plotting a lot faster with complex meshes.\n\n alpha : float, optional (default: 1)\n Alpha value of the surface / wireframe that will be plotted\n\n Returns\n -------\n ax : Matplotlib 3d axis\n New or old axis\n \"\"\"\n if ax is None:\n from .plot_utils import make_3d_axis\n ax = make_3d_axis(ax_s)\n for obj in objects:\n ax = obj.plot(\n self, frame, ax, wireframe=wireframe,\n convex_hull=convex_hull_of_mesh, alpha=alpha)\n return ax\n\n\ndef parse_urdf(urdf_xml, mesh_path=None, package_dir=None, strict_check=True):\n \"\"\"Parse information from URDF file.\n\n Parameters\n ----------\n urdf_xml : str\n Robot definition in URDF\n\n mesh_path : str, optional (default: None)\n Path in which we search for meshes that are defined in the URDF.\n Meshes will be ignored if it is set to None and no 'package_dir'\n is given.\n\n package_dir : str, optional (default: None)\n Some URDFs start file names with 'package://' to refer to the ROS\n package in which these files (textures, meshes) are located. This\n variable defines to which path this prefix will be resolved.\n\n strict_check : bool, optional (default: True)\n Raise a ValueError if the transformation matrix is not numerically\n close enough to a real transformation matrix. Otherwise we print a\n warning.\n\n Returns\n -------\n robot_name : str\n Name of the robot\n\n links : list of Link\n Links of the robot\n\n joints : list of Joint\n Joints of the robot\n\n Raises\n ------\n UrdfException\n If URDF is not valid\n \"\"\"\n urdf = BeautifulSoup(urdf_xml, \"xml\")\n\n # URDF XML schema:\n # https://github.com/ros/urdfdom/blob/master/xsd/urdf.xsd\n\n robot = urdf.find(\"robot\")\n if robot is None:\n raise UrdfException(\"Robot tag is missing.\")\n\n if not robot.has_attr(\"name\"):\n raise UrdfException(\"Attribute 'name' is missing in robot tag.\")\n\n robot_name = robot[\"name\"]\n\n materials = dict([\n _parse_material(material)\n for material in robot.findAll(\"material\", recursive=False)])\n\n links = [_parse_link(link, materials, mesh_path, package_dir, strict_check)\n for link in robot.findAll(\"link\", recursive=False)]\n\n link_names = [link.name for link in links]\n joints = [_parse_joint(joint, link_names, strict_check)\n for joint in robot.findAll(\"joint\", recursive=False)]\n\n return robot_name, links, joints\n\n\ndef initialize_urdf_transform_manager(tm, robot_name, links, joints):\n \"\"\"Initializes transform manager from previously parsed URDF data.\n\n Parameters\n ----------\n tm : UrdfTransformManager\n Transform manager\n\n robot_name : str\n Name of the robot\n\n links : list of Link\n Links of the robot\n\n joints : list of Joint\n Joints of the robot\n \"\"\"\n tm.add_transform(links[0].name, robot_name, np.eye(4))\n _add_links(tm, links)\n _add_joints(tm, joints)\n\n\ndef _parse_material(material):\n \"\"\"Parse material.\"\"\"\n if not material.has_attr(\"name\"):\n raise UrdfException(\"Material name is missing.\")\n colors = material.findAll(\"color\")\n if len(colors) not in [0, 1]:\n raise UrdfException(\"More than one color is not allowed.\")\n if len(colors) == 1:\n color = _parse_color(colors[0])\n else:\n color = None\n # TODO texture is currently ignored\n return material[\"name\"], color\n\n\ndef _parse_color(color):\n \"\"\"Parse color.\"\"\"\n if not color.has_attr(\"rgba\"):\n raise UrdfException(\"Attribute 'rgba' of color tag is missing.\")\n return np.fromstring(color[\"rgba\"], sep=\" \")\n\n\ndef _parse_link(link, materials, mesh_path, package_dir, strict_check):\n \"\"\"Create link.\"\"\"\n if not link.has_attr(\"name\"):\n raise UrdfException(\"Link name is missing.\")\n\n result = Link()\n result.name = link[\"name\"]\n\n visuals, visual_transforms = _parse_link_children(\n link, \"visual\", materials, mesh_path, package_dir, strict_check)\n result.visuals = visuals\n result.transforms.extend(visual_transforms)\n\n collision_objects, collision_object_transforms = _parse_link_children(\n link, \"collision\", dict(), mesh_path, package_dir, strict_check)\n result.collision_objects = collision_objects\n result.transforms.extend(collision_object_transforms)\n\n inertial = link.find(\"inertial\")\n if inertial is not None:\n result.inertial_frame[:, :] = _parse_origin(inertial, strict_check)\n result.mass = _parse_mass(inertial)\n result.inertia[:, :] = _parse_inertia(inertial)\n result.transforms.append(\n (\"inertial_frame:%s\" % result.name, result.name,\n result.inertial_frame))\n\n return result\n\n\ndef _parse_link_children(link, child_type, materials, mesh_path, package_dir,\n strict_check):\n \"\"\"Parse collision objects or visuals.\"\"\"\n children = link.findAll(child_type)\n shape_objects = []\n transforms = []\n for i, child in enumerate(children):\n if child.has_attr(\"name\"):\n name = \"%s:%s/%s\" % (child_type, link[\"name\"], child[\"name\"])\n else:\n name = \"%s:%s/%s\" % (child_type, link[\"name\"], i)\n\n color = None\n if child_type == \"visual\":\n material = child.find(\"material\")\n if material is not None:\n material_name, color = _parse_material(material)\n if color is None and material_name in materials:\n color = materials[material_name]\n\n child2link = _parse_origin(child, strict_check)\n transforms.append((name, link[\"name\"], child2link))\n\n shape_objects.extend(_parse_geometry(\n child, name, color, mesh_path, package_dir))\n return shape_objects, transforms\n\n\ndef _parse_geometry(child, name, color, mesh_path, package_dir):\n \"\"\"Parse geometric primitives (box, cylinder, sphere) or meshes.\"\"\"\n geometry = child.find(\"geometry\")\n if geometry is None:\n raise UrdfException(\"Missing geometry tag in link '%s'\" % name)\n result = []\n for shape_type in [\"box\", \"cylinder\", \"sphere\", \"mesh\"]:\n shapes = geometry.findAll(shape_type)\n Cls = shape_classes[shape_type]\n for shape in shapes:\n shape_object = Cls(\n name, mesh_path=mesh_path, package_dir=package_dir,\n color=color)\n shape_object.parse(shape)\n result.append(shape_object)\n return result\n\n\ndef _parse_origin(entry, strict_check):\n \"\"\"Parse transformation.\"\"\"\n origin = entry.find(\"origin\")\n translation = np.zeros(3)\n rotation = np.eye(3)\n if origin is not None:\n if origin.has_attr(\"xyz\"):\n translation = np.fromstring(origin[\"xyz\"], sep=\" \")\n if origin.has_attr(\"rpy\"):\n roll_pitch_yaw = np.fromstring(origin[\"rpy\"], sep=\" \")\n # URDF and KDL use the active convention for rotation matrices.\n # For more details on how the URDF parser handles the\n # conversion from Euler angles, see this blog post:\n # https://orbitalstation.wordpress.com/tag/quaternion/\n rotation = active_matrix_from_extrinsic_roll_pitch_yaw(\n roll_pitch_yaw)\n return transform_from(\n rotation, translation, strict_check=strict_check)\n\n\ndef _parse_mass(inertial):\n \"\"\"Parse link mass.\"\"\"\n mass = inertial.find(\"mass\")\n if mass is not None and mass.has_attr(\"value\"):\n result = float(mass[\"value\"])\n else:\n result = 0.0\n return result\n\n\ndef _parse_inertia(inertial):\n \"\"\"Parse inertia matrix.\"\"\"\n inertia = inertial.find(\"inertia\")\n\n result = np.zeros((3, 3))\n if inertia is None:\n return result\n\n if inertia.has_attr(\"ixx\"):\n result[0, 0] = float(inertia[\"ixx\"])\n if inertia.has_attr(\"ixy\"):\n ixy = float(inertia[\"ixy\"])\n result[0, 1] = ixy\n result[1, 0] = ixy\n if inertia.has_attr(\"ixz\"):\n ixz = float(inertia[\"ixz\"])\n result[0, 2] = ixz\n result[2, 0] = ixz\n if inertia.has_attr(\"iyy\"):\n result[1, 1] = float(inertia[\"iyy\"])\n if inertia.has_attr(\"iyz\"):\n iyz = float(inertia[\"iyz\"])\n result[1, 2] = iyz\n result[2, 1] = iyz\n if inertia.has_attr(\"izz\"):\n result[2, 2] = float(inertia[\"izz\"])\n return result\n\n\ndef _parse_joint(joint, link_names, strict_check):\n \"\"\"Create joint object.\"\"\"\n j = Joint()\n\n if not joint.has_attr(\"name\"):\n raise UrdfException(\"Joint name is missing.\")\n j.joint_name = joint[\"name\"]\n\n if not joint.has_attr(\"type\"):\n raise UrdfException(\"Joint type is missing in joint '%s'.\"\n % j.joint_name)\n\n parent = joint.find(\"parent\")\n if parent is None:\n raise UrdfException(\"No parent specified in joint '%s'\"\n % j.joint_name)\n if not parent.has_attr(\"link\"):\n raise UrdfException(\"No parent link name given in joint '%s'.\"\n % j.joint_name)\n j.parent = parent[\"link\"]\n if j.parent not in link_names:\n raise UrdfException(\"Parent link '%s' of joint '%s' is not \"\n \"defined.\" % (j.parent, j.joint_name))\n\n child = joint.find(\"child\")\n if child is None:\n raise UrdfException(\"No child specified in joint '%s'\"\n % j.joint_name)\n if not child.has_attr(\"link\"):\n raise UrdfException(\"No child link name given in joint '%s'.\"\n % j.joint_name)\n j.child = child[\"link\"]\n if j.child not in link_names:\n raise UrdfException(\"Child link '%s' of joint '%s' is not \"\n \"defined.\" % (j.child, j.joint_name))\n\n j.joint_type = joint[\"type\"]\n\n if j.joint_type in [\"planar\", \"floating\"]:\n raise UrdfException(\"Unsupported joint type '%s'\" % j.joint_type)\n if j.joint_type not in [\"revolute\", \"continuous\", \"prismatic\",\n \"fixed\"]:\n raise UrdfException(\"Joint type '%s' is not allowed in a URDF \"\n \"document.\" % j.joint_type)\n\n j.child2parent = _parse_origin(joint, strict_check)\n\n j.joint_axis = np.array([1, 0, 0])\n if j.joint_type in [\"revolute\", \"continuous\", \"prismatic\"]:\n axis = joint.find(\"axis\")\n if axis is not None and axis.has_attr(\"xyz\"):\n j.joint_axis = np.fromstring(axis[\"xyz\"], sep=\" \")\n\n j.limits = _parse_limits(joint)\n return j\n\n\ndef _parse_limits(joint):\n \"\"\"Parse joint limits.\"\"\"\n limit = joint.find(\"limit\")\n lower, upper = float(\"-inf\"), float(\"inf\")\n if limit is not None:\n if limit.has_attr(\"lower\"):\n lower = float(limit[\"lower\"])\n if limit.has_attr(\"upper\"):\n upper = float(limit[\"upper\"])\n return lower, upper\n\n\ndef _add_links(tm, links):\n \"\"\"Add previously parsed links.\n\n Parameters\n ----------\n tm : UrdfTransformManager\n Transform manager\n\n links : list of Link\n Joint information from URDF\n \"\"\"\n for link in links:\n tm.visuals.extend(link.visuals)\n tm.collision_objects.extend(link.collision_objects)\n\n for from_frame, to_frame, transform in link.transforms:\n tm.add_transform(from_frame, to_frame, transform)\n\n\ndef _add_joints(tm, joints):\n \"\"\"Add previously parsed joints.\n\n Parameters\n ----------\n tm : UrdfTransformManager\n Transform manager\n\n joints : list of Joint\n Joint information from URDF\n \"\"\"\n for joint in joints:\n if joint.joint_type in [\"revolute\", \"continuous\"]:\n tm.add_joint(\n joint.joint_name, joint.child, joint.parent,\n joint.child2parent, joint.joint_axis, joint.limits,\n \"revolute\")\n elif joint.joint_type == \"prismatic\":\n tm.add_joint(\n joint.joint_name, joint.child, joint.parent,\n joint.child2parent, joint.joint_axis, joint.limits,\n \"prismatic\")\n else:\n assert joint.joint_type == \"fixed\"\n tm.add_transform(joint.child, joint.parent, joint.child2parent)\n\n\nclass Link(object):\n \"\"\"Link from URDF file.\n\n This class is only required temporarily while we parse the URDF.\n\n Attributes\n ----------\n name : str\n Link name\n\n visuals : list of Geometry\n Visual geometries\n\n collision_objects : list of Geometry\n Geometries for collision calculation\n\n transforms : list\n Transformations given as tuples: name of frame A, name of frame B,\n transform A2B\n\n inertial_frame : array, shape (4, 4)\n Pose of inertial frame with respect to the link\n\n mass : float\n Mass of the link\n\n inertia : array, shape (3, 3)\n Inertia matrix\n \"\"\"\n def __init__(self):\n self.name = None\n self.visuals = []\n self.collision_objects = []\n self.transforms = []\n self.inertial_frame = np.eye(4)\n self.mass = 0.0\n self.inertia = np.zeros((3, 3))\n\n\nclass Joint(object):\n \"\"\"Joint from URDF file.\n\n This class is only required temporarily while we parse the URDF.\n\n Attributes\n ----------\n child : str\n Name of the child\n\n parent : str\n Name of the parent frame\n\n child2parent : array-like, shape (4, 4)\n Transformation from child to parent\n\n joint_name : str\n Name of the joint that defines the transformation\n\n joint_axis : array-like, shape (3,)\n Rotation axis of the joint (defined in the child frame)\n\n joint_type : str\n Either 'fixed' or 'revolute'\n\n limits : pair of float\n Lower and upper joint angle limit\n \"\"\"\n def __init__(self):\n self.child = None\n self.parent = None\n self.child2parent = np.eye(4)\n self.joint_name = None\n self.joint_axis = None\n self.joint_type = \"fixed\"\n self.limits = float(\"-inf\"), float(\"inf\")\n\n\nclass Geometry(object):\n \"\"\"Geometrical object.\"\"\"\n def __init__(self, frame, mesh_path, package_dir, color):\n self.frame = frame\n self.mesh_path = mesh_path\n self.package_dir = package_dir\n self.color = color\n\n def parse(self, xml):\n \"\"\"Parse parameters of geometry.\"\"\"\n\n def plot(self, tm, frame, ax=None, alpha=0.3, wireframe=True,\n convex_hull=True):\n \"\"\"Plot geometry.\"\"\"\n\n\nclass Box(Geometry):\n \"\"\"Geometrical object: box.\"\"\"\n def __init__(self, frame, mesh_path, package_dir, color):\n super(Box, self).__init__(frame, mesh_path, package_dir, color)\n self.size = np.zeros(3)\n\n def parse(self, xml):\n \"\"\"Parse box size.\"\"\"\n if xml.has_attr(\"size\"):\n self.size[:] = np.fromstring(xml[\"size\"], sep=\" \")\n\n def plot(self, tm, frame, ax=None, alpha=0.3, wireframe=True,\n convex_hull=True): # pragma: no cover\n \"\"\"Plot box.\"\"\"\n A2B = tm.get_transform(self.frame, frame)\n color = self.color if self.color is not None else \"k\"\n from .plot_utils import plot_box\n return plot_box(\n ax, self.size, A2B, wireframe=wireframe, alpha=alpha, color=color)\n\n\nclass Sphere(Geometry):\n \"\"\"Geometrical object: sphere.\"\"\"\n def __init__(self, frame, mesh_path, package_dir, color):\n super(Sphere, self).__init__(frame, mesh_path, package_dir, color)\n self.radius = 0.0\n\n def parse(self, xml):\n \"\"\"Parse sphere radius.\"\"\"\n if not xml.has_attr(\"radius\"):\n raise UrdfException(\"Sphere has no radius.\")\n self.radius = float(xml[\"radius\"])\n\n def plot(self, tm, frame, ax=None, alpha=0.3, wireframe=True,\n convex_hull=True): # pragma: no cover\n \"\"\"Plot sphere.\"\"\"\n center = tm.get_transform(self.frame, frame)[:3, 3]\n color = self.color if self.color is not None else \"k\"\n from .plot_utils import plot_sphere\n return plot_sphere(\n ax, self.radius, center, wireframe=wireframe, alpha=alpha,\n color=color)\n\n\nclass Cylinder(Geometry):\n \"\"\"Geometrical object: cylinder.\"\"\"\n def __init__(self, frame, mesh_path, package_dir, color):\n super(Cylinder, self).__init__(frame, mesh_path, package_dir, color)\n self.radius = 0.0\n self.length = 0.0\n\n def parse(self, xml):\n \"\"\"Parse cylinder radius and length.\"\"\"\n if not xml.has_attr(\"radius\"):\n raise UrdfException(\"Cylinder has no radius.\")\n self.radius = float(xml[\"radius\"])\n if not xml.has_attr(\"length\"):\n raise UrdfException(\"Cylinder has no length.\")\n self.length = float(xml[\"length\"])\n\n def plot(self, tm, frame, ax=None, alpha=0.3, wireframe=True,\n convex_hull=True): # pragma: no cover\n \"\"\"Plot cylinder.\"\"\"\n A2B = tm.get_transform(self.frame, frame)\n color = self.color if self.color is not None else \"k\"\n from .plot_utils import plot_cylinder\n return plot_cylinder(\n ax, self.length, self.radius, 0.0, A2B, wireframe=wireframe,\n alpha=alpha, color=color)\n\n\nclass Mesh(Geometry):\n \"\"\"Geometrical object: mesh.\"\"\"\n def __init__(self, frame, mesh_path, package_dir, color):\n super(Mesh, self).__init__(frame, mesh_path, package_dir, color)\n self.filename = None\n self.scale = np.ones(3)\n\n def parse(self, xml):\n \"\"\"Parse mesh filename and scale.\"\"\"\n if self.mesh_path is None and self.package_dir is None:\n self.filename = None\n else:\n if not xml.has_attr(\"filename\"):\n raise UrdfException(\"Mesh has no filename.\")\n if self.mesh_path is not None:\n self.filename = os.path.join(self.mesh_path, xml[\"filename\"])\n else:\n assert self.package_dir is not None\n self.filename = xml[\"filename\"].replace(\n \"package://\", self.package_dir)\n if xml.has_attr(\"scale\"):\n self.scale = np.fromstring(xml[\"scale\"], sep=\" \")\n\n def plot(self, tm, frame, ax=None, alpha=0.3, wireframe=True,\n convex_hull=True): # pragma: no cover\n \"\"\"Plot mesh.\"\"\"\n from .plot_utils import plot_mesh\n A2B = tm.get_transform(self.frame, frame)\n color = self.color if self.color is not None else \"k\"\n return plot_mesh(\n ax, self.filename, A2B, self.scale, wireframe=wireframe,\n convex_hull=convex_hull, alpha=alpha, color=color)\n\n\nshape_classes = {\"box\": Box,\n \"sphere\": Sphere,\n \"cylinder\": Cylinder,\n \"mesh\": Mesh}\n\n\nclass UrdfException(Exception):\n \"\"\"Exception while parsing URDF files.\"\"\"\n", "meta": {"hexsha": "0eee6d2b9703b4e79d9abf83d1222cd7c89e1d77", "size": 28092, "ext": "py", "lang": "Python", "max_stars_repo_path": "pytransform3d/urdf.py", "max_stars_repo_name": "alek5k/pytransform3d", "max_stars_repo_head_hexsha": "c6fb10b1d17713bd8a2d6becb928c4f6dcf611f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 304, "max_stars_repo_stars_event_min_datetime": "2019-01-16T15:14:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:14:37.000Z", "max_issues_repo_path": "pytransform3d/urdf.py", "max_issues_repo_name": "alek5k/pytransform3d", "max_issues_repo_head_hexsha": "c6fb10b1d17713bd8a2d6becb928c4f6dcf611f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 94, "max_issues_repo_issues_event_min_datetime": "2018-12-07T14:54:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T22:38:20.000Z", "max_forks_repo_path": "pytransform3d/urdf.py", "max_forks_repo_name": "alek5k/pytransform3d", "max_forks_repo_head_hexsha": "c6fb10b1d17713bd8a2d6becb928c4f6dcf611f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 37, "max_forks_repo_forks_event_min_datetime": "2018-12-09T23:58:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T02:29:53.000Z", "avg_line_length": 32.9331770223, "max_line_length": 79, "alphanum_fraction": 0.6074327211, "include": true, "reason": "import numpy", "num_tokens": 6413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.2814056194821861, "lm_q1q2_score": 0.1439999281460966}} {"text": "import os\n\nimport numpy as np\n\nimport torch\nfrom torch import nn\nfrom boxlist import cat_boxlist, boxlist_iou\n\nimport math\n\nINF = 100000000\n \nclass SigmoidFocalLoss(nn.Module):\n def __init__(self, gamma, alpha):\n super().__init__()\n\n self.gamma = gamma\n self.alpha = alpha\n self.eps = 1e-6\n\n def forward(self, out, target):\n n_class = out.shape[1]\n class_ids = torch.arange(\n 1, n_class + 1, dtype=target.dtype, device=target.device\n ).unsqueeze(0)\n\n t = target.unsqueeze(1)\n p = torch.sigmoid(out)\n p = torch.clamp(p, self.eps, 1-self.eps) # for numerical stability\n\n gamma = self.gamma\n alpha = self.alpha\n\n term1 = (1 - p) ** gamma * torch.log(p)\n term2 = p ** gamma * torch.log(1 - p)\n\n # print(term1.sum(), term2.sum())\n\n loss = (\n -(t == class_ids).float() * alpha * term1\n - ((t != class_ids) * (t >= 0)).float() * (1 - alpha) * term2\n )\n\n return loss.sum()\n\ndef get_num_gpus():\n return int(os.environ[\"WORLD_SIZE\"]) if \"WORLD_SIZE\" in os.environ else 1\n\ndef reduce_sum(tensor):\n if get_num_gpus() <= 1:\n return tensor\n import torch.distributed as dist\n tensor = tensor.clone()\n dist.all_reduce(tensor, op=dist.reduce_op.SUM)\n return tensor\n\ndef cat(tensors, dim=0):\n \"\"\"\n Efficient version of torch.cat that avoids a copy if there is only a single element in a list\n \"\"\"\n assert isinstance(tensors, (list, tuple))\n if len(tensors) == 1:\n return tensors[0]\n return torch.cat(tensors, dim)\n\ndef permute_and_flatten(layer, N, A, C, H, W):\n layer = layer.view(N, -1, C, H, W)\n layer = layer.permute(0, 3, 4, 1, 2)\n layer = layer.reshape(N, -1, C)\n return layer\n\ndef concat_box_prediction_layers(pred_cls, pred_reg):\n pred_cls_flattened = []\n pred_reg_flattened = []\n # for each feature level, permute the outputs to make them be in the\n # same format as the labels. Note that the labels are computed for\n # all feature levels concatenated, so we keep the same representation\n # for the objectness and the pred_reg\n for pred_cls_per_level, pred_reg_per_level in zip(pred_cls, pred_reg):\n N, AxC, H, W = pred_cls_per_level.shape\n Cx16 = pred_reg_per_level.shape[1]\n C = Cx16 // 16\n A = 1\n pred_cls_per_level = permute_and_flatten(\n pred_cls_per_level, N, A, C, H, W\n )\n pred_cls_flattened.append(pred_cls_per_level)\n\n pred_reg_per_level = permute_and_flatten(\n pred_reg_per_level, N, A, (C*16), H, W\n )\n pred_reg_flattened.append(pred_reg_per_level)\n # concatenate on the first dimension (representing the feature levels), to\n # take into account the way the labels were generated (with all feature maps\n # being concatenated as well)\n pred_cls = cat(pred_cls_flattened, dim=1).reshape(-1, C)\n pred_reg = cat(pred_reg_flattened, dim=1).reshape(-1, C*16)\n return pred_cls, pred_reg\n\nclass PoseLoss(object):\n def __init__(self, gamma, alpha, anchor_sizes, anchor_strides, positive_num, positive_lambda,\n loss_weight_cls, loss_weight_reg, internal_K, diameters, target_coder):\n self.cls_loss_func = SigmoidFocalLoss(gamma, alpha)\n # self.centerness_loss_func = nn.BCEWithLogitsLoss(reduction=\"sum\")\n # self.matcher = Matcher(fg_iou_threshold, bg_iou_threshold, True)\n self.anchor_sizes = anchor_sizes\n self.anchor_strides = anchor_strides\n self.positive_num = positive_num\n self.positive_lambda = positive_lambda\n self.loss_weight_cls = loss_weight_cls\n self.loss_weight_reg = loss_weight_reg\n self.internal_K = internal_K\n self.target_coder = target_coder\n self.diameters = diameters\n\n def ObjectSpaceLoss(self, pred, target_3D_in_camera_frame, cls_labels, anchors, weight=None):\n if not isinstance(self.diameters, torch.Tensor):\n self.diameters = torch.FloatTensor(self.diameters).to(device=pred.device).view(-1)\n \n diameter_ext = self.diameters[cls_labels.view(-1,1).repeat(1, 8*3).view(-1, 3, 1)]\n\n cellNum = pred.shape[0]\n pred_filtered = pred.view(cellNum, -1, 16)[torch.arange(cellNum), cls_labels]\n\n pred_xy = self.target_coder.decode(pred_filtered, anchors)\n # target_xy = self.target_coder.decode(target, anchors)\n\n pred_xy = pred_xy.view(-1,2,8).transpose(1,2).contiguous().view(-1,2)\n\n # construct normalized 2d\n B = torch.inverse(self.internal_K).mm(torch.cat((pred_xy.t(), torch.ones_like(pred_xy[:,0]).view(1,-1)), dim=0)).t()\n # compute projection matrices\n P = torch.bmm(B.view(-1, 3, 1), B.view(-1, 1, 3)) / torch.bmm(B.view(-1, 1, 3), B.view(-1, 3, 1))\n\n target_3D_in_camera_frame = target_3D_in_camera_frame.view(-1, 3, 1)\n px = torch.bmm(P, target_3D_in_camera_frame)\n\n target_3D_in_camera_frame = target_3D_in_camera_frame / diameter_ext\n px = px / diameter_ext\n scaling_factor = 50 # 0.02d\n losses = nn.SmoothL1Loss(reduction='none')(scaling_factor * px, scaling_factor * target_3D_in_camera_frame).view(cellNum, -1).mean(dim=1)\n losses = losses / scaling_factor\n\n if weight is not None and weight.sum() > 0:\n return (losses * weight).sum()\n else:\n assert losses.numel() != 0\n return losses.sum()\n\n def prepare_targets(self, targets, anchors):\n cls_labels = []\n reg_targets = []\n aux_raw_boxes = []\n aux_3D_in_camera_frame = []\n level_cnt = len(anchors[0])\n for im_i in range(len(targets)):\n pose_targets_per_im = targets[im_i]\n bbox_targets_per_im = pose_targets_per_im.to_object_boxlist()\n assert bbox_targets_per_im.mode == \"xyxy\"\n bboxes_per_im = bbox_targets_per_im.bbox\n labels_per_im = pose_targets_per_im.class_ids + 1\n anchors_per_im = cat_boxlist(anchors[im_i])\n num_gt = bboxes_per_im.shape[0]\n assert(level_cnt == len(anchors[im_i]))\n # \n rotations_per_im = pose_targets_per_im.rotations\n translations_per_im = pose_targets_per_im.translations\n mask_per_im = pose_targets_per_im.mask\n\n # \n anchor_sizes_per_level_interest = self.anchor_sizes[:level_cnt]\n anchor_strides_per_level_interst = self.anchor_strides[:level_cnt]\n gt_object_sizes = bbox_targets_per_im.box_span()\n\n num_anchors_per_level = [len(anchors_per_level.bbox) for anchors_per_level in anchors[im_i]]\n \n anchors_cx_per_im = (anchors_per_im.bbox[:, 2] + anchors_per_im.bbox[:, 0]) / 2.0\n anchors_cy_per_im = (anchors_per_im.bbox[:, 3] + anchors_per_im.bbox[:, 1]) / 2.0\n anchors_cx_per_im = torch.clamp(anchors_cx_per_im, min = 0, max = mask_per_im.shape[1] - 1).long()\n anchors_cy_per_im = torch.clamp(anchors_cy_per_im, min = 0, max = mask_per_im.shape[0] - 1).long()\n\n mask_at_anchors = mask_per_im[anchors_cy_per_im, anchors_cx_per_im]\n mask_labels = []\n for gt_i in range(num_gt):\n valid_mask = (mask_at_anchors == (gt_i+1))\n mask_labels.append(valid_mask)\n mask_labels = torch.stack(mask_labels).t()\n mask_labels = mask_labels.long()\n\n # random selecting candidates from each level first\n candidate_idxs = [[] for i in range(num_gt)]\n start_idx = 0\n gt_sz = gt_object_sizes.view(1,-1).repeat(level_cnt,1)\n lv_sz = torch.FloatTensor(anchor_sizes_per_level_interest).type_as(gt_sz)\n lv_sz = lv_sz.view(-1,1).repeat(1,num_gt)\n dk = torch.log2(gt_sz/lv_sz).abs()\n nk = torch.exp(-self.positive_lambda * (dk * dk))\n nk = self.positive_num * nk / nk.sum(0, keepdim=True)\n nk = (nk + 0.5).int()\n for level in range(level_cnt):\n end_idx = start_idx + num_anchors_per_level[level]\n is_in_mask_per_level = mask_labels[start_idx:end_idx, :]\n # \n for gt_i in range(num_gt):\n posi_num = nk[level][gt_i]\n\n valid_pos = is_in_mask_per_level[:, gt_i].nonzero().view(-1)\n posi_num = min(posi_num, len(valid_pos))\n # rand_idx = torch.randint(0, len(valid_pos), (int(posi_num),)) # randoms with replacement\n rand_idx = torch.randperm(len(valid_pos))[:posi_num] # randoms without replacement\n candi_pos = valid_pos[rand_idx] + start_idx\n candidate_idxs[gt_i].append(candi_pos)\n # \n start_idx = end_idx\n\n # flagging selected positions\n roi = torch.full_like(mask_labels, -INF)\n for gt_i in range(num_gt):\n tmp_idx = torch.cat(candidate_idxs[gt_i], dim=0)\n roi[tmp_idx, gt_i] = 1\n\n anchors_to_gt_values, anchors_to_gt_indexs = roi.max(dim=1)\n cls_labels_per_im = labels_per_im[anchors_to_gt_indexs]\n cls_labels_per_im[anchors_to_gt_values == -INF] = 0 # background setting\n\n mask_visibilities, _ = mask_labels.max(dim=1)\n # logical_and, introduced only after pytorch 1.5\n # ignored_indexs = torch.logical_and(mask_visibilities==1, cls_labels_per_im==0)\n ignored_indexs = (mask_visibilities == 1) * (cls_labels_per_im == 0)\n cls_labels_per_im[ignored_indexs] = -1 # positions within mask but not selected will not be touched\n\n # \n matched_boxes = bboxes_per_im[anchors_to_gt_indexs]\n matched_classes = (labels_per_im - 1)[anchors_to_gt_indexs]\n matched_rotations = rotations_per_im[anchors_to_gt_indexs]\n matched_translations = translations_per_im[anchors_to_gt_indexs]\n\n # \n matched_3Ds = pose_targets_per_im.keypoints_3d[matched_classes]\n # matched_Ks = pose_targets_per_im.K.repeat(matched_classes.shape[0], 1, 1)\n # TODO\n # assert equals self K\n if not isinstance(self.internal_K, torch.Tensor):\n self.internal_K = torch.FloatTensor(self.internal_K).to(device=matched_3Ds.device).view(3, 3)\n reg_targets_per_im = self.target_coder.encode(\n self.internal_K, matched_3Ds, \n matched_rotations, matched_translations,\n anchors_per_im.bbox)\n cls_labels.append(cls_labels_per_im)\n reg_targets.append(reg_targets_per_im)\n aux_raw_boxes.append(matched_boxes)\n matched_3D_in_camera_frame = torch.bmm(matched_rotations, matched_3Ds.transpose(1, 2)) + matched_translations\n aux_3D_in_camera_frame.append(matched_3D_in_camera_frame.transpose(1, 2))\n\n return cls_labels, reg_targets, aux_raw_boxes, aux_3D_in_camera_frame\n\n def __call__(self, pred_cls, pred_reg, targets, anchors):\n labels, reg_targets, aux_raw_boxes, aux_3D_in_camera_frame = self.prepare_targets(targets, anchors)\n\n N = len(labels)\n pred_cls_flatten, pred_reg_flatten = concat_box_prediction_layers(pred_cls, pred_reg)\n\n labels_flatten = torch.cat(labels, dim=0)\n reg_targets_flatten = torch.cat(reg_targets, dim=0)\n aux_raw_boxes_flatten = torch.cat(aux_raw_boxes, dim=0)\n aux_3D_in_camera_frame_flatten = torch.cat(aux_3D_in_camera_frame, dim=0)\n anchors_flatten = torch.cat([cat_boxlist(anchors_per_image).bbox for anchors_per_image in anchors], dim=0)\n\n pos_inds = torch.nonzero(labels_flatten > 0).squeeze(1)\n\n valid_cls_inds = torch.nonzero(labels_flatten >= 0).squeeze(1)\n cls_loss = self.cls_loss_func(pred_cls_flatten[valid_cls_inds], labels_flatten[valid_cls_inds])\n\n if pos_inds.numel() > 0:\n pred_reg_flatten = pred_reg_flatten[pos_inds]\n cls_label_flatten = labels_flatten[pos_inds] - 1 # start from class 0\n reg_targets_flatten = reg_targets_flatten[pos_inds]\n aux_raw_boxes_flatten = aux_raw_boxes_flatten[pos_inds]\n aux_3D_in_camera_frame_flatten = aux_3D_in_camera_frame_flatten[pos_inds]\n anchors_flatten = anchors_flatten[pos_inds]\n\n reg_loss = self.ObjectSpaceLoss(\n pred_reg_flatten, aux_3D_in_camera_frame_flatten, \n cls_label_flatten, anchors_flatten\n )\n else:\n reg_loss = pred_reg_flatten.sum()\n\n return cls_loss * self.loss_weight_cls, reg_loss * self.loss_weight_reg\n", "meta": {"hexsha": "3fd2fc8a3ccd35e55c0da0d050bb5a3a976892a5", "size": 12750, "ext": "py", "lang": "Python", "max_stars_repo_path": "loss.py", "max_stars_repo_name": "garrofederico/wide-depth-range-pose-improved", "max_stars_repo_head_hexsha": "42203babf49f98d83003e6d0ad9fe13c97d96761", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2021-04-02T07:20:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T02:43:24.000Z", "max_issues_repo_path": "loss.py", "max_issues_repo_name": "garrofederico/wide-depth-range-pose-improved", "max_issues_repo_head_hexsha": "42203babf49f98d83003e6d0ad9fe13c97d96761", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-07-09T02:33:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-17T08:34:30.000Z", "max_forks_repo_path": "loss.py", "max_forks_repo_name": "garrofederico/wide-depth-range-pose-improved", "max_forks_repo_head_hexsha": "42203babf49f98d83003e6d0ad9fe13c97d96761", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2021-04-07T08:47:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-04T22:16:52.000Z", "avg_line_length": 43.9655172414, "max_line_length": 145, "alphanum_fraction": 0.6418823529, "include": true, "reason": "import numpy", "num_tokens": 3212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.28140560742914383, "lm_q1q2_score": 0.14399992197835473}} {"text": "#!/usr/bin/env python\n# encoding: utf-8\n\n\n\"\"\"\nA module for parsing information from various files.\n\"\"\"\n\nfrom __future__ import (absolute_import, division, print_function, unicode_literals)\nimport numpy as np\nimport os\n\nfrom arkane.statmech import determine_qm_software\nfrom arkane.qchem import QChemLog\nfrom arkane.gaussian import GaussianLog\nfrom arkane.molpro import MolproLog\n\nfrom arc.common import get_logger\nfrom arc.species.converter import get_xyz_string, standardize_xyz_string\nfrom arc.arc_exceptions import InputError, ParserError\n\n##################################################################\n\nlogger = get_logger()\n\n\ndef parse_frequencies(path, software):\n \"\"\"\n Parse the frequencies from a freq job output file.\n \"\"\"\n lines = _get_lines_from_file(path)\n freqs = np.array([], np.float64)\n if software.lower() == 'qchem':\n for line in lines:\n if ' Frequency:' in line:\n items = line.split()\n for i, item in enumerate(items):\n if i:\n freqs = np.append(freqs, [(float(item))])\n elif software.lower() == 'gaussian':\n with open(path, 'r') as f:\n line = f.readline()\n while line != '':\n if 'Frequencies --' in line:\n freqs = np.append(freqs, [float(frq) for frq in line.split()[2:]])\n line = f.readline()\n elif software.lower() == 'molpro':\n read = False\n for line in lines:\n if 'Nr' in line and '[1/cm]' in line:\n continue\n if read:\n if line == os.linesep:\n read = False\n continue\n freqs = np.append(freqs, [float(line.split()[-1])])\n if 'Low' not in line and 'Vibration' in line and 'Wavenumber' in line:\n read = True\n else:\n raise ParserError('parse_frequencies() can currently only parse Molpro, QChem and Gaussian files,'\n ' got {0}'.format(software))\n logger.debug('Using parser.parse_frequencies. Determined frequencies are: {0}'.format(freqs))\n return freqs\n\n\ndef parse_t1(path):\n \"\"\"\n Parse the T1 parameter from a Molpro coupled cluster calculation.\n \"\"\"\n lines = _get_lines_from_file(path)\n t1 = None\n for line in lines:\n if 'T1 diagnostic:' in line:\n t1 = float(line.split()[-1])\n return t1\n\n\ndef parse_e_elect(path, zpe_scale_factor=1.):\n \"\"\"\n Parse the zero K energy, E0, from an sp job output file.\n \"\"\"\n if not os.path.isfile(path):\n raise InputError('Could not find file {0}'.format(path))\n log = determine_qm_software(fullpath=path)\n try:\n e_elect = log.loadEnergy(zpe_scale_factor) * 0.001 # convert to kJ/mol\n except Exception:\n logger.warning('Could not read e_elect from {0}'.format(path))\n e_elect = None\n return e_elect\n\n\ndef parse_xyz_from_file(path):\n \"\"\"\n Parse xyz coordinated from:\n .xyz - XYZ file\n .gjf - Gaussian input file\n .out or .log - ESS output file (Gaussian, QChem, Molpro)\n other - Molpro or QChem input file\n \"\"\"\n lines = _get_lines_from_file(path)\n file_extension = os.path.splitext(path)[1]\n\n xyz = None\n relevant_lines = list()\n\n if file_extension == '.xyz':\n relevant_lines = lines[2:]\n elif file_extension == '.gjf':\n start_parsing = False\n for line in lines:\n if start_parsing and line and line != '\\n' and line != '\\r\\n':\n relevant_lines.append(line)\n elif start_parsing:\n break\n else:\n splits = line.split()\n if len(splits) == 2 and all([s.isdigit() for s in splits]):\n start_parsing = True\n elif 'out' in file_extension or 'log' in file_extension:\n log = determine_qm_software(fullpath=path)\n coords, number, _ = log.loadGeometry()\n xyz = get_xyz_string(coords=coords, numbers=number)\n else:\n record = False\n for line in lines:\n if '$end' in line or '}' in line:\n break\n if record and len(line.split()) == 4:\n relevant_lines.append(line)\n elif '$molecule' in line:\n record = True\n elif 'geometry={' in line:\n record = True\n if not relevant_lines:\n raise ParserError('Could not parse xyz coordinates from file {0}'.format(path))\n if xyz is None and relevant_lines:\n xyz = ''.join([line for line in relevant_lines if line])\n return standardize_xyz_string(xyz)\n\n\ndef parse_dipole_moment(path):\n \"\"\"\n Parse the dipole moment in Debye from an opt job output file.\n \"\"\"\n lines = _get_lines_from_file(path)\n log = determine_qm_software(path)\n dipole_moment = None\n if isinstance(log, GaussianLog):\n # example:\n # Dipole moment (field-independent basis, Debye):\n # X= -0.0000 Y= -0.0000 Z= -1.8320 Tot= 1.8320\n read = False\n for line in lines:\n if 'dipole moment' in line.lower() and 'debye' in line.lower():\n read = True\n elif read:\n dipole_moment = float(line.split()[-1])\n read = False\n elif isinstance(log, QChemLog):\n # example:\n # Dipole Moment (Debye)\n # X 0.0000 Y 0.0000 Z 2.0726\n # Tot 2.0726\n skip = False\n read = False\n for line in lines:\n if 'dipole moment' in line.lower() and 'debye' in line.lower():\n skip = True\n elif skip:\n skip = False\n read = True\n elif read:\n dipole_moment = float(line.split()[-1])\n read = False\n elif isinstance(log, MolproLog):\n # example:\n # Dipole moment /Debye 2.96069859 0.00000000 0.00000000\n for line in lines:\n if 'dipole moment' in line.lower() and '/debye' in line.lower():\n splits = line.split()\n dm_x, dm_y, dm_z = float(splits[-3]), float(splits[-2]), float(splits[-1])\n dipole_moment = (dm_x ** 2 + dm_y ** 2 + dm_z ** 2) ** 0.5\n else:\n raise ParserError('Currently dipole moments can only be parsed from either Gaussian, Molpro, or QChem '\n 'optimization output files')\n if dipole_moment is None:\n raise ParserError('Could not parse the dipole moment')\n return dipole_moment\n\n\ndef parse_polarizability(path):\n \"\"\"\n Parse the polarizability from a freq job output file, returns the value in Angstrom^3.\n \"\"\"\n lines = _get_lines_from_file(path)\n polarizability = None\n for line in lines:\n if 'Isotropic polarizability for W' in line:\n # example: Isotropic polarizability for W= 0.000000 11.49 Bohr**3.\n # 1 Bohr = 0.529177 Angstrom\n polarizability = float(line.split()[-2]) * 0.529177 ** 3\n return polarizability\n\n\ndef _get_lines_from_file(path):\n \"\"\"\n A helper function for getting a list of lines from the file at `path`.\n \"\"\"\n if os.path.isfile(path):\n with open(path, 'r') as f:\n lines = f.readlines()\n else:\n raise InputError('Could not find file {0}'.format(path))\n return lines\n\n\ndef process_conformers_file(conformers_path):\n \"\"\"\n Parse coordinates and energies from an ARC conformers file of either species or TSs.\n\n Args:\n conformers_path (str): The path to an ARC conformers file\n (either a \"conformers_before_optimization\" or\n a \"conformers_after_optimization\" file).\n\n Returns:\n xyz (list): Entries are optimized xyz's in a string format.\n Returns:\n energies (list): Entries float numbers representing the energies in kJ/mol.\n \"\"\"\n if not os.path.isfile(conformers_path):\n raise ValueError('Conformers file {0} could not be found'.format(conformers_path))\n with open(conformers_path, 'r') as f:\n lines = f.readlines()\n xyzs, energies = list(), list()\n line_index = 0\n while line_index < len(lines):\n if 'conformer' in lines[line_index] and ':' in lines[line_index] and lines[line_index].strip()[-2].isdigit():\n xyz, energy = '', None\n line_index += 1\n print(lines[line_index].strip())\n while line_index < len(lines) and lines[line_index].strip() and 'SMILES' not in lines[line_index]\\\n and 'energy' not in lines[line_index].lower() and 'guess method' not in lines[line_index].lower():\n xyz += lines[line_index]\n line_index += 1\n while line_index < len(lines) and 'conformer' not in lines[line_index]:\n if 'relative energy:' in lines[line_index].lower():\n energy = float(lines[line_index].split()[2])\n line_index += 1\n xyzs.append(xyz)\n energies.append(energy)\n else:\n line_index += 1\n return xyzs, energies\n", "meta": {"hexsha": "f05fc9e4de742b000a609417a3987d49d049ed00", "size": 9239, "ext": "py", "lang": "Python", "max_stars_repo_path": "arc/parser.py", "max_stars_repo_name": "yunsiechung/ARC", "max_stars_repo_head_hexsha": "a99988916b2dfa4347c0ad2be3e6d72ccc84c40e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "arc/parser.py", "max_issues_repo_name": "yunsiechung/ARC", "max_issues_repo_head_hexsha": "a99988916b2dfa4347c0ad2be3e6d72ccc84c40e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "arc/parser.py", "max_forks_repo_name": "yunsiechung/ARC", "max_forks_repo_head_hexsha": "a99988916b2dfa4347c0ad2be3e6d72ccc84c40e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.08984375, "max_line_length": 118, "alphanum_fraction": 0.5711657106, "include": true, "reason": "import numpy", "num_tokens": 2199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.2782567996876011, "lm_q1q2_score": 0.1434747476042769}} {"text": "#!/usr/bin/env python\n# Copyright 2014-2020 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Qiming Sun \n#\n\n\nimport numpy\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf.cc import ccsd_lambda\n\neinsum = lib.einsum\n\ndef kernel(mycc, eris=None, t1=None, t2=None, l1=None, l2=None,\n max_cycle=50, tol=1e-8, verbose=logger.INFO):\n if eris is None: eris = mycc.ao2mo()\n return ccsd_lambda.kernel(mycc, eris, t1, t2, l1, l2, max_cycle, tol,\n verbose, make_intermediates, update_lambda)\n\n# l2, t2 as ijab\ndef make_intermediates(mycc, t1, t2, eris):\n nocc, nvir = t1.shape\n foo = eris.fock[:nocc,:nocc]\n fov = eris.fock[:nocc,nocc:]\n fvo = eris.fock[nocc:,:nocc]\n fvv = eris.fock[nocc:,nocc:]\n\n tau = t2 + einsum('ia,jb->ijab', t1, t1) * 2\n\n v1 = fvv - einsum('ja,jb->ba', fov, t1)\n v1-= numpy.einsum('jbac,jc->ba', eris.ovvv, t1)\n v1+= einsum('jkca,jkbc->ba', eris.oovv, tau) * .5\n\n v2 = foo + einsum('ib,jb->ij', fov, t1)\n v2-= numpy.einsum('kijb,kb->ij', eris.ooov, t1)\n v2+= einsum('ikbc,jkbc->ij', eris.oovv, tau) * .5\n\n v3 = einsum('ijcd,klcd->ijkl', eris.oovv, tau)\n v4 = einsum('ljdb,klcd->jcbk', eris.oovv, t2)\n v4+= numpy.asarray(eris.ovvo)\n\n v5 = fvo + numpy.einsum('kc,jkbc->bj', fov, t2)\n tmp = fov - numpy.einsum('kldc,ld->kc', eris.oovv, t1)\n v5+= numpy.einsum('kc,kb,jc->bj', tmp, t1, t1)\n v5-= einsum('kljc,klbc->bj', eris.ooov, t2) * .5\n v5+= einsum('kbdc,jkcd->bj', eris.ovvv, t2) * .5\n\n w3 = v5 + numpy.einsum('jcbk,jb->ck', v4, t1)\n w3 += numpy.einsum('cb,jb->cj', v1, t1)\n w3 -= numpy.einsum('jk,jb->bk', v2, t1)\n\n woooo = numpy.asarray(eris.oooo) * .5\n woooo+= v3 * .25\n woooo+= einsum('jilc,kc->jilk', eris.ooov, t1)\n\n wovvo = v4 - numpy.einsum('ljdb,lc,kd->jcbk', eris.oovv, t1, t1)\n wovvo-= einsum('ljkb,lc->jcbk', eris.ooov, t1)\n wovvo+= einsum('jcbd,kd->jcbk', eris.ovvv, t1)\n\n wovoo = einsum('icdb,jkdb->icjk', eris.ovvv, tau) * .25\n wovoo+= numpy.einsum('jkic->icjk', numpy.asarray(eris.ooov).conj()) * .5\n wovoo+= einsum('icbk,jb->icjk', v4, t1)\n wovoo-= einsum('lijb,klcb->icjk', eris.ooov, t2)\n\n wvvvo = einsum('jcak,jb->bcak', v4, t1)\n wvvvo+= einsum('jlka,jlbc->bcak', eris.ooov, tau) * .25\n wvvvo-= numpy.einsum('jacb->bcaj', numpy.asarray(eris.ovvv).conj()) * .5\n wvvvo+= einsum('kbad,jkcd->bcaj', eris.ovvv, t2)\n\n class _IMDS: pass\n imds = _IMDS()\n imds.ftmp = lib.H5TmpFile()\n dtype = numpy.result_type(t2, eris.vvvv).char\n imds.woooo = imds.ftmp.create_dataset('woooo', (nocc,nocc,nocc,nocc), dtype)\n imds.wovvo = imds.ftmp.create_dataset('wovvo', (nocc,nvir,nvir,nocc), dtype)\n imds.wovoo = imds.ftmp.create_dataset('wovoo', (nocc,nvir,nocc,nocc), dtype)\n imds.wvvvo = imds.ftmp.create_dataset('wvvvo', (nvir,nvir,nvir,nocc), dtype)\n imds.woooo[:] = woooo\n imds.wovvo[:] = wovvo\n imds.wovoo[:] = wovoo\n imds.wvvvo[:] = wvvvo\n imds.v1 = v1\n imds.v2 = v2\n imds.w3 = w3\n imds.ftmp.flush()\n return imds\n\n\n# update L1, L2\ndef update_lambda(mycc, t1, t2, l1, l2, eris, imds):\n time0 = logger.process_clock(), logger.perf_counter()\n log = logger.Logger(mycc.stdout, mycc.verbose)\n nocc, nvir = t1.shape\n fov = eris.fock[:nocc,nocc:]\n mo_e_o = eris.mo_energy[:nocc]\n mo_e_v = eris.mo_energy[nocc:] + mycc.level_shift\n v1 = imds.v1 - numpy.diag(mo_e_v)\n v2 = imds.v2 - numpy.diag(mo_e_o)\n\n l1new = numpy.zeros_like(l1)\n l2new = numpy.zeros_like(l2)\n\n mba = einsum('klca,klcb->ba', l2, t2) * .5\n mij = einsum('kicd,kjcd->ij', l2, t2) * .5\n m3 = einsum('klab,ijkl->ijab', l2, numpy.asarray(imds.woooo))\n tau = t2 + einsum('ia,jb->ijab', t1, t1) * 2\n tmp = einsum('ijcd,klcd->ijkl', l2, tau)\n oovv = numpy.asarray(eris.oovv)\n m3 += einsum('klab,ijkl->ijab', oovv, tmp) * .25\n tmp = einsum('ijcd,kd->ijck', l2, t1)\n m3 -= einsum('kcba,ijck->ijab', eris.ovvv, tmp)\n m3 += einsum('ijcd,cdab->ijab', l2, eris.vvvv) * .5\n\n l2new += oovv\n l2new += m3\n fov1 = fov + einsum('kjcb,kc->jb', oovv, t1)\n tmp = einsum('ia,jb->ijab', l1, fov1)\n tmp+= einsum('kica,jcbk->ijab', l2, numpy.asarray(imds.wovvo))\n tmp = tmp - tmp.transpose(1,0,2,3)\n l2new += tmp - tmp.transpose(0,1,3,2)\n tmp = einsum('ka,ijkb->ijab', l1, eris.ooov)\n tmp+= einsum('ijca,cb->ijab', l2, v1)\n tmp1vv = mba + einsum('ka,kb->ba', l1, t1)\n tmp+= einsum('ca,ijcb->ijab', tmp1vv, oovv)\n l2new -= tmp - tmp.transpose(0,1,3,2)\n tmp = einsum('ic,jcba->jiba', l1, eris.ovvv)\n tmp+= einsum('kiab,jk->ijab', l2, v2)\n tmp1oo = mij + einsum('ic,kc->ik', l1, t1)\n tmp-= einsum('ik,kjab->ijab', tmp1oo, oovv)\n l2new += tmp - tmp.transpose(1,0,2,3)\n\n l1new += fov\n l1new += einsum('jb,ibaj->ia', l1, eris.ovvo)\n l1new += einsum('ib,ba->ia', l1, v1)\n l1new -= einsum('ja,ij->ia', l1, v2)\n l1new -= einsum('kjca,icjk->ia', l2, imds.wovoo)\n l1new -= einsum('ikbc,bcak->ia', l2, imds.wvvvo)\n l1new += einsum('ijab,jb->ia', m3, t1)\n l1new += einsum('jiba,bj->ia', l2, imds.w3)\n tmp =(t1 + einsum('kc,kjcb->jb', l1, t2)\n - einsum('bd,jd->jb', tmp1vv, t1)\n - einsum('lj,lb->jb', mij, t1))\n l1new += numpy.einsum('jiba,jb->ia', oovv, tmp)\n l1new += numpy.einsum('icab,bc->ia', eris.ovvv, tmp1vv)\n l1new -= numpy.einsum('jika,kj->ia', eris.ooov, tmp1oo)\n tmp = fov - einsum('kjba,jb->ka', oovv, t1)\n l1new -= numpy.einsum('ik,ka->ia', mij, tmp)\n l1new -= numpy.einsum('ca,ic->ia', mba, tmp)\n\n eia = lib.direct_sum('i-j->ij', mo_e_o, mo_e_v)\n l1new /= eia\n l2new /= lib.direct_sum('ia+jb->ijab', eia, eia)\n\n time0 = log.timer_debug1('update l1 l2', *time0)\n return l1new, l2new\n\n\nif __name__ == '__main__':\n from pyscf import gto\n from pyscf import scf\n from pyscf.cc import gccsd\n\n mol = gto.Mole()\n mol.atom = [\n [8 , (0. , 0. , 0.)],\n [1 , (0. , -0.757 , 0.587)],\n [1 , (0. , 0.757 , 0.587)]]\n mol.basis = '631g'\n mol.spin = 0\n mol.build()\n mf = scf.RHF(mol).run()\n mf0 = mf\n mf = scf.addons.convert_to_ghf(mf)\n mycc = gccsd.GCCSD(mf)\n eris = mycc.ao2mo()\n mycc.kernel(eris=eris)\n l1, l2 = mycc.solve_lambda(mycc.t1, mycc.t2, eris=eris)\n l1 = mycc.spin2spatial(l1, mycc.mo_coeff.orbspin)\n l2 = mycc.spin2spatial(l2, mycc.mo_coeff.orbspin)\n print(lib.finger(l1[0]) --0.0030030170069977758)\n print(lib.finger(l1[1]) --0.0030030170069977758)\n print(lib.finger(l2[0]) --0.041444910588788492 )\n print(lib.finger(l2[1]) - 0.1077575086912813 )\n print(lib.finger(l2[2]) --0.041444910588788492 )\n print(abs(l2[1]-l2[1].transpose(1,0,2,3)-l2[0]).max())\n print(abs(l2[1]-l2[1].transpose(0,1,3,2)-l2[0]).max())\n\n from pyscf.cc import ccsd\n mycc0 = ccsd.CCSD(mf0)\n eris0 = mycc0.ao2mo()\n mycc0.kernel(eris=eris0)\n t1 = mycc0.t1\n t2 = mycc0.t2\n imds = ccsd_lambda.make_intermediates(mycc0, t1, t2, eris0)\n l1, l2 = ccsd_lambda.update_lambda(mycc0, t1, t2, t1, t2, eris0, imds)\n l1ref, l2ref = ccsd_lambda.update_lambda(mycc0, t1, t2, l1, l2, eris0, imds)\n t1 = mycc.spatial2spin(t1, mycc.mo_coeff.orbspin)\n t2 = mycc.spatial2spin(t2, mycc.mo_coeff.orbspin)\n l1 = mycc.spatial2spin(l1, mycc.mo_coeff.orbspin)\n l2 = mycc.spatial2spin(l2, mycc.mo_coeff.orbspin)\n imds = make_intermediates(mycc, t1, t2, eris)\n l1, l2 = update_lambda(mycc, t1, t2, l1, l2, eris, imds)\n l1 = mycc.spin2spatial(l1, mycc.mo_coeff.orbspin)\n l2 = mycc.spin2spatial(l2, mycc.mo_coeff.orbspin)\n print(abs(l1[0]-l1ref).max())\n print(abs(l2[1]-l2ref).max())\n", "meta": {"hexsha": "0eda310cdf267869a54c28b2531c9ce93714765a", "size": 8214, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/cc/gccsd_lambda.py", "max_stars_repo_name": "QuESt-Calculator/pyscf", "max_stars_repo_head_hexsha": "0ed03633b699505c7278f1eb501342667d0aa910", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 501, "max_stars_repo_stars_event_min_datetime": "2018-12-06T23:48:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T11:53:18.000Z", "max_issues_repo_path": "pyscf/cc/gccsd_lambda.py", "max_issues_repo_name": "QuESt-Calculator/pyscf", "max_issues_repo_head_hexsha": "0ed03633b699505c7278f1eb501342667d0aa910", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 710, "max_issues_repo_issues_event_min_datetime": "2018-11-26T22:04:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T03:53:12.000Z", "max_forks_repo_path": "pyscf/cc/gccsd_lambda.py", "max_forks_repo_name": "QuESt-Calculator/pyscf", "max_forks_repo_head_hexsha": "0ed03633b699505c7278f1eb501342667d0aa910", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 273, "max_forks_repo_forks_event_min_datetime": "2018-11-26T10:10:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:25:28.000Z", "avg_line_length": 37.3363636364, "max_line_length": 80, "alphanum_fraction": 0.6155344534, "include": true, "reason": "import numpy", "num_tokens": 3379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.27202456289736326, "lm_q1q2_score": 0.14344304273950084}} {"text": "from datetime import datetime\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nnp.seterr(over='ignore')\n\nfrom .Continuum import continuum\nfrom .Ion import ion\nimport ChiantiPy.tools.data as chdata\nimport ChiantiPy.tools.constants as const\nimport ChiantiPy.tools.util as util\nimport ChiantiPy.Gui as chGui\nfrom ChiantiPy.base import specTrails\nfrom ChiantiPy.base import ionTrails\n\n\nclass radLoss(ionTrails, specTrails):\n '''\n Calculate the emission spectrum as a function of temperature and density.\n\n includes elemental abundances or ionization equilibria\n\n temperature and density can be arrays but, unless the size of either is one (1),\n the two must have the same size\n\n the returned spectrum will be convolved with a filter of the specified width on the\n specified wavelength array\n\n the default filter is gaussianR with a resolving power of 1000. Other filters,\n such as gaussian, box and lorentz, are available in ChiantiPy.filters. When using the box filter,\n the width should equal the wavelength interval to keep the units of the continuum and line\n spectrum the same.\n\n A selection of ions can be make with ionList containing the names of\n the desired lines in Chianti notation, i.e. C VI = c_6\n\n a minimum abundance can be specified so that the calculation can be speeded up by excluding\n elements with a low abundance. With solar photospheric abundances -\n\n setting minAbund = 1.e-4 will include H, He, C, O, Ne\n setting minAbund = 2.e-5 adds N, Mg, Si, S, Fe\n setting minAbund = 1.e-6 adds Na, Al, Ar, Ca, Ni\n\n Setting em will multiply the spectrum at each temperature by the value of em.\n\n em [for emission measure], can be a float or an array of the same length as the\n temperature/density.\n\n abundance: to select a particular set of abundances, set abundance to the name of a CHIANTI abundance file,\n without the '.abund' suffix, e.g. 'sun_photospheric_1998_grevesse'\n If set to a blank (''), a gui selection menu will popup and allow the selection of an set of abundances\n '''\n def __init__(self, temperature, eDensity, elementList=None, ionList = None, minAbund=None, doContinuum=1, abundance=None, verbose=0, allLines=1, keepIons=0):\n t1 = datetime.now()\n masterlist = chdata.MasterList\n # use the ionList but make sure the ions are in the database\n if ionList:\n alist=[]\n for one in ionList:\n if masterlist.count(one):\n alist.append(one)\n else:\n if verbose:\n pstring = ' %s not in CHIANTI database'%(one)\n print(pstring)\n masterlist = alist\n self.Defaults=chdata.Defaults\n self.argCheck(temperature=temperature, eDensity=eDensity, pDensity=None, em=None)\n\n #\n if abundance is not None:\n if type(abundance) == str:\n if abundance in chdata.AbundanceList:\n self.AbundanceName = abundance\n else:\n abundChoices = chdata.AbundanceList\n abundChoice = chGui.gui.selectorDialog(abundChoices,label='Select Abundance name',multiChoice=False)\n abundChoice_idx = abundChoice.selectedIndex\n self.AbundanceName = abundChoices[abundChoice_idx[0]]\n if verbose:\n print(' %s abundances chosen'%(self.AbundanceName))\n else:\n print(' keyword abundance must be a string, either a blank (\\'\\') or the name of an abundance file')\n return\n else:\n self.AbundanceName = self.Defaults['abundfile']\n if hasattr(self,'AbundanceName'):\n self.Abundance = chdata.Abundance[self.AbundanceName]['abundance']\n #\n# abundAll = chdata.Abundance[self.AbundanceName]['abundance']\n# # needed by ionGate\n self.AbundAll = self.Abundance\n #\n nonzed = self.Abundance > 0.\n minAbundAll = self.Abundance[nonzed].min()\n # if minAbund is even set\n if minAbund:\n if minAbund < minAbundAll:\n minAbund = minAbundAll\n self.MinAbund = minAbund\n# ionInfo = util.masterListInfo()\n #\n nTempDens = self.NTempDens\n freeFreeLoss = np.zeros_like(self.Temperature)\n freeBoundLoss = np.zeros_like(self.Temperature)\n twoPhotonLoss = np.zeros_like(self.Temperature)\n boundBoundLoss = np.zeros_like(self.Temperature)\n twoPhotonLoss = np.zeros_like(self.Temperature)\n #\n self.IonsCalculated = []\n if keepIons:\n self.IonInstances = {}\n self.Finished = []\n #\n self.WvlRange = [0., 1.e+30]\n #\n self.ionGate(elementList = elementList, ionList = ionList, minAbund=minAbund, doContinuum=doContinuum, doWvlTest=0, verbose=verbose)\n #\n #\n for akey in sorted(self.Todo.keys()):\n zStuff = util.convertName(akey)\n Z = zStuff['Z']\n ionstage = zStuff['Ion']\n dielectronic = zStuff['Dielectronic']\n abundance = self.Abundance[Z - 1]\n if verbose:\n print(' %5i %5s abundance = %10.2e '%(Z, const.El[Z-1], abundance))\n if verbose:\n print(' doing ion %s for the following processes %s'%(akey, self.Todo[akey]))\n if ionstage != 1:\n if verbose:\n print(' calculating ff continuum for : %s'%(akey))\n if 'ff' in self.Todo[akey]:\n # need to skip the neutral\n cont = continuum(akey, temperature, abundance=abundance)\n cont.freeFreeLoss()\n freeFreeLoss += cont.FreeFreeLoss['rate']\n if 'fb' in self.Todo[akey]:\n if verbose:\n print(' calculating fb continuum for : %s'%(akey))\n cont = continuum(akey, temperature, abundance=abundance)\n cont.freeBoundLoss(verbose=verbose)\n if 'errorMessage' not in cont.FreeBoundLoss.keys():\n freeBoundLoss += cont.FreeBoundLoss['rate']\n if 'line' in self.Todo[akey]:\n if verbose:\n print(' calculating spectrum for : %s'%(akey))\n thisIon = ion(akey, temperature, eDensity, abundance=abundance)\n thisIon.intensity(allLines=allLines)\n self.IonsCalculated.append(akey)\n if 'errorMessage' not in thisIon.Intensity.keys():\n self.Finished.append(akey)\n thisIon.boundBoundLoss()\n boundBoundLoss += thisIon.BoundBoundLoss['rate']\n else:\n if verbose:\n print(thisIon.Intensity['errorMessage'])\n # get 2 photon emission for H and He sequences\n if (Z - ionstage) in [0, 1] and not dielectronic:\n thisIon.twoPhotonLoss()\n twoPhotonLoss += thisIon.TwoPhotonLoss['rate']\n self.FreeFreeLoss = freeFreeLoss\n self.FreeBoundLoss = freeBoundLoss\n self.BoundBoundLoss = boundBoundLoss\n self.TwoPhotonLoss = twoPhotonLoss\n #\n total = freeFreeLoss + freeBoundLoss + boundBoundLoss + twoPhotonLoss\n t2 = datetime.now()\n dt=t2-t1\n print(' elapsed seconds = %10.2e'%(dt.seconds))\n xlabel = 'Temperature (K)'\n ylabel = r'erg s$^{-1}$ cm$^{3}$'\n self.RadLoss = {'rate':total, 'temperature':self.Temperature, 'density':self.EDensity, 'minAbund':minAbund, 'abundance':self.AbundanceName, 'ylabel':ylabel, 'xlabel':xlabel}\n #\n # -------------------------------------------------------------------\n #\n def radLossPlot(self, title=0):\n '''\n to plot the radiative losses vs temperature\n '''\n fontsize = 16\n temp = self.RadLoss['temperature']\n rate = self.RadLoss['rate']\n plt.loglog(temp, rate)\n# plt.ylabel(r'erg s$^{-1}$ ($\\int\\,$ N$_e\\,$N$_H\\,$d${\\it l}$)$^{-1}$',fontsize=fontsize)\n plt.xlabel(self.RadLoss['xlabel'],fontsize=fontsize)\n plt.ylabel(self.RadLoss['ylabel'],fontsize=fontsize)\n if title:\n title = 'Radiative loss rate, minAbund = %10.2e'%(self.MinAbund)\n if self.EDensity.size == 1:\n title += ', density = %10.2e'%(self.EDensity)\n plt.title(title, fontsize=fontsize)\n plt.tight_layout()\n", "meta": {"hexsha": "4c803e78bac310c33c02a02b9966b3b1299b403e", "size": 8625, "ext": "py", "lang": "Python", "max_stars_repo_path": "ChiantiPy/core/RadLoss.py", "max_stars_repo_name": "kdere/ChiantiPy", "max_stars_repo_head_hexsha": "2d17585d64dd1ed5a92edc645d6c85176899c185", "max_stars_repo_licenses": ["0BSD", "MIT"], "max_stars_count": 56, "max_stars_repo_stars_event_min_datetime": "2016-01-14T15:34:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T10:41:36.000Z", "max_issues_repo_path": "ChiantiPy/core/RadLoss.py", "max_issues_repo_name": "kdere/ChiantiPy", "max_issues_repo_head_hexsha": "2d17585d64dd1ed5a92edc645d6c85176899c185", "max_issues_repo_licenses": ["0BSD", "MIT"], "max_issues_count": 163, "max_issues_repo_issues_event_min_datetime": "2015-11-12T16:01:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T14:19:59.000Z", "max_forks_repo_path": "ChiantiPy/core/RadLoss.py", "max_forks_repo_name": "chianti-atomic/ChiantiPy", "max_forks_repo_head_hexsha": "0d47cc1c5855ab0290d0c6bd43628722651a77c5", "max_forks_repo_licenses": ["0BSD", "MIT"], "max_forks_count": 36, "max_forks_repo_forks_event_min_datetime": "2015-11-12T16:03:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T17:53:39.000Z", "avg_line_length": 44.4587628866, "max_line_length": 181, "alphanum_fraction": 0.5929275362, "include": true, "reason": "import numpy", "num_tokens": 2021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.14339960450921746}} {"text": "'''\n.. module:: controller\n :synopsis: Control algorithms for lateral control of vehicle dynamics\n.. moduleauthor:: Yongkyun Shin \n\nThis module is a collection of algorithms for control of lateral vehicle dynamics.\nCurrently implemented algorithms are PID controller, Model-Predictive controller,\nand Deep-Deterministic Policy Gradient (DDPG) controller.\n'''\n\nimport numpy as np\nfrom scipy import sparse\nimport cvxpy as cp\nimport torch\nfrom .learning.ddpg_agent import Agent\nfrom .learning.model import Actor\nimport sys, os\n# import acado\n\n# DDPG Params\nSTATE_SIZE = 4\nACTION_SIZE = 1\nRANDOM_SEED = 1\nCHECK_POINT = 'checkpoint_actor.pth'\n\nPOS = 0\nANG = 1\nNOW = 0\nFUTURE = 4\n\n\nclass Controller:\n '''\n Generic controller parent class with some common variables (e.g. sample time, number of states, etc.)\n '''\n\n def __init__(self, NU=1, NY=1, T=1, dt=0.01):\n self.reference = np.zeros((NY, T))\n self.measured_output = np.zeros((NY, T))\n self.control_input = np.zeros(NU)\n self.dt = dt # Controller sample time\n self.T = T # Number of control points along the path\n\n def control(self):\n pass\n\n\nclass PathController(Controller):\n '''\n PathController has projection horizon in extension to generic Controller class.\n Projection horizon defines the preview, or lookahead distances w.r.t. vehicle\n '''\n def __init__(self, NU=1, NY=1, T=1, dt=0.01, proj_horizon=0.5):\n super().__init__(NU=NU, NY=NY, T=T, dt=dt)\n # [sec] Use T control points along desired path for proj_horizon time\n self.proj_horizon = proj_horizon\n\n @property\n def proj_step(self):\n return self.proj_horizon / self.T\n\n\nclass DDPG(PathController):\n '''\n Experimental controller which uses reinforcement learning algorithm.\n '''\n def __init__(self, check_point=CHECK_POINT, dt=0.01, T=1, NY=1, proj_horizon=0.5):\n super().__init__(dt=dt, T=T, proj_horizon=proj_horizon)\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n if torch.cuda.is_available():\n trained_model = torch.load(CHECK_POINT)\n else:\n trained_model = torch.load(\n CHECK_POINT, map_location={'cuda:0': 'cpu'})\n\n self.agent = Agent(state_size=STATE_SIZE,\n action_size=ACTION_SIZE, random_seed=RANDOM_SEED)\n self.agent.actor_local = Actor(\n STATE_SIZE, ACTION_SIZE, RANDOM_SEED).to(device)\n self.agent.actor_local.load_state_dict(trained_model)\n\n def get_state(self, yref):\n # current/future pos reference, current/future heading reference\n states = np.array([yref[POS, NOW], yref[POS, FUTURE],\n yref[ANG, NOW], yref[ANG, FUTURE]])\n states = np.reshape(states, [ACTION_SIZE, STATE_SIZE])\n return states\n\n def control(self, yref):\n states = self.get_state(yref)\n action = self.agent.act(states, add_noise=False)\n return float(action)\n\n\nclass PID(PathController):\n '''\n PID controller with variable number of control points along desired path.\n Control parameters are lateral position and heading. For each control point & parameter,\n there is a corresponding normalized weight which adds up to 1. Therefore, a single PID\n controller is used to control all of the controlled states and points along desired path.\n\n ================ ==================================================\n **Arguments:**\n NU (int) Number of controlled states\n NY (int) Number of outputs\n T (int) Number of reference points along trajectory\n dt (float) Sample time [sec] of the controller\n P_Gain (float) Proportional gain of the controller\n I_Gain (float) Integral gain of the controller\n D_Gain (float) Derivative gain of the controller\n weight_split_T (list) Determine how to split weight on reference points (e.g. [0.5, 0.5] for equal split on all reference points)\n weight_split_Y (list) Determine how to split weight on measured output (e.g. [0.5, 0.5] for equal split on position and heading control)\n\n **Variables:**\n weight_table (numpy array) NY-by-T array of normalized weight for each controlled point & parameter \n ================ ==================================================\n '''\n\n def __init__(self, NU=1,\n NY=1,\n T=1,\n dt=0.01,\n P_Gain=1,\n I_Gain=0.1,\n D_Gain=0.01,\n weight_split_T=None,\n weight_split_Y=None,\n proj_horizon=0.5):\n super().__init__(T=T, dt=dt, proj_horizon=proj_horizon)\n self.P_Gain = P_Gain\n self.I_Gain = I_Gain\n self.D_Gain = D_Gain\n\n self.weight_table = self.__calc_weight_table(\n T, NY, weight_split_T, weight_split_Y)\n\n self._integral = np.zeros(T)\n self._error_old = np.zeros(T)\n\n def __calc_weight_table(self, T, NY, T_split, Y_split):\n '''\n Update normalized weight table for PID control. \n '''\n if T_split == None and Y_split == None:\n table = np.ones((NY, T)) / (NY*T)\n else:\n table = np.zeros((NY, T))\n vec_T = np.linspace(T_split[0], T_split[1], num=T)\n vec_Y = Y_split\n for i in range(NY):\n for j in range(T):\n table[i, j] = vec_Y[i] * vec_T[j]\n if np.sum(table) > 0:\n table /= np.sum(table)\n return table\n\n def control(self, error_table):\n '''\n Calculate control input\n '''\n u = np.zeros(self.T)\n for i in range(self.T):\n e = 0\n for j in range(self.weight_table.shape[0]):\n e += self.weight_table[j, i] * error_table[j, i]\n self._integral[i] += e * self.dt\n u[i] = (self.P_Gain * e) + (self.I_Gain * self._integral[i]\n ) + (self.D_Gain * (e-self._error_old[i])/self.dt)\n self._error_old[i] = e\n return np.sum(u)\n\n\nclass MPC(PathController):\n '''\n Generic model predictive controller class. Uses linearized state-space model.\n Convex optimization is solved through cvxpy module.\n\n ================ ==================================================\n **Arguments:**\n getModel (function) Function which should return linearized state-space dynamics model as numpy array\n NU (int) Number of controlled states\n NY (int) Number of outputs\n T (int) Number of reference points along trajectory\n dt (float) Sample time [sec] of the controller\n output_weight (float) Weight for control of the output\n input_weight (float) Weight for input constraint control\n input_lim (float) Control input limit\n input_rate_lim (float) Control input rate limit\n ================ ==================================================\n '''\n\n def __init__(self, getModel,\n T=5,\n dt=0.01,\n output_weight=None,\n input_weight=None,\n input_lim=None,\n input_rate_lim=None,\n proj_horizon=0.5):\n \n super().__init__(NU=1, NY=1, T=T, dt=dt, proj_horizon=proj_horizon)\n self.getModel = getModel\n self.output_weight = output_weight\n self.input_weight = input_weight\n self.input_lim = input_lim\n self.input_rate_lim = input_rate_lim\n\n self.setup_problem()\n \n\n def setup_problem(self):\n A, B, C, _ = self.getModel(sample_time=self.dt)\n NU = B.shape[1] # Number of inputs to state-space model\n NX = A.shape[1] # Number of states\n NY = C.shape[0] # Number of outputs\n T = self.T # Prediction horizon\n Q_DEFAULT = 5\n R_DEFAULT = 1\n\n # Constraints\n if self.input_lim is not None:\n umax = np.array(self.input_lim)\n umin = -1 * umax\n if self.input_rate_lim is not None:\n urmax = np.array([[1], [1]]) * 1\n urmin = -1 * urmax\n\n # Objective function\n if self.output_weight is None:\n Q = sparse.eye(NY) * Q_DEFAULT\n else:\n Q = sparse.diags(self.output_weight)\n\n if self.input_weight is None:\n R = sparse.eye(NU) * R_DEFAULT\n else:\n R = sparse.diags(self.input_weight)\n\n # Define problem\n self.u = cp.Variable((NU, T+1)) # T has one extra buffer element at the end \n x = cp.Variable((NX, T+1))\n y = cp.Variable((NY, T+1))\n self.y_ref = cp.Parameter((NY, T))\n # self.y_ref.value = np.zeros((NY, T))\n self.x_init = cp.Parameter(NX)\n # self.x_init.value = np.zeros((NX,1))\n objective = 0\n constraints = [x[:, 0] == self.x_init]\n\n for k in range(T):\n objective += cp.quad_form(y[:, k] -\n self.y_ref[:, k], Q) + cp.quad_form(self.u[:, k], R)\n\n constraints += [x[:, k+1] == A*x[:, k] + B*self.u[:, k]]\n constraints += [y[:, k] == C*x[:, k]]\n\n if self.input_rate_lim is not None:\n constraints += [urmin <= self.u[:, k+1] -\n self.u[:, k], self.u[:, k+1] - self.u[:, k] <= urmax]\n if self.input_lim is not None:\n constraints += [umin <= self.u[:, k], self.u[:, k] <= umax]\n\n self.prob = cp.Problem(cp.Minimize(objective), constraints)\n\n\n def update_values(self, x_init, y_ref):\n self.y_ref.value = y_ref\n self.x_init.value = x_init\n\n def control(self,y_desired, init_state):\n self.update_values(init_state, y_desired)\n # self.prob.solve(solver=cp.OSQP, max_iter=100,\n # verbose=False, warm_start=True)\n self.prob.solve(cp.ECOS)\n return self.u[:, 0].value[0]\n\n def control_with_acado(self, y_desired, init_state):\n A, B, C, _ = self.getModel(sample_time=self.dt)\n NU = B.shape[1] # Number of inputs to state-space model\n NX = A.shape[1] # Number of states\n NYN = NX#C.shape[0] # Number of outputs\n NY = NX+NU # Control problem\n T = self.T # Prediction horizon\n\n x0=np.zeros((1,NX)) \n X=np.zeros((T+1,NX))\n X[0:T,1] = y_desired[0,:]\n X[0:T,3] = y_desired[1,:]\n U=np.zeros((T,NU)) \n Y=np.concatenate((X[0:T,:],np.zeros((T,NU))),axis=1)\n # Y = np.zeros((T,NY)) \n yN=np.zeros((1,NYN)) \n x0[0,:]=init_state # initial state \n yN[0,:]=Y[-1,:NYN] # reference terminal state \n\n # Objective function\n Q_DEFAULT = 5\n R_DEFAULT = 1\n # Q = sparse.eye(NY) * Q_DEFAULT\n # Qf = sparse.eye(NYN) * Q_DEFAULT\n # R = sparse.eye(NU) * R_DEFAULT\n Q = np.diag([Q_DEFAULT,0,Q_DEFAULT,0,R_DEFAULT])\n Qf = np.diag([Q_DEFAULT,0,Q_DEFAULT,0])\n\n X, U = acado.mpc(0, 1, x0, X,U,Y,yN, np.transpose(np.tile(Q,T)), Qf, 0) \n\n if U[0] != 0 or U[4] != 0:\n print('NOT ZERO!!!!')\n return 0\n\n # def control2(self, y_desired, init_state):\n # A, B, C, _ = self.getModel(sample_time=self.dt)\n\n # NU = B.shape[1] # Number of inputs to state-space model\n # NX = A.shape[1] # Number of states\n # NY = C.shape[0] # Number of outputs\n # T = self.T # Prediction horizon\n # Q_DEFAULT = 5\n # R_DEFAULT = 1\n\n # # Constraints\n # if self.input_lim is not None:\n # umax = np.array(self.input_lim)\n # umin = -1 * umax\n # if self.input_rate_lim is not None:\n # urmax = np.array([[1], [1]]) * 1\n # urmin = -1 * urmax\n\n # # Objective function\n # if self.output_weight is None:\n # Q = sparse.eye(NY) * Q_DEFAULT\n # else:\n # Q = sparse.diags(self.output_weight)\n\n # if self.input_weight is None:\n # R = sparse.eye(NU) * R_DEFAULT\n # else:\n # R = sparse.diags(self.input_weight)\n\n # # Define problem\n # u = cp.Variable((NU, T+1)) # T has one extra buffer element at the end \n # x = cp.Variable((NX, T+1))\n # y = cp.Variable((NY, T+1))\n # yref = cp.Parameter((NY, T))\n # x_init = cp.Parameter(NX)\n # objective = 0\n # constraints = [x[:, 0] == x_init]\n \n # yref.value = y_desired\n # x_init.value = init_state\n\n # for k in range(T):\n # objective += cp.quad_form(y[:, k] -\n # yref[:, k], Q) + cp.quad_form(u[:, k], R)\n\n # constraints += [x[:, k+1] == A*x[:, k] + B*u[:, k]]\n # constraints += [y[:, k] == C*x[:, k]]\n\n # if self.input_rate_lim is not None:\n # constraints += [urmin <= u[:, k+1] -\n # u[:, k], u[:, k+1] - u[:, k] <= urmax]\n # if self.input_lim is not None:\n # constraints += [umin <= u[:, k], u[:, k] <= umax]\n\n # prob = cp.Problem(cp.Minimize(objective), constraints)\n # prob.solve(solver=cp.OSQP, max_iter=100,\n # verbose=False, warm_start=True)\n\n # return u[:, 0].value[0]\n\n\n\ndef main():\n pass\n\n\nif __name__ == '__main__':\n main()\n", "meta": {"hexsha": "7f3ebbcbfd5ac080c9116853088c52b6a25402da", "size": 13632, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyvehsim/core/controller.py", "max_stars_repo_name": "yongkyuns/PythonVehicleControl", "max_stars_repo_head_hexsha": "e68e6a1882c38150d85690aaf2afd9d613fade8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-04-22T02:22:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T17:41:18.000Z", "max_issues_repo_path": "pyvehsim/core/controller.py", "max_issues_repo_name": "yongkyuns/PythonVehicleControl", "max_issues_repo_head_hexsha": "e68e6a1882c38150d85690aaf2afd9d613fade8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-11-13T18:44:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T01:52:42.000Z", "max_forks_repo_path": "pyvehsim/core/controller.py", "max_forks_repo_name": "yongkyuns/PythonVehicleControl", "max_forks_repo_head_hexsha": "e68e6a1882c38150d85690aaf2afd9d613fade8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9683377309, "max_line_length": 143, "alphanum_fraction": 0.5437940141, "include": true, "reason": "import numpy,from scipy,import cvxpy", "num_tokens": 3472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.2845760042165267, "lm_q1q2_score": 0.14339960450921746}} {"text": "'''\nAuthor: Jin\nGoal: DQN\nFollowing https://www.zhihu.com/people/fuckyou-74/posts\n'''\n\nimport numpy as np\nimport tensorflow as tf\n# np.random.seed(2020)\n\nclass DoubleDQN(object):\n def __init__(self, config):\n self.state_maxlength = config['STATE_MAXLENGTH']\n self.action_space = config['ACTION_SPACE']\n self.action_feature = None\n if 'ACTION_FEATURE' in config:\n self.action_feature = config['ACTION_FEATURE']\n self.action_dim = self.action_feature.shape[1]\n else:\n self.action_dim = config['ACTION_DIM'] # todo: pretrain action feature?\n self.rnn_state_dim = config['RNN_STATE_DIM']\n self.memory_size = config['MEMORY_SIZE']\n self.memory = np.zeros((self.memory_size, self.state_maxlength*4+4), dtype='object')\n self.gamma = config['GAMMA']\n self.lr = config['LEARNING_RATE']\n self.lr_decay_step = int(config['lr_decay_step'])\n self.epsilon_min = config['EPSILON']\n self.epsilon = 0.8\n self.epsilon_decay_step = int(config['epsilon_decay_step'])\n self.batch_size = config['BATCH_SIZE']\n self.learn_step_counter = 0\n self.replace_TargetNet_iter = config['REPLACE_TARGETNET']\n self.optimizer_name = config['OPTIMIZER']\n self.state_encoder = config[\"state_encoder\"]\n self.double_q = True\n\n self.save_model_file = 'DoubleDQN'\n if 'SAVE_MODEL_FILE' in config:\n self.save_model_file = config['SAVE_MODEL_FILE']\n \n # tf.set_random_seed(2020)\n # init sess\n self._build_net()\n mainNet_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='MainNet')\n TargetNet_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='TargetNet')\n with tf.variable_scope('replacement'):\n self.target_replace_op = [tf.assign(t, e) for t, e in zip(TargetNet_params, mainNet_params)] # update TargetNet params by using MainNet params\n\n gpu_options = tf.GPUOptions(allow_growth=True)\n self.sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\n self.sess.run(tf.global_variables_initializer())\n self.saver = tf.train.Saver()\n # self.writer = tf.summary.FileWriter(\"log/logs/\", self.sess.graph)\n # exit(0)\n self.with_userinit = False\n print(\"DQN with user_init:\", self.with_userinit)\n\n def _build_net(self):\n # ---- input ---- \n self.s = tf.placeholder(tf.int32, [None, self.state_maxlength], name='s') # todo: return s as a representation, not do rnn O(n) everytime \n self.s_= tf.placeholder(tf.int32, [None, self.state_maxlength], name='s_')\n self.f = tf.placeholder(tf.int32, [None, self.state_maxlength], name='f') \n self.f_= tf.placeholder(tf.int32, [None, self.state_maxlength], name='f_')\n # self.r = tf.placeholder(tf.float32, [None, ], name='r')\n self.a = tf.placeholder(tf.int32, [None, ], name='a')\n self.q_target = tf.placeholder(tf.float32, [None, ], name='Q_next')\n self.len_s = tf.placeholder(tf.int32, [None, ], name='len_s')\n self.len_s_ = tf.placeholder(tf.int32, [None, ], name='len_s_')\n \n # ----- embedding -----\n if self.action_feature is not None:\n self.action_embeddings = tf.constant(dtype=tf.float32, value=self.action_feature)\n else:\n self.action_embeddings = tf.Variable(tf.random_normal(shape=[self.action_space, self.action_dim], mean=0.0, stddev=0.01), name='action_embeddings', dtype=tf.float32)\n # deal with the masked item:\n self.action_embeddings = tf.concat([self.action_embeddings, tf.constant(np.zeros([1, self.action_dim]), dtype='float32')], axis=0)\n self.feedback_embeddings = tf.Variable(tf.random_normal(shape=[2, self.action_dim], mean=0.0, stddev=0.01), name='feedback_embeddings', dtype=tf.float32)\n\n # --------- get the feedback embeddings\n self.input_f = tf.nn.embedding_lookup(self.feedback_embeddings, tf.reshape(self.f, [-1]))\n self.input_f_ = tf.nn.embedding_lookup(self.feedback_embeddings, tf.reshape(self.f_, [-1]))\n # -------- be careful: here merge the state (items) with feedback_emb\n self.input_s = tf.reshape(tf.nn.embedding_lookup(self.action_embeddings, tf.reshape(self.s, [-1])) * self.input_f, [-1, self.state_maxlength, self.action_dim]) #(None, d) -> (None, s_lengh, d)\n self.input_s_ = tf.reshape(tf.nn.embedding_lookup(self.action_embeddings, tf.reshape(self.s_, [-1])) * self.input_f_, [-1, self.state_maxlength, self.action_dim]) #(None, d) -> (None, s_lengh, d)\n\n # # ********* here we use rnn, it can be MLP, CNN ....\n if self.state_encoder.lower() == 'gru':\n w_init, b_init = tf.random_normal_initializer(), tf.constant_initializer()\n # ----- build MainNet -----\n with tf.variable_scope('MainNet'):\n cell_main = tf.contrib.rnn.GRUCell(num_units=self.rnn_state_dim)\n _, h_s = tf.nn.dynamic_rnn(cell_main, dtype=tf.float32, sequence_length=self.len_s, inputs=self.input_s)\n self.q_eval = tf.layers.dense(h_s, self.action_space, kernel_initializer=w_init, bias_initializer=b_init, name='q')\n # ----- build TargetNet -----\n with tf.variable_scope('TargetNet'):\n cell_target = tf.contrib.rnn.GRUCell(num_units=self.rnn_state_dim)\n _, h_s_ = tf.nn.dynamic_rnn(cell_target, dtype=tf.float32, sequence_length=self.len_s_, inputs=self.input_s_)\n self.q_next = tf.layers.dense(h_s_, self.action_space, kernel_initializer=w_init, bias_initializer=b_init, name='t2')\n\n # ********* here we use 1-layer dense\n elif self.state_encoder.lower() == 'mlp':\n w_init, b_init = tf.random_normal_initializer(), tf.constant_initializer()\n ## before the code is h_s = tf.reduce_mean(self.input_s, axis=1)\n h_s = tf.reduce_sum(self.input_s, axis=1) / tf.reshape(tf.cast(self.len_s, dtype=tf.float32), [-1, 1]) # (None, d)\n h_s_ = tf.reduce_sum(self.input_s_, axis=1) / tf.reshape(tf.cast(self.len_s_, dtype=tf.float32), [-1, 1]) # (None, d) \n # ----- build MainNet -----\n with tf.variable_scope('MainNet'):\n self.q_eval = tf.layers.dense(h_s, self.action_space, kernel_initializer=w_init, bias_initializer=b_init, name='q_eval')\n # ----- build TargetNet -----\n with tf.variable_scope('TargetNet'):\n self.q_next = tf.layers.dense(h_s_, self.action_space, kernel_initializer=w_init, bias_initializer=b_init, name='q_next')\n else:\n print(\"error state_encoder\")\n exit(1)\n \n # ----- DQN-loss ----- \n with tf.variable_scope('q_eval'):\n a_indices = tf.stack([tf.range(tf.shape(self.a)[0],dtype=tf.int32), self.a], axis=1)\n self.q_eval_s_a = tf.gather_nd(self.q_eval, a_indices)\n # with tf.variable_scope('q_next'):\n # self.q_target = self.r + self.gamma * tf.reduce_max(self.q_next, axis=1, name='Qmax_s_')\n # self.q_target = tf.stop_gradient(self.q_target)\n \n with tf.variable_scope('loss'):\n # self.loss = tf.reduce_mean(tf.squared_difference(self.q_target, self.q_eval_s_a))\n # smooth-l1-loss: https://blog.csdn.net/u014365862/article/details/79924201\n diff = self.q_target - self.q_eval_s_a\n abs_diff = tf.abs(diff)\n smoothL1_sign = tf.stop_gradient(tf.to_float(tf.less(abs_diff, 1.)))\n loss = tf.pow(diff, 2) * 0.5 * smoothL1_sign + (abs_diff - 0.5) * (1 - smoothL1_sign)\n self.loss = tf.reduce_mean(loss)\n\n with tf.variable_scope('optimize'):\n self.global_step = tf.Variable(0, trainable=False)\n self.decayed_lr = tf.train.exponential_decay(self.lr, \\\n self.global_step, 1, 0.9, staircase=True)\n ## self.decayed_lr = self.lr\n if self.optimizer_name.lower() == 'adam':\n self.optimizer = tf.train.AdamOptimizer(self.decayed_lr).minimize(self.loss)\n elif self.optimizer_name.lower() == 'rmsprop':\n self.optimizer = tf.train.RMSPropOptimizer(learning_rate=self.decayed_lr, decay=0.99999).minimize(self.loss)\n else:\n print(\"Wrong optimizer. Stopped\")\n exit(1)\n self.add_global = self.global_step.assign_add(1)\n \n # def _pad_(self, state, max_length, value):\n def _pad_(self, state, value):\n return state + [value] * (self.state_maxlength - len(state))\n # store (s, a, r, s') in Memory\n def store_memory(self, s, a, r, s_): # s = [[item], [feedback]]\n len_s, len_s_ = len(s[0]), len(s_[0])\n if not hasattr(self, 'memory_counter'): # first (s, a, r, s')\n self.memory_counter = 0\n # replace the first input (first in first out)\n index = self.memory_counter % self.memory_size\n state = self._pad_(s[0], self.action_space)\n state_ = self._pad_(s_[0], self.action_space)\n f = self._pad_(s[1], 0) # feedback is 0 or 1 now, it is ok to set 0 or 1, because refering s is [0, 0, 0] so the sum should be 0 too.\n f_ = self._pad_(s_[1], 0)\n self.memory[index, :] = state + state_ + f + f_ + [a, r, len_s, len_s_]\n self.memory_counter += 1\n def store_memorys(self, states, actions, rewards, states_, len_s, len_s_): # s = [[item], [feedback]]\n if (len_s == 0) and (self.with_userinit == False):\n return\n u_batch_size = states.shape[0]\n assert (len_s + 1) == len_s_\n if not hasattr(self, 'memory_counter'): # first (s, a, r, s')\n self.memory_counter = 0\n # replace the first input (first in first out)\n index = self.memory_counter % self.memory_size\n s = states[:, 0]\n f = states[:, 1]\n s_ = states_[:, 0]\n f_ = states_[:, 1]\n r = np.expand_dims(rewards, axis=-1)\n a = np.expand_dims(actions, axis=-1)\n len_s = np.full((u_batch_size, 1), len_s, dtype=np.int32)\n len_s_ = np.full((u_batch_size, 1), len_s_, dtype=np.int32)\n if (index+u_batch_size) > self.memory_size:\n part2_len = index+u_batch_size - self.memory_size\n indices = list(range(index, self.memory_size)) + list(range(part2_len))\n assert len(indices) == u_batch_size\n self.memory[indices, :] = np.hstack((s, s_, f, f_, a, r, len_s, len_s_))\n else:\n self.memory[index:(index+u_batch_size), :] = np.hstack((s, s_, f, f_, a, r, len_s, len_s_))\n self.memory_counter += u_batch_size\n \n def choose_action(self, s, greedy='false'):\n if ((np.random.uniform() < self.epsilon) and (greedy == 'false')) or (len(s[0]) == 0):\n action = np.random.randint(0, self.action_space)\n while action in s[0]:\n action = np.random.randint(0, self.action_space)\n else:\n state = np.array(self._pad_(s[0], self.action_space), dtype=np.int32)\n f = np.array(self._pad_(s[1], 0), dtype=np.int32)\n action_value = self.sess.run(self.q_eval, feed_dict={self.f:f[None, :], self.s:state[None, :], self.len_s:np.array([len(s[0])], dtype=np.int32)})\n action_value = action_value[0, :]\n assert len(action_value) == self.action_space\n action = np.argmax(action_value)\n change_v = np.min(action_value) - 1.0\n while action in s[0]:\n action_value[action] = change_v\n action = np.argmax(action_value)\n return action\n def choose_actions(self, states, len_s, greedy='false'):\n if not hasattr(self, 'interact_count'):\n self.interact_count = 0\n # self.epsilon = max(self.epsilon_min, self.epsilon - self.epsilon_delta)\n self.interact_count += 1\n # if greedy is false, then do \\epsilon-greedy. or just use policy to max\n s = states[:, 0]\n f = states[:, 1]\n batch_size = s.shape[0]\n ## indices for items can not be choosed\n indices_x = np.repeat(range(batch_size), len_s).astype('int')\n indices_y = s[:, :len_s].flatten()\n\n select_p = np.random.uniform(size=(batch_size, self.action_space))\n select_p[indices_x, indices_y] = -1.\n actions_random = np.argmax(select_p, axis=1)\n\n # # decrease the epsilon for exploration\n if self.interact_count % self.epsilon_decay_step == 0:\n self.epsilon = max(self.epsilon_min, self.epsilon-0.1)\n\n if (not self.with_userinit) and (len_s == 0):\n return actions_random\n \n ### use policy\n # --- normal way ----\n action_values = self.sess.run(self.q_eval, feed_dict={self.f:f, self.s:s, self.len_s:np.full((batch_size), len_s, dtype=np.int32)})\n\n # set the historical action very small value, deal with repeat items\n replace_value = np.min(action_values) - 1.\n action_values[indices_x, indices_y] = replace_value\n actions = np.argmax(action_values, axis=1)\n if greedy.lower() == 'true':\n return actions\n \n return np.where(np.random.uniform(size=(s.shape[0],)) self.memory_size:\n sample_index = np.random.choice(self.memory_size, size=self.batch_size)\n else:\n sample_index = np.random.choice(self.memory_counter, size=self.batch_size)\n # print(self.memory_counter, sample_index)\n batch_memory = self.memory[sample_index, :]\n # deal with states with unfixed length\n # states = tf.keras.preprocessing.sequence.pad_sequences(batch_memory[:, 0], \\\n # maxlen=self.state_maxlength, padding='post', value=self.action_space)\n # states_ = tf.keras.preprocessing.sequence.pad_sequences(batch_memory[:, 3], \\\n # maxlen=self.state_maxlength, padding='post', value=self.action_space)\n states = np.array(batch_memory[:, :self.state_maxlength], dtype='int')\n states_ = np.array(batch_memory[:, self.state_maxlength:(self.state_maxlength*2)], dtype='int')\n f = np.array(batch_memory[:, (self.state_maxlength*2):(self.state_maxlength*3)], dtype='int')\n f_ = np.array(batch_memory[:, (self.state_maxlength*3):(self.state_maxlength*4)], dtype='int')\n # learn\n actions = batch_memory[:, -4]\n rewards = batch_memory[:, -3]\n len_s, len_s_ = batch_memory[:, -2], batch_memory[:, -1]\n # print(\"s, s_:\\n\", states[:5], '\\n', states_[:5], '\\n')\n # print(\"actions, rewards:\\n\", actions[:5], '\\n', rewards[:5], '\\n')\n # print(\"len_s, len_s_\", len_s[:5], len_s_[:5])\n q_next, q_eval_next = self.sess.run([self.q_next, self.q_eval], \\\n feed_dict={self.s_:states_, self.f_:f_, self.s:states_, self.f:f_, \\\n self.len_s:len_s_, self.len_s_:len_s_})\n\n batch_index = np.arange(self.batch_size, dtype=np.int32)\n if self.double_q:\n max_act4_next=np.argmax(q_eval_next, axis=1)\n selected_q_next = q_next[batch_index, max_act4_next]\n else:\n selected_q_next = np.max(q_next, axis=1)\n\n q_target = rewards + self.gamma * selected_q_next\n\n _, loss = self.sess.run([self.optimizer, self.loss], \\\n feed_dict={self.s:states, self.f:f, self.a:actions, self.len_s:len_s,self.q_target:q_target})\n # todo: can \\epislon can be decreased\n\n self.learn_step_counter += 1\n # check if change TargetNet params or not\n if self.learn_step_counter % self.replace_TargetNet_iter == 0:\n self.sess.run(self.target_replace_op)\n if self.learn_step_counter % self.lr_decay_step == 0:\n self.lr_decay()\n return loss\n \n def lr_decay(self):\n _, lr = self.sess.run([self.add_global, self.decayed_lr])\n return lr\n def get_lr(self):\n return self.sess.run(self.decayed_lr)\n\n def load_pretrain_model(self):\n self.saver.restore(self.sess, './checkpoint_dir/' + self.save_model_file)\n def save_model(self):\n self.saver.save(self.sess, './checkpoint_dir/' + self.save_model_file)", "meta": {"hexsha": "dc803de2d2549e7bcbd583ad956f4f0cdb47bff0", "size": 17986, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/nn/DoubleDQN.py", "max_stars_repo_name": "BetsyHJ/SOFA", "max_stars_repo_head_hexsha": "a80e684b8047496dac6a164893b9e0666fa474a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2020-07-28T09:57:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T12:42:12.000Z", "max_issues_repo_path": "src/nn/DoubleDQN.py", "max_issues_repo_name": "BetsyHJ/SOFA", "max_issues_repo_head_hexsha": "a80e684b8047496dac6a164893b9e0666fa474a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nn/DoubleDQN.py", "max_forks_repo_name": "BetsyHJ/SOFA", "max_forks_repo_head_hexsha": "a80e684b8047496dac6a164893b9e0666fa474a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-03-24T08:33:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T03:14:22.000Z", "avg_line_length": 53.8502994012, "max_line_length": 203, "alphanum_fraction": 0.6151451129, "include": true, "reason": "import numpy", "num_tokens": 4440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.2845759920814681, "lm_q1q2_score": 0.14339959839428654}} {"text": "#!/usr/bin/env python\r\n\"\"\"\r\nThe :mod:`hotspots.calculation` handles the main Fragment Hotspot Maps algorithm. In addition, an alternative pocket burial method, Ghecom, is provided.\r\n\r\nThe main classes of the :mod:`hotspots.calculation` module are:\r\n\r\n- :class:`hotspots.calculation.Buriedness`\r\n- :class:`hotspots.calculation.Runner`\r\n\r\nMore information about the Fragment Hotspot Maps method is available from:\r\n - Radoux, C.J. et. al., Identifying the Interactions that Determine Fragment Binding at Protein Hotspots J. Med. Chem. 2016, 59 (9), 4314-4325 [dx.doi.org/10.1021/acs.jmedchem.5b01980]\r\n\r\nMore information about the Ghecom method is available from:\r\n - Kawabata T, Go N. Detection of pockets on protein surfaces using small and large probe spheres to find putative ligand binding sites. Proteins 2007; 68: 516-529\r\n\"\"\"\r\nfrom __future__ import print_function, division\r\n\r\nimport multiprocessing\r\nimport operator\r\nimport random\r\nimport shutil\r\nimport sys\r\nimport tempfile\r\nimport time\r\nfrom functools import reduce\r\nfrom os import system, environ\r\nfrom os.path import join\r\n\r\nimport numpy as np\r\nimport pkg_resources\r\n\r\nfrom scipy import ndimage\r\nfrom skimage.morphology import ball\r\nfrom skimage.transform import resize\r\n# from hotspots.protoss import Protoss\r\nfrom tqdm import tqdm\r\n\r\n# Development note. We import the CCDC modules after 3rd part modules where possible as\r\n# we generally find that the ccdc package is less fussy about the underlying compiled\r\n# libraries used.\r\n# \r\n\r\nfrom ccdc.cavity import Cavity\r\nfrom ccdc.io import MoleculeWriter, MoleculeReader\r\nfrom ccdc.molecule import Molecule, Coordinates\r\nfrom ccdc.protein import Protein\r\nfrom ccdc.utilities import PushDir\r\n\r\nfrom hotspots.atomic_hotspot_calculation import _AtomicHotspot\r\nfrom hotspots.grid_extension import Grid\r\nfrom hotspots.hs_utilities import Helper\r\nfrom hotspots.wrapper_pdb import PDBResult\r\nfrom hotspots.wrapper_ghecom import Ghecom\r\nfrom hotspots.result import Results\r\n\r\n\r\nclass ExpBuriedness(object):\r\n\r\n def __init__(self, prot, out_grid, max_probe_radius=11):\r\n self.prot = prot\r\n self.out_grid = out_grid\r\n self.max_probe = max_probe_radius\r\n self.probe_selem_dict = self._generate_probe_selem()\r\n self.protein_grid = self._from_molecule(prot)\r\n if self.out_grid is None:\r\n self.out_grid = self.protein_grid.copy_and_clear()\r\n print(\"buriedness init\")\r\n\r\n\r\n def _generate_probe_selem(self):\r\n \"\"\"\r\n Generates a set of structuring elements (i.e. probe spheres) starting from a 3x3 cross (0.5 A radius) probe up\r\n to the max probe radius\r\n :return:\r\n \"\"\"\r\n probe_selem_dict = {}\r\n\r\n # Small probe\r\n\r\n probe_selem_dict[2] = ball(2)\r\n # r= probe radius\r\n for r in range(3,self.max_probe +1):\r\n probe_selem_dict[r] = ball(r)\r\n print(\"generating probes\")\r\n return probe_selem_dict\r\n\r\n def _from_molecule(self, mol, scaling=1):\r\n \"\"\"\r\n generate a molecule mask where gp within the vdw radius of the molecule heavy atoms are set to 1.0\r\n :param mol: `ccdc.molecule.Molecule`\r\n :param padding: int\r\n :param scaling: float\r\n :return: `hotspots.grid_extension.Grid`\r\n \"\"\"\r\n\r\n coords = [a.coordinates for a in mol.atoms]\r\n g = Grid.initalise_grid(coords=coords, padding= 10, spacing=1)\r\n\r\n for probe in sorted(self.probe_selem_dict.keys(), reverse=True):\r\n for a in mol.heavy_atoms:\r\n g.set_sphere(point=a.coordinates,\r\n radius=probe * scaling,\r\n value=probe,\r\n mode='replace',\r\n scaling='None')\r\n\r\n for a in mol.heavy_atoms:\r\n g.set_sphere(point=a.coordinates,\r\n radius=a.vdw_radius,\r\n value=100,\r\n mode='replace',\r\n scaling='None')\r\n\r\n try:\r\n out_bound_box = self.out_grid.bounding_box\r\n print(out_bound_box)\r\n origin_indices = g.point_to_indices(out_bound_box[0])\r\n far_indices = g.point_to_indices(out_bound_box[1])\r\n region = origin_indices + far_indices\r\n print(region)\r\n return g.sub_grid(region)\r\n except AttributeError:\r\n return g\r\n\r\n def _close_grid(self, g, probe):\r\n\r\n g_array = g.get_array().astype(int)\r\n closed_array = ndimage.binary_erosion(g_array, structure=self.probe_selem_dict[probe])\r\n return Grid.array_to_grid(closed_array.astype(int), g)\r\n\r\n def _multiscale_closing(self,g):\r\n\r\n\r\n #probe_sizes.reverse()\r\n all_g = None\r\n prot_mask = g > 90\r\n\r\n for probe in sorted(self.probe_selem_dict.keys())[1:]:\r\n if all_g is None:\r\n all_g = prot_mask.copy()\r\n\r\n probe_mask = ((g < probe+0.1) & (g>0)) | (prot_mask)\r\n\r\n\r\n probe_mask = self._close_grid(probe_mask,probe)\r\n novel = (-all_g) * (g>0)\r\n all_g += (probe_mask * novel * (self.max_probe - probe))\r\n\r\n return all_g * (prot_mask < 1)\r\n\r\n def _open_grid(self, g, probe):\r\n\r\n g_array = g.get_array().astype(int)\r\n opened_array = ndimage.binary_opening(g_array, structure=self.probe_selem_dict[probe])\r\n return Grid.array_to_grid(opened_array.astype(int), g)\r\n\r\n def buriedness_grid(self):\r\n\r\n closed_g = self._multiscale_closing(self.protein_grid)\r\n print(\"close_g\")\r\n out_g = self._open_grid(closed_g,2) * closed_g\r\n print(\"out_g\")\r\n out_array = out_g.get_array()\r\n print(\"out array\")\r\n scaled_g = Grid.initalise_grid(self.out_grid.bounding_box, padding=0, spacing=0.5)\r\n print(\"scaled_g\")\r\n scaled_array = resize(out_array, scaled_g.nsteps ,anti_aliasing=False)\r\n print(scaled_array)\r\n\r\n\r\n # Future tweaking here\r\n final_array = scaled_array\r\n print(\"array to grid\")\r\n return Grid.array_to_grid(final_array.astype(int), scaled_g)\r\n\r\n\r\nclass _WeightedResult(object):\r\n \"\"\"\r\n private class\r\n\r\n A class to handle the weighted grid results\r\n\r\n :param str identifier: identifier, default is the probe identifier assigned at the Atomic Hotspot Calculation stage\r\n :param `ccdc.utilities.Grid` grid: result grid\r\n \"\"\"\r\n\r\n def __init__(self, identifier, grid):\r\n self.identifier = identifier\r\n self.grid = grid\r\n\r\n\r\nclass _SampleGrid(object):\r\n \"\"\"\r\n private class\r\n\r\n class to handle sampled grids\r\n\r\n :param name: str, name of probe (donor, acceptor, apolar, positive, negative)\r\n :param grid: a :class: `ccdc.utilities.Grid` instance\r\n :param atom_predicate: atom_predicate will be used to select atoms of a molecule for sampling\r\n \"\"\"\r\n\r\n def __init__(self, name, grid, atom_predicate):\r\n self.name = name\r\n self.grid = grid\r\n self.atom_predicate = atom_predicate\r\n self.mol = None\r\n\r\n @staticmethod\r\n def add_coordinates(coord, trans):\r\n \"\"\"\r\n provides a coordinate list of atoms to be scored be scored in the SampleGrid\r\n :param coord: tup, (float(x), float(y), float(z)), set of atomic coordinates for \"active\" coordinates\r\n :param trans: tup, (float(x), float(y), float(z)), set of translations to translate probes to points\r\n above threshold\r\n :return: list of tup\r\n \"\"\"\r\n\r\n return [coord[i] + trans[i] for i in range(0, len(trans))]\r\n\r\n def sample(self, coordinate_list, trans):\r\n \"\"\"\r\n score Molecule in grids for which it has active atoms\r\n :param coordinate_list: list, set of coordinates of translated and rotated probe atoms to be scored\r\n :param trans:\r\n :return:\r\n \"\"\"\r\n\r\n try:\r\n return [self.grid._grid.value(self.add_coordinates(c, trans)) for c in coordinate_list]\r\n except RuntimeError:\r\n return [0]\r\n\r\n def set_molecule(self, mol, polar_contribution):\r\n \"\"\"\r\n set which atoms match the grid\r\n probes with polar atoms contribute do not contribute to apolar maps as this leads to artefacts\r\n\r\n :param mol:\r\n :param polar_contribution:\r\n :return:\r\n \"\"\"\r\n self.mol = mol\r\n if self.name == 'apolar' and not polar_contribution and len([a for a in mol.atoms\r\n if a.is_donor or a.is_acceptor]) > 0:\r\n self._active_atoms = []\r\n elif not hasattr(self, '_active_atoms'):\r\n self._active_atoms = [a for a in self.mol.atoms if self.atom_predicate(a)]\r\n\r\n @staticmethod\r\n def is_donor(a):\r\n \"\"\"\r\n returns true if a given atom is a donor\r\n\r\n :param a: a `ccdc.molecule.Atom` instance\r\n :return: bool, true if the atom classification is \"donor\"\r\n \"\"\"\r\n\r\n if a.is_donor and a.formal_charge == 0:\r\n return True\r\n else:\r\n return False\r\n\r\n @staticmethod\r\n def is_acceptor(a):\r\n \"\"\"\r\n returns true if a given atom is a acceptor\r\n\r\n :param a: a `ccdc.molecule.Atom` instance\r\n :return: bool, true if the atom classification is \"acceptor\"\r\n \"\"\"\r\n if a.is_acceptor and a.formal_charge == 0:\r\n return True\r\n else:\r\n return False\r\n\r\n @staticmethod\r\n def is_apolar(a):\r\n \"\"\"\r\n returns true if a given atom is a apolar\r\n\r\n :param a: a `ccdc.molecule.Atom` instance\r\n :return: bool, true if the atom classification is \"apolar\"\r\n \"\"\"\r\n if a.is_donor or a.is_acceptor or a.formal_charge != 0 or a.atomic_symbol == \"Xe\":\r\n return False\r\n else:\r\n return True\r\n\r\n @staticmethod\r\n def is_positive(a):\r\n \"\"\"\r\n returns true if a given atom is a positively charged\r\n\r\n :param a: a `ccdc.molecule.Atom` instance\r\n :return: bool, true if the atom is positively charged\r\n \"\"\"\r\n return a.formal_charge > 0\r\n\r\n @staticmethod\r\n def is_negative(a):\r\n \"\"\"\r\n returns true if a given atom is a negatively charged\r\n\r\n :param a: a `ccdc.molecule.Atom` instance\r\n :return: bool, true if the atom is negatively charged\r\n \"\"\"\r\n return a.formal_charge < 0\r\n\r\n @staticmethod\r\n def is_aromatic(a):\r\n \"\"\"\r\n returns true if a given atom is aromatic\r\n\r\n :param a: a `ccdc.molecule.Atom` instance\r\n :return: bool, true if the atom is aromatic\r\n \"\"\"\r\n return a.atomic_symbol == 'C' and a.is_cyclic and any(b.atom_type == 'aromatic' for b in a.bonds)\r\n\r\n\r\nclass Runner(object):\r\n \"\"\"\r\n A class for running the Fragment Hotspot Map calculation\r\n \"\"\"\r\n\r\n class Settings(object):\r\n \"\"\"\r\n adjusts the default settings for the calculation\r\n\r\n :param int nrotations: number of rotations (keep it below 10**6)\r\n :param float apolar_translation_threshold: translate probe to grid points above this threshold. Give lower values for greater sampling. Default 15\r\n :param float polar_translation_threshold: translate probe to grid points above this threshold. Give lower values for greater sampling. Default 15\r\n :param bool polar_contributions: allow carbon atoms of probes with polar atoms to contribute to the apolar output map.\r\n :param bool return_probes: Generate a sorted list of molecule objects, corresponding to probe poses\r\n :param bool sphere_maps: When setting the probe score on the output maps, set it for a sphere (radius 1.5) instead of a single point.\r\n \"\"\"\r\n\r\n def __init__(self, nrotations=3000, apolar_translation_threshold=15, polar_translation_threshold=15,\r\n polar_contributions=False, return_probes=False, sphere_maps=False):\r\n self.nrotations = nrotations\r\n self.apolar_translation_threshold = apolar_translation_threshold\r\n self.polar_translation_threshold = polar_translation_threshold\r\n self.polar_contributions = polar_contributions\r\n self.return_probes = return_probes\r\n self.sphere_maps = sphere_maps\r\n\r\n @property\r\n def _num_gp(self):\r\n \"\"\"\r\n number of grid point for a given volume\r\n :return:\r\n \"\"\"\r\n return int(float(500) / self.nrotations ** 3)\r\n\r\n class _Sampler(object):\r\n \"\"\"\r\n Samples one or more grids with a probe molecule\r\n \"\"\"\r\n\r\n def __init__(self, *grids, **kw):\r\n \"\"\"\r\n Settings used to run fragment-hotspot-maps script\r\n\r\n :param grids: list, list of :class:`ccdc.utilities.Grid` instances\r\n :param kw: 'settings'\r\n \"\"\"\r\n\r\n self.grids = grids\r\n self.grid_dic = {}\r\n for g in grids:\r\n self.grid_dic[g.name] = g\r\n settings = kw.get('settings')\r\n if settings is None:\r\n settings = self.Settings()\r\n\r\n self.settings = settings\r\n self.probe_grids = [_SampleGrid(g.name, g.grid.copy_and_clear(), g.atom_predicate) for g in self.grids]\r\n\r\n def get_priority_atom(self, molecule):\r\n \"\"\"\r\n Select priority atom. Select polar atom. If multiple polar atoms, select the one furthest from the centre of\r\n geometry. If no polar atoms, select atom furthest from centre of geometry\r\n\r\n :param molecule: a :class: `ccdc.molecule.Molecule` instance\r\n :return: a :class: `ccdc.molecule.Molecule` instance, str atom type\r\n \"\"\"\r\n c = molecule.centre_of_geometry()\r\n polar_atoms = [a for a in molecule.atoms if a.is_donor or a.is_acceptor]\r\n atom_by_distance = {}\r\n if len(polar_atoms) > 0:\r\n for a in polar_atoms:\r\n d = Helper.get_distance(c, a.coordinates)\r\n atom_by_distance[d] = a\r\n else:\r\n for a in molecule.atoms:\r\n d = Helper.get_distance(c, a.coordinates)\r\n atom_by_distance[d] = a\r\n\r\n greatest_distance = sorted(atom_by_distance.keys())[0]\r\n priority_atom = atom_by_distance[greatest_distance]\r\n\r\n pa_type = None\r\n if priority_atom.formal_charge != 0:\r\n if priority_atom.formal_charge < 0:\r\n pa_type = \"acceptor\"\r\n elif priority_atom.formal_charge > 0:\r\n pa_type = \"donor\"\r\n else:\r\n if priority_atom.is_acceptor:\r\n pa_type = \"acceptor\"\r\n elif priority_atom.is_donor:\r\n pa_type = \"donor\"\r\n else:\r\n pa_type = \"apolar\"\r\n\r\n return priority_atom, pa_type\r\n\r\n def get_translation_points(self, priority_atom_type):\r\n \"\"\"\r\n returns a list of coordinates that are greater than the threshold, that the probe will be translated to\r\n\r\n :param priority_atom_type: str, atomic interaction type\r\n :return: list, list of :class: `ccdc.molecule.Molecule` instances\r\n \"\"\"\r\n translate_probe = []\r\n wg = self.grid_dic[priority_atom_type]\r\n\r\n if priority_atom_type == 'apolar':\r\n translation_threshold = self.settings.apolar_translation_threshold\r\n else:\r\n translation_threshold = self.settings.polar_translation_threshold\r\n hs = wg.grid.islands(translation_threshold)\r\n for g in hs:\r\n nx, ny, nz = g.nsteps\r\n\r\n maxima = [g.indices_to_point(i, j, k)\r\n for i in range(nx) for j in range(ny) for k in range(nz)\r\n if g.value(i, j, k) >= translation_threshold]\r\n\r\n translate_probe = translate_probe + maxima\r\n return translate_probe\r\n\r\n def generate_rand_quaternions(self):\r\n \"\"\"\r\n Returns a list of random quaternions. Length matches settings.nrotations\r\n\r\n :return: tup, (a,b,c,d)\r\n \"\"\"\r\n quaternions = []\r\n i = 1\r\n if self.settings.nrotations > 1:\r\n while i <= self.settings.nrotations:\r\n r1 = random.uniform(-1, 1)\r\n r2 = random.uniform(-1, 1)\r\n s1 = r1 * r1 + r2 * r2\r\n if s1 < 1:\r\n r3 = random.uniform(-1, 1)\r\n r4 = random.uniform(-1, 1)\r\n\r\n s2 = r3 * r3 + r4 * r4\r\n if s2 < 1:\r\n q = (r1, r2, r3 * (np.sqrt((1 - s1) / s2)), r4 * (np.sqrt((1 - s1) / s2)))\r\n quaternions.append(q)\r\n\r\n i += 1\r\n\r\n return quaternions\r\n\r\n @staticmethod\r\n def score(values):\r\n \"\"\"\r\n Calculate geometric mean of scores\r\n\r\n :param values: float, scores of atoms in probe\r\n :return: float, geometric mean of probe atom scores\r\n \"\"\"\r\n\r\n return reduce(operator.__mul__, values, 1.0) ** (1. / len(values))\r\n # return sum(values)\r\n\r\n def sample_pose(self, trans, active_atoms_dic, probe):\r\n \"\"\"\r\n Return a pose score (as defined by the score(self,dic) function) and a dictionary of atom:scores\r\n\r\n :param trans: list of translations\r\n :param active_atoms_dic: dict {\"interaction type\": \"atoms to be scored\"}\r\n :param probe: str, interaction_type\r\n :return:\r\n \"\"\"\r\n if probe == \"negative\" or probe == \"positive\":\r\n atoms = [g.mol.atoms for g in self.grids if g.name == \"positive\"][0]\r\n weight = int(6 / len([a for a in atoms if str(a.atomic_symbol) == \"C\"]))\r\n\r\n apolar_values = [g.sample(active_atoms_dic[g.name], trans) for g in self.grids if\r\n len(active_atoms_dic[g.name]) > 0 and g.name == \"apolar\"] * weight\r\n charged_values = [g.sample(active_atoms_dic[g.name], trans) for g in self.grids if\r\n len(active_atoms_dic[g.name]) > 0 and g.name != \"apolar\"]\r\n values = apolar_values + charged_values\r\n\r\n else:\r\n values = [g.sample(active_atoms_dic[g.name], trans) for g in self.grids if\r\n len(active_atoms_dic[g.name]) > 0]\r\n scores = [item for sublist in values for item in sublist]\r\n return self.score(scores)\r\n\r\n def update_out_grids(self, score, active_coordinates_dic, trans):\r\n \"\"\"\r\n For active atoms for a given grid, set closest grid point value to score, unless already set to a higher\r\n value\r\n\r\n :param score: float, score of a given probe\r\n :param active_coordinates_dic:\r\n :param trans: list of translations\r\n :return:\r\n \"\"\"\r\n\r\n for pg in self.probe_grids:\r\n actives = active_coordinates_dic[pg.name]\r\n if len(actives) == 0:\r\n continue\r\n for a in actives:\r\n coords = pg.add_coordinates(a, trans)\r\n i, j, k = pg.grid.point_to_indices(coords)\r\n orig_value = pg.grid.value(i, j, k)\r\n #\r\n if self.settings.sphere_maps:\r\n # pg.grid.set_sphere(coords, 2, score, mode='max')\r\n if score > orig_value:\r\n pg.grid.set_sphere(coords, 1.5, score, mode='max', scaling='None')\r\n else:\r\n pg.grid.set_value(i, j, k, max(score, orig_value))\r\n\r\n def get_active_coordinates(self):\r\n \"\"\"\r\n Returns a dictionary of {grid_name:[Coordinates]}\r\n\r\n :return:\r\n \"\"\"\r\n active_coords_dic = {\r\n g.name: [a.coordinates for a in g._active_atoms]\r\n for g in self.grids\r\n }\r\n\r\n return active_coords_dic\r\n\r\n def sample(self, molecule, probe, update_grids = True):\r\n \"\"\"\r\n Sample the grids according to the settings\r\n\r\n :param molecule:\r\n :param probe: str, interaction type, (donor, acceptor, negative, positive, apolar)\r\n :return:\r\n \"\"\"\r\n priority_atom, priority_atom_type = self.get_priority_atom(molecule)\r\n translate_points = self.get_translation_points(priority_atom_type)\r\n molecule.remove_hydrogens()\r\n quaternions = self.generate_rand_quaternions()\r\n high_scoring_probes = {}\r\n print(\"\\n nRotations:\", len(quaternions), \"nTranslations:\", len(translate_points), \"probename:\", probe)\r\n\r\n for g in self.grids:\r\n g.set_molecule(molecule, True)\r\n\r\n for g in self.probe_grids:\r\n g.set_molecule(molecule, self.settings.polar_contributions)\r\n\r\n for q in tqdm(quaternions):\r\n molecule.apply_quaternion(q)\r\n priority_atom_coordinates = priority_atom.coordinates\r\n active_coordinates_dic = self.get_active_coordinates()\r\n\r\n for priority_atom_point in translate_points:\r\n\r\n translation = [priority_atom_point[i] - priority_atom_coordinates[i]\r\n for i in range(0, len(priority_atom_coordinates))]\r\n\r\n score = self.sample_pose(translation, active_coordinates_dic, probe)\r\n\r\n try:\r\n if score < 1:\r\n continue\r\n except TypeError:\r\n continue\r\n if update_grids:\r\n self.update_out_grids(score, active_coordinates_dic, translation)\r\n\r\n if self.settings.return_probes is True:\r\n if score > 10:\r\n m = molecule.copy()\r\n m.translate(translation)\r\n m.identifier = \"{}\".format(score)\r\n\r\n try:\r\n high_scoring_probes[score].append(m)\r\n except KeyError:\r\n high_scoring_probes[score] = [m]\r\n\r\n if self.settings.return_probes is True:\r\n sampled_probes = []\r\n for key in sorted(high_scoring_probes.keys(), reverse=True)[:100]:\r\n sampled_probes.extend(high_scoring_probes[key])\r\n print('Returned probes = ', len(sampled_probes))\r\n return sampled_probes\r\n\r\n # if len(sampled_probes) > 100:\r\n # return sampled_probes[:100]\r\n # else:\r\n # return sampled_probes\r\n\r\n def __init__(self, settings=None):\r\n self.out_grids = {}\r\n self.super_grids = {}\r\n self.buriedness = None\r\n self.sampled_probes = {}\r\n\r\n if settings is None:\r\n self.sampler_settings = self.Settings()\r\n else:\r\n self.sampler_settings = settings\r\n\r\n @property\r\n def protein(self):\r\n \"\"\"\r\n protein submitted for calculation\r\n :return:\r\n \"\"\"\r\n return self._protein\r\n\r\n @protein.setter\r\n def protein(self, prot):\r\n \"\"\"\r\n protein submitted for calculation\r\n :param `ccdc.protein.Protein` prot: protein\r\n :return:\r\n \"\"\"\r\n if isinstance(prot, Protein):\r\n self._protein = prot\r\n else:\r\n raise TypeError(\"`ccdc.protein.Protein` must be supplied. Hint: Use Protein.from_file()\")\r\n\r\n @property\r\n def charged_probes(self):\r\n \"\"\"\r\n optional settings, True if charged features are to be calculated\r\n :return:\r\n \"\"\"\r\n return self._charged_probes\r\n\r\n @charged_probes.setter\r\n def charged_probes(self, option):\r\n \"\"\"\r\n optional settings, True if charged features are to be calculated\r\n :param bool option: (default = True)\r\n :return:\r\n \"\"\"\r\n if type(option) is bool:\r\n self._charged_probes = option\r\n else:\r\n raise TypeError(\"Expecting a bool, got {} instead\".format(type(option)))\r\n\r\n @property\r\n def probe_size(self):\r\n \"\"\"\r\n optional settings, change probe size. NB: feature has not been tested.\r\n :return:\r\n \"\"\"\r\n return self._probe_size\r\n\r\n @probe_size.setter\r\n def probe_size(self, size):\r\n \"\"\"\r\n optional settings, change probe size. NB: feature has not been tested.\r\n :param int size: number of heavy atoms contain within the molecular probes (integer between 3 and 8)\r\n :return:\r\n \"\"\"\r\n if size in range(3, 8):\r\n self._probe_size = size\r\n else:\r\n raise ValueError(\"Probe size must be an integer between 3-7\")\r\n\r\n @property\r\n def buriedness_method(self):\r\n \"\"\"\r\n optional settings, pocket detection method. (default = \"ghecom\")\r\n :return:\r\n \"\"\"\r\n return self._buriedness_method\r\n\r\n @buriedness_method.setter\r\n def buriedness_method(self, method):\r\n \"\"\"\r\n optional settings, pocket detection method. (default = \"ghecom\")\r\n :param str method: either 'ghecom' or 'ligsite'\r\n :return:\r\n \"\"\"\r\n method = method.lower()\r\n if method == 'ghecom':\r\n if sys.platform == 'linux' or sys.platform == 'linux2':\r\n if 'GHECOM_EXE' in environ:\r\n self._buriedness_method = method\r\n else:\r\n raise EnvironmentError(\"Must set Ghecom environment variable\")\r\n else:\r\n raise OSError('Ghecom is only supported on linux')\r\n\r\n elif method == 'ghecom_internal':\r\n self._buriedness_method = method\r\n\r\n elif method == 'ligsite':\r\n if sys.platform == 'linux' or sys.platform == 'linux2':\r\n print(\"RECOMMENDATION: you have chosen LIGSITE as buriedness method, ghecom is recommended\")\r\n self._buriedness_method = method\r\n\r\n else:\r\n raise ValueError(\"Buriedness method must be 'ghecom' (default) or 'ligsite\")\r\n\r\n @property\r\n def cavities(self):\r\n \"\"\"\r\n optional settings, cavities supplied to the calculation\r\n :return:\r\n \"\"\"\r\n return self._cavities\r\n\r\n @cavities.setter\r\n def cavities(self, obj):\r\n \"\"\"\r\n optional settings, cavities supplied to the calculation\r\n :param list or Coordinate or `ccdc.molecule.Molecule` or `ccdc.cavity.Cavity`: cavity information provided\r\n :return:\r\n \"\"\"\r\n if obj is not None:\r\n if isinstance(obj, list) or isinstance(obj, tuple):\r\n if isinstance(obj, Coordinates):\r\n try:\r\n print(obj.x)\r\n self._cavities = [obj]\r\n except AttributeError:\r\n self._cavities = obj\r\n\r\n self._cavities = [obj]\r\n elif isinstance(obj[0], Molecule):\r\n self._cavities = [m.centre_of_geometry() for m in obj]\r\n elif isinstance(obj[0], Cavity):\r\n self._cavities = [Helper.cavity_centroid(c) for c in obj]\r\n else:\r\n try:\r\n self._cavities = [Coordinates(x=obj[0], y=obj[1], z=obj[2])]\r\n except RuntimeError:\r\n print(\"WARNING! Failed to detected cavity, Atomic Hotspot detection to run on whole protein\")\r\n self._cavities = None\r\n\r\n elif isinstance(obj, Molecule):\r\n self._cavities = [obj.centre_of_geometry()]\r\n elif isinstance(obj, Cavity):\r\n self._cavities = [Helper.cavity_centroid(obj)]\r\n\r\n else:\r\n print(\"WARNING! Failed to detected cavity, Atomic Hotspot detection to run on whole protein\")\r\n self._cavities = None\r\n else:\r\n self._cavities = None\r\n\r\n @property\r\n def nprocesses(self):\r\n \"\"\"\r\n number of processes used in parallelisation\r\n :return:\r\n \"\"\"\r\n return self._nprocesses\r\n\r\n @nprocesses.setter\r\n def nprocesses(self, num):\r\n \"\"\"\r\n number of processes used in parallelisation\r\n :param int num: number of processor\r\n :return:\r\n \"\"\"\r\n num = int(num)\r\n if num in range(0, int(multiprocessing.cpu_count())):\r\n self._nprocesses = num\r\n else:\r\n raise OSError(\"CPU count = {}\".format(multiprocessing.cpu_count()))\r\n\r\n @property\r\n def sampler_settings(self):\r\n \"\"\"\r\n sampler settings\r\n :return:\r\n \"\"\"\r\n return self._sampler_settings\r\n\r\n @sampler_settings.setter\r\n def sampler_settings(self, settings):\r\n \"\"\"\r\n sampler settings\r\n :param `hotspots.calculation.Runner.Settings` settings: adjust run settings\r\n :return:\r\n \"\"\"\r\n if isinstance(settings, self.Settings):\r\n self._sampler_settings = settings\r\n else:\r\n self._sampler_settings = None\r\n\r\n def _get_weighted_maps(self):\r\n \"\"\"\r\n private method\r\n\r\n weight superstar output by burriedness\r\n :return: a list of :class:`WeightedResult` instances\r\n \"\"\"\r\n results = []\r\n for s in self.superstar_grids:\r\n g, b = Grid.common_grid([s.grid, self.buriedness], padding=1)\r\n weighted_grid = g * b\r\n results.append(_WeightedResult(s.identifier, weighted_grid))\r\n\r\n return results\r\n\r\n def _dock_probe(self,mol, grid_dict):\r\n\r\n donor_grid = _SampleGrid('donor', grid_dict['donor'], _SampleGrid.is_donor)\r\n acceptor_grid = _SampleGrid('acceptor', grid_dict['acceptor'], _SampleGrid.is_acceptor)\r\n apolar_grid = _SampleGrid('apolar', grid_dict['apolar'], _SampleGrid.is_apolar)\r\n\r\n kw = {'settings': self.sampler_settings}\r\n self.sampler = self._Sampler(apolar_grid, donor_grid, acceptor_grid, **kw)\r\n\r\n probes = self.sampler.sample(mol, probe='probe', update_grids=False)\r\n return probes\r\n\r\n def _get_out_maps(self, probe, grid_dict, return_probes=False):\r\n \"\"\"\r\n private method\r\n\r\n organises the sampling of weighted superstar maps by molecular probes\r\n :param str probe: probe identifier set in the Atomic Hotspot calculation\r\n :param dict grid_dict: dictionary with key = probe identifier and value = `hotspots.grid_extension.Grid`\r\n :param bool return_probes: optional, bool indicating if probe molecules should be returned\r\n :return:\r\n \"\"\"\r\n donor_grid = _SampleGrid('donor', grid_dict['donor'], _SampleGrid.is_donor)\r\n acceptor_grid = _SampleGrid('acceptor', grid_dict['acceptor'], _SampleGrid.is_acceptor)\r\n apolar_grid = _SampleGrid('apolar', grid_dict['apolar'], _SampleGrid.is_apolar)\r\n\r\n if self.charged_probes:\r\n negative_grid = _SampleGrid('negative', grid_dict['negative'], _SampleGrid.is_negative)\r\n positive_grid = _SampleGrid('positive', grid_dict['positive'], _SampleGrid.is_positive)\r\n\r\n kw = {'settings': self.sampler_settings}\r\n if self.charged_probes:\r\n self.sampler = self._Sampler(apolar_grid, donor_grid, acceptor_grid, negative_grid, positive_grid, **kw)\r\n else:\r\n self.sampler = self._Sampler(apolar_grid, donor_grid, acceptor_grid, **kw)\r\n\r\n probe_path = pkg_resources.resource_filename('hotspots', 'probes/')\r\n\r\n if self.charged_probes:\r\n if probe == \"negative\" or probe == \"positive\":\r\n mol = MoleculeReader(join(probe_path, \"rotate-{}_{}_flat.mol2\".format(probe, \"test\")))[0]\r\n else:\r\n mol = MoleculeReader(join(probe_path, \"rotate-{}_{}_flat.mol2\".format(probe, self.probe_size)))[0]\r\n else:\r\n mol = MoleculeReader(join(probe_path, \"rotate-{}_{}_flat.mol2\".format(probe, self.probe_size)))[0]\r\n\r\n probes = self.sampler.sample(mol, probe=probe)\r\n\r\n for pg in self.sampler.probe_grids:\r\n if pg.name.lower() == probe:\r\n try:\r\n self.out_grids[pg.name].append(pg.grid)\r\n except KeyError:\r\n self.out_grids[pg.name] = [pg.grid]\r\n\r\n if return_probes is True:\r\n return probes\r\n\r\n def _calc_hotspots(self, return_probes=False):\r\n \"\"\"\r\n handles the organisation of the hotspot calculation\r\n :param return_probes: optional, bool indicating if probe molecules should be returned\r\n :return:\r\n \"\"\"\r\n print(\"Start atomic hotspot detection\\n Processors: {}\".format(self.nprocesses))\r\n a = _AtomicHotspot()\r\n a.settings.atomic_probes = {\"apolar\": \"AROMATIC CH CARBON\",\r\n \"donor\": \"UNCHARGED NH NITROGEN\",\r\n \"acceptor\": \"CARBONYL OXYGEN\"}\r\n if self.charged_probes:\r\n a.settings.atomic_probes = {\"negative\": \"CARBOXYLATE OXYGEN\", \"positive\": \"CHARGED NH NITROGEN\"}\r\n\r\n probe_types = a.settings.atomic_probes.keys()\r\n self.superstar_grids = a.calculate(protein=self.protein,\r\n nthreads=self.nprocesses,\r\n cavity_origins=self.cavities)\r\n\r\n if self.clear_tmp == True:\r\n shutil.rmtree(a.settings.temp_dir)\r\n\r\n print(\"Atomic hotspot detection complete\\n\")\r\n\r\n print(\"Start buriedness calculation\")\r\n if self.buriedness_method.lower() == 'ghecom' and self.buriedness is None:\r\n print(\" method: Ghecom\")\r\n out_grid = self.superstar_grids[0].buriedness.copy_and_clear()\r\n\r\n ghecom = Ghecom()\r\n path = ghecom.run(self.protein)\r\n self.buriedness = ghecom.pdb_to_grid(path, out_grid)\r\n\r\n shutil.rmtree(ghecom.temp) # probs not needed\r\n\r\n elif self.buriedness_method.lower() == 'ghecom_internal' and self.buriedness is None:\r\n print(\" method: Internal version Ghecom\")\r\n out_grid = self.superstar_grids[0].buriedness.copy_and_clear()\r\n b = ExpBuriedness(prot=self.protein, out_grid=None)\r\n self.buriedness = b.buriedness_grid()\r\n\r\n elif self.buriedness_method.lower() == 'ligsite' and self.buriedness is None:\r\n print(\" method: LIGSITE\")\r\n self.buriedness = Grid.get_single_grid(grd_dict={s.identifier: s.buriedness for s in self.superstar_grids},\r\n mask=False)\r\n\r\n self.weighted_grids = self._get_weighted_maps()\r\n\r\n print(\"Buriedness calcualtion complete\\n\")\r\n\r\n print(\"Start sampling\")\r\n grid_dict = {w.identifier: w.grid for w in self.weighted_grids}\r\n\r\n for probe in probe_types:\r\n if return_probes is True:\r\n ps = self._get_out_maps(probe, grid_dict, return_probes=True)\r\n print(len(ps))\r\n self.sampled_probes.update({probe: ps})\r\n\r\n else:\r\n self._get_out_maps(probe, grid_dict)\r\n\r\n print(\"Sampling complete\\n\")\r\n\r\n def _prepare_protein(self, protoss=False):\r\n \"\"\"\r\n default protein preparation settings on the protein\r\n :return:\r\n \"\"\"\r\n self.protein.remove_all_waters()\r\n for lig in self.protein.ligands:\r\n self.protein.remove_ligand(lig.identifier)\r\n self.protein.remove_all_metals()\r\n\r\n if protoss is False:\r\n self.protein.add_hydrogens()\r\n\r\n def from_superstar(self, protein, superstar_grids, buriedness, charged_probes=False, probe_size=7,\r\n settings=None, clear_tmp=False):\r\n \"\"\"\r\n calculate hotspot maps from precalculated superstar maps. This enables more effective parallelisation and reuse\r\n of object such as the Buriedness grids\r\n\r\n :param protein: a :class:`ccdc.protein.Protein` instance\r\n :param superstar_grids: a :class:`hotspots.atomic_hotspot_calculation._AtomicHotspotResult` instance\r\n :param buriedness: a :class:`hotspots.grid_extension.Grid` instance\r\n :param bool charged_probes: If True, include positive and negative probes\r\n :param int probe_size: Size of probe in number of heavy atoms (3-8 atoms)\r\n :param settings: `hotspots.calculation.Runner.Settings` settings: holds the sampler settings\r\n :param bool clear_tmp: If True, clear the temporary directory\r\n :return:\r\n \"\"\"\r\n start = time.time()\r\n self.super_grids = {}\r\n self.superstar_grids = superstar_grids\r\n self.probe_types = [p.identifier for p in self.superstar_grids]\r\n self.buriedness = buriedness\r\n\r\n self.protein = protein\r\n self.charged_probes = charged_probes\r\n self.probe_size = probe_size\r\n self.clear_tmp = clear_tmp\r\n\r\n if settings is None:\r\n self.sampler_settings = self.Settings()\r\n else:\r\n self.sampler_settings = settings\r\n\r\n self.weighted_grids = self._get_weighted_maps()\r\n\r\n print(\"Start sampling\")\r\n grid_dict = {w.identifier: w.grid for w in self.weighted_grids}\r\n\r\n for probe in self.probe_types:\r\n self._get_out_maps(probe, grid_dict)\r\n\r\n self.super_grids = {p: g[0] for p, g in self.out_grids.items()}\r\n\r\n print(\"Sampling complete\\n\")\r\n print(\"Runtime = {}seconds\".format(time.time() - start))\r\n\r\n return Results(super_grids=self.super_grids,\r\n protein=self.protein,\r\n buriedness=self.buriedness)\r\n\r\n\r\n def from_protein(self, protein, charged_probes=False, probe_size=7, buriedness_method='ghecom',\r\n cavities=None, nprocesses=1, settings=None, buriedness_grid=None, clear_tmp=False):\r\n \"\"\"\r\n generates a result from a protein\r\n\r\n :param protein: a :class:`ccdc.protein.Protein` instance\r\n :param bool charged_probes: If True include positive and negative probes\r\n :param int probe_size: Size of probe in number of heavy atoms (3-8 atoms)\r\n :param str buriedness_method: Either 'ghecom' or 'ligsite'\r\n :param cavities: Coordinate or `ccdc.cavity.Cavity` or `ccdc.molecule.Molecule` or list specifying the cavity or cavities on which the calculation should be run\r\n :param int nprocesses: number of CPU's used\r\n :param `hotspots.calculation.Runner.Settings` settings: holds the sampler settings\r\n :param `ccdc.utilities.Grid` buriedness_grid: pre-calculated buriedness grid\r\n :return: a :class:`hotspots.result.Results` instance\r\n\r\n\r\n >>> from ccdc.protein import Protein\r\n >>> from hotspots.calculation import Runner\r\n\r\n >>> protein = Protein.from_file()\r\n\r\n >>> runner = Runner()\r\n >>> settings = Runner.Settings()\r\n >>> settings.nrotations = 1000 # fewer rotations increase speed at the expense of accuracy\r\n >>> runner.from_protein(protein, nprocesses=3, settings=settings)\r\n Result()\r\n\r\n \"\"\"\r\n start = time.time()\r\n self.super_grids = {}\r\n self.buriedness = buriedness_grid\r\n self.protein = protein\r\n self.charged_probes = charged_probes\r\n self.probe_size = probe_size\r\n self.buriedness_method = buriedness_method\r\n self.cavities = cavities\r\n self.clear_tmp = clear_tmp\r\n\r\n print(self.cavities)\r\n self.nprocesses = nprocesses\r\n if settings is None:\r\n self.sampler_settings = self.Settings()\r\n else:\r\n self.sampler_settings = settings\r\n self._calc_hotspots() # return probes = False by default\r\n self.super_grids = {p: g[0] for p, g in self.out_grids.items()}\r\n print(\"Runtime = {}seconds\".format(time.time() - start))\r\n\r\n return Results(super_grids=self.super_grids,\r\n protein=self.protein,\r\n buriedness=self.buriedness,\r\n superstar={x.identifier: x.grid for x in self.superstar_grids},\r\n weighted_superstar={x.identifier: x.grid for x in self.weighted_grids})\r\n\r\n def from_pdb(self, pdb_code, charged_probes=False, probe_size=7, buriedness_method='ghecom', nprocesses=3,\r\n cavities=False, settings=None, clear_tmp=False):\r\n \"\"\"\r\n generates a result from a pdb code\r\n\r\n :param str pdb_code: PDB code\r\n :param bool charged_probes: If True include positive and negative probes\r\n :param int probe_size: Size of probe in number of heavy atoms (3-8 atoms)\r\n :param str buriedness_method: Either 'ghecom' or 'ligsite'\r\n :param int nprocesses: number of CPU's used\r\n :param `hotspots.calculation.Runner.Settings` settings: holds the calculation settings\r\n :return: a :class:`hotspots.result.Result` instance\r\n\r\n\r\n >>> from hotspots.calculation import Runner\r\n\r\n >>> runner = Runner()\r\n >>> runner.from_pdb(\"1hcl\")\r\n Result()\r\n\r\n \"\"\"\r\n protoss = False\r\n\r\n tmp = tempfile.mkdtemp()\r\n # if protoss is True:\r\n # protoss = Protoss(out_dir=tmp)\r\n # self.protein = protoss.add_hydrogens(pdb_code).protein\r\n #\r\n # else:\r\n PDBResult(identifier=pdb_code).download(out_dir=tmp)\r\n fname = join(tmp, \"{}.pdb\".format(pdb_code))\r\n self.protein = Protein.from_file(fname)\r\n self._prepare_protein(protoss)\r\n self.charged_probes = charged_probes\r\n self.probe_size = probe_size\r\n self.buriedness_method = buriedness_method\r\n self.clear_tmp = clear_tmp\r\n self.cavities = None\r\n if cavities is True:\r\n self.cavities = Cavity.from_pdb_file(fname)\r\n self.nprocesses = nprocesses\r\n\r\n if settings is None:\r\n self.sampler_settings = self.Settings()\r\n else:\r\n self.sampler_settings = settings\r\n\r\n if self.sampler_settings.return_probes is True:\r\n print('here')\r\n self._calc_hotspots(return_probes=True)\r\n\r\n else:\r\n self._calc_hotspots()\r\n\r\n self.super_grids = {p: g[0] for p, g in self.out_grids.items()}\r\n\r\n if clear_tmp == True:\r\n shutil.rmtree(tmp)\r\n\r\n return Results(super_grids=self.super_grids,\r\n protein=self.protein,\r\n buriedness=self.buriedness,\r\n superstar={x.identifier: x.grid for x in self.superstar_grids},\r\n weighted_superstar={x.identifier: x.grid for x in self.weighted_grids})\r\n\r\n def global_dock(self, hr:Results, mol, settings = None):\r\n self.super_grids = hr.super_grids\r\n self.buriedness = hr.buriedness\r\n self.protein = hr.protein\r\n self.charged_probes = False\r\n self.probe_size = 7\r\n self.buriedness_method = 'ligsite'\r\n self.cavities = None\r\n self.clear_tmp = True\r\n\r\n if settings is None:\r\n self.sampler_settings = self.Settings()\r\n\r\n self.sampler_settings.return_probes = True\r\n self.sampler_settings.nrotations = 2000\r\n self.apolar_translation_threshold = 17\r\n self.polar_translation_threshold = 17\r\n\r\n print(hr.weighted_superstar)\r\n\r\n grid_dict = hr.weighted_superstar\r\n\r\n\r\n ps = self._dock_probe(mol, grid_dict)\r\n return ps\r\n\r\n", "meta": {"hexsha": "6ffa8776f2a50982f482e3cd1875da8bad226ba9", "size": 44179, "ext": "py", "lang": "Python", "max_stars_repo_path": "hotspots/calculation.py", "max_stars_repo_name": "prcurran/fragment_hotspot_maps", "max_stars_repo_head_hexsha": "a6dbd7f650d28a867594ca48597f7e1b3a131168", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2019-02-14T00:02:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T02:27:52.000Z", "max_issues_repo_path": "hotspots/calculation.py", "max_issues_repo_name": "prcurran/fragment_hotspot_maps", "max_issues_repo_head_hexsha": "a6dbd7f650d28a867594ca48597f7e1b3a131168", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2019-02-06T12:18:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-30T14:26:08.000Z", "max_forks_repo_path": "hotspots/calculation.py", "max_forks_repo_name": "prcurran/fragment_hotspot_maps", "max_forks_repo_head_hexsha": "a6dbd7f650d28a867594ca48597f7e1b3a131168", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2019-02-13T20:38:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T01:20:54.000Z", "avg_line_length": 38.4499564839, "max_line_length": 189, "alphanum_fraction": 0.5795061002, "include": true, "reason": "import numpy,from scipy", "num_tokens": 9507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.2658804789168741, "lm_q1q2_score": 0.1433051168446007}} {"text": "\"\"\"\nPhoton emission and absoprtion models.\n\"\"\"\nimport numpy as np\nimport h5py\n\nfrom soxs.spectra import ApecGenerator, \\\n get_wabs_absorb, get_tbabs_absorb\nfrom soxs.utils import parse_prng\nfrom pyxsim.utils import mylog\nfrom yt.funcs import get_pbar\nfrom yt.units.yt_array import YTArray, YTQuantity\nfrom yt.utilities.physical_constants import hcgs, clight\n\nhc = (hcgs*clight).in_units(\"keV*angstrom\").v\n# NOTE: XSPEC has hc = 12.39854 keV*A, so there may be slight differences in\n# placement of spectral lines due to the above\ncl = clight.v\n\n\nclass TableApecModel(ApecGenerator):\n r\"\"\"\n Initialize a thermal gas emission model from the AtomDB APEC tables\n available at http://www.atomdb.org. This code borrows heavily from Python\n routines used to read the APEC tables developed by Adam Foster at the\n CfA (afoster@cfa.harvard.edu).\n\n Parameters\n ----------\n emin : float\n The minimum energy for the spectral model.\n emax : float\n The maximum energy for the spectral model.\n nchan : integer\n The number of channels in the spectral model. If one\n is thermally broadening lines, it is recommended that \n this value result in an energy resolution per channel\n of roughly 1 eV.\n var_elem : list of strings, optional\n The names of elements to allow to vary freely\n from the single abundance parameter. Default:\n None\n model_root : string, optional\n The directory root where the model files are stored. If \n not provided, the default SOXS-provided files are used.\n model_vers : string, optional\n The version identifier string for the APEC files, e.g.\n \"3.0.3\". Default: 3.0.8\n thermal_broad : boolean, optional\n Whether or not the spectral lines should be thermally\n broadened. Default: True\n nolines : boolean, optional\n Turn off lines entirely for generating spectra.\n Default: False\n abund_table : string or array_like, optional\n The abundance table to be used for solar abundances. \n Either a string corresponding to a built-in table or an array\n of 30 floats corresponding to the abundances of each element\n relative to the abundance of H. Default is \"angr\".\n Built-in options are:\n \"angr\" : from Anders E. & Grevesse N. (1989, Geochimica et \n Cosmochimica Acta 53, 197)\n \"aspl\" : from Asplund M., Grevesse N., Sauval A.J. & Scott \n P. (2009, ARAA, 47, 481)\n \"wilm\" : from Wilms, Allen & McCray (2000, ApJ 542, 914 \n except for elements not listed which are given zero abundance)\n \"lodd\" : from Lodders, K (2003, ApJ 591, 1220)\n nei : boolean, optional\n If True, use the non-equilibrium ionization tables. These are\n not supplied with pyXSIM/SOXS but must be downloaded separately, in\n which case the *apec_root* parameter must also be set to their\n location. Default: False\n\n Examples\n --------\n >>> apec_model = TableApecModel(0.05, 50.0, 1000, apec_vers=\"3.0.3\",\n ... thermal_broad=False)\n \"\"\"\n def __init__(self, emin, emax, nchan, var_elem=None,\n model_root=None, model_vers=None, \n thermal_broad=True, nolines=False,\n abund_table=\"angr\", nei=False):\n super(TableApecModel, self).__init__(emin, emax, nchan, var_elem=var_elem,\n apec_root=model_root, apec_vers=model_vers, \n broadening=thermal_broad, nolines=nolines,\n abund_table=abund_table, nei=nei)\n self.nchan = self.nbins\n\n def prepare_spectrum(self, zobs):\n \"\"\"\n Prepare the thermal model for execution given a redshift *zobs* for the spectrum.\n \"\"\"\n cosmic_spec, metal_spec, var_spec = \\\n self._get_table(list(range(self.nT)), zobs, 0.0)\n self.cosmic_spec = YTArray(cosmic_spec, \"cm**3/s\")\n self.metal_spec = YTArray(metal_spec, \"cm**3/s\")\n if var_spec is None:\n self.var_spec = var_spec\n else:\n self.var_spec = YTArray(var_spec, \"cm**3/s\")\n\n def get_spectrum(self, kT):\n \"\"\"\n Get the thermal emission spectrum given a temperature *kT* in keV. \n \"\"\"\n tindex = np.searchsorted(self.Tvals, kT)-1\n var_spec = None\n if tindex >= self.Tvals.shape[0]-1 or tindex < 0:\n cosmic_spec = YTArray(np.zeros(self.nchan), \"cm**3/s\")\n metal_spec = cosmic_spec\n if self.var_spec is not None:\n var_spec = YTArray(np.zeros((self.num_var_elem, self.nchan)), \"cm**3/s\")\n else:\n dT = (kT-self.Tvals[tindex])/self.dTvals[tindex]\n cspec_l = self.cosmic_spec[tindex, :]\n mspec_l = self.metal_spec[tindex, :]\n cspec_r = self.cosmic_spec[tindex+1, :]\n mspec_r = self.metal_spec[tindex+1, :]\n cosmic_spec = cspec_l*(1.-dT)+cspec_r*dT\n metal_spec = mspec_l*(1.-dT)+mspec_r*dT\n if self.var_spec is not None:\n vspec_l = self.var_spec[:, tindex, :]\n vspec_r = self.var_spec[:, tindex+1, :]\n var_spec = vspec_l*(1.-dT) + vspec_r*dT\n return cosmic_spec, metal_spec, var_spec\n\n def return_spectrum(self, temperature, metallicity, redshift, norm,\n velocity=0.0, elem_abund=None):\n \"\"\"\n Given the properties of a thermal plasma, return a spectrum.\n\n Parameters\n ----------\n temperature : float\n The temperature of the plasma in keV.\n metallicity : float\n The metallicity of the plasma in solar units.\n redshift : float\n The redshift of the plasma.\n norm : float\n The normalization of the model, in the standard Xspec units of\n 1.0e-14*EM/(4*pi*(1+z)**2*D_A**2).\n velocity : float, optional\n Velocity broadening parameter in km/s. Default: 0.0\n elem_abund : dict of element name, float pairs\n A dictionary of elemental abundances to vary\n freely of the abund parameter. Default: None\n \"\"\"\n spec = super(TableApecModel, self).get_spectrum(temperature, metallicity, \n redshift, norm, velocity=velocity,\n elem_abund=elem_abund)\n return YTArray(spec.flux*spec.de, \"photons/s/cm**2\")\n\n\nthermal_models = {\"apec\": TableApecModel}\n\n\nclass AbsorptionModel(object):\n _name = \"\"\n def __init__(self, nH, energy, cross_section):\n self.nH = YTQuantity(nH*1.0e22, \"cm**-2\")\n self.emid = YTArray(energy, \"keV\")\n self.sigma = YTArray(cross_section, \"cm**2\")\n\n def get_absorb(self, e):\n \"\"\"\n Get the absorption spectrum.\n \"\"\"\n sigma = np.interp(e, self.emid, self.sigma, left=0.0, right=0.0)\n return np.exp(-sigma*self.nH)\n\n def absorb_photons(self, eobs, prng=None):\n r\"\"\"\n Determine which photons will be absorbed by foreground\n galactic absorption.\n\n Parameters\n ----------\n eobs : array_like\n The energies of the photons in keV.\n prng : integer, :class:`~numpy.random.RandomState` object or :mod:`~numpy.random`, optional\n A pseudo-random number generator. Typically will only be specified\n if you have a reason to generate the same set of random numbers, such as for a\n test. Default is the :mod:`numpy.random` module.\n \"\"\"\n prng = parse_prng(prng)\n n_events = eobs.size\n if n_events == 0:\n return np.array([], dtype='bool')\n detected = np.zeros(n_events, dtype='bool')\n nchunk = n_events // 100\n if nchunk == 0:\n nchunk = n_events\n k = 0\n pbar = get_pbar(\"Absorbing photons\", n_events)\n while k < n_events:\n absorb = self.get_absorb(eobs[k:k+nchunk])\n nabs = absorb.size\n randvec = prng.uniform(size=nabs)\n detected[k:k+nabs] = randvec < absorb\n k += nabs\n pbar.update(k)\n pbar.finish()\n return detected\n\nclass TBabsModel(AbsorptionModel):\n r\"\"\"\n Initialize a Tuebingen-Boulder (Wilms, J., Allen, A., & \n McCray, R. 2000, ApJ, 542, 914) ISM absorption model.\n\n Parameters\n ----------\n nH : float\n The foreground column density in units of 10^22 cm^{-2}.\n\n Examples\n --------\n >>> tbabs_model = TBabsModel(0.1)\n \"\"\"\n _name = \"tbabs\"\n def __init__(self, nH):\n self.nH = YTQuantity(nH, \"1.0e22*cm**-2\")\n\n def get_absorb(self, e):\n e = np.array(e)\n return get_tbabs_absorb(e, self.nH.v)\n\nclass WabsModel(AbsorptionModel):\n r\"\"\"\n Initialize a Wisconsin (Morrison and McCammon; ApJ 270, 119) \n absorption model.\n\n Parameters\n ----------\n nH : float\n The foreground column density in units of 10^22 cm^{-2}.\n\n Examples\n --------\n >>> wabs_model = WabsModel(0.1)\n \"\"\"\n _name = \"wabs\"\n def __init__(self, nH):\n self.nH = YTQuantity(nH, \"1.0e22*cm**-2\")\n\n def get_absorb(self, e):\n e = np.array(e)\n return get_wabs_absorb(e, self.nH.v)\n\nabsorb_models = {\"wabs\": WabsModel,\n \"tbabs\": TBabsModel}\n", "meta": {"hexsha": "54edbc99a557b620118e80dea2d4f6c59adb9f80", "size": 9453, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyxsim/spectral_models.py", "max_stars_repo_name": "MaggieLieu/pyxsim", "max_stars_repo_head_hexsha": "ba97dd68a3df82a61492ea747564a087fb574d04", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyxsim/spectral_models.py", "max_issues_repo_name": "MaggieLieu/pyxsim", "max_issues_repo_head_hexsha": "ba97dd68a3df82a61492ea747564a087fb574d04", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyxsim/spectral_models.py", "max_forks_repo_name": "MaggieLieu/pyxsim", "max_forks_repo_head_hexsha": "ba97dd68a3df82a61492ea747564a087fb574d04", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5119047619, "max_line_length": 99, "alphanum_fraction": 0.5970591347, "include": true, "reason": "import numpy", "num_tokens": 2430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.2658804672827598, "lm_q1q2_score": 0.14330511057400833}} {"text": "\"\"\"\nThis creates the plot that is used as Fig. 8 in Lyke et al. 2020. This spectrum\nfile and the catalog file is needed to make this plot. This will not work (and\nhas no error-trapping) for records that are missing any data from:\nUKIDSS, ROSAT, FIRST, GALEX, or WISE. The spectrum file must have a positive\nvalue for flux and ivar at every point. Spectra with bad pixels are NOT supported.\n\nAs UKIDSS and 2MASS overlap in wavelength coverage, only one should be used. 2MASS\ndata conversion is not supported here. This pretty much leaves UKIDSS only (for\nthis script).\n\nThere will be NO updates to this script to include 2MASS conversions.\n\nGaia data is not converted or plotted as the large time gap between SDSS optical and\nGaia optical observations cannot be plotted together in a meaningful way due to\nknown quasar flux variability.\n\nThe terms 'flux' and 'flux density' are used interchangeably throughout. Context\nis key.\n\nDependencies\n----------\nspec file : requires the SDSS full spectrum file in ../data/\ngithub repository : https://github.com/bradlyke/utilities\nNote: To get these plots, LaTeX must be installed and\n matplotlib must be able to compile LaTeX commands\n\n\nInput file\n----------\nThe most recent version of the DR16Q quasar-only catalog.\n\n\nParameters\n----------\ninput_file : the file name for the DR16Q FITS file in the\n ../data folder. No path needed.\npt,mt,ft : Plate, MJD, and FiberID for a record that has all multiwavelength data\n The values used to make the paper plot are hardcoded in __main__\n No guarantees are made about script viability or plot viability\n for any spectrum other than the hardcoded one.\noutput_plot_name : the name of the plot written out\nplot_fontsize : The fontsize for everything in the plot\n For a 10x4 plot spanning twocolumn, 11 works best.\nsave_check : 0 - don't save, just plot\n 1 - don't plot, just save into ../plots/\n\n\nOutput\n----------\nIf selected, an EPS file of the plot.\n\n\"\"\"\n\nfrom astropy.io import fits\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nmatplotlib.rc('text',usetex=True)\nimport progressBar_fancy as pbf\nimport cat_tools as ct\nfrom sciCon import mks\nimport sys\n\n#This function will smooth the SDSS spectrum using a boxcar window of a\n#given pixel size (smooth_pct).\n#This is a copy of the smoothing function from another of my repositories:\n# https://github.com/bradlyke/ica_5010/rolling_boxcar.ipynb\n#Copied over so users don't have to clone another repository for one function.\ndef boxcar(flux_arr,flux_var,smooth_pct,weighted=False):\n spc = smooth_pct\n num_dpoints = len(flux_arr) #how many data points\n box_flux = np.zeros(num_dpoints,dtype='f8') #This is the smoothed flux data\n box_err = np.zeros(num_dpoints,dtype='f8') #This is the smoother flux error\n\n #This does the box. 10 pixels wide, so choose 5 on each side of current pixel\n for i in range(num_dpoints):\n #Define range of values to smooth\n if i < int(spc/2):\n lower = 0\n else:\n lower = -int(spc/2) + i\n if ((int(spc/2) + i) > num_dpoints):\n upper = num_dpoints\n else:\n upper = int(spc/2) + i\n #Smooth the values depending on smoothing type\n #Weighted takes each pixels error into account and the pixel flux is inversely\n #proportional to the pixel uncertainty\n if weighted==True:\n noise_temp = np.sqrt(flux_var[lower:upper])\n signal_temp = flux_arr[lower:upper]\n flux_temp = np.average(signal_temp,weights=noise_temp)\n ivar_temp = (np.average((signal_temp-flux_temp)**2, weights=noise_temp))**(-1.0)\n #Unweighted version. Why would you want to use this?\n else:\n flux_temp = np.median(flux_arr[lower:upper])\n ivar_temp = flux_var[i]\n\n #Save the NEW smoothed flux value\n box_flux[i] = flux_temp\n box_err[i] = ivar_temp\n\n return box_flux,box_err\n\n\"\"\"\nTo make a Spectral Energy Distribution (SED), all of the different sources\nof data have to be on the same flux scale (y-axis). These following functions\nwill convert the different surveys' data in DR16Q to the standard SDSS flux\nunits of 10^(-17) erg/s/cm^2/Angstrom.\nuk_convert(): UKIDSS data\njy_convert(): Anything in Janskys.\nnano_convert(): Anything in nanomaggies (GALEX or WISE data)\nxray_convert(): Anything in flux, F (erg/s/cm^2), but NOT flux density, F_lambda (erg/s/cm^2/Ang)\n ROSAT and XMM both use F.\n\n\"\"\"\n#Remember that the ouput on all of these needs to be:\n# 10^(-17) erg/s/cm^2/Ang\ndef uk_convert(influx,inlam):\n #I will convert W/m^2/Hz from UKIDSS here\n flux_temp = influx*1000 #converts W/m^2/Hz to erg/s/cm^2/Hz\n flux_temp = flux_temp * (mks.c*10**(10)) * inlam**(-2.0) #converts /Hz to /Ang\n flux_temp = flux_temp * 1e17 #convert to SDSS version\n return flux_temp\n\ndef jy_convert(fjy,inlam):\n #I will convert Jy or mJy here\n flux_temp = fjy / 1000 #converts mJy to Jy\n flux_temp = flux_temp * 1e-26 #converts Jy to W/m^2/Hz\n flux_temp = uk_convert(flux_temp,inlam) #converts W/m^2/Hz to erg/s/cm^2/Ang\n #uk_convert() already reports in SDSS version\n return flux_temp\n\ndef nano_convert(influx,inlam):\n #I will convert nanomaggies from GALEX and WISE here\n #flux_source will be 'GALEX' or 'WISE' as they may be on separate systems\n flux_temp = influx * 3.631e-6 #converts to Jy\n flux_temp = flux_temp * 1e-26 #converts to W/m^2/Hz\n flux_temp = uk_convert(flux_temp,inlam) #converts W/m^2/Hz to erg/s/cm^2/Ang\n #uk_convert() already reports in SDSS version\n\n return flux_temp\n\ndef xray_convert(influx,inlam):\n #I will convert ROSAT/XMM here. They are in Flux, not flux density\n #ROSAT(2RXS) will have one data point. XMM will have 2 (soft/hard) or\n #3 (soft/hard/total). The inlam should be the center wavelength for the range\n #and must be input in Angstroms. Conversion from keV to Ang in sed_plotter()\n flux_temp = influx / inlam\n flux_temp = flux_temp * 1e17 #convert to SDSS scaling\n\n return flux_temp\n\n#def tmass_convert(influx,inlam):\n #Convert 2MASS magnitudes here. An online program does this, check there:\n # http://ssc.spitzer.caltech.edu/warmmission/propkit/pet/magtojy/\n #2MASS conversions are not supported for DR16Q. The spectrum in the paper\n #used UKIDSS data for the wavelenghts in question.\n\ndef sed_plotter(infile,pt,mt,ft,fname,fntsize,write_check):\n dr = fits.open(infile)[1].data #Load the catalog file\n matplotlib.rc('font',size=fntsize)\n matplotlib.rcParams['text.latex.preamble'] = [r'\\boldmath']\n\n drloc = ct.find_rec(dr,pt,mt,ft) #Find record for the specified quasar\n\n #Load the SDSS spectrum\n spec_iname = '../data/spec-{0}-{1}-{2:04d}.fits'.format(pt,mt,ft)\n spec_data = fits.open(spec_iname)[1].data\n spec_lam = 10**spec_data['loglam'] #wavelength stored as log10(lambda) in file.\n spec_err = spec_data['ivar'] #error stored as inverse variance per pixel\n wspec = np.where(spec_lam <= 10000)[0] #We don't want UKIDSS to overlap SDSS\n #Note that SDSS spectra above lambda=10,000 Ang are typically dominated by sky emission\n spec_flux = spec_data['flux']\n spec_fluxS, spec_errS = boxcar(spec_flux,spec_err,10,weighted=True) #10 pixel window size\n\n #Converting the GALEX data\n gal_data = np.zeros(2,dtype=[('LAM','float64'),('FLUX_RAW','float64'),('FLUX_CONV','float64'),\n ('FLUX_ERR_RAW','float64'),('FLUX_ERR_CONV','float64')])\n gal_data['LAM'][0] = 1550 #Angstroms, FUV bandpass = 1350 - 1750 Ang\n gal_data['LAM'][1] = 2275 #Angstroms, NUV bandpass = 1750 - 2800 Ang\n gal_data['FLUX_RAW'][0] = dr['FUV'][drloc]\n gal_data['FLUX_RAW'][1] = dr['NUV'][drloc]\n #Convert inverse variance to a 1-sigma uncertainty for error bars later\n gal_data['FLUX_ERR_RAW'][0] = 1/np.sqrt(dr['FUV_IVAR'][drloc])\n gal_data['FLUX_ERR_RAW'][1] = 1/np.sqrt(dr['NUV_IVAR'][drloc])\n #Convert GALEX flux and uncertainty to SDSS units\n gal_data['FLUX_CONV'] = nano_convert(gal_data['FLUX_RAW'],gal_data['LAM'])\n gal_data['FLUX_ERR_CONV'] = nano_convert(gal_data['FLUX_ERR_RAW'],gal_data['LAM'])\n\n #Converting the UKIDSS data\n ukid_data = np.zeros(4,dtype=[('LAM','float64'),('FLUX_RAW','float64'),('FLUX_CONV','float64'),\n ('FLUX_ERR_RAW','float64'),('FLUX_ERR_CONV','float64')])\n #Get passband centers in Angstroms (comments are in microns)\n ukid_data['LAM'][0] = 10200 #Y-band, Angstroms, 50% cuton/cutoff = 0.97/1.07 microns Y\n ukid_data['LAM'][1] = 12500 #J 1.17/1.33\n ukid_data['LAM'][2] = 16350 #H 1.49/1.78\n ukid_data['LAM'][3] = 22000 #K 2.03/2.37\n ukid_data['FLUX_RAW'][0] = dr['YFLUX'][drloc]\n ukid_data['FLUX_RAW'][1] = dr['JFLUX'][drloc]\n ukid_data['FLUX_RAW'][2] = dr['HFLUX'][drloc]\n ukid_data['FLUX_RAW'][3] = dr['KFLUX'][drloc]\n ukid_data['FLUX_ERR_RAW'][0] = dr['YFLUX_ERR'][drloc]\n ukid_data['FLUX_ERR_RAW'][1] = dr['JFLUX_ERR'][drloc]\n ukid_data['FLUX_ERR_RAW'][2] = dr['HFLUX_ERR'][drloc]\n ukid_data['FLUX_ERR_RAW'][3] = dr['KFLUX_ERR'][drloc]\n #Convert UKIDSS flux and error to SDSS units\n ukid_data['FLUX_CONV'] = uk_convert(ukid_data['FLUX_RAW'],ukid_data['LAM'])\n ukid_data['FLUX_ERR_CONV'] = uk_convert(ukid_data['FLUX_ERR_RAW'],ukid_data['LAM'])\n\n #Radio, X-ray, and WISE (infrared) data. Radio/X-ray does not appear on the plot\n #as these are so far out in wavelength space they are difficult to plot even on\n #a log scale. The flux ranges for these are also of significantly\n #lesser (radio)/greater (X-ray) magnitude to SDSS, that the y-axis also won't\n #work well. Converted here for instructional purposes, but not used in the plot.\n radxw_data = np.zeros(4,dtype=[('LAM','float64'),('FLUX_RAW','float64'),('FLUX_CONV','float64'),\n ('FLUX_ERR_RAW','float64'),('FLUX_ERR_CONV','float64')])\n #Convert ROSAT data (not used)\n radxw_data['LAM'][0] = ((mks.h * mks.c)/(1250*mks.eV))*(10**10) #Angstroms, ROSAT is 0.5 - 2.0 keV\n radxw_data['FLUX_RAW'][0] = dr['2RXS_SRC_FLUX'][drloc]\n radxw_data['FLUX_CONV'][0] = xray_convert(radxw_data['FLUX_RAW'][0],radxw_data['LAM'][0])\n radxw_data['FLUX_ERR_RAW'][0] = dr['2RXS_SRC_FLUX_ERR'][drloc]\n radxw_data['FLUX_ERR_CONV'][0] = xray_convert(radxw_data['FLUX_ERR_RAW'][0],radxw_data['LAM'][0])\n #Convert WISE infrared data (USED in plot)\n radxw_data['LAM'][1] = 34000 #Angstroms, W1 band center\n radxw_data['LAM'][2] = 46000 #Angstroms, W2 band center\n radxw_data['FLUX_RAW'][1] = dr['W1_FLUX'][drloc]\n radxw_data['FLUX_RAW'][2] = dr['W2_FLUX'][drloc]\n radxw_data['FLUX_CONV'][1:3] = nano_convert(radxw_data['FLUX_RAW'][1:3],radxw_data['LAM'][1:3])\n radxw_data['FLUX_ERR_RAW'][1] = 1/np.sqrt(dr['W1_FLUX_IVAR'][drloc])\n radxw_data['FLUX_ERR_RAW'][2] = 1/np.sqrt(dr['W2_FLUX_IVAR'][drloc])\n radxw_data['FLUX_ERR_CONV'][1:3] = nano_convert(radxw_data['FLUX_ERR_RAW'][1:3],radxw_data['LAM'][1:3])\n #Convert FIRST radio data (not used)\n radxw_data['LAM'][3] = 20e8 #Angstroms, 20cm for FIRST\n radxw_data['FLUX_RAW'][3] = dr['FIRST_FLUX'][drloc]\n radxw_data['FLUX_CONV'][3] = jy_convert(radxw_data['FLUX_RAW'][3],radxw_data['LAM'][3])\n radxw_data['FLUX_ERR_RAW'][3] = (dr['FIRST_FLUX'][drloc]-0.25)/dr['FIRST_SNR'][drloc]\n radxw_data['FLUX_ERR_CONV'][3] = jy_convert(radxw_data['FLUX_ERR_RAW'][3],radxw_data['LAM'][3])\n\n #Print the converted flux values for each band pass. Using the default spectrum\n #in the paper, this will show why FIRST and ROSAT were not plotted.\n print('\\n')\n print('LAMBDA: FUV | FLUX: {:.3e} | ERR: {:.3e}'.format(gal_data['FLUX_CONV'][0],gal_data['FLUX_ERR_CONV'][0]))\n print('LAMBDA: NUV | FLUX: {:.3e} | ERR: {:.3e}'.format(gal_data['FLUX_CONV'][1],gal_data['FLUX_ERR_CONV'][1]))\n\n print('LAMBDA: Y | FLUX: {:.3e}'.format(ukid_data['FLUX_CONV'][0]))\n print('LAMBDA: J | FLUX: {:.3e}'.format(ukid_data['FLUX_CONV'][1]))\n print('LAMBDA: H | FLUX: {:.3e}'.format(ukid_data['FLUX_CONV'][2]))\n print('LAMBDA: K | FLUX: {:.3e}'.format(ukid_data['FLUX_CONV'][3]))\n\n print('LAMBDA: ROSAT | FLUX: {:.3e}'.format(radxw_data['FLUX_CONV'][0]))\n print('LAMBDA: W1 | FLUX: {:.3e}'.format(radxw_data['FLUX_CONV'][1]))\n print('LAMBDA: W2 | FLUX: {:.3e}'.format(radxw_data['FLUX_CONV'][2]))\n print('LAMBDA: FIRST | FLUX: {:.3e}'.format(radxw_data['FLUX_CONV'][3]))\n\n print('\\nFIRST RAW: {:.3e}'.format(radxw_data['FLUX_RAW'][3]))\n\n #The bottom x-axis will be in the observed frame, the top will have the\n #wavelengths in the rest frame. These need different tick labels.\n xtick_obsLabs = np.array([1400,2000,4000,10000,20000,40000])\n xtick_restLabs = np.array([1000,2000,4000,10000,20000])\n\n #The SDSS name of the quasar and redshift to include in a text box.\n name_str = r'\\textbf{SDSS J002912.35+022549.5, z = 0.576}'\n\n #Now we plot. Error bars for multiwave data may not display as they are\n #very small compared to the flux values (1 to 2 orders of magnitude smaller)\n fig,ax = plt.subplots(figsize=(10,4))\n axT = ax.twiny() #This makes a set of tick labels along the top (twin ALONG y-axis)\n #ax.errorbar(radxw_data['LAM'][0],radxw_data['FLUX_CONV'][0],yerr=radxw_data['FLUX_ERR_CONV'][0],label='ROSAT') #ROSAT DATA\n ax.errorbar(gal_data['LAM'],gal_data['FLUX_CONV'],yerr=gal_data['FLUX_ERR_CONV'],color='blue',alpha=0.7,fmt='d',label=r'\\textbf{GALEX}') #GALEX DATA with ERROR\n ax.plot(spec_lam[wspec],spec_flux[wspec],linewidth=0.8,color='0.70',alpha=1.0,label=r'\\textbf{SDSS Raw}') #SDSS DATA\n ax.plot(spec_lam[wspec],spec_fluxS[wspec],linewidth=0.6,color='black',alpha=1.0,label=r'\\textbf{SDSS Smoothed}') #SDSS DATA\n ax.errorbar(ukid_data['LAM'],ukid_data['FLUX_CONV'],yerr=ukid_data['FLUX_ERR_CONV'],color='darkorange',alpha=1.0,fmt='^',label=r'\\textbf{UKIDSS}') #UKIDSS DATA with ERROR\n ax.errorbar(radxw_data['LAM'][1:3],radxw_data['FLUX_CONV'][1:3],yerr=radxw_data['FLUX_ERR_CONV'][1:3],color='red',fmt='o',label=r'\\textbf{WISE}') #WISE DATA with ERROR\n #ax.errorbar(radxw_data['LAM'][3],radxw_data['FLUX_CONV'][3],yerr=radxw_data['FLUX_ERR_CONV'][3],label='FIRST') #FIRST DATA\n\n ax.set_xscale('log') #Lower x-axis scale\n #Convert observed wavelengths to rest by lam_obs / (1+z)\n top_lim = np.array(ax.get_xlim())/1.576\n print('Rest Limits: ',top_lim) #Print these for verification by user\n #Top x-axis labels and scale\n axT.set_xlim(top_lim)\n axT.set_xscale('log')\n #Everything done to the bottom x-axis ticks needs to be done to the top (axT)\n ax.set_xticks(xtick_obsLabs)\n ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())\n axT.set_xticks(xtick_restLabs)\n axT.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())\n ax.set_xlabel(r'\\textbf{Observed Frame Wavelength (\\AA)}')\n axT.set_xlabel(r'\\textbf{Rest Frame Wavelength (\\AA)}')\n ax.set_ylabel(r'$f_{\\lambda}$ ($10^{-17}$ \\textbf{erg s}$^{-1}$\\, \\textbf{cm}$^{-2}$\\, \\textbf{\\AA}$^{-1}$)')\n\n ##Bottom X-axis and Left/Right Y-axis minor ticks\n ax.tick_params(axis='both',direction='in')\n ax.tick_params(axis='both',which='minor',direction='in')\n\n #Right-side ticks\n ax.tick_params(right=True)\n ax.tick_params(which='minor',right=True)\n\n #Top minor ticks\n axT.tick_params(direction='in')\n axT.tick_params(which='minor',direction='in')\n ax.yaxis.set_minor_locator(ticker.MultipleLocator(10)) #Y-axis minor ticks locations\n ax.legend(loc='upper right',facecolor='white',edgecolor='white')\n\n #This calls the name_str from earlier. Puts it in the bottom left\n ax.text(0.01,0.1,name_str,transform=ax.transAxes, verticalalignment='top',bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0))\n\n #Write out the plot, or just view it\n if write_check == 1:\n fig.savefig(fname,bbox_inches='tight',pad_inches=0.03,format='eps')\n plt.close()\n else:\n plt.tight_layout()\n plt.show()\n\n#Call from the command line with:\n# python sed_plot.py \n# Example:\n# python sed_plot.py DR16Q_v3.fits sed.eps 11 1\nif __name__=='__main__':\n input_file = '../data/{}'.format(sys.argv[1])\n output_plot_name = '../plots/{}'.format(sys.argv[2])\n plot_fontsize = int(sys.argv[3])\n save_check = int(sys.argv[4])\n pt,mt,ft = 7855,57011,530\n sed_plotter(input_file,pt,mt,ft,output_plot_name,plot_fontsize,save_check)\n", "meta": {"hexsha": "4b650bb3b1cb9e67a42cc2a17f668c11257cb5c1", "size": 16655, "ext": "py", "lang": "Python", "max_stars_repo_path": "plot_progs/sed_plot.py", "max_stars_repo_name": "bradlyke/dr16q", "max_stars_repo_head_hexsha": "5645491bc05806c5b956e76c5bcec939722c065f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-21T23:12:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-23T03:54:06.000Z", "max_issues_repo_path": "plot_progs/sed_plot.py", "max_issues_repo_name": "bradlyke/dr16q", "max_issues_repo_head_hexsha": "5645491bc05806c5b956e76c5bcec939722c065f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plot_progs/sed_plot.py", "max_forks_repo_name": "bradlyke/dr16q", "max_forks_repo_head_hexsha": "5645491bc05806c5b956e76c5bcec939722c065f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.1656626506, "max_line_length": 174, "alphanum_fraction": 0.6859801861, "include": true, "reason": "import numpy,from astropy", "num_tokens": 5188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.25091278688527247, "lm_q1q2_score": 0.14298331688028784}} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 2 11:08:09 2020\n\n@author: alvarezguido\nGITHUB: https://github.com/alvarezguido\n\"\"\"\n\n\"\"\"\nSYNOPSIS\n----\n----\n-----\n\n\"\"\"\n\nimport simpy\nimport random\nimport numpy as np\nimport math\n#import sys\n#import re\n#import matplotlib.pyplot as plt\n#import os\n#import operator\n#from mpl_toolkits import mplot3d\n#from mpl_toolkits.mplot3d import Axes3D\n#import PIL\nimport random\nimport re\nimport os\nimport datetime\nimport sys\n\nname = \"ER\"\nmode_debbug = 0\n\nif not mode_debbug:\n null = open(os.devnull, 'w')\n old_stdout = sys.stdout\n sys.stdout = null\n####WE START BY USING SF=12 ADN BW=125 AND CR=1, FOR ALL NODES AND ALL TRANSMISIONS######\n\nif mode_debbug:\n RANDOM_SEED = 5\n chan = 1\n packetlen = 20\n total_data = 60\n beacon_time = 120\n maxBSReceives = 500\n multi_nodes = [1500]\nelse:\n RANDOM_SEED = int(sys.argv[1])\n chan = int(sys.argv[2])\n packetlen = int(sys.argv[3]) ##NODES SEND PACKETS OF JUST 20 Bytes\n total_data = int(sys.argv[4]) ##TOTAL DATA ON BUFFER, FOR EACH NODE (IT'S THE BUFFER O DATA BEFORE START SENDING)\n beacon_time = int(sys.argv[5]) ###SAT SENDS BEACON EVERY CERTAIN TIME\n maxBSReceives = int(sys.argv[6]) ##MAX NUMBER OF PACKETS THAT BS (ie SATELLITE) CAN RECEIVE AT SAME TIME\n \n #multi_nodes = [int(sys.argv[7]), int(sys.argv[8]) ,int(sys.argv[9])]\n multi_nodes = [int(sys.argv[7]), int(sys.argv[8]) ,int(sys.argv[9]), int(sys.argv[10]),int(sys.argv[11]),int(sys.argv[12]),int(sys.argv[13]),int(sys.argv[14]),int(sys.argv[15]),int(sys.argv[16]),int(sys.argv[17]),int(sys.argv[18]),int(sys.argv[19]),int(sys.argv[20])]\nrandom.seed(RANDOM_SEED) #RANDOM SEED IS FOR GENERATE ALWAYS THE SAME RANDOM NUMBERS (ie SAME RESULTS OF SIMULATION)\nnodesToSend = []\npacketsToSend = math.ceil(total_data/packetlen)\n###GLOBAL PARAMS ####\nbsId = 1 ##ID OF BASE STATION (NOT USED)\n\navgSendTime = 3 ## NOT USED! --> A NODE SENDS A PACKET EVERY X SECS\n\nback_off = beacon_time * 0.95 ###BACK OFF TIME FOR SEND A PACKET\npacketsAtBS = [] ##USED FOR CHEK IF THERE ARE ALREADY PACKETS ON THE SATELLITE\nc = 299792.458 ###SPEED LIGHT [km/s]\nPtx = 14\nG_device = 0; ##ANTENNA GAIN FOR AN END-DEVICE\nG_sat = 12; ##ANTENNA GAIN FOR SATELLITE\nnodes = [] ###EACH NODE WILL BE APPENDED TO THIS VARIABLE\nfreq =868e6 ##USED FOR PATH LOSS CALCULATION\nfrequency = [868100000, 868300000, 868500000] ##FROM LORAWAN REGIONAL PARAMETERS EU863-870 / EU868\n\n\nnrLost = 0 ### TOTAL OF LOST PACKETS DUE Lpl\nnrCollisions = 0 ##TOTAL OF COLLIDED PACKETS\nnrProcessed = 0 ##TOTAL OF PROCESSED PACKETS\nnrReceived = 0 ###TOTAL OF RECEIVED PACKETS\nnrNoProcessed = 0 ##TOTAL OF INTRA-PACKETS NO PROCESSED\nnrIntraTot = 0\nnrLostMaxRec = 0\nnrCollFullPacket = 0\nnrSentIntra = 0 ##TOTAL OF SENT INTRA-PACKTES\nnrReceivedIntra = 0 ##TOTAL OF RECEIVED INTRA-PACKETS\n\n\n##ARRAY WITH MEASURED VALUES FOR SENSIBILITY, NEW VALUES\n##THE FOLLOWING VALUES CORRESPOND TO:\n# - FIRST ELEMENT: IT'S THE SF (NOT USABLE)\n# - SECOND ELEMENT: SENSIBILITY FOR 125KHZ BW\n# - THIRD ELEMENT: SENSIBILITY FOR 250KHZ BW\n# - FOURTH ELEMENT: SENSIBILITY FOR 500KHZ BW\n# NOTICE THAT SENSIBILITY DECREASE ALONG BW INCREASES, ALSO WITH LOWER SF\n# THIS VALUES RESPONDS TO:\n# wf = -174 + 10 log(BW) +NF +SNRf\nsf7 = np.array([7,-123,-120,-117.0])\nsf8 = np.array([8,-126,-123,-120.0])\nsf9 = np.array([9,-129,-126,-123.0])\nsf10 = np.array([10,-132,-129,-126.0])\nsf11 = np.array([11,-134.53,-131.52,-128.51])\nsf12 = np.array([12,-137,-134,-131.0])\n\nsensi = np.array([sf7,sf8,sf9,sf10,sf11,sf12])\n\n#DR = [\"dr8\",\"dr9\",\"dr10\",\"dr11\"]\nDR = [-137,-134.5,-134,-131.5]\n\n## READ PARAMS FROM DIRECTORY ##\npath = \"./wider_scenario_2/\"\n\n### -137dB IS THE MINIMUN TOLERABLE SENSIBILITY, FOR SF=12 AND BW=125KHz ###\n\nleo_pos=np.loadtxt( path + \"LEO-XYZ-Pos.csv\",skiprows=1,delimiter=',',usecols=(1,2,3))\n## WHERE:\n ## leo_pos[i,j]:\n ## i --> the step time in sat pass\n ## j --> 0 for x-position, 1 for y-position, 2 for z-position\n\nsites_pos = np.loadtxt( path + \"SITES-XYZ-Pos.csv\",skiprows=1,delimiter=',',usecols=(1,2,3))\n## WHERE:\n ## sites_pos[i,j]:\n ## i --> the node i\n ## j --> 0 for x-position, 1 for y-position, 2 for z-position\n\n\ndist_sat = np.zeros((sites_pos.shape[0],3,leo_pos.shape[0]))\nt = 0\nfor i in range(leo_pos.shape[0]):\n t+=1\n dist_sat [:,:,i] = leo_pos[i,:] - sites_pos\n## WHERE:\n ## dist_sat[i,j,k]:\n ## i --> the node i\n ## j --> 0 for x-position, 1 for y-position, 2 for z-position\n ## k --> the step time in sat pass\n \n#### FOR COMPUTE DISTANCE MAGNITUDE (ABS) FROM END-DEVICE TO SAT PASSING BY ####\ndistance = np.zeros((sites_pos.shape[0],leo_pos.shape[0]))\ndistance[:,:] = (dist_sat[:,0,:]**2 + dist_sat[:,1,:]**2 + dist_sat[:,2,:]**2)**(1/2)\n## WHERE:\n ## distance[i,j]:\n ## i --> the node i\n ## j --> the step time in sat pass\n\n\n##MATRIX FOR LINK BUDGET Lpl ###\nLpl = np.zeros((sites_pos.shape[0],leo_pos.shape[0])) \nLpl = 20*np.log10(distance*1000) + 20*np.log10(freq) - 147.55 #DISTANCE MUST BE IN METERS\n## WHERE:\n ## Lpl[i,j]:\n ## i --> the node i\n ## j --> the step time in sat pass \n\n##MATRIX FOR LINK BUDGET, USING Prx ###\nPrx = np.zeros((sites_pos.shape[0],leo_pos.shape[0])) \nPrx = Ptx + G_sat + G_device -20*np.log10(distance*1000) - 20*np.log10(freq) + 147.55 #DISTANCE IS CONVERTED TO METERS\n## WHERE:\n ## Prx[i,j]:\n ## i --> the node i\n ## j --> the step time in sat pass \n\ndistance = np.concatenate((distance,distance,distance,distance,distance,distance,distance,distance,distance,distance,\\\n distance,distance,distance,distance,distance,distance,distance,distance,distance,distance,\\\n distance,distance,distance,distance,distance,distance,distance,distance,distance,distance,\\\n distance,distance,distance,distance,distance,distance,distance,distance,distance,distance,\\\n distance,distance,distance,distance,distance,distance,distance,distance,distance,distance,\\\n distance,distance,distance,distance,distance,distance,distance,distance,distance,distance,\\\n distance,distance,distance,distance,distance,distance,distance,distance,distance,distance,\\\n distance,distance,distance,distance,distance,distance,distance,distance,distance,distance,\\\n distance,distance,distance,distance,distance,distance,distance,distance,distance,distance,\\\n distance,distance,distance,distance,distance,distance,distance,distance,distance,distance,\\\n distance,distance,distance,distance,distance,distance,distance,distance,distance,distance,\\\n distance,distance,distance,distance,distance,distance,distance,distance,distance,distance,\\\n distance,distance,distance,distance,distance,distance,distance,distance,distance,distance,\\\n distance,distance,distance,distance,distance,distance,distance,distance,distance,distance,\\\n distance,distance,distance,distance,distance,distance,distance,distance,distance,distance))\n\nLpl = np.concatenate((Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,\\\n Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,\\\n Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,\\\n Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,\\\n Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,\\\n Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,\\\n Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,\\\n Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,\\\n Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,\\\n Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,\\\n Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,\\\n Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,\\\n Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,\\\n Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,\\\n Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl,Lpl))\n\nPrx = np.concatenate((Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,\\\n Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,\\\n Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,\\\n Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,\\\n Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,\\\n Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,\\\n Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,\\\n Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,\\\n Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,\\\n Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,\\\n Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,\\\n Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,\\\n Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,\\\n Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,\\\n Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx,Prx))\n\nelev = np.degrees(np.arcsin(599/distance))\n\n# =============================================================================\n# IS7 = np.array([1,-8,-9,-9,-9,-9])\n# IS8 = np.array([-11,1,-11,-12,-13,-13])\n# IS9 = np.array([-15,-13,1,-13,-14,-15])\n# IS10 = np.array([-19,-18,-17,1,-17,-18])\n# IS11 = np.array([-22,-22,-21,-20,1,-20])\n# IS12 = np.array([-25,-25,-25,-24,-23,1])\n# IsoThresholds = np.array([IS7,IS8,IS9,IS10,IS11,IS12])\n# \n# =============================================================================\nISDR8 = np.array([1,-23,-24,-25])\nISDR9 = np.array([-20,1,-20,-21])\nISDR10 = np.array([-18,-17,1,-17])\nISDR11 = np.array([-15,-14,-13,1])\n\nIsoThresholds = np.array([ISDR8,ISDR9,ISDR10,ISDR11])\n\n#THIS IS THE MATRIX OF CROSS INTERFERENCE BETWEEN SF\n\nCollmap = [[0 for i in range(0,6)] for j in range(0,6)]\n\ndef simulate_scenario (nrNodes):\n env = simpy.Environment()\n \n def powerCollision_2(p1, p2):\n #powerThreshold = 6\n global Collmap\n #print (\"SF: node {} has {} ; node {} has {}\".format(p1.nodeid,p1.sf, p2.nodeid, p2.sf))\n #print (\"pwr: node {} with rssi {} dBm and node {} with rssi {} dBm; diff {:3.2f} dBm\".format(p1,p1.rssi[math.ceil(env.now)], p2.nodeid,p2.rssi[math.ceil(env.now)], p1.rssi[math.ceil(env.now)] - p2.rssi[math.ceil(env.now)]))\n if True: #p1.sf == p2.sf:\n if abs(p1.rssi[math.ceil(env.now)] - p2.rssi[math.ceil(env.now)]) < IsoThresholds[p1.dr-8][p2.dr-8]:\n print (\"collision pwr both node {} and node {}\".format(p1.nodeid, p2.nodeid))\n #Collmap[p1.sf-7][p2.sf-7] += 1\n #Collmap[p2.sf-7][p1.sf-7] += 1\n # packets are too close to each other, both collide\n # return both packets as casualties\n return (p1, p2)\n elif p1.rssi[math.ceil(env.now)] - p2.rssi[math.ceil(env.now)] < IsoThresholds[p1.dr-8][p2.dr-8]:\n # p2 overpowered p1, return p1 as casualty\n print (\"collision pwr node {} overpowered node {}\".format(p2.nodeid, p1.nodeid))\n print (\"capture - p2 wins, p1 lost\")\n #Collmap[p1.sf-7][p2.sf-7] += 1\n return (p1,)\n print (\"capture - p1 wins, p2 lost\")\n # p2 was the weaker packet, return it as a casualty\n #Collmap[p2.sf-7][p1.sf-7] += 1\n return (p2,)\n \n def checkcollision(packet):\n col = 0 # flag needed since there might be several collisions for packet\n processing = 0\n #print (\"MAX RECEIVE IS: \", maxBSReceives)\n for i in range(0,len(packetsAtBS)):\n if packetsAtBS[i].header.processed == 1 or packetsAtBS[i].intraPacket.processed == 1:\n processing = processing + 1\n if (processing > maxBSReceives):\n packet.processed = 0\n else:\n packet.processed = 1\n if packetsAtBS:\n #print (\"{:3.5f} || >> FOUND overlap... node {} (sf:{} bw:{} freq:{}) others: {}\".format(env.now,packet.nodeid, packet.sf, packet.bw,packet.freq,len(packetsAtBS)))\n for other in packetsAtBS:\n if other.nodeid != packet.nodeid:\n #print (\"{:3.5f} || >> node {} overlapped with node {} (sf:{} bw:{} freq:{}). Let's check Freq...\".format(env.now,packet.nodeid, other.nodeid, other.packet.sf, other.packet.bw,other.packet.freq))\n # simple collision\n #if frequencyCollision(packet, other.packet) and sfCollision(packet, other.packet):\n if frequencyCollision(packet, other.header):# and timingCollision(packet, other.packet):\n c = powerCollision_2(packet, other.header)\n for p in c:\n p.col = 1\n if p == packet:\n col = 1\n if frequencyCollision(packet, other.intraPacket):# and timingCollision(packet, other.packet):\n c = powerCollision_2(packet, other.intraPacket)\n for p in c:\n p.col = 1\n if p == packet:\n col = 1\n return col\n return 0\n \n \n def frequencyCollision(p1,p2):\n if (p1.ch == p2.ch):\n #print (\"{:3.5f} || >> same channel for header on node {} and node {}.. Let's check sub-channels...\".format(env.now,p1.nodeid,p2.nodeid))\n #if (p1.freqHopHeader[replica] == p2.freqHopHeader[replica]):\n if (p1.subCh == p2.subCh):\n #print (\"{:3.5f} || >> same sub-channel for header on node {} and node {}\".format(env.now,p1.nodeid,p2.nodeid))\n #print (\"{:3.5f} || >> Header {} from node {} collided!!!\".format(env.now,replica,p1.nodeid))\n return True\n else:\n #print (\"{:3.5f} || >> No sub-channel collision\".format(env.now))\n return False\n else:\n #print (\"{:3.5f} || >> No header channel collision..\".format(env.now))\n return False\n \n \n class myNode():\n def __init__(self, nodeid, bs, avgSendTime, packetlen, total_data):\n global channel\n global DR\n self.dr = 8\n #carriers = list(range(280))\n #random.shuffle(carriers) #TO CHOOSE THE HOPPING JUMPS\n self.nodeid = nodeid\n self.avgSendTime = avgSendTime\n self.bs = bs\n self.dist = distance[nodeid,:]\n self.elev = elev[nodeid,:]\n self.mindist = np.amin(distance[nodeid,:])\n self.mindist_pos = int(np.where(distance[nodeid,:] == np.amin(distance[nodeid,:]))[0])\n #print('node %d' %nodeid, \"dist: \", self.dist[0])\n self.buffer = total_data\n self.packetlen = packetlen\n self.ch = int(random.choice(channel)) \n self.packet = myPacket(self.nodeid, packetlen, self.dist)\n #self.freqHop = carriers[0:35]\n self.sent = 0 #INITIAL SENT PACKETS\n self.totalLost = 0 #INITIAL TOTAL LOST FOR PARTICULAR NODE\n self.totalColl = 0\n self.totalRec = 0\n self.totalProc = 0\n if self.dr == 8:\n carriers = list(range(280))\n random.shuffle(carriers) #TO CHOOSE THE HOPPING JUMPS\n self.freqHop = carriers[0:35]\n elif self.dr == 9:\n carriers = list(range(280))\n random.shuffle(carriers) #TO CHOOSE THE HOPPING JUMPS\n self.freqHop = carriers[0:35]\n elif self.dr == 10:\n carriers = list(range(688))\n random.shuffle(carriers) #TO CHOOSE THE HOPPING JUMPS\n self.freqHop = carriers[0:86]\n elif self.dr == 11:\n carriers = list(range(688))\n random.shuffle(carriers) #TO CHOOSE THE HOPPING JUMPS\n self.freqHop = carriers[0:86]\n \n self.header = myHeader(self.nodeid,self.dist,self.ch,self.freqHop, self.dr)\n self.intraPacket = myIntraPacket(self.nodeid,self.dist,self.ch,self.freqHop,self.dr)\n \n \n class myHeader ():\n def __init__(self,nodeid,dist,ch,freqHop,dr):\n global Ptx\n global Prx\n global Lpl\n global c\n global distance\n global channel\n global frequency\n self.nodeid = nodeid\n self.txpow = Ptx\n self.transRange = 150\n self.arriveTime = 0\n self.rssi = Prx[nodeid,:]\n self.rectime = 0.233\n #self.rectime = 1.5\n self.proptime = distance[nodeid,:]*(1/c)\n self.collided = 0\n self.noCollided = 0\n self.processed = 0\n self.noProcessed = 0\n self.ch = ch\n self.lost = bool\n self.Nlost = 0\n self.subCh = 0\n self.sentIntra = 0\n self.dr = dr\n self.col =0\n if dr == \"dr8\":\n self.freqHopHeader = freqHop[0:3]\n elif dr == \"dr9\":\n self.freqHopHeader = freqHop[0:2]\n elif dr == \"dr10\":\n self.freqHopHeader = freqHop[0:3]\n elif dr == \"dr11\":\n self.freqHopHeader = freqHop[0:2]\n \n \n class myIntraPacket ():\n def __init__(self,nodeid,dist,ch,freqHop,dr):\n global Ptx\n global Prx\n global Lpl\n global c\n global distance\n global channel\n global frequency\n self.nodeid = nodeid\n self.txpow = Ptx\n self.transRange = 150\n self.arriveTime = 0\n self.rssi = Prx[nodeid,:]\n self.freqHopIntraPacket = freqHop[3:]\n self.rectime = 50e-3\n #self.rectime = 3\n self.proptime = distance[nodeid,:]*(1/c)\n self.collided = 0\n self.noCollided = 0\n self.nrColl = 0\n self.processed = 0\n self.noProcessed = 0\n self.ch = ch\n self.lost = bool\n self.Nlost = 0\n self.subCh = 0\n self.sentIntra = 0\n self.dr = dr\n self.col =0\n if dr == \"dr8\":\n self.freqHopIntraPacket = freqHop[3:]\n elif dr == \"dr9\":\n self.freqHopIntraPacket = freqHop[2:]\n elif dr == \"dr10\":\n self.freqHopIntraPacket = freqHop[3:]\n elif dr == \"dr11\":\n self.freqHopIntraPacket = freqHop[2:]\n \n class myPacket():\n def __init__(self, nodeid, packetlen, dist):\n #global experiment\n global Ptx\n global Prx\n #global gamma\n #global d0\n #global var\n global Lpl\n #global freq\n #global GL\n global c\n global distance\n global channel\n global frequency\n #SF = [7,8,9,10,11,12]\n self.nodeid = nodeid\n self.txpow = Ptx\n #self.sf = random.choice(SF)\n self.sf = 12\n self.cr = 1 ##CODING RATE\n self.bw = 125\n # transmission range, needs update XXX\n self.transRange = 150\n self.pl = packetlen\n self.symTime = (2.0**self.sf)/self.bw\n self.arriveTime = 0\n self.rssi = Prx[nodeid,:]\n self.freq = int(random.choice(frequency)) \n self.rectime = airtime(self.sf,self.cr,self.pl,self.bw) ##RECTIME IS THE RECEPTION TIME (ie AIRTIME)\n self.proptime = distance[nodeid,:]*(1/c)\n #print (\"rectime node \", self.nodeid, \" \", self.rectime)\n #print (\"Airtime for node {} is {} [seconds]\".format(self.nodeid,self.rectime)) #from https://www.loratools.nl/#/airtime\n # denote if packet is collided\n self.collided = 0\n self.processed = 0\n self.lost = bool\n \n \n def airtime(sf,cr,pl,bw):\n H = 0 # implicit header disabled (H=0) or not (H=1)\n DE = 0 # low data rate optimization enabled (=1) or not (=0)\n Npream = 8 # number of preamble symbol (12.25 from Utz paper)\n \n if bw == 125 and sf in [11, 12]:\n # low data rate optimization mandated for BW125 with SF11 and SF12\n DE = 1\n if sf == 6:\n # can only have implicit header with SF6\n H = 1\n \n Tsym = (2.0**sf)/bw\n Tpream = (Npream + 4.25)*Tsym\n #print (\"PARAMS FOR TRANSMISION: sf\", sf, \" cr\", cr, \"pl\", pl, \"bw\", bw)\n payloadSymbNB = 8 + max(math.ceil((8.0*pl-4.0*sf+28+16-20*H)/(4.0*(sf-2*DE)))*(cr+4),0)\n Tpayload = payloadSymbNB * Tsym\n return ((Tpream + Tpayload)/1000) ##IN SECS\n \n def selectDR (env,node):\n global DR\n dr = [8,9,10,11]\n node.dr = random.choice(dr)\n node.header.dr = node.dr\n node.intraPacket.dr = node.dr\n if node.dr == 11:\n node.sensi = DR[3]\n carriers = list(range(688))\n random.shuffle(carriers) #TO CHOOSE THE HOPPING JUMPS\n node.freqHop = carriers[0:86]\n node.header.freqHopHeader = node.freqHop[0:2]\n node.intraPacket.freqHopIntraPacket = node.freqHop [2:]\n elif node.dr == 10:\n node.sensi = DR[2]\n carriers = list(range(688))\n random.shuffle(carriers) #TO CHOOSE THE HOPPING JUMPS\n node.freqHop = carriers[0:86]\n node.header.freqHopHeader = node.freqHop[0:3]\n node.intraPacket.freqHopIntraPacket = node.freqHop [3:]\n elif node.dr == 9:\n node.sensi = DR[1]\n carriers = list(range(280))\n random.shuffle(carriers) #TO CHOOSE THE HOPPING JUMPS\n node.freqHop = carriers[0:35]\n node.header.freqHopHeader = node.freqHop[0:2]\n node.intraPacket.freqHopIntraPacket = node.freqHop [2:]\n else:\n node.sensi = DR[0]\n carriers = list(range(280))\n random.shuffle(carriers) #TO CHOOSE THE HOPPING JUMPS\n node.freqHop = carriers[0:35]\n node.header.freqHopHeader = node.freqHop[0:3]\n node.intraPacket.freqHopIntraPacket = node.freqHop [3:]\n \n \n def transmit(env,node):\n #while nodes[node.nodeid].buffer > 0.0:\n global wait_min\n global wait_max\n global back_off\n global beacon_time\n global logs\n global nodesToSend\n global DR\n while node.buffer > 0.0:\n #######STARTS TRANSMISSION AS DR8\n node.dr = 8\n node.sensi = -137\n carriers = list(range(280))\n random.shuffle(carriers) #TO CHOOSE THE HOPPING JUMPS\n node.freqHop = carriers[0:35]\n node.header.freqHopHeader = node.freqHop[0:3]\n node.intraPacket.freqHopIntraPacket = node.freqHop [3:]\n #######\n yield env.timeout(node.packet.rectime + float(node.packet.proptime[math.ceil(env.now)])) ##GIVE TIME TO RECEIVE BEACON\n \n if node in packetsAtBS:\n print (\"{:3.5f} || ERROR: packet is already in...\".format(env.now))\n else:\n sensibility = sensi[12 - 7, [125,250,500].index(node.packet.bw) + 1]\n if node.packet.rssi[math.ceil(env.now)] < sensibility: #HERE WE ARE CONSIDERING RSSI AT TIME ENV.NOW\n print (\"{:3.5f} || Node {}: Can not reach beacon due Lpl\".format(env.now,node.nodeid))\n wait =0 ##LETS WAIT FOR NEXT BEACON\n node.header.lost = False\n node.intraPacket.lost = False\n trySend = False\n nIntraPackets = 0\n else:\n selectDR(env,node)\n nodesToSend.append(node.nodeid)\n wait = random.uniform(1,back_off - node.packet.rectime - float(node.packet.proptime[math.ceil(env.now)])) ##TRIGGER BACK-OFF TIME\n yield env.timeout(wait)\n #print (\"{:3.5f} || Node {} begins to transmit a packet\".format(env.now,node.nodeid))\n trySend = True\n node.sent = node.sent + 1\n node.buffer = node.buffer - node.packetlen\n if node in packetsAtBS:\n print (\"{} || ERROR: packet is already in...\".format(env.now))\n else:\n #sensibility = sensi[node.packet.sf - 7, [125,250,500].index(node.packet.bw) + 1]\n sensibility = node.sensi\n #print (\"------Sensi is: \",sensibility)\n if node.packet.rssi[math.ceil(env.now)] < sensibility: #HERE WE ARE CONSIDERING RSSI AT TIME ENV.NOW\n print (\"{:3.5f} || Node {}: The Packet will be Lost due Lpl\".format(env.now,node.nodeid))\n node.header.lost = True ## LOST ONLY CONSIDERING Lpl\n node.intraPacket.lost = True ## LOST ONLY CONSIDERING Lpl\n #nIntraPackets = 0\n print (\"###############lost !!!!!!!!\")\n else:\n node.header.lost = False ## LOST ONLY CONSIDERING Lpl\n node.intraPacket.lost = False ## LOST ONLY CONSIDERING Lpl\n #print (\"{:3.5f} || Prx for node {} is {:3.2f} dB\".format(env.now, node.nodeid, node.packet.rssi[math.ceil(env.now)]))\n #print (\"Prx for node\",node.nodeid, \"is: \",node.packet.rssi[math.ceil(env.now)],\"at time\",env.now)\n \n for i in range(len(node.header.freqHopHeader)):\n ###print (\"{:3.5f} || Sending Header replica {} node {}...\".format(env.now,i,node.nodeid))\n ###print (\"{:3.5f} || Let's try if there are collisions...\".format(env.now))\n node.header.subCh = node.header.freqHopHeader[i]\n #print (\"SUBCHANELLLL: \",node.header.subCh)\n node.header.sentIntra +=1\n isLost =0\n if node.packet.rssi[math.ceil(env.now)] < sensibility:\n node.header.Nlost +=1\n isLost =1\n if (checkcollision(node.header)==1):\n #pass\n if node.header.col == 1:\n if isLost == 0:\n node.header.collided +=1\n #node.packet.collided = 1\n #print (\"---{:3.5f} || Collision for Header replica {} node {} !!!\".format(env.now,i,node.nodeid))\n #node.packet.collided = 1\n #node.header.collided +=1 #ALREADY COUNTED IN FUNCTION \n else:\n ###print (\"{:3.5f} || ...No Collision for Header replica {} node {}!\".format(env.now,i,node.nodeid))\n #node.packet.collided = 0\n node.header.noCollided = 1 ##ALMOST ONE HEADER IS OK, THEN HEADER IS OK\n packetsAtBS.append(node)\n node.packet.addTime = env.now\n isLost =0\n yield env.timeout(node.header.rectime)\n if (node in packetsAtBS):\n packetsAtBS.remove(node)\n \n ##CALCULATE N OF INTRAPACKETS BASED ON PACKETLEN\n #airtime(12,1,node.packetlen,125)\n if node.dr == 8 or node.dr == 10:\n payloadTime = 1.85 - 0.233*3 \n elif node.dr == 9 or node.dr ==11:\n payloadTime = 1.07 - 0.233*2\n \n nIntraPackets = math.ceil(payloadTime / 50e-3)\n #print (\"NUMBER OF INTRA PACKETSSSS\",nIntraPackets)\n \n for j in range (nIntraPackets):\n ###print (\"{:3.5f} || Sending intra-packet {} of {} for node {}...\".format(env.now,j,nIntraPackets-1,node.nodeid))\n ###print (\"{:3.5f} || Let's try if there are collisions...\".format(env.now))\n node.intraPacket.subCh = node.intraPacket.freqHopIntraPacket[j]\n node.intraPacket.sentIntra +=1\n isLost =0\n if node.packet.rssi[math.ceil(env.now)] < sensibility:\n node.intraPacket.Nlost +=1\n isLost =1\n #print (\"INTRA-PACKT SUB CHANNELLLL\", node.intraPacket.subCh)\n if (checkcollision(node.intraPacket)==1):\n #pass\n if node.intraPacket.col ==1:\n if isLost == 0:\n node.intraPacket.collided+=1\n #print (\"---{:3.5f} || Collision for intra-packet {} for node {} !!!\".format(env.now,j,node.nodeid))\n #node.intraPacket.collided+=1 #ALREADY COUNTED ON FUNCTION\n else:\n ###print (\"{:3.5f} || ...No Collision for intra-packet {} for node {}!\".format(env.now,j,node.nodeid))\n node.intraPacket.noCollided +=1\n pass\n packetsAtBS.append(node)\n node.packet.addTime = env.now\n yield env.timeout(node.intraPacket.rectime)\n if (node in packetsAtBS):\n packetsAtBS.remove(node)\n #print (\"INTRA-PACKET NO-PROCESEDDD\",node.intraPacket.noProcessed)\n isLost =0\n \n node.header.noCollided = len(node.header.freqHopHeader)-node.header.Nlost-node.header.collided\n node.intraPacket.noCollided = nIntraPackets-node.intraPacket.Nlost-node.intraPacket.collided\n \n if node.header.noCollided <0:\n node.header.noCollided = 0\n if node.intraPacket.noCollided <0:\n node.intraPacket.noCollided = 0\n \n if trySend == 1:\n #print (\"----count intra-packet collided\", node.intraPacket.collided)\n if node.header.lost or node.intraPacket.lost:\n logs.append(\"{:3.3f},{},{:3.3f},{:3.3f},{},PL,#{},#{},#{},#{}\".format(env.now,node.nodeid,node.dist[math.ceil(env.now)],node.elev[math.ceil(env.now)],node.dr,nIntraPackets,node.intraPacket.noCollided,len(node.header.freqHopHeader),node.header.noCollided))\n else:\n if node.dr ==8 or node.dr==10:\n if node.header.collided == 3:\n logs.append(\"{:3.3f},{},{:3.3f},{:3.3f},{},PCh,#{},#{},#{},#{}\".format(env.now,node.nodeid,node.dist[math.ceil(env.now)],node.elev[math.ceil(env.now)],node.dr,nIntraPackets,node.intraPacket.noCollided,len(node.header.freqHopHeader),node.header.noCollided))\n elif node.intraPacket.collided > (1/3)*nIntraPackets:\n logs.append(\"{:3.3f},{},{:3.3f},{:3.3f},{},PCp,#{},#{},#{},#{}\".format(env.now,node.nodeid,node.dist[math.ceil(env.now)],node.elev[math.ceil(env.now)],node.dr,nIntraPackets,node.intraPacket.noCollided,len(node.header.freqHopHeader),node.header.noCollided))\n elif node.header.noProcessed == 3:\n logs.append(\"{:3.3f},{},{:3.3f},{:3.3f},{},NP,#{},#{},#{},#{}\".format(env.now,node.nodeid,node.dist[math.ceil(env.now)],node.elev[math.ceil(env.now)],node.dr,nIntraPackets,node.intraPacket.noCollided,len(node.header.freqHopHeader),node.header.noCollided))\n elif node.intraPacket.noProcessed > (1/3)*nIntraPackets:\n logs.append(\"{:3.3f},{},{:3.3f},{:3.3f},{},NP,#{},#{},#{},#{}\".format(env.now,node.nodeid,node.dist[math.ceil(env.now)],node.elev[math.ceil(env.now)],node.dr,nIntraPackets,node.intraPacket.noCollided,len(node.header.freqHopHeader),node.header.noCollided))\n else:\n logs.append(\"{:3.3f},{},{:3.3f},{:3.3f},{},PE,#{},#{},#{},#{}\".format(env.now,node.nodeid,node.dist[math.ceil(env.now)],node.elev[math.ceil(env.now)],node.dr,nIntraPackets,node.intraPacket.noCollided,len(node.header.freqHopHeader),node.header.noCollided))\n \n elif node.dr==9 or node.dr==11:\n if node.header.collided == 2:\n logs.append(\"{:3.3f},{},{:3.3f},{:3.3f},{},PCh,#{},#{},#{},#{}\".format(env.now,node.nodeid,node.dist[math.ceil(env.now)],node.elev[math.ceil(env.now)],node.dr,nIntraPackets,node.intraPacket.noCollided,len(node.header.freqHopHeader),node.header.noCollided))\n elif node.intraPacket.collided > (2/3)*nIntraPackets:\n logs.append(\"{:3.3f},{},{:3.3f},{:3.3f},{},PCp,#{},#{},#{},#{}\".format(env.now,node.nodeid,node.dist[math.ceil(env.now)],node.elev[math.ceil(env.now)],node.dr,nIntraPackets,node.intraPacket.noCollided,len(node.header.freqHopHeader),node.header.noCollided))\n elif node.header.noProcessed == 2:\n logs.append(\"{:3.3f},{},{:3.3f},{:3.3f},{},NP,#{},#{},#{},#{}\".format(env.now,node.nodeid,node.dist[math.ceil(env.now)],node.elev[math.ceil(env.now)],node.dr,nIntraPackets,node.intraPacket.noCollided,len(node.header.freqHopHeader),node.header.noCollided))\n elif node.intraPacket.noProcessed > (2/3)*nIntraPackets:\n logs.append(\"{:3.3f},{},{:3.3f},{:3.3f},{},NP,#{},#{},#{},#{}\".format(env.now,node.nodeid,node.dist[math.ceil(env.now)],node.elev[math.ceil(env.now)],node.dr,nIntraPackets,node.intraPacket.noCollided,len(node.header.freqHopHeader),node.header.noCollided))\n else:\n logs.append(\"{:3.3f},{},{:3.3f},{:3.3f},{},PE,#{},#{},#{},#{}\".format(env.now,node.nodeid,node.dist[math.ceil(env.now)],node.elev[math.ceil(env.now)],node.dr,nIntraPackets,node.intraPacket.noCollided,len(node.header.freqHopHeader),node.header.noCollided))\n \n ##RESET\n node.header.collided = 0\n node.header.processed = 0\n node.header.noProcessed = 0\n node.header.lost = False\n node.header.noCollided =0\n node.intraPacket.nrColl = 0\n node.intraPacket.collided = 0\n node.intraPacket.processed = 0\n node.intraPacket.noProcessed = 0\n node.intraPacket.lost = False\n node.intraPacket.noCollided = 0\n node.header.sentIntra = 0\n node.intraPacket.sentIntra = 0\n node.header.Nlost =0\n node.intraPacket.Nlost = 0\n \n if trySend:\n #print (\"BEACON TIMEEE\",beacon_time)\n #print (\"WAITTT\",wait)\n #print (\"NODE HEADER TIME\",node.header.rectime)\n #print (\"ONE INTRA-PACKET TIMEE\",node.intraPacket.rectime)\n #yield env.timeout(beacon_time-wait)\n yield env.timeout(beacon_time-wait-2*3*node.header.rectime-2*nIntraPackets*node.intraPacket.rectime)\n else:\n nIntraPackets = 0\n yield env.timeout(beacon_time-wait-3*node.header.rectime-nIntraPackets*node.intraPacket.rectime)\n \n def beacon (env):\n global beacon_time\n global nodesToSend\n global logs\n i = 0\n while True:\n if i == 0:\n yield env.timeout(0) \n else:\n yield env.timeout(beacon_time-2)\n i=i+1\n print (\"{:3.5f} || ***A new beacon has been sended from Satellite***\".format(env.now))\n yield env.timeout(2)\n logs.append(\"{:3.3f},B,{}\".format(env.now,nodesToSend))\n nodesToSend = [] \n \n env.process(beacon(env)) ##BEACON SENDER\n \n ### THIS IS GOING TO CREATE NODES AND DO TRAMSMISIONS. IS THE MAIN PROGRAM ###\n for i in range(nrNodes):\n node = myNode(i,bsId, avgSendTime, packetlen, total_data)\n nodes.append(node)\n env.process(transmit(env,node))\n \n env.run(until=600*2)\n \n sent = sum(n.sent for n in nodes)\n return ([sent,nrCollFullPacket,None,None,nrReceived],logs)\n\n\n\n#########################################################################\nif chan == 1:\n ###SCENARIO 1 CHANNEL###\n channel = [0]\n \n nodes = [] ###EACH NODE WILL BE APPENDED TO THIS VARIABLE\n nrLost = 0 ### TOTAL OF LOST PACKETS DUE Lpl\n nrCollisions = 0 ##TOTAL OF COLLIDED PACKETS\n nrProcessed = 0 ##TOTAL OF PROCESSED PACKETS\n nrReceived = 0 ###TOTAL OF RECEIVED PACKETS\n nrNoProcessed = 0 ##TOTAL OF INTRA-PACKETS NO PROCESSED\n nrIntraTot = 0\n nrLostMaxRec = 0\n nrCollFullPacket = 0\n nrSentIntra = 0 ##TOTAL OF SENT INTRA-PACKTES\n nrReceivedIntra = 0 ##TOTAL OF RECEIVED INTRA-PACKETS\n \n i =0\n scenario_1ch = np.zeros((len(multi_nodes),5))\n results = []\n ## WHERE:\n ## scenario_1ch[i,j]:\n ## i --> the node i\n ## j --> [sent, nrCollisions, nrLost, nrProcessed, nrReceived]\n \n for nrNodes in multi_nodes:\n print (\"\\n\\n***NEW SCENARIO BEGINS***\\n\")\n logs = []\n results,logs = simulate_scenario(nrNodes)\n scenario_1ch[i,:] = results\n folder = name+'_1CH_s'+str(RANDOM_SEED)+'_p'+str(packetsToSend)\n if not os.path.exists(folder):\n os.makedirs(folder)\n fname = \"./\"+folder+\"/\" + str(name+\"_\"+str(nrNodes)+\"_1CH_\"+str(maxBSReceives)+\"_s\"+str(RANDOM_SEED)+\"_p\"+str(packetsToSend)) + \".csv\"\n with open(fname,\"w\") as myfile:\n myfile.write(\"\\n\".join(logs))\n myfile.close()\n i=i+1\n if not mode_debbug:\n nodes = [] ###EACH NODE WILL BE APPENDED TO THIS VARIABLE\n nrLost = 0 ### TOTAL OF LOST PACKETS DUE Lpl\n nrCollisions = 0 ##TOTAL OF COLLIDED PACKETS\n nrProcessed = 0 ##TOTAL OF PROCESSED PACKETS\n nrReceived = 0 ###TOTAL OF RECEIVED PACKETS\n nrNoProcessed = 0 ##TOTAL OF INTRA-PACKETS NO PROCESSED\n nrIntraTot = 0\n nrLostMaxRec = 0\n nrCollFullPacket = 0\n nrSentIntra = 0 ##TOTAL OF SENT INTRA-PACKTES\n nrReceivedIntra = 0 ##TOTAL OF RECEIVED INTRA-PACKETS\n\n\n#########################################################################\nif chan ==3:\n ###SCENARIO 3 CHANNELS###\n channel = [0,1,2]\n nodes = [] ###EACH NODE WILL BE APPENDED TO THIS VARIABLE\n nrLost = 0 ### TOTAL OF LOST PACKETS DUE Lpl\n nrCollisions = 0 ##TOTAL OF COLLIDED PACKETS\n nrProcessed = 0 ##TOTAL OF PROCESSED PACKETS\n nrReceived = 0 ###TOTAL OF RECEIVED PACKETS\n nrNoProcessed = 0 ##TOTAL OF INTRA-PACKETS NO PROCESSED\n nrIntraTot = 0\n nrLostMaxRec = 0\n nrCollFullPacket = 0\n nrSentIntra = 0 ##TOTAL OF SENT INTRA-PACKTES\n nrReceivedIntra = 0 ##TOTAL OF RECEIVED INTRA-PACKETS\n i =0\n scenario_3ch = np.zeros((len(multi_nodes),5))\n results = []\n \n for nrNodes in multi_nodes:\n print (\"\\n\\n***NEW SCENARIO BEGINS***\\n\")\n logs = []\n results,logs = simulate_scenario(nrNodes)\n scenario_3ch[i,:] = results\n folder = name+'_3CH_s'+str(RANDOM_SEED)+'_p'+str(packetsToSend)\n if not os.path.exists(folder):\n os.makedirs(folder)\n fname = \"./\"+folder+\"/\" + str(name+\"_\"+str(nrNodes)+\"_3CH_\"+str(maxBSReceives)+\"_s\"+str(RANDOM_SEED)+\"_p\"+str(packetsToSend)) + \".csv\"\n with open(fname,\"w\") as myfile:\n myfile.write(\"\\n\".join(logs))\n myfile.close()\n i=i+1\n if not mode_debbug:\n nodes = [] ###EACH NODE WILL BE APPENDED TO THIS VARIABLE\n nrLost = 0 ### TOTAL OF LOST PACKETS DUE Lpl\n nrCollisions = 0 ##TOTAL OF COLLIDED PACKETS\n nrProcessed = 0 ##TOTAL OF PROCESSED PACKETS\n nrReceived = 0 ###TOTAL OF RECEIVED PACKETS\n nrNoProcessed = 0 ##TOTAL OF INTRA-PACKETS NO PROCESSED\n nrIntraTot = 0\n nrLostMaxRec = 0\n nrCollFullPacket = 0\n nrSentIntra = 0 ##TOTAL OF SENT INTRA-PACKTES\n nrReceivedIntra = 0 ##TOTAL OF RECEIVED INTRA-PACKETS\n\nif not mode_debbug:\n sys.stdout = old_stdout\n print(\"done \",name)\n\n\n\n", "meta": {"hexsha": "8a069a983645c01e2ba18cc409994440ea223cbc", "size": 41328, "ext": "py", "lang": "Python", "max_stars_repo_path": "ER_args_v05.py", "max_stars_repo_name": "alvarezguido/lora-space", "max_stars_repo_head_hexsha": "904ce6ec99777f510c6f653dbfab0848524bce48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ER_args_v05.py", "max_issues_repo_name": "alvarezguido/lora-space", "max_issues_repo_head_hexsha": "904ce6ec99777f510c6f653dbfab0848524bce48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ER_args_v05.py", "max_forks_repo_name": "alvarezguido/lora-space", "max_forks_repo_head_hexsha": "904ce6ec99777f510c6f653dbfab0848524bce48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.0, "max_line_length": 284, "alphanum_fraction": 0.5399728997, "include": true, "reason": "import numpy", "num_tokens": 11029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.2628418431456957, "lm_q1q2_score": 0.142687185925185}} {"text": "\"\"\"Implementation on top of MultiNest via PyMultiNest.\n\nThis module defines the class for Nested Sampling using the MultiNest\nprogram via its Python wrapper PyMultiNest. Note that PyMultiNest and MultiNest\nhave to be built and installed separately (from gleipnir) before this module\ncan be used.\n\nPyMultiNest: https://github.com/JohannesBuchner/PyMultiNest\nMultiNest: https://github.com/JohannesBuchner/MultiNest\n\nReferences:\n MultiNest:\n 1. Feroz, Farhan, and M. P. Hobson. \"Multimodal nested sampling: an\n efficient and robust alternative to Markov Chain Monte Carlo\n methods for astronomical data analyses.\" Monthly Notices of the\n Royal Astronomical Society 384.2 (2008): 449-463.\n 2. Feroz, F., M. P. Hobson, and M. Bridges. \"MultiNest: an efficient\n and robust Bayesian inference tool for cosmology and particle\n physics.\" Monthly Notices of the Royal Astronomical Society 398.4\n (2009): 1601-1614.\n 3. Feroz, F., et al. \"Importance nested sampling and the MultiNest\n algorithm.\" arXiv preprint arXiv:1306.2144 (2013).\n PyMultiNest:\n 4. Buchner, J., et al. \"X-ray spectral modelling of the AGN obscuring\n region in the CDFS: Bayesian model selection and catalogue.\"\n Astronomy & Astrophysics 564 (2014): A125.\n\n\"\"\"\n\nimport numpy as np\nimport warnings\nfrom .nsbase import NestedSamplingBase\n\ntry:\n import pymultinest\n from pymultinest.solve import solve\n from pymultinest.analyse import Analyzer\nexcept ImportError as err:\n #print(err)\n raise err\n\nclass MultiNestNestedSampling(NestedSamplingBase):\n \"\"\"Nested Sampling using MultiNest.\n PyMultiNest: https://github.com/JohannesBuchner/PyMultiNest\n MultiNest: https://github.com/JohannesBuchner/MultiNest\n\n Attributes:\n sampled_parameters (list of :obj:gleipnir.sampled_parameter.SampledParameter):\n The parameters that are being sampled during the Nested Sampling\n run.\n loglikelihood (function): The log-likelihood function to use for\n assigning a likelihood to parameter vectors during the sampling.\n population_size (int): The number of points to use in the Nested\n Sampling active population.\n multinest_kwargs (dict): Additional keyword arguments that should be\n passed to the PyMultiNest MultiNest solver. Available options are:\n importance_nested_sampling (bool): Should MultiNest use\n Importance Nested Sampling (INS). Default: True\n constant_efficiency_mode (bool): Should MultiNest run in\n constant sampling efficiency mode. Default: False\n\t sampling_efficiency (float): Set the MultiNest sampling\n efficiency. 0.3 is recommended for evidence evaluation,\n while 0.8 is recommended for parameter estimation.\n Default: 0.8\n resume (bool): Resume from a previous MultiNest run (using\n the last saved checkpoint in the MultiNest output files).\n Default: True\n write_output (bool): Specify whether MultiNest should write\n to output files. True is required for additional\n analysis. Default: True\n multimodal (bool): Set whether MultiNest performs mode\n separation. Default: True\n max_mode (int): Set the maximum number of modes allowed in\n mode separation (if multimodal=True). Default: 100\n mode_tolerance (float): A lower bound for which MultiNest will\n use to separate mode samples and statistics with\n log-evidence value greater the given value.\n Default: -1e90\n n_clustering_params (int): If multimodal=True, set the number\n of parameters to use in clustering during mode separation.\n If None, then MultiNest will use all the paramters for\n clustering during mode separation. If\n n<(number of sampled parameters), then MultiNest will only\n use a subset composed of the first n parameters for\n clustering during mode separation. Default: None\n null_log_evidence (float): If multimodal=True, a lower bound\n for which MultiNest can use to separte mode samples and\n statistics with a local log-evidence value greater than the\n given bound. Default: -1.e90\n log_zero (float): Set a threshold value for which points with\n a loglikelihood less than the given value will be ignored\n by MultiNest. Default: -1e100\n max_iter (int): Set the maximum number of nested sampling\n iterations performed by MultiNest. If 0, then it is\n unlimited and MultiNest will stop using a different\n criterion. Default: 0\n\n\n References:\n 1. Feroz, Farhan, and M. P. Hobson. \"Multimodal nested sampling: an\n efficient and robust alternative to Markov Chain Monte Carlo\n methods for astronomical data analyses.\" Monthly Notices of the\n Royal Astronomical Society 384.2 (2008): 449-463.\n 2. Feroz, F., M. P. Hobson, and M. Bridges. \"MultiNest: an efficient\n and robust Bayesian inference tool for cosmology and particle\n physics.\" Monthly Notices of the Royal Astronomical Society 398.4\n (2009): 1601-1614.\n 3. Feroz, F., et al. \"Importance nested sampling and the MultiNest\n algorithm.\" arXiv preprint arXiv:1306.2144 (2013).\n 4. Buchner, J., et al. \"X-ray spectral modelling of the AGN obscuring\n region in the CDFS: Bayesian model selection and catalogue.\"\n Astronomy & Astrophysics 564 (2014): A125.\n \"\"\"\n\n def __init__(self, sampled_parameters, loglikelihood, population_size,\n **multinest_kwargs):\n \"\"\"Initialize the MultiNest Nested Sampler.\"\"\"\n self.sampled_parameters = sampled_parameters\n self.loglikelihood = loglikelihood\n self.population_size = population_size\n self.multinest_kwargs = multinest_kwargs\n\n self._nDims = len(sampled_parameters)\n self._nDerived = 0\n self._output = None\n self._post_eval = False\n #if self.population_size is None:\n # self.population_size = 25*self._nDims\n\n # Make the prior function for PyMultiNest.\n def prior(hypercube):\n return np.array([self.sampled_parameters[i].invcdf(value) for i,value in enumerate(hypercube)])\n\n self._prior = prior\n # multinest settings\n self._file_root = 'multinest_run_' #string\n\n return\n\n\n def run(self, verbose=False):\n \"\"\"Initiate the MultiNest Nested Sampling run.\"\"\"\n output = solve(LogLikelihood=self.loglikelihood, Prior=self._prior,\n n_dims = self._nDims,\n n_live_points=self.population_size,\n outputfiles_basename=self._file_root,\n verbose=verbose,\n **self.multinest_kwargs)\n self._output = output\n return self.log_evidence, self.log_evidence_error\n\n @property\n def evidence(self):\n \"\"\"float: Estimate of the Bayesian evidence, or Z.\"\"\"\n return np.exp(self._output['logZ'])\n @evidence.setter\n def evidence(self, value):\n warnings.warn(\"evidence is not settable\")\n\n @property\n def evidence_error(self):\n \"\"\"float: Estimate (rough) of the error in the evidence, or Z.\"\"\"\n return np.exp(self._output['logZerr'])\n @evidence_error.setter\n def evidence_error(self, value):\n warnings.warn(\"evidence_error is not settable\")\n\n @property\n def log_evidence(self):\n \"\"\"float: Estimate of the natural logarithm of the Bayesian evidence, or ln(Z).\n \"\"\"\n return self._output['logZ']\n @log_evidence.setter\n def log_evidence(self, value):\n warnings.warn(\"log_evidence is not settable\")\n\n @property\n def log_evidence_error(self):\n \"\"\"float: Estimate of the error in the natural logarithm of the evidence.\n \"\"\"\n return self._output['logZerr']\n @log_evidence_error.setter\n def log_evidence_error(self, value):\n warnings.warn(\"log_evidence_error is not settable\")\n\n @property\n def information(self):\n \"\"\"None: Not implemented yet->Estimate of the Bayesian information, or H.\"\"\"\n return None\n @information.setter\n def information(self, value):\n warnings.warn(\"information is not settable\")\n\n @property\n def multinest_file_root(self):\n \"\"\"str. The root name used for MultNest output files.\"\"\"\n return self._file_root\n @multinest_file_root.setter\n def multinest_file_root(self, value):\n self._file_root = value\n return\n\n def posteriors(self, nbins=None):\n \"\"\"Estimates of the posterior marginal probability distributions of each parameter.\n Returns:\n dict of tuple of (numpy.ndarray, numpy.ndarray, numpy.ndarray): The\n histogram estimates of the posterior marginal probability\n distributions. The returned dict is keyed by the sampled\n parameter names and each element is a tuple with\n (marginal_weights, bin_edges, bin_centers).\n \"\"\"\n # Lazy evaluation at first call of the function and store results\n # so that subsequent calls don't have to recompute.\n #print('nbins', nbins)\n if not self._post_eval:\n # Here the samples are samples directly from the posterior\n # (i.e. equal weights).\n samples = self._output['samples']\n # Rice bin count selection\n if nbins is None:\n nbins = 2 * int(np.cbrt(len(samples)))\n # print('nbins', nbins)\n nd = samples.shape[1]\n self._posteriors = dict()\n for ii in range(nd):\n marginal, edge = np.histogram(samples[:,ii], density=True, bins=nbins)\n center = (edge[:-1] + edge[1:])/2.\n self._posteriors[self.sampled_parameters[ii].name] = (marginal, edge, center)\n self._post_eval = True\n\n return self._posteriors\n\n def max_loglikelihood(self):\n mn_data = Analyzer(len(self.sampled_parameters), self._file_root, verbose=False).get_data()\n log_ls = -0.5*mn_data[:,1]\n ml = log_ls.max()\n return ml\n\n def deviance_ic(self):\n \"\"\"Estimate Deviance Information Criterion.\n This function estimates the Deviance Information Criterion (DIC) for the\n model simulated with Nested Sampling (NS). It does so by using the\n posterior distribution estimates computed from the NS outputs.\n The DIC formula is given by:\n DIC = p_D + D_bar,\n where p_D = D_bar - D(theta_bar), D_bar is the posterior average of\n the deviance D(theta)= -2*ln(L(theta)) with L(theta) the likelihood\n of parameter set theta, and theta_bar is posterior average parameter set.\n\n Returns:\n float: The DIC estimate.\n \"\"\"\n mn_data = Analyzer(len(self.sampled_parameters), self._file_root, verbose=False).get_data()\n params = mn_data[:,2:]\n log_likelihoods = -0.5*mn_data[:,1]\n prior_mass = mn_data[:,0]\n norm_weights = (prior_mass*np.exp(log_likelihoods))/self.evidence\n nw_mask = np.isnan(norm_weights)\n if np.any(nw_mask):\n return np.inf\n D_of_theta = -2.*log_likelihoods\n D_bar = np.average(D_of_theta, weights=norm_weights)\n theta_bar = np.average(params, axis=0, weights=norm_weights)\n D_of_theta_bar = -2. * self.loglikelihood(theta_bar)\n p_D = D_bar - D_of_theta_bar\n return p_D + D_bar\n\n def best_fit_likelihood(self):\n \"\"\"Parameter vector with the maximum likelihood.\n Returns:\n numpy.array: The parameter vector.\n \"\"\"\n mn_data = Analyzer(len(self.sampled_parameters), self._file_root, verbose=False).get_data()\n log_ls = -0.5*mn_data[:,1]\n midx = np.argmax(log_ls)\n ml = mn_data[midx][2:]\n return ml\n", "meta": {"hexsha": "fea06435b7609d27f9afae2019a9c17f373e66af", "size": 12430, "ext": "py", "lang": "Python", "max_stars_repo_path": "gleipnir/multinest.py", "max_stars_repo_name": "LoLab-VU/Gleipnir", "max_stars_repo_head_hexsha": "6085435f4840d403c0878b0d50192565ccc82965", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-07-11T14:45:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-29T16:21:41.000Z", "max_issues_repo_path": "gleipnir/multinest.py", "max_issues_repo_name": "LoLab-VU/Gleipnir", "max_issues_repo_head_hexsha": "6085435f4840d403c0878b0d50192565ccc82965", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2019-05-20T03:14:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-07T17:23:23.000Z", "max_forks_repo_path": "gleipnir/multinest.py", "max_forks_repo_name": "LoLab-VU/Gleipnir", "max_forks_repo_head_hexsha": "6085435f4840d403c0878b0d50192565ccc82965", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-05-29T04:53:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-25T22:15:11.000Z", "avg_line_length": 44.7122302158, "max_line_length": 107, "alphanum_fraction": 0.6373290426, "include": true, "reason": "import numpy", "num_tokens": 2777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.24508501313237172, "lm_q1q2_score": 0.14246867204896155}} {"text": "# python \nimport os\n\n# site-packages\nimport numpy as np\n\n# local imports\nimport utils, tasks\n\n\nclass simulation( object ): \n\n def __init__(self, dir_name):\n \n # intialize data structure to store simulation data\n self.data = {\n # from simulation configuration file\n 'name': None,\n 'friction': None,\n 'rough_fault_seed': None,\n 'fault_roughness': None,\n 'ihypo': None,\n\n # calculated from simulation output\n 'rupture_length' : None,\n 'rupture_area' : None,\n 'avg_stress_drop' : None,\n 'avg_slip': None,\n 'avg_psv' : None,\n 'avg_surf_slip': None,\n 'avg_surf_psv': None,\n 'max_slip' : None,\n 'max_psv' : None,\n 'max_surf_slip' : None,\n 'max_surf_psv' : None,\n 'moment': None,\n 'mw': None,\n }\n \n # populated from parsing the parameter file\n self.params = {}\n\n # hardcoded\n self.__config_file = 'meta.py'\n\n # simulation directory\n self.dir = os.path.expanduser( dir_name )\n\n # read simulation details and update data\n self.data.update( self.parse_simulation_details() )\n\n # add some parameters to top level class for easy access\n self.dt = self.params['dt']\n self.dx = self.params['dx'][0]\n self.nx = int(self.params['nn'][0])\n self.nz = int(self.params['nn'][1])\n self.ihypo = self.params['ihypo']\n self.name = self.params['name']\n\n # load slip, psv, and trup\n nx = int(self.params['shape']['su1'][0])\n nz = int(self.params['shape']['su1'][1])\n self.dtype = self.params['dtype']\n\n su1 = np.fromfile(os.path.join(self.dir, 'out/su1'), dtype=self.dtype).reshape([nz,nx])\n su2 = np.fromfile(os.path.join(self.dir, 'out/su2'), dtype=self.dtype).reshape([nz,nx])\n self.slip = np.sqrt( su1**2 + su2**2 )\n self.trup = np.fromfile(os.path.join(self.dir, 'out/trup'), dtype=self.dtype).reshape([nz,nx])\n self.psv = np.fromfile(os.path.join(self.dir, 'out/psv'), dtype=self.dtype).reshape([nz,nx])\n\n # load shear stress\n nx = int(self.params['shape']['tsm'][0])\n nz = int(self.params['shape']['tsm'][1])\n nt = int(self.params['shape']['tsm'][2]) # some models didn't write out all timesteps\n\n self.tsm = np.fromfile( os.path.join(self.dir, 'out/tsm'), dtype=self.dtype )\n\n # sometimes the simulations finish early\n try:\n self.tsm = self.tsm.reshape([nt,nz,nx]) \n except ValueError:\n n = len( self.tsm )\n sdim = int(n / ( nx * nz ))\n self.tsm = self.tsm.reshape([sdim,nz,nx])\n\n def parse_simulation_details( self ):\n \"\"\" \n parse parameters from meta.py file. will populate specifics for database.\n\n inputs\n config_file (string of file object) : configuration file for simulation\n \n returns\n params (dict) : params.keys() = ['name', 'friction', rough_fault_seed', 'fault_roughness']\n\n \"\"\" \n # read meta.py file\n meta = utils.parse( os.path.join( self.dir, self.__config_file ) )\n\n # update simulation object with all parameters\n self.params.update( meta )\n\n # extract parameters\n data = {}\n data['name'] = meta['name']\n data['friction'] = meta['friction']\n data['rough_fault_seed'] = utils.extract_from_string( data['name'], ['rf','seed'] )\n data['fault_roughness'] = utils.extract_from_string( data['name'], 'a' )\n data['ihypo'] = str(meta['ihypo'])\n return data\n\n\n\n\n def get_masked_field(self, field_name, tind = None, mask='psv', tol=0.001, hypo_tol=4000):\n \"\"\" \n masks a rupture field around hypocenter, velocity strengthening region, and based on\n field values. currently, masking where psv < 0.001 seems to be the most general approach.\n\n notes: returns the mask that is the same shape as 'field'\n \n inputs\n sim : simulation object\n field : string of field in simulation object to use.\n hypo_tol : radius to mask around hypocenter.\n vel_str_tol : velocity strengthening tolerance.\n field_tol : tolerance of simulation field. \n\n return:\n field (ndarray.masked) \n \n \"\"\"\n\n # get reference to fields\n field = getattr(self, field_name)\n mask_field = getattr(self, mask)\n \n nskipx_mask = self.params['indices'][mask][0][2] \n if field_name is 'slip':\n nskipx_field = self.params['indices']['su1'][0][2]\n else:\n nskipx_field = self.params['indices'][field_name][0][2]\n \n\n # get dims of field\n nt = 0\n try:\n nx,nz,nt = field.shape\n except ValueError:\n nx,nz = field.shape\n\n # some sanity checks\n if len(mask_field.shape) > len(field.shape):\n raise ValueError(\"Mask should not have higher dimensionality that field being masked.\")\n\n if mask_field.shape != (self.nz, self.nx):\n raise ValueError(\"Masking field should cover entire fault plane. Try trup, or psv, or slip.\")\n\n if nskipx_mask > nskipx_field:\n raise ValueError(\"Mask has less resolution that field. Unable to mask field.\")\n\n # calculate hypocentral mask\n hx = int(self.ihypo[0])\n hz = int(self.ihypo[1])\n r = int(hypo_tol / self.dx)\n z,x = np.ogrid[-hz:self.nz-hz, -hx:self.nx-hx]\n mask1 = x*x + z*z <= r*r\n\n # mask unruptured area based on mask and tol\n mask2 = np.zeros( mask_field.shape, dtype=bool )\n mask2[np.where( mask_field < tol )] = True\n\n # decimate mask if necessary\n ratio = 1\n if nskipx_field != nskipx_mask:\n ratio = int(nskipx_field / nskipx_mask)\n\n # combine masks using logical or\n mask = np.ma.mask_or(mask1, mask2)[::ratio, ::ratio] \n\n # return at time\n if tind is not None:\n masked = np.ma.array( np.squeeze(field[tind, :, :]), mask = mask )\n else:\n masked = np.ma.array( field, mask = mask )\n\n return masked\n\n\n def process( self ):\n \"\"\" process the simulation from folders in tasks. make sure to update data as we go along. \"\"\"\n print(f'processing sim: {self.name}')\n \n self.data['rupture_length'] = tasks.get_fault_extent( self )\n self.data['rupture_area'] = tasks.get_area( self )\n self.data['rupture_area_bbox'] = tasks.get_area_bbox( self ) \n self.data['avg_stress_drop'] = tasks.compute_stress_drop( self )\n\n avg, avg_surf, mx, mx_surf = tasks.rupture_field_stats( self , 'slip' )\n self.data['avg_slip'] = avg\n self.data['avg_surf_slip']= avg_surf\n self.data['max_slip'] = mx\n self.data['max_surf_slip'] = mx_surf\n\n avg, avg_surf, mx, mx_surf = tasks.rupture_field_stats( self , 'psv' )\n self.data['avg_psv'] = avg\n self.data['avg_surf_psv'] = avg_surf\n self.data['max_psv'] = mx\n self.data['max_surf_psv'] = mx_surf\n\n self.data['mw'] = tasks.get_mw( self, dtype=self.dtype )\n self.data['moment'] = utils.mw_to_m0( self.data['mw'] )\n\n return self\n\n\n\n\n\n\n", "meta": {"hexsha": "f401bc535f17cc5e9fb5bac127387ed3a9eacf36", "size": 7385, "ext": "py", "lang": "Python", "max_stars_repo_path": "models.py", "max_stars_repo_name": "billtr0n/serial_processing", "max_stars_repo_head_hexsha": "93a4c9b2df42905730379a566d146b98dfae28aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models.py", "max_issues_repo_name": "billtr0n/serial_processing", "max_issues_repo_head_hexsha": "93a4c9b2df42905730379a566d146b98dfae28aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models.py", "max_forks_repo_name": "billtr0n/serial_processing", "max_forks_repo_head_hexsha": "93a4c9b2df42905730379a566d146b98dfae28aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4162895928, "max_line_length": 106, "alphanum_fraction": 0.5741367637, "include": true, "reason": "import numpy", "num_tokens": 1843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.2782567996876011, "lm_q1q2_score": 0.1423886247719863}} {"text": "from typing import List, Tuple, Union, Mapping, TypeVar, Callable, Iterable, Optional\nfrom typing_extensions import Literal\n\nfrom copy import copy\nfrom enum import auto\nfrom types import FunctionType, MappingProxyType\nfrom inspect import signature\nfrom pathlib import Path\nfrom functools import wraps\nfrom itertools import combinations\n\nfrom anndata import AnnData\nfrom cellrank import logging as logg\nfrom cellrank._key import Key\nfrom cellrank.tl._enum import ModeEnum\nfrom cellrank.ul._docs import d, inject_docs\nfrom cellrank.tl._utils import save_fig, _convert_lineage_name, _unique_order_preserving\nfrom cellrank.tl._colors import (\n _get_bg_fg_colors,\n _compute_mean_color,\n _create_categorical_colors,\n)\n\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import entropy\nfrom pandas.api.types import infer_dtype, is_categorical_dtype\n\nimport matplotlib.colors as c\nimport matplotlib.pyplot as plt\n\nColorLike = TypeVar(\"ColorLike\")\n_ERROR_NOT_ITERABLE = \"Expected `{}` to be iterable, found type `{}`.\"\n_ERROR_WRONG_SIZE = \"Expected `{}` to be of size `{{}}`, found `{{}}`.\"\n\n_HT_CELLS = 10 # head and tail cells to show\n_HTML_REPR_THRESH = 100\n_DUMMY_CELL = \"...\"\n_ORDER = \"C\"\n\n\nclass PrimingDegree(ModeEnum): # noqa: D101\n KL_DIVERGENCE = auto()\n ENTROPY = auto()\n\n\nclass Lin(ModeEnum): # noqa: D101\n REST = auto()\n OTHERS = auto()\n\n\nclass DistanceMeasure(ModeEnum): # noqa: D101\n COSINE_SIM = auto()\n WASSERSTEIN_DIST = auto()\n KL_DIV = auto()\n JS_DIV = auto()\n MUTUAL_INFO = auto()\n EQUAL = auto()\n\n\nclass NormWeights(ModeEnum): # noqa: D101\n SCALE = auto()\n SOFTMAX = auto()\n\n\nclass Reduction(ModeEnum): # noqa: D101\n DIST = auto()\n SCALE = auto()\n\n\nclass LinKind(ModeEnum): # noqa: D101\n MACROSTATES = auto()\n TERM_STATES = auto()\n ABS_PROBS = auto()\n\n\ndef _at_least_2d(array: np.ndarray, dim: int):\n return np.expand_dims(array, dim) if array.ndim < 2 else array\n\n\ndef wrap(numpy_func: Callable) -> Callable:\n \"\"\"\n Wrap an numpy function.\n\n Modifies functionality of some function (e.g. ignoring `.squeeze`, retaining dimensions).\n\n Parameters\n ----------\n numpy_func\n Function to be wrapped.\n\n Returns\n -------\n Wrapped function which takes a :class:`cellrank.tl.Lineage` and return :class:`cellrank.tl.Lineage`.\n \"\"\"\n\n @wraps(numpy_func)\n def decorator(array, *args, **kwargs):\n if not isinstance(array, Lineage):\n raise TypeError(\n f\"Expected array to be of type `Lineage`, found `{type(array).__name__}`.\"\n )\n if fname == \"squeeze\":\n return array\n if fname == \"array_repr\":\n return repr(array)\n\n if \"axis\" in kwargs:\n axis = kwargs[\"axis\"]\n elif axis_ix < len(args):\n axis = args[axis_ix]\n else:\n axis = default_axis\n\n res = np.array(numpy_func(array.X, *args, **kwargs), copy=False)\n\n # handle expand_dim\n if res.ndim > 2:\n return array\n\n # handle reductions\n if not res.shape:\n return Lineage(np.array([[res]]), names=[fname], colors=[\"grey\"])\n if res.shape == array.shape:\n return Lineage(res, names=array.names, colors=array.colors)\n\n res = np.expand_dims(res, axis)\n\n is_t = int(array._is_transposed)\n if is_t:\n res = res.T\n\n lin = None\n if res.shape[0] == array.shape[is_t]:\n lin = Lineage(\n res,\n names=[f\"{fname} of {', '.join(array.names)}\"],\n colors=[\"grey\"],\n )\n\n if res.shape[1] == array.shape[1 - is_t]:\n lin = Lineage(\n res, names=[f\"{fname} of {n}\" for n in array.names], colors=array.colors\n )\n\n if lin is not None:\n return lin.T if is_t else lin\n\n raise RuntimeError(\n f\"Unable to interpret result of function `{fname}` called \"\n f\"with args `{args}`, kwargs: `{kwargs}`.\"\n )\n\n params = signature(numpy_func).parameters\n if \"axis\" in params:\n axis_ix = list(params.keys()).index(\"axis\") - 1\n default_axis = params[\"axis\"].default\n else:\n axis_ix = 256\n default_axis = None\n assert (\n axis_ix >= 0\n ), f\"Expected argument `'axis'` not to be first for function `{numpy_func.__name__}`.\"\n\n fname = numpy_func.__name__\n if fname == \"amin\":\n fname = \"min\"\n elif fname == \"amax\":\n fname = \"max\"\n\n return decorator\n\n\ndef _register_handled_functions():\n handled_fns = {}\n\n for attrname in dir(np):\n fn = getattr(np, attrname)\n if isinstance(fn, FunctionType):\n try:\n sig = signature(fn)\n if \"axis\" in sig.parameters.keys():\n handled_fns[fn] = wrap(fn)\n except ValueError:\n pass\n\n handled_fns.pop(np.expand_dims, None)\n\n handled_fns[np.allclose] = wrap(np.allclose)\n handled_fns[np.array_repr] = wrap(np.array_repr)\n handled_fns[entropy] = wrap(entropy) # qol change\n\n return handled_fns\n\n\n_HANDLED_FUNCTIONS = _register_handled_functions()\n\n\nclass LineageMeta(type):\n \"\"\"\n Metaclass for Lineaage.\n\n Registers functions which are handled by us and overloads common attributes, such as `.sum` with these functions.\n \"\"\"\n\n __overloaded_functions__ = dict( # noqa\n sum=np.sum,\n mean=np.mean,\n min=np.min,\n argmin=np.argmin,\n max=np.max,\n argmax=np.argmax,\n std=np.std,\n var=np.var,\n sort=np.sort,\n squeeze=np.squeeze,\n entropy=entropy,\n )\n\n def __new__(cls, clsname, superclasses, attributedict): # noqa\n res = type.__new__(cls, clsname, superclasses, attributedict)\n for attrname, fn in LineageMeta.__overloaded_functions__.items():\n wrapped_fn = _HANDLED_FUNCTIONS.get(fn, None)\n if wrapped_fn:\n setattr(res, attrname, wrapped_fn)\n\n return res\n\n\nclass Lineage(np.ndarray, metaclass=LineageMeta):\n \"\"\"\n Lightweight :class:`numpy.ndarray` wrapper that adds names and colors.\n\n Parameters\n ----------\n input_array\n Input array containing lineage probabilities, each lineage being stored in a column.\n names\n Names of the lineages.\n colors\n Colors of the lineages.\n \"\"\"\n\n def __new__(\n cls,\n input_array: np.ndarray,\n *,\n names: Iterable[str],\n colors: Optional[Iterable[ColorLike]] = None,\n ) -> \"Lineage\":\n \"\"\"Create and return a new object.\"\"\"\n\n if not isinstance(input_array, np.ndarray):\n raise TypeError(\n f\"Input array must be of type `numpy.ndarray`, found `{type(input_array).__name__!r}`.\"\n )\n\n if input_array.ndim == 1:\n input_array = np.expand_dims(input_array, -1)\n elif input_array.ndim > 2:\n raise ValueError(\n f\"Input array must be 2-dimensional, found `{input_array.ndim}`.\"\n )\n\n if input_array.shape[0] == 0:\n raise ValueError(\"Expected number cells to be at least 1, found 0.\")\n if input_array.shape[1] == 0:\n raise ValueError(\"Expected number of lineages to be at least 1, found 0.\")\n\n obj = np.array(input_array, copy=True).view(cls)\n obj._n_lineages = obj.shape[1]\n obj._is_transposed = False\n obj.names = names # these always create a copy, which is a good thing\n obj.colors = colors\n\n return obj\n\n def __array_finalize__(self, obj) -> None:\n if obj is None:\n return\n\n _names = getattr(obj, \"_names\", None)\n if _names is not None:\n self._names = _names\n self._n_lineages = len(_names)\n self._names_to_ixs = {n: i for i, n in enumerate(self.names)}\n else:\n self._names = None\n self._names_to_ixs = None\n self._n_lineages = getattr(\n obj, \"_n_lineages\", obj.shape[1] if obj.ndim == 2 else 0\n )\n\n self._colors = getattr(obj, \"colors\", None)\n self._is_transposed = getattr(obj, \"_is_transposed\", False)\n\n def _mixer(self, rows, mixtures):\n def update_entries(key):\n if key:\n res.append(self[rows, key].X.sum(1))\n # item = (key, rows) if self._is_transposed else (rows, key)\n # res.append(self[item].X.sum(int(not self._is_transposed)))\n names.append(\" or \".join(self.names[key]))\n colors.append(_compute_mean_color(self.colors[key]))\n\n lin_kind = [_ for _ in mixtures if isinstance(_, Lin)]\n if len(lin_kind) > 1:\n raise ValueError(\n f\"`Lin` enum is allowed only once in the expression, found `{len(lin_kind)}`.\"\n )\n\n keys = [\n tuple(\n self._maybe_convert_names(\n _convert_lineage_name(mixture), default=mixture\n )\n )\n if isinstance(mixture, str)\n else (mixture,)\n for mixture in mixtures\n if not (isinstance(mixture, Lin))\n ]\n keys = _unique_order_preserving(keys)\n\n # check the `keys` are unique\n overlap = [set(ks) for ks in keys]\n for c1, c2 in combinations(overlap, 2):\n overlap = c1 & c2\n if overlap:\n raise ValueError(\n f\"Found overlapping keys: `{self.names[list(overlap)]}`.\"\n )\n\n seen = set()\n names, colors, res = [], [], []\n for key in map(list, keys):\n seen.update(self.names[key])\n update_entries(key)\n\n if len(lin_kind) == 1:\n lin_kind = lin_kind[0]\n keys = [i for i, n in enumerate(self.names) if n not in seen]\n\n if lin_kind == Lin.OTHERS:\n for key in keys:\n update_entries([key])\n elif lin_kind == Lin.REST:\n update_entries(keys)\n if keys:\n names[-1] = str(lin_kind)\n else:\n raise NotImplementedError(\n f\"Mixing `{lin_kind}` is not yet implemented.\"\n )\n\n res = np.stack(res, axis=-1)\n return Lineage(res, names=names, colors=colors)\n\n def __getitem__(self, item) -> \"Lineage\":\n was_transposed = False\n if self._is_transposed:\n was_transposed = True\n self = self.T\n if isinstance(item, tuple):\n item = item[::-1]\n\n obj = self.__getitem(item)\n\n return obj.T if was_transposed else obj\n\n def __getitem(self, item):\n if isinstance(item, tuple):\n if len(item) > 2:\n raise ValueError(\n f\"Expected key to be of length `2`, found `{len(item)}`.\"\n )\n\n item = list(item)\n if item[0] is Ellipsis or item[0] is None:\n item[0] = range(self.shape[0])\n if len(item) == 2 and (item[1] is Ellipsis or item[1] is None):\n item[1] = range(self.shape[1])\n item = tuple(item)\n\n is_tuple_len_2 = (\n isinstance(item, tuple)\n and len(item) == 2\n and isinstance(\n item[0], (int, np.integer, range, slice, tuple, list, np.ndarray)\n )\n )\n if is_tuple_len_2:\n rows, col = item\n\n if isinstance(col, (int, np.integer, str)):\n col = [col]\n\n try:\n # slicing an array where row/col are like 2D indices\n if 1 < len(col) == len(rows) and len(rows) == self.shape[0]:\n col = self._maybe_convert_names(col, make_unique=False)\n return Lineage(\n # never remove this expand_dims - it's critical\n np.expand_dims(self.X[rows, col], axis=-1),\n names=[\"mixture\"],\n colors=[\"#000000\"],\n )\n except TypeError: # because of range\n pass\n\n if isinstance(col, (list, tuple, np.ndarray)):\n if any(\n map(\n lambda i: isinstance(i, Lin)\n or (isinstance(i, str) and (\",\" in i or \"or\" in i)),\n col,\n )\n ):\n return self._mixer(rows, col)\n col = self._maybe_convert_names(col)\n item = rows, col\n else:\n if isinstance(item, (int, np.integer, str)):\n item = [item]\n\n col = range(len(self.names))\n if isinstance(item, (tuple, list, np.ndarray)):\n if any(\n map(\n lambda i: isinstance(i, Lin)\n or (isinstance(i, str) and (\",\" in i or \"or\" in i)),\n item,\n )\n ):\n return self._mixer(slice(None, None, None), item)\n elif any(map(lambda i: isinstance(i, str), item)):\n item = (slice(None, None, None), self._maybe_convert_names(item))\n col = item[1]\n\n shape, row_order, col_order = None, None, None\n if (\n is_tuple_len_2\n and not isinstance(item[0], slice)\n and not isinstance(item[1], slice)\n ):\n item_0 = (\n np.array(item[0]) if not isinstance(item[0], np.ndarray) else item[0]\n )\n item_1 = (\n np.array(item[1]) if not isinstance(item[1], np.ndarray) else item[1]\n )\n item_0 = _at_least_2d(item_0, -1)\n item_1 = _at_least_2d(item_1, 0)\n\n if item_1.dtype == bool:\n if item_0.dtype != bool:\n if not issubclass(item_0.dtype.type, np.integer):\n raise TypeError(f\"Invalid type `{item_0.dtype.type}`.\")\n row_order = (\n item_0[:, 0]\n if item_0.shape[0] == self.shape[0]\n else np.argsort(np.argsort(item_0[:, 0]))\n )\n item_0 = _at_least_2d(np.isin(np.arange(self.shape[0]), item_0), -1)\n item = item_0 * item_1\n shape = np.max(np.sum(item, axis=0)), np.max(np.sum(item, axis=1))\n col = np.where(np.all(item_1, axis=0))[0]\n elif item_0.dtype == bool:\n if item_1.dtype != bool:\n if not issubclass(item_1.dtype.type, np.integer):\n raise TypeError(f\"Invalid type `{item_1.dtype.type}`.\")\n col_order = (\n item_1[0, :]\n if item_1.shape[1] == self.shape[1]\n else np.argsort(np.argsort(item_1[0, :]))\n )\n item_1 = _at_least_2d(np.isin(np.arange(self.shape[1]), item_1), 0)\n\n item = item_0 * item_1\n shape = np.max(np.sum(item, axis=0)), np.max(np.sum(item, axis=1))\n col = np.where(np.all(item_1, axis=0))[0]\n else:\n item = (item_0, item_1)\n\n obj = super().__getitem__(item)\n\n if shape is not None: # keep the resulting shape\n obj = obj.reshape(shape)\n if row_order is not None:\n obj = obj[row_order, :]\n if col_order is not None:\n obj = obj[:, col_order]\n\n if isinstance(obj, Lineage):\n obj._names = np.atleast_1d(self.names[col])\n obj._colors = np.atleast_1d(self.colors[col])\n if col_order is not None:\n obj._names = obj._names[col_order]\n obj._colors = obj._colors[col_order]\n obj._names_to_ixs = {name: i for i, name in enumerate(obj._names)}\n\n return obj\n\n def __array_function__(self, func, types, args, kwargs):\n if func not in _HANDLED_FUNCTIONS:\n return NotImplemented\n # Note: this allows subclasses that don't override\n # __array_function__ to handle MyArray objects\n if not all(issubclass(t, type(self)) for t in types):\n return NotImplemented\n\n return _HANDLED_FUNCTIONS[func](*args, **kwargs)\n\n @property\n def names(self) -> np.ndarray:\n \"\"\"Lineage names. Must be unique.\"\"\"\n return self._names\n\n @names.setter\n def names(self, value: Iterable[str]):\n if not isinstance(value, Iterable):\n raise TypeError(_ERROR_NOT_ITERABLE.format(\"names\", type(value).__name__))\n\n value = [v if isinstance(v, str) else str(v) for v in value]\n value = self._check_shape(value, _ERROR_WRONG_SIZE.format(\"names\"))\n\n if len(set(value)) != len(value):\n raise ValueError(f\"Not all lineage names are unique: `{value}`.\")\n\n self._names = self._prepare_annotation(value)\n self._names_to_ixs = {name: ix for ix, name in enumerate(self.names)}\n\n @property\n def colors(self) -> np.ndarray:\n \"\"\"Lineage colors.\"\"\"\n return self._colors\n\n @colors.setter\n def colors(self, value: Optional[Iterable[ColorLike]]):\n if value is None:\n value = _create_categorical_colors(self._n_lineages)\n elif not isinstance(value, Iterable):\n raise TypeError(_ERROR_NOT_ITERABLE.format(\"colors\", type(value).__name__))\n\n value = self._check_shape(value, _ERROR_WRONG_SIZE.format(\"colors\"))\n self._colors = self._prepare_annotation(\n value,\n checker=c.is_color_like,\n transformer=c.to_hex,\n checker_msg=\"Value `{}` is not a valid color.\",\n )\n\n def _maybe_convert_names(\n self,\n names: Iterable[Union[int, str, bool]],\n is_singleton: bool = False,\n default: Optional[Union[int, str]] = None,\n make_unique: bool = True,\n ) -> Union[int, List[int], List[bool]]:\n if all(map(lambda n: isinstance(n, (bool, np.bool_)), names)):\n return list(names)\n res = []\n for name in names:\n if isinstance(name, str):\n if name in self._names_to_ixs:\n name = self._names_to_ixs[name]\n elif default is not None:\n if isinstance(default, str):\n if default not in self._names_to_ixs:\n raise KeyError(\n f\"Invalid lineage name: `{name}`. \"\n f\"Valid names are: `{list(self.names)}`.\"\n )\n name = self._names_to_ixs[default]\n else:\n name = default\n else:\n raise KeyError(\n f\"Invalid lineage name `{name}`. \"\n f\"Valid names are: `{list(self.names)}`.\"\n )\n res.append(name)\n\n if make_unique:\n res = _unique_order_preserving(res)\n\n return res[0] if is_singleton else res\n\n def _check_shape(\n self, array: Iterable[Union[str, ColorLike]], msg: str\n ) -> List[Union[str, ColorLike]]:\n array = list(array)\n if len(array) != self._n_lineages:\n raise ValueError(msg.format(self._n_lineages, len(array)))\n\n return array\n\n def _prepare_annotation(\n self,\n array: List[str],\n checker: Optional[Callable] = None,\n transformer: Optional[Callable] = None,\n checker_msg: Optional[str] = None,\n ) -> np.ndarray:\n if checker:\n assert checker_msg, \"Please provide a message when `checker` is not `None`.\"\n for v in array:\n if not checker(v):\n raise ValueError(checker_msg.format(v))\n\n if transformer is not None:\n array = np.array([transformer(v) for v in array])\n\n return np.array(array)\n\n @property\n def X(self) -> np.ndarray:\n \"\"\"Convert self to numpy array, losing names and colors.\"\"\"\n return np.array(self, copy=False)\n\n @property\n def T(self):\n \"\"\"Transpose of self.\"\"\"\n obj = self.transpose()\n obj._is_transposed = not self._is_transposed\n return obj\n\n def view(self, dtype=None, type=None) -> \"LineageView\":\n \"\"\"Return a view of self.\"\"\"\n return LineageView(self)\n\n def __repr__(self) -> str:\n return f'{super().__repr__()[:-1]},\\n names([{\", \".join(self.names)}]))'\n\n def __str__(self):\n return f'{super().__str__()}\\n names=[{\", \".join(self.names)}]'\n\n @property\n def _fmt(self) -> Callable:\n if np.issubdtype(self.dtype, float):\n return \"{:.06f}\".format\n return \"{}\".format\n\n def _repr_html_(self) -> str:\n def format_row(r):\n rng = (\n range(self.shape[1])\n if not self._is_transposed\n or (self._is_transposed and self.shape[1] <= _HTML_REPR_THRESH)\n else list(range(_HT_CELLS))\n + [...]\n + list(range(self.shape[1] - _HT_CELLS - 1, self.shape[1] - 1))\n )\n\n cells = \"\".join(\n f\"\" f\"{self._fmt(self.X[r, c])}\" f\"\"\n if isinstance(c, int)\n else _DUMMY_CELL\n for c in rng\n )\n return f\"{(names[r] if self._is_transposed else '') + cells}\"\n\n def dummy_row():\n values = \"\".join(_DUMMY_CELL for _ in range(self.shape[1]))\n return f\"{values}\"\n\n if self.names is None or self.colors is None:\n raise RuntimeError(\n f\"Name or colors are `None`. This can happen when running `array.view({type(self).__name__}`.\"\n )\n\n if self.ndim != 2:\n return repr(self)\n\n styles = [\n f\"'background-color: {bg}; color: {fg}; text-align: center; word-wrap: break-word; max-width: 100px'\"\n for bg, fg in map(_get_bg_fg_colors, self.colors)\n ]\n names = [f\"{n}\" for n, style in zip(self.names, styles)]\n header = f\"{''.join(names)}\"\n\n if self.shape[0] > _HTML_REPR_THRESH:\n body = \"\".join(format_row(i) for i in range(_HT_CELLS))\n body += dummy_row()\n body += \"\".join(\n format_row(i)\n for i in range(self.shape[0] - _HT_CELLS - 1, self.shape[0] - 1)\n )\n else:\n body = \"\".join(format_row(i) for i in range(self.shape[0]))\n\n cells = \"cells\" if self.shape[0] > 1 else \"cell\"\n lineages = \"lineages\" if self.shape[1] > 1 else \"lineage\"\n if self._is_transposed:\n cells, lineages = lineages, cells\n metadata = f\"

{self.shape[0]} {cells} x {self.shape[1]} {lineages}

\"\n\n if self._is_transposed:\n header = \"\"\n return (\n f\"
\"\n f\"{header}{body}
{metadata}\"\n f\"
\"\n )\n\n def __format__(self, format_spec):\n if self.shape == (1, 1):\n return format_spec.format(self.X[0, 0])\n if self.shape == (1,):\n return format_spec.format(self.X[0])\n return NotImplemented\n\n def __setstate__(self, state):\n *state, names, colors, is_t = state\n names = names[-1]\n colors = colors[-1]\n\n self._names = np.empty(names[1])\n self._colors = np.empty(colors[1])\n\n super().__setstate__(tuple(state))\n self._names.__setstate__(tuple(names))\n self._colors.__setstate__(tuple(colors))\n\n self._is_transposed = is_t\n self._n_lineages = len(self.names)\n self._names_to_ixs = {name: ix for ix, name in enumerate(self.names)}\n\n def __reduce__(self):\n res = list(super().__reduce__())\n\n names = self.names.__reduce__()\n colors = self.colors.__reduce__()\n res[-1] += (names, colors, self._is_transposed)\n\n return tuple(res)\n\n def copy(self, _=\"C\") -> \"Lineage\":\n \"\"\"Return a copy of itself.\"\"\"\n obj = Lineage(\n self.T if self._is_transposed else self,\n names=np.array(self.names, copy=True, order=_ORDER),\n colors=np.array(self.colors, copy=True, order=_ORDER),\n )\n return obj.T if self._is_transposed else obj\n\n def __copy__(self):\n return self.copy()\n\n @d.get_full_description(base=\"lin_pd\")\n @d.get_sections(base=\"lin_pd\", sections=[\"Parameters\", \"Returns\"])\n def priming_degree(\n self,\n method: Literal[\"kl_divergence\", \"entropy\"] = \"kl_divergence\",\n early_cells: Optional[np.ndarray] = None,\n ) -> np.ndarray:\n \"\"\"\n Compute the degree of lineage priming.\n\n It returns a score in `[0, 1]` where `0` stands for naive and `1` stands for committed.\n\n Parameters\n ----------\n method\n The method used to compute the degree of lineage priming. Valid options are:\n\n - `'kl_divergence'` - as in :cite:`velten:17`, computes KL-divergence between the fate probabilities of\n a cell and the average fate probabilities. Computation of average fate probabilities can be restricted\n to a set of user-defined ``early_cells``.\n - `'entropy'` - as in :cite:`setty:19`, computes entropy over a cell's fate probabilities.\n early_cells\n Cell IDs or a mask marking early cells. If `None`, use all cells.\n Only used when ``method = 'kl_divergence'``.\n\n Returns\n -------\n The priming degree.\n \"\"\"\n early_cells = (\n np.ones((len(self),), dtype=np.bool_)\n if early_cells is None\n else np.asarray(early_cells)\n )\n if not np.issubdtype(early_cells.dtype, np.bool_):\n early_cells = np.unique(early_cells)\n\n method = PrimingDegree(method)\n probs = self.X\n early_subset = probs[early_cells, :]\n if not len(early_subset):\n raise ValueError(\"No early cells have been specified.\")\n\n with np.errstate(divide=\"ignore\", invalid=\"ignore\"):\n if method == PrimingDegree.KL_DIVERGENCE:\n probs = np.nan_to_num(\n np.sum(\n probs * np.log2(probs / np.mean(early_subset, axis=0)), axis=1\n ),\n nan=1.0,\n copy=False,\n )\n elif method == PrimingDegree.ENTROPY:\n probs = entropy(probs, axis=1)\n probs = np.max(probs) - probs\n else:\n raise NotImplementedError(f\"Method `{method}` is not yet implemented\")\n\n minn, maxx = np.min(probs), np.max(probs)\n return (probs - minn) / (maxx - minn)\n\n @d.dedent\n def plot_pie(\n self,\n reduction: Callable,\n title: Optional[str] = None,\n legend_loc: Optional[str] = \"on data\",\n legend_kwargs: Mapping = MappingProxyType({}),\n figsize: Optional[Tuple[float, float]] = None,\n dpi: Optional[float] = None,\n save: Optional[Union[Path, str]] = None,\n **kwargs,\n ) -> None:\n \"\"\"\n Plot a pie chart visualizing aggregated lineage probabilities.\n\n Parameters\n ----------\n reduction\n Function that will be applied lineage-wise.\n title\n Title of the figure.\n legend_loc\n Location of the legend. If `None`, it is not shown.\n legend_kwargs\n Keyword arguments for :func:`matplotlib.axes.Axes.legend`.\n %(plotting)s\n\n Returns\n -------\n %(just_plots)s\n \"\"\"\n\n if len(self.names) == 1:\n raise ValueError(\"Cannot plot pie chart for only 1 lineage.\")\n\n fig, ax = plt.subplots(figsize=figsize, dpi=dpi)\n\n if \"autopct\" not in kwargs:\n autopct_found = False\n autopct = (\n \"{:.1f}%\".format\n ) # we don't really care, we don't shot the pct, but the value\n else:\n autopct_found = True\n autopct = kwargs.pop(\"autopct\")\n\n if title is None:\n title = reduction.__name__ if hasattr(reduction, \"__name__\") else None\n\n reduction = reduction(self, axis=int(self._is_transposed)).X.squeeze()\n reduction_norm = reduction / np.sum(reduction)\n\n wedges, texts, *autotexts = ax.pie(\n reduction_norm.squeeze(),\n labels=self.names if legend_loc == \"on data\" else None,\n autopct=autopct,\n wedgeprops={\"edgecolor\": \"w\"},\n colors=self.colors,\n **kwargs,\n )\n\n # if autopct is not None\n if len(autotexts):\n autotexts = autotexts[0]\n for name, at in zip(self.names, autotexts):\n ix = self._names_to_ixs[name]\n at.set_color(_get_bg_fg_colors(self.colors[ix])[1])\n if not autopct_found:\n at.set_text(f\"{reduction[ix]:.4f}\")\n\n if legend_loc not in (None, \"none\", \"on data\"):\n ax.legend(\n wedges,\n self.names,\n title=\"lineages\",\n loc=legend_loc,\n **legend_kwargs,\n )\n\n ax.set_title(title)\n ax.set_aspect(\"equal\")\n\n if save is not None:\n save_fig(fig, save)\n\n @d.dedent\n @inject_docs(m=Reduction, dm=DistanceMeasure, nw=NormWeights)\n def reduce(\n self,\n *keys: str,\n mode: Literal[\"dist\", \"scale\"] = Reduction.DIST,\n dist_measure: Literal[\n \"cosine_sim\", \"wasserstein_dist\", \"kl_div\", \"js_div\", \"mutual_info\", \"equal\"\n ] = DistanceMeasure.MUTUAL_INFO,\n normalize_weights: Literal[\"scale\", \"softmax\"] = NormWeights.SOFTMAX,\n softmax_scale: float = 1,\n return_weights: bool = False,\n ) -> Union[\"Lineage\", Tuple[\"Lineage\", Optional[pd.DataFrame]]]:\n \"\"\"\n Subset states and normalize them so that they again sum to 1.\n\n Parameters\n ----------\n keys\n List of keys that define the states, to which this object will be reduced by projecting the values\n of the other states.\n mode\n Reduction mode to use. Valid options are:\n\n - `{m.DIST!r}` - use a distance measure ``dist_measure`` to compute weights.\n - `{m.SCALE!r}` - just rescale the values.\n dist_measure\n Used to quantify similarity between query and reference states. Valid options are:\n\n - `{dm.COSINE_SIM!r}` - cosine similarity.\n - `{dm.WASSERSTEIN_DIST!r}` - Wasserstein distance.\n - `{dm.KL_DIV!r}` - Kullback–Leibler divergence.\n - `{dm.JS_DIV!r}` - Jensen–Shannon divergence.\n - `{dm.MUTUAL_INFO!r}` - mutual information.\n - `{dm.EQUAL!r}` - equally redistribute the mass among the rest.\n\n Only use when ``mode = {m.DIST!r}``.\n normalize_weights\n How to row-normalize the weights. Valid options are:\n\n - `{nw.SCALE!r}` - divide by the sum.\n - `{nw.SOFTMAX!r}`- use a softmax.\n\n Only use when ``mode = {m.DIST!r}``.\n softmax_scale\n Scaling factor in the softmax, used for normalizing the weights to sum to `1`.\n return_weights\n If `True`, a :class:`pandas.DataFrame` of the weights used for the projection is also returned.\n If ``mode = {m.SCALE!r}``, the weights will be `None`.\n\n Returns\n -------\n The lineage object, reduced to the %(initial_or_terminal)s states.\n The weights used for the projection of shape ``(n_query, n_reference)``, if ``return_weights = True``.\n \"\"\"\n\n mode = Reduction(mode)\n dist_measure = DistanceMeasure(dist_measure)\n normalize_weights = NormWeights(normalize_weights)\n\n if self._is_transposed:\n raise RuntimeError(\"This method works only on non-transposed lineages.\")\n\n if not len(keys):\n raise ValueError(\"Unable to perform the reduction, no keys specified.\")\n\n # check the lineage object\n if not np.allclose(np.sum(self, axis=1).X, 1.0):\n raise ValueError(\"Memberships do not sum to one row-wise.\")\n\n if len(keys) == 1:\n tmp = self[:, keys]\n return Lineage(\n np.ones((self.shape[0], 1), dtype=self.dtype),\n names=tmp.names,\n colors=tmp.colors,\n )\n\n # check input parameters\n if return_weights and mode == Reduction.SCALE:\n logg.warning(\n f\"If `mode={mode!r}`, no weights are computed. Returning `None`\"\n )\n\n reference = self[:, keys]\n rest = [\n k for k in self.names if all(map(lambda rk: k not in rk, reference.names))\n ]\n if not len(rest):\n logg.warning(\n \"Unable to perform reduction because all keys have been selected. Returning combined object only\"\n )\n return (reference.copy(), None) if return_weights else reference.copy()\n\n query = self[:, rest]\n\n if mode == Reduction.SCALE:\n reference = _row_normalize(reference)\n elif mode == Reduction.DIST:\n # compute a set of weights of shape (n_query x n_reference)\n if dist_measure == DistanceMeasure.COSINE_SIM:\n weights = _cosine_sim(reference.X, query.X)\n elif dist_measure == DistanceMeasure.WASSERSTEIN_DIST:\n weights = _wasserstein_dist(reference.X, query.X)\n elif dist_measure == DistanceMeasure.KL_DIV:\n weights = _kl_div(reference.X, query.X)\n elif dist_measure == DistanceMeasure.JS_DIV:\n weights = _js_div(reference.X, query.X)\n elif dist_measure == DistanceMeasure.MUTUAL_INFO:\n weights = _mutual_info(reference.X, query.X)\n elif dist_measure == DistanceMeasure.EQUAL:\n weights = _row_normalize(np.ones((query.shape[1], reference.shape[1])))\n else:\n raise NotImplementedError(\n f\"Distance measure `{dist_measure}` is not yet implemented.\"\n )\n\n # make some checks on the weights\n if weights.shape != (query.shape[1], reference.shape[1]):\n raise ValueError(\n f\"Expected weight matrix to be of shape `({query.shape[1]}, {reference.shape[1]})`, \"\n f\"found `{weights.shape}`.\"\n )\n if not np.isfinite(weights).all():\n raise ValueError(\n \"Weights matrix contains elements that are not finite.\"\n )\n if (weights < 0).any():\n raise ValueError(\"Weights matrix contains negative elements.\")\n\n if (weights == 0).any():\n logg.warning(\"Weights matrix contains exact zeros.\")\n\n # normalize the weights to row-sum to one\n if normalize_weights == NormWeights.SCALE:\n weights_n = _row_normalize(weights)\n elif normalize_weights == NormWeights.SOFTMAX:\n weights_n = _softmax(_row_normalize(weights), softmax_scale)\n else:\n raise NotImplementedError(\n f\"Normalization method `{normalize_weights}` is yet implemented.\"\n )\n\n # check that the weights row-sum to one now\n if not np.allclose(weights_n.sum(1), 1.0):\n raise ValueError(\"Weights do not sum to 1 row-wise.\")\n\n # use the weights to re-distribute probability mass form query to reference\n for i, w in enumerate(weights_n):\n reference += np.dot(query[:, i].X, w[None, :])\n else:\n raise NotImplementedError(\n f\"Reduction mode `{mode}` is not yet implemented.\"\n )\n\n # check that the lineages row-sum to one now\n if not np.allclose(reference.sum(1), 1.0):\n raise ValueError(\"Reduced lineage rows do not sum to 1.\")\n\n # potentially create a weights-df and return everything\n if return_weights:\n if mode == Reduction.DIST:\n return (\n reference,\n pd.DataFrame(\n data=weights_n, columns=reference.names, index=query.names\n ),\n )\n return reference, None\n\n return reference\n\n @classmethod\n @d.dedent\n @inject_docs(lk=LinKind)\n def from_adata(\n cls,\n adata: AnnData,\n backward: bool = False,\n kind: Literal[\"macrostates\", \"term_states\", \"abs_probs\"] = LinKind.ABS_PROBS,\n ) -> \"Lineage\":\n \"\"\"\n Reconstruct :class:`cellrank.tl.Lineage` from :class:`anndata.AnnData`.\n\n Parameters\n ----------\n %(adata)s\n %(backward)s\n kind\n Which kind of object to reconstruct. Valid options are:\n\n - `{lk.MACROSTATES!r}`- macrostates memberships from :class:`cellrank.tl.estimators.GPCCA`.\n - `{lk.TERM_STATES!r}`- terminal states memberships from :class:`cellrank.tl.estimators.GPCCA`.\n - `{lk.ABS_PROBS!r}`- the absorption probabilities.\n\n Returns\n -------\n The reconstructed lineage object.\n \"\"\"\n kind = LinKind(kind)\n if kind == LinKind.MACROSTATES:\n nkey = Key.obs.macrostates(backward)\n key = Key.obsm.memberships(nkey)\n elif kind == LinKind.TERM_STATES:\n nkey = Key.obs.term_states(backward)\n key = Key.obsm.memberships(nkey)\n elif kind == LinKind.ABS_PROBS:\n nkey = Key.obs.term_states(backward)\n key = Key.obsm.abs_probs(backward)\n else:\n raise NotImplementedError(f\"Lineage kind `{kind}` is not yet implemented.\")\n\n ckey = Key.uns.colors(nkey)\n\n data: Optional[Union[np.ndarray, Lineage]] = copy(adata.obsm.get(key, None))\n if data is None:\n raise KeyError(f\"Unable to find lineage data in `adata.obsm[{key!r}]`.\")\n if isinstance(data, Lineage):\n return data\n if data.ndim != 2:\n raise ValueError(f\"Expected 2 dimensional data, found `{data.ndim}`.\")\n\n states = adata.obs.get(nkey, None)\n if states is None:\n logg.warning(\n f\"Unable to find states in `adata.obs[{nkey!r}]`. Using default names\"\n )\n elif not is_categorical_dtype(states):\n logg.warning(\n f\"Expected `adata.obs[{key!r}]` to be `categorical`, \"\n f\"found `{infer_dtype(adata.obs[nkey])}`. Using default names\"\n )\n else:\n states = list(states.cat.categories)\n if len(states) != data.shape[1]:\n logg.warning(\n f\"Expected to find `{data.shape[1]}` names, found `{len(states)}`. \"\n f\"Using default names\"\n )\n if states is None or len(states) != data.shape[1]:\n states = [str(i) for i in range(data.shape[1])]\n\n colors = adata.uns.get(ckey, None)\n if colors is None:\n logg.warning(\n f\"Unable to find colors in `adata.uns[{ckey!r}]`. \"\n f\"Using default colors\"\n )\n elif len(colors) != data.shape[1]:\n logg.warning(\n f\"Expected to find `{data.shape[1]}` colors, found `{len(colors)}`. \"\n f\"Using default colors\"\n )\n colors = None\n\n return Lineage(data, names=states, colors=colors)\n\n\nclass LineageView(Lineage):\n \"\"\"View of :class:`cellrank.tl.Lineage`.\"\"\"\n\n def __new__(cls, lineage: Lineage) -> \"LineageView\":\n \"\"\"Create a LineageView.\"\"\"\n if not isinstance(lineage, Lineage):\n raise TypeError(\n f\"Cannot create a `{cls.__name__}` of `{type(lineage).__name__}`.\"\n )\n\n view = np.array(lineage, copy=False).view(cls)\n view._owner = lineage\n view._names = lineage.names\n view._n_lineages = len(view.names)\n view._names_to_ixs = lineage._names_to_ixs\n view._colors = lineage.colors\n view._is_transposed = lineage._is_transposed\n\n return view\n\n @property\n def names(self) -> np.ndarray:\n \"\"\"Lineage names.\"\"\"\n return super().names\n\n @property\n def owner(self) -> Lineage:\n \"\"\"Return the lineage associated with this view.\"\"\"\n return self._owner\n\n @names.setter\n def names(self, _):\n raise RuntimeError(f\"Unable to set names of `{type(self).__name__}`.\")\n\n @property\n def colors(self) -> np.ndarray:\n \"\"\"Lineage colors.\"\"\"\n return super().colors\n\n @colors.setter\n def colors(self, _):\n raise RuntimeError(f\"Unable to set colors of `{type(self).__name__}`.\")\n\n def view(self, dtype=None, type=None) -> \"LineageView\":\n \"\"\"Return self.\"\"\"\n return self\n\n def copy(self, _=\"C\") -> Lineage:\n \"\"\"Return a copy of itself.\"\"\"\n was_trasposed = False\n if self._is_transposed:\n self = self.T\n was_trasposed = True\n\n obj = Lineage(\n self,\n names=np.array(self.names, copy=True, order=_ORDER),\n colors=np.array(self.colors, copy=True, order=_ORDER),\n )\n return obj.T if was_trasposed else obj\n\n\ndef _remove_zero_rows(a: np.ndarray, b: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:\n if a.shape[0] != b.shape[0]:\n raise ValueError(\"Lineage objects have unequal cell numbers\")\n\n bool_a = (a == 0).any(axis=1)\n bool_b = (b == 0).any(axis=1)\n mask = ~np.logical_or(bool_a, bool_b)\n\n logg.warning(\n f\"Removed {a.shape[0] - np.sum(mask)} rows because they contained zeros\"\n )\n\n return a[mask, :], b[mask, :]\n\n\ndef _softmax(X, beta: float = 1):\n return np.exp(X * beta) / np.expand_dims(np.sum(np.exp(X * beta), axis=1), -1)\n\n\ndef _row_normalize(X):\n if isinstance(X, Lineage):\n return X / X.sum(1) # Lineage is shape-preserving\n return X / np.expand_dims(X.sum(1), -1)\n\n\ndef _col_normalize(X, norm_ord=2):\n from numpy.linalg import norm\n\n return X / norm(X, ord=norm_ord, axis=0)\n\n\ndef _cosine_sim(reference, query):\n # the cosine similarity is symmetric\n\n # normalize these to have 2-norm 1\n reference_n, query_n = _col_normalize(reference, 2), _col_normalize(query, 2)\n\n return (reference_n.T @ query_n).T\n\n\ndef _point_wise_distance(reference, query, distance):\n # utility function for all point-wise distances/divergences\n # take care of rows that contain zeros\n reference_no_zero, query_no_zero = _remove_zero_rows(reference, query)\n\n # normalize these to be valid probability distributions (column-wise)\n reference_n, query_n = (\n _col_normalize(reference_no_zero, 1),\n _col_normalize(query_no_zero, 1),\n )\n\n # loop over query and reference columns and compute pairwise wasserstein distances\n weights = np.zeros((query.shape[1], reference.shape[1]))\n for i, q_d in enumerate(query_n.T):\n for j, r_d in enumerate(reference_n.T):\n weights[i, j] = 1.0 / distance(q_d, r_d)\n\n return weights\n\n\ndef _wasserstein_dist(reference, query):\n # the wasserstein distance is symmetric\n from scipy.stats import wasserstein_distance\n\n return _point_wise_distance(reference, query, wasserstein_distance)\n\n\ndef _kl_div(reference, query):\n # the KL divergence is not symmetric\n from scipy.stats import entropy\n\n return _point_wise_distance(reference, query, entropy)\n\n\ndef _js_div(reference, query):\n # the js divergence is symmetric\n from scipy.spatial.distance import jensenshannon\n\n return _point_wise_distance(reference, query, jensenshannon)\n\n\ndef _mutual_info(reference, query):\n # mutual information is not symmetric. We don't need to normalise the vectors, it's invariant under scaling.\n from sklearn.feature_selection import mutual_info_regression\n\n weights = np.zeros((query.shape[1], reference.shape[1]))\n for i, target in enumerate(query.T):\n weights[i, :] = mutual_info_regression(reference, target)\n\n return weights\n", "meta": {"hexsha": "d027c35dea69f7e7a40ca1f3cdedf8a7c6462064", "size": 44874, "ext": "py", "lang": "Python", "max_stars_repo_path": "cellrank/tl/_lineage.py", "max_stars_repo_name": "WeilerP/cellrank", "max_stars_repo_head_hexsha": "c8c2b9f6bd2448861fb414435aee7620ca5a0bad", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 172, "max_stars_repo_stars_event_min_datetime": "2020-03-19T19:50:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T09:36:04.000Z", "max_issues_repo_path": "cellrank/tl/_lineage.py", "max_issues_repo_name": "WeilerP/cellrank", "max_issues_repo_head_hexsha": "c8c2b9f6bd2448861fb414435aee7620ca5a0bad", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 702, "max_issues_repo_issues_event_min_datetime": "2020-03-19T08:09:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T09:55:14.000Z", "max_forks_repo_path": "cellrank/tl/_lineage.py", "max_forks_repo_name": "WeilerP/cellrank", "max_forks_repo_head_hexsha": "c8c2b9f6bd2448861fb414435aee7620ca5a0bad", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2020-04-07T03:11:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T20:39:16.000Z", "avg_line_length": 34.3598774885, "max_line_length": 120, "alphanum_fraction": 0.5545973169, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 10307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.2782567937024021, "lm_q1q2_score": 0.1423886217092606}} {"text": "# -*- coding: utf-8 -*-\n\"\"\"\nSVGPATH2MPL\n~~~~~~~~~~~\nParse SVG path definition strings into matplotlib Path objects.\nA path in SVG is defined by a 'path' element which contains a\n``d=\"(path data)\"`` attribute that contains moveto, line, curve (both\ncubic and quadratic Béziers), arc and closepath instructions. See the SVG\nPath specification at .\n\n:copyright: (c) 2016, Nezar Abdennur.\n:license: BSD.\n\n\"\"\"\nfrom __future__ import division, print_function\nfrom math import sin, cos, sqrt, degrees, radians, acos\nimport re\n\nfrom matplotlib.path import Path\nimport matplotlib.transforms as transforms\nimport numpy as np\n\n__version__ = '1.0.0'\n__all__ = ['parse_path']\n\n\nCOMMANDS = set('MmZzLlHhVvCcSsQqTtAa')\nUPPERCASE = set('MZLHVCSQTA')\n\nCOMMAND_RE = re.compile(r\"([MmZzLlHhVvCcSsQqTtAa])\")\nFLOAT_RE = re.compile(r\"[-+]?[0-9]*\\.?[0-9]+(?:[eE][-+]?[0-9]+)?\")\n\nCOMMAND_CODES = {\n 'M': (Path.MOVETO,), # moveto\n 'L': (Path.LINETO,), # line\n 'H': (Path.LINETO,), # shorthand for horizontal line\n 'V': (Path.LINETO,), # shorthand for vertical line\n 'Q': (Path.CURVE3,)*2, # quadratic bezier\n 'T': (Path.CURVE3,)*2, # shorthand for smooth quadratic bezier\n 'C': (Path.CURVE4,)*3, # cubic bezier\n 'S': (Path.CURVE4,)*3, # shorthand for smooth cubic bezier\n 'Z': (Path.CLOSEPOLY,), # closepath\n 'A': None # arc\n}\n\nPARAMS = {\n 'M': 2, # moveto\n 'L': 2, # line\n 'H': 1, # shorthand for horizontal line\n 'V': 1, # shorthand for vertical line\n 'Q': 4, # quadratic bezier\n 'T': 4, # shorthand for smooth quadratic bezier\n 'C': 6, # cubic bezier\n 'S': 6, # shorthand for smooth cubic bezier\n 'Z': 0, # closepath\n 'A': 7 # arc\n}\n\n\ndef endpoint_to_center(start, radius, rotation, large, sweep, end):\n \"\"\"\n Translates the \"endpoint\" parameterization of an elliptical arc used by\n the SVG spec to the \"center\" parameterization.\n\n Parameters\n ----------\n start : complex\n Starting point (x1, y1).\n radius : complex\n Two elliptical radii (rx, ry).\n rotation : float\n Angle from the x-axis of the current coordinate system to the x-axis of\n the ellipse.\n large : bool\n False if an arc spanning < 180 degrees is to be drawn, True if an arc\n spanning >= 180 degrees is to be drawn.\n sweep : bool\n If sweep-flag is True, then the arc will be drawn in a \"positive-angle\"\n direction from start to end.\n end : complex\n End point (x2, y2).\n\n Returns\n -------\n radius : complex\n Radii of the ellipse (rx, ry), potentially corrected if out-of-range.\n center : complex\n Center of the ellipse (xc, yc).\n theta1, theta2 : float\n Start and end angles of an arc on the unit circle prior to being\n stretched and rotated into an elliptical arc.\n\n Notes\n -----\n See [1]_, `svg.path `_, and this\n `SO question `_.\n\n References\n ----------\n\n .. [1] http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes\n\n \"\"\"\n # Step 1: compute x1prim, y1prim\n cosr = cos(radians(rotation))\n sinr = sin(radians(rotation))\n dx = (start.real - end.real) / 2\n dy = (start.imag - end.imag) / 2\n x1prim = cosr * dx + sinr * dy\n y1prim = -sinr * dx + cosr * dy\n x1prim_sq = x1prim * x1prim\n y1prim_sq = y1prim * y1prim\n\n rx = abs(radius.real)\n ry = abs(radius.imag)\n rx_sq = rx * rx\n ry_sq = ry * ry\n\n # Correct out of range radii\n radius_scale = (x1prim_sq / rx_sq) + (y1prim_sq / ry_sq)\n if radius_scale > 1:\n radius_scale = sqrt(radius_scale)\n rx *= radius_scale\n ry *= radius_scale\n rx_sq = rx * rx\n ry_sq = ry * ry\n else:\n # SVG spec only scales UP\n radius_scale = 1\n radius = rx + ry * 1j\n\n # Step 2: compute cxprim, cyprim\n t1 = rx_sq * y1prim_sq\n t2 = ry_sq * x1prim_sq\n c = sqrt(abs((rx_sq * ry_sq - t1 - t2) / (t1 + t2)))\n if large == sweep:\n c = -c\n cxprim = c * rx * y1prim / ry\n cyprim = -c * ry * x1prim / rx\n\n # Step 3: compute the center from cxprim, cyprim\n center = complex(\n (cosr * cxprim - sinr * cyprim) + ((start.real + end.real) / 2),\n (sinr * cxprim + cosr * cyprim) + ((start.imag + end.imag) / 2),\n )\n\n # Step 4: compute theta and delta_theta\n ux = (x1prim - cxprim) / rx\n uy = (y1prim - cyprim) / ry\n vx = (-x1prim - cxprim) / rx\n vy = (-y1prim - cyprim) / ry\n n = sqrt(ux * ux + uy * uy)\n p = ux\n theta = degrees(acos(p / n))\n if uy < 0:\n theta = -theta\n theta = theta % 360\n\n n = sqrt((ux * ux + uy * uy) * (vx * vx + vy * vy))\n p = ux * vx + uy * vy\n d = p / n\n # In certain cases the above calculation can through inaccuracies\n # become just slightly out of range, f ex -1.0000000000000002.\n d = np.clip(d, -1.0, 1.0)\n\n delta = degrees(acos(d))\n if (ux * vy - uy * vx) < 0:\n delta = -delta\n delta = delta % 360\n if not sweep:\n if delta > 0:\n delta -= 360\n\n return radius, center, theta, theta + delta\n\n\ndef arc_path(start, radius, rotation, large, sweep, end):\n \"\"\"\n Generate an elliptical arc path given an endpoint parameterization.\n\n Uses matplotlib to draw the arc using quadratic Bezier curves.\n\n Parameters\n ----------\n start : complex\n Starting point (x1, y1).\n radius : complex\n Two elliptical radii (rx, ry).\n rotation : float\n Angle from the x-axis of the current coordinate system to the x-axis of\n the ellipse.\n large : bool\n False if an arc spanning < 180 degrees is to be drawn, True if an arc\n spanning >= 180 degrees is to be drawn.\n sweep : bool\n If sweep-flag is True, then the arc will be drawn in a \"positive-angle\"\n direction from start to end.\n end : complex\n End point (x2, y2).\n\n Returns\n -------\n codes : array (n,)\n Command codes\n verts : array (n,2)\n Vertices\n\n Notes\n -----\n We first perform a conversion to center parameterization and generate\n a circular arc at the origin. Then we apply scaling, translation and\n rotation.\n\n One can think of an ellipse as a circle that has been stretched and then\n rotated. Start by making an arc along the unit circle from `theta1` to\n `theta2`, centered at `center`. Then scale the circle along the x and y\n axes according to the given radii. Finally, rotate the arc around the\n center through the given angle `rotation`.\n\n \"\"\"\n radius, center, theta1, theta2 = endpoint_to_center(\n start,\n radius,\n rotation,\n large,\n sweep,\n end\n )\n\n # Create an arc on the unit circle\n # Matplotlib does this using CURVE4 operations\n # https://matplotlib.org/stable/_modules/matplotlib/path.html#Path.arc\n if theta2 > theta1:\n arc = Path.arc(theta1=theta1, theta2=theta2)\n reverse_path = False\n else:\n arc = Path.arc(theta1=theta2, theta2=theta1)\n reverse_path = True\n\n # Transform it into an elliptical arc:\n # * scale the minor and major axes\n # * translate it to the center\n # * rotate the x-axis of the ellipse from the x-axis of the current\n # coordinate system\n trans = (\n transforms.Affine2D()\n .scale(radius.real, radius.imag)\n .translate(center.real, center.imag)\n .rotate_deg_around(center.real, center.imag, rotation)\n )\n arc = trans.transform_path(arc)\n codes = np.array(arc.codes)\n verts = np.array(arc.vertices)\n\n # Make sure we are drawing from start to end\n if reverse_path:\n verts = verts[::-1, :]\n\n # Change the initial MOVETO operation into a LINETO to connect to the\n # previous path\n codes[0] = Path.LINETO\n\n return codes, verts\n\n\ndef _tokenize_path(pathdef):\n for x in COMMAND_RE.split(pathdef):\n if x in COMMANDS:\n yield x\n for token in FLOAT_RE.findall(x):\n yield token\n\n\ndef _next_pos(elements):\n return float(elements.pop()) + float(elements.pop()) * 1j\n\n\ndef _parse_path(pathdef, current_pos):\n # In the SVG specs, initial movetos are absolute, even if specified as 'm'.\n # This is the default behavior here as well. But if you pass in a\n # current_pos variable, the initial moveto will be relative to that\n # current_pos. This is useful.\n elements = list(_tokenize_path(pathdef))\n # Reverse for easy use of .pop()\n elements.reverse()\n\n start_pos = None\n command = None\n\n while elements:\n\n # 1. Determine the current command\n\n if elements[-1] in COMMANDS:\n # New command.\n last_command = command # Used by S and T\n command = elements.pop()\n absolute = command in UPPERCASE\n command = command.upper()\n else:\n # Implicit command.\n # If this element starts with numbers, it is an implicit command\n # and we don't change the command. Check that it's allowed:\n if command is None:\n raise ValueError(\n \"Unallowed implicit command in {}, position {}\".format(\n pathdef, len(pathdef.split()) - len(elements))\n )\n last_command = command # Used by S and T\n\n # 2. Parse the current command\n\n # MOVETO\n if command == 'M':\n pos = _next_pos(elements)\n if absolute:\n current_pos = pos\n else:\n current_pos += pos\n\n # when M is called, reset start_pos\n # This behavior of Z is defined in svg spec:\n # http://www.w3.org/TR/SVG/paths.html#PathDataClosePathCommand\n start_pos = current_pos\n\n yield COMMAND_CODES['M'], [(current_pos.real, current_pos.imag)]\n\n # Implicit moveto commands are treated as lineto commands.\n # So we set command to lineto here, in case there are\n # further implicit commands after this moveto.\n command = 'L'\n\n # CLOSEPATH\n elif command == 'Z':\n # path closure\n if current_pos != start_pos:\n verts = [(start_pos.real, start_pos.imag)]\n yield COMMAND_CODES['L'], verts\n\n # mpl.Path: a point is required but ignored\n verts = [(start_pos.real, start_pos.imag)]\n yield COMMAND_CODES['Z'], verts\n\n current_pos = start_pos\n start_pos = None\n command = None # You can't have implicit commands after closing.\n\n # LINETO\n elif command == 'L':\n pos = _next_pos(elements)\n if not absolute:\n pos += current_pos\n verts = [(pos.real, pos.imag)]\n yield COMMAND_CODES['L'], verts\n current_pos = pos\n\n # HORIZONTAL_PATHTO\n elif command == 'H':\n x = elements.pop()\n pos = float(x) + current_pos.imag * 1j\n if not absolute:\n pos += current_pos.real\n verts = [(pos.real, pos.imag)]\n yield COMMAND_CODES['H'], verts\n current_pos = pos\n\n # VERTICAL_PATHTO\n elif command == 'V':\n y = elements.pop()\n pos = current_pos.real + float(y) * 1j\n if not absolute:\n pos += current_pos.imag * 1j\n verts = [(pos.real, pos.imag)]\n yield COMMAND_CODES['V'], verts\n current_pos = pos\n\n # CUBIC_BEZIER\n elif command == 'C':\n control1 = _next_pos(elements)\n control2 = _next_pos(elements)\n end = _next_pos(elements)\n if not absolute:\n control1 += current_pos\n control2 += current_pos\n end += current_pos\n verts = [\n (control1.real, control1.imag),\n (control2.real, control2.imag),\n (end.real, end.imag)\n ]\n yield COMMAND_CODES['C'], verts\n current_pos = end\n\n # SMOOTH_CUBIC_BEZIER\n elif command == 'S':\n # Smooth curve. First control point is the \"reflection\" of\n # the second control point in the previous path.\n if last_command not in 'CS':\n # If there is no previous command or if the previous command\n # was not an C, c, S or s, assume the first control point is\n # coincident with the current point.\n control1 = current_pos\n else:\n # The first control point is assumed to be the reflection of\n # the second control point on the previous command relative\n # to the current point.\n last_control = control2\n control1 = current_pos + current_pos - last_control\n control2 = _next_pos(elements)\n end = _next_pos(elements)\n if not absolute:\n control2 += current_pos\n end += current_pos\n verts = [\n (control1.real, control1.imag),\n (control2.real, control2.imag),\n (end.real, end.imag)\n ]\n yield COMMAND_CODES['S'], verts\n current_pos = end\n\n # QUADRATIC_BEZIER\n elif command == 'Q':\n control = _next_pos(elements)\n end = _next_pos(elements)\n if not absolute:\n control += current_pos\n end += current_pos\n verts = [\n (control.real, control.imag),\n (end.real, end.imag)\n ]\n yield COMMAND_CODES['Q'], verts\n current_pos = end\n\n # SMOOTH_QUADRATIC_BEZIER\n elif command == 'T':\n # Smooth curve. Control point is the \"reflection\" of\n # the second control point in the previous path.\n if last_command not in 'QT':\n # If there is no previous command or if the previous command\n # was not an Q, q, T or t, assume the first control point is\n # coincident with the current point.\n control = current_pos\n else:\n # The control point is assumed to be the reflection of\n # the control point on the previous command relative\n # to the current point.\n last_control = control\n control = current_pos + current_pos - last_control\n end = _next_pos(elements)\n if not absolute:\n end += current_pos\n verts = [\n (control.real, control.imag),\n (end.real, end.imag)\n ]\n yield COMMAND_CODES['T'], verts\n current_pos = end\n\n # ELLIPTICAL_ARC\n elif command == 'A':\n radius = _next_pos(elements)\n rotation = float(elements.pop())\n large = float(elements.pop())\n sweep = float(elements.pop())\n end = _next_pos(elements)\n\n if not absolute:\n end += current_pos\n\n if current_pos == end:\n # This is equivalent of omitting the segment, so do nothing\n continue\n elif radius.real == 0 or radius.imag == 0:\n # This should be treated as a straight line\n verts = [(end.real, end.imag)]\n yield COMMAND_CODES['L'], verts\n else:\n codes, verts = arc_path(\n current_pos, radius, rotation, large, sweep, end\n )\n yield codes, verts\n\n current_pos = end\n\n\ndef parse_path(pathdef, current_pos=0 + 0j):\n \"\"\"\n Parse an SVG path definition string into a matplotlib Path object.\n\n Parameters\n ----------\n pathdef : str\n SVG path 'd' attribute, e.g. 'M 100 100 L 300 100 L 200 300 z'.\n current_pos : complex, optional\n Coordinates of the starting position of the path, given as a complex\n number. When provided, an initial moveto operation will be intepreted\n as relative to this position even if given as M.\n\n Returns\n -------\n :class:`matplotlib.path.Path` instance\n\n See also\n --------\n matplotlib.path.Path\n matplotlib.patches.PathPatch\n matplotlib.collections.PathCollection\n matplotlib.transforms\n\n \"\"\"\n codes = []\n verts = []\n for c, v in _parse_path(pathdef, current_pos):\n codes.extend(c)\n verts.extend(v)\n return Path(verts, codes)", "meta": {"hexsha": "0790525a159cb0dbdf4df6172ae049a3eac0ad48", "size": 16695, "ext": "py", "lang": "Python", "max_stars_repo_path": "graph/svg2mpl.py", "max_stars_repo_name": "kUNWAR-DIVYANSHU/stockui", "max_stars_repo_head_hexsha": "f85a26b461512fefd33a4f2acfa30d178de3d118", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-28T20:37:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T12:01:33.000Z", "max_issues_repo_path": "graph/svg2mpl.py", "max_issues_repo_name": "kUNWAR-DIVYANSHU/stockui", "max_issues_repo_head_hexsha": "f85a26b461512fefd33a4f2acfa30d178de3d118", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graph/svg2mpl.py", "max_forks_repo_name": "kUNWAR-DIVYANSHU/stockui", "max_forks_repo_head_hexsha": "f85a26b461512fefd33a4f2acfa30d178de3d118", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2297297297, "max_line_length": 79, "alphanum_fraction": 0.5689128482, "include": true, "reason": "import numpy", "num_tokens": 4135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.27825678173200435, "lm_q1q2_score": 0.1423886155838093}} {"text": "# The original code requires pylcaio release v1.0, from Agez, found at:\n# https://github.com/MaximeAgez/pylcaio\n\nimport pandas as pd\nimport numpy as np\nimport os, sys\nimport pickle\nimport logging\nimport pylcaio\n\nfp_results = os.path.join(os.path.curdir, 'results')\nfp_output = os.path.join(os.path.curdir, 'output')\n\ndef hybrid_emission_factors(trade_only, year):\n Analysis = pylcaio.Analysis('ecoinvent3.5','exiobase3', method_double_counting='STAM')\n\n # For making human-readable indices; consists of all ecoinvent process metadata\n labels = Analysis.PRO_f\n\n # Make DataFrame for whole ecoinvent requirements matrix with human-readable indices\n Aff_labels = (labels.join(Analysis.A_ff,how='inner'))\n Aff_labels = (Aff_labels).set_index(keys=['activityName', 'geography', 'productName'], append=True)\n Aff_labels = Aff_labels.iloc[:,19:] # remove extraeneous metadata\n Aff_labels.columns = Aff_labels.index\n\n # Calculate life cycle impacts\n I = pd.DataFrame(np.eye(len(Analysis.A_ff)), Analysis.A_ff.index, Analysis.A_ff.columns)\n X = pd.DataFrame(np.linalg.solve(I-Analysis.A_ff, I), Analysis.A_ff.index, I.columns) # pro x pro\n D = Analysis.C_f.fillna(0).dot(Analysis.F_f).dot(X) # pro x imp\n\n D = D.T\n D_labels = labels.join(D, how='inner')\n D_labels.set_index(keys=['activityName', 'geography', 'productName'], append=True, inplace=True)\n D_labels = D_labels.iloc[:, 19:]\n D_labels = D_labels.T\n\n # Other possible impact methods\n imp_list = ['EDIP; environmental impact; global warming, GWP 100a; kg CO2-Eq', 'ReCiPe Midpoint (H); climate change; GWP100; kg CO2-Eq', 'ReCiPe Midpoint (H) V1.13; climate change; GWP100; kg CO2-Eq', 'IPCC 2013; climate change; GTP 100a; kg CO2-Eq']\n D_labels_comp = D_labels.loc[imp_list]\n D_labels = D_labels.loc['EDIP; environmental impact; global warming, GWP 100a; kg CO2-Eq']\n\n # the footprint of all hybridized processes from ecoinvent, with their original footprint\n fp_hybrid = os.path.join(os.path.curdir, 'data', 'Results_full_database_STAM_2011.xlsx')\n hybrid_results = pd.read_excel(fp_hybrid, 'GWP_only_hyb', usecols='A:E,G', index_col=[0,1,2,3,4])\n\n # ## List of ENTSO-E countries\n country_list = ['AL','AT','BA','BE','BG','CH','CZ','DE','DK','EE',\n 'ES','FI','FR','GR','HR','HU','IE','IT','LT','LU',\n 'LV','ME','MK','NL','NO','PL','PT','RO','RS','SE',\n 'SI','SK','GB','TR','GE','CY','HR','NI','UK']\n\n # Find all electricity processes\n set(labels.loc[labels['activityName'].str.contains('electricity')]['activityName'])\n\n # Isolate high voltage (production) mixes and low voltage mixes (which includes solar PV)\n # note that pumped storage hydropower in CH gets excluded as it has 0 contribution to the production mix (for whatever reason)\n market_mixes = labels.loc[labels['activityName'].str.contains('electricity, high voltage, production mix')] # production mixes, do not include solar or waste (or Swiss pumped hydro)\n waste_mixes = labels.loc[labels['activityName'].str.contains('electricity, from municipal waste incineration to generic market for electricity, medium voltage')] # production mixes, do not include solar\n solar_mixes = labels.loc[labels['activityName'].str.contains('electricity, low voltage')] # use low voltage mixes to get shares of solar photovoltaic\n\n # ### Filter for high-voltage production mixes\n # First, retrieve electricity mixes, and reduce un-needed processes\n df = Aff_labels[market_mixes.index]\n df_waste = Aff_labels.loc[waste_mixes.index]\n df_solar = Aff_labels[solar_mixes.index]\n\n df = df.loc[:, df.columns.isin(country_list, level=2)]\n\n # manual workaround for keeping CH pumped hydro after removing unneeded rows\n # (since this ecoinvent process apparently does not contribute to any electricity mixes in ecoinvent)\n ind =('69ccf019-081e-42e3-b7f5-879dc7dde86a_66c93e71-f32b-4591-901c-55395db5c132', 'electricity production, hydro, pumped storage', 'CH', 'electricity, high voltage') # Activityid for Swiss pumped hydro\n col = df.columns.get_loc(('54ed269b-e329-469c-902e-a8991ee7d24a_66c93e71-f32b-4591-901c-55395db5c132', 'electricity, high voltage, production mix', 'CH', 'electricity, high voltage'))\n index = df.index.get_loc(ind)\n df.iloc[index, col] = 1e-7\n\n df = df.replace(0, np.nan).dropna(how='all', axis=0)\n\n # ### Filter for medium-voltage mixes ( to find waste incineration shares)\n df_waste = df_waste.loc[:, df_waste.columns.isin(country_list, level=2)]\n df_waste = df_waste.replace(to_replace=0, value=np.nan).dropna(how='all', axis=0)\n\n # check unique waste incineration activities\n set(df_waste.index.get_level_values('activityName'))\n\n # ### Filter for low-voltage mixes (to find solar photovoltaic shares)\n df_solar = df_solar.loc[:, df_solar.columns.isin(country_list, level=2)]\n df_solar = df_solar.replace(to_replace=0, value=np.nan).dropna(how='all', axis=0)\n\n # ### Develop correspondence between ecoinvent and ENTSO-E technology categories\n\n # Correspondence from ENTSO-E technology categories to keywords for searching in ecoinvent processes\n # Note that the 'fossil oil shale', 'other' and 'other renewable' do not have ecoinvent equivalents;\n # these are dealt with later\n tec_dict = {'Biomass': ['biogas', 'wood chips'],\n 'Fossil Brown coal/Lignite': 'lignite',\n 'Fossil Coal-derived gas': 'coal gas',\n 'Fossil Gas': 'natural gas',\n 'Fossil Hard coal': 'hard coal',\n 'Fossil Oil': ' oil',\n 'Fossil Oil shale': '--',\n 'Fossil Peat': 'peat',\n 'Geothermal': 'geothermal',\n 'Hydro Pumped Storage': 'pumped storage',\n 'Hydro Run-of-river and poundage': 'run-of-river',\n 'Hydro Water Reservoir': 'reservoir',\n 'Nuclear': 'nuclear',\n 'Other': '---',\n 'Other renewable': '----',\n 'Solar': ['solar thermal', 'solar tower', 'photovoltaic'],\n 'Waste': 'waste incineration',\n 'Wind Offshore': 'offshore',\n 'Wind Onshore': 'onshore'\n }\n\n # reverse correspondence from ecoinvent search keywords to ENTSO-E categories\n temp_tecdict = { 'biogas':'Biomass',\n 'wood chips':'Biomass',\n 'lignite': 'Fossil Brown coal/Lignite' ,\n 'coal gas': 'Fossil Coal-derived gas',\n 'natural gas': 'Fossil Gas' ,\n 'hard coal': 'Fossil Hard coal' ,\n ' oil': 'Fossil Oil',\n '--' : 'Fossil Oil shale',\n 'peat': 'Fossil Peat' ,\n 'geothermal':'Geothermal',\n 'pumped storage': 'Hydro Pumped Storage',\n 'run-of-river': 'Hydro Run-of-river and poundage',\n 'reservoir': 'Hydro Water Reservoir',\n 'nuclear' : 'Nuclear',\n '---':'Other' ,\n '----': 'Other renewable',\n 'solar thermal': 'Solar',\n 'solar tower': 'Solar',\n 'photovoltaic': 'Solar',\n 'waste incineration': 'Waste', # 'electricity, from municipal waste incineration to generic market for electricity, medium voltage',\n 'offshore': 'Wind Offshore',\n 'onshore':'Wind Onshore'\n }\n\n # flatten tec list\n tec_list = list(tec_dict.values())\n for item in tec_list:\n if type(item)==list:\n for subitem in item:\n tec_list.append(subitem)\n tec_list.remove(item)\n\n # Get list of solar PV processes in ecoinvent\n d = list(set(df_solar.index.get_level_values(level=1)))\n pv = [entry for entry in d if 'electricity production' in entry] # all low-voltage production technologies\n\n # Fetch waste incineration process names\n waste = ['electricity, from municipal waste incineration to generic market for electricity, medium voltage']\n\n # Make list of electricity generation technologies (both high voltage and low-voltage, i.e., solar PV)\n ecoinvent_tecs = list(set(df.index.get_level_values(level=1))) + pv + waste\n\n # Quality assurance; make sure all ecoinvent technologies are covered by the keyword search, and keyword matches are correct\n # also, check number of matches for each keyword\n matches = []\n match_keys = []\n num_matches = dict((keyword,0) for keyword in tec_list)\n\n for tec in ecoinvent_tecs:\n for keyword in tec_list:\n if keyword in tec and tec not in matches:\n# print(f'{keyword} is in {tec}')\n matches.append(tec)\n match_keys.append(temp_tecdict[keyword])\n num_matches[keyword] += 1\n\n print(num_matches)\n\n # Find ecoinvent tecs that were not matched\n if len(ecoinvent_tecs)-len(matches) > 0:\n print('ecoinvent process(es) not matched:')\n print(set(ecoinvent_tecs).difference(set(matches)))\n\n # Correspondence of ENTSO-E categories and specific ecoinvent processes\n from collections import defaultdict\n\n ei_tec_dict = defaultdict(list) # keys as entso-e categories, values are corresponding ei\n rev_ei_tec_dict = defaultdict(list) # vice-versa; keys as ei, values are entso-e categories\n for i, j in zip(match_keys, matches):\n ei_tec_dict[i].append(j)\n rev_ei_tec_dict[j].append(i)\n\n # Build correspondence table for Supplementary Information\n tec_index = pd.Index(list(ei_tec_dict.keys()))\n tec_values = list(ei_tec_dict.values())\n ei_tec_table = pd.DataFrame(tec_values, index=tec_index).stack()\n ei_tec_table.index = ei_tec_table.index.droplevel(level=1)\n ei_tec_table.sort_index(axis=0, inplace=True)\n\n\n # ### Calculate shares of ecoinvent processes\n # For multi-process technology categories, e.g., solar, biomass...\n\n # combine high-, medium- and low-voltage electricity mixes for full tech resolution\n f = pd.concat([df, df_waste, df_solar], axis=1)\n\n rev_ei_tec_dict = {k: v for k, v in rev_ei_tec_dict.items() if not not v}\n\n temp_list = f.index.get_level_values('activityName')\n entso_list = []\n f_check = []\n\n # For every activity in ecoinvent,if they are related to electricity production, add to entso_list\n # If not, drop from the matrix; they are irrelevant\n for entry in temp_list:\n try:\n entso_list.append(rev_ei_tec_dict[entry])\n except:\n f_check.append(entry)\n\n f.drop(index=set(f_check), level=1, axis=0, inplace=True)\n\n # inputs to electricity mixes not included in the calculations of emission factors\n set(f_check)\n\n entso_list = [item for sublist in entso_list for item in sublist] #flatten list\n\n entso_index = pd.Index(tuple(entso_list), name='entso_e')\n f.set_index(entso_index, append=True, inplace=True)\n\n\n # ### Get shares of each ecoinvent process for each ENTSO-E technology category\n\n f_gpby = f.groupby(level='entso_e')\n\n # Get shares of each ecoinvent process in each ENTSO-E technology category;\n # for calculating weighted average for emission factor\n ei_process_shares = f.divide(f_gpby.sum(), level=4, axis=1)\n\n hybrid_temp = hybrid_results.reset_index(level=[1,2,3,4], drop=True)\n g_temp = ei_process_shares.reset_index(level=[1,2,3,4], drop=True)\n\n\n # ### Calculate weighted average, hybridized emissions factor for each technology\n\n ef = ei_process_shares.mul(hybrid_temp.iloc[:, 0], axis=0, level=0)\n\n ef_aggregated = ef.groupby(level='entso_e').sum()\n\n ef_countries = ef_aggregated.sum(axis=1, level='geography')\n ef_countries.replace(0, np.nan, inplace=True)\n ef_countries.dropna(axis=1, how='all', inplace=True)\n ef_countries.sort_index(inplace=True)\n\n ef_countries = ef_countries.T\n ef_countries.sort_index(axis=0, inplace=True)\n\n entso_fp = os.path.join(fp_output, 'entsoe', 'ENTSO_production_volumes_' + str(year) + '.csv')\n\n entso_e_production = pd.read_csv(entso_fp, header=0, index_col=[0])\n entso_e_production.replace(0, np.nan,inplace=True)\n entso_mask = entso_e_production.isna().sort_index()\n ef_mask = ef_countries.sort_index().isna()\n\n entso_mask.drop(columns=['Fossil Oil shale', 'Other', 'Other renewable', 'Marine'], inplace=True)\n\n entso_mask.index.rename('geography', inplace=True)\n entso_mask.columns.rename('entso_e', inplace=True)\n\n # Countries for which we have production data, but no hybridized emission factors\n no_ef_countries = set(entso_e_production.index) - set(ef_countries.index)\n print('Countries with production data, but no hybridized emission factors:')\n print(no_ef_countries)\n logging.warning(f'{no_ef_countries} have production data from ENTSO_E but no hybridized emission factors')\n\n list(set(ef_countries.columns) - set(entso_e_production.index))\n\n\n check_df = entso_mask.eq(ef_mask, axis=0)\n\n # Find countries missing from ecoinvent\n missing_countries = []\n for country, row in check_df.iterrows():\n if not row.any():\n missing_countries.append(country)\n # Optionally, drop them from mask\n check_df.drop(index = missing_countries, inplace=True)\n\n # Find the technology-country pairs that are missing hybridized emission factors\n countries_missing_ef = {}\n for tec, col in check_df.iteritems():\n temp = check_df.index[check_df[tec] == False].tolist()\n print(f'For {tec}, regionalized, hybridized emission factors are missing for {temp}. Using technological average from available regions instead.')\n temp2 = []\n for country in temp:\n if ef_mask.loc[country, tec]:\n temp2.append(country)\n countries_missing_ef[tec] = temp2#.append(country)\n countries_missing_ef\n\n no_ef = pd.DataFrame({k:pd.Series(v[:13]) for k, v in countries_missing_ef.items()})\n\n\n # ## Calculate LC emissions for production mix for countries with missing production data\n\n# trade_only = ['AL','BY','HR','LU','MD','MT','RU','TR','UA']\n low_volt = labels.loc[labels['activityName'] == 'market for electricity, low voltage']\n trade_only_mixes_lv = low_volt.loc[low_volt['geography'].isin(trade_only)].index\n lv_mix_ef = D_labels.loc[trade_only_mixes_lv] # low voltage mixes, not used\n\n high_volt = labels.loc[labels['activityName'] == 'market for electricity, high voltage']\n trade_only_mixes_hv = high_volt.loc[high_volt['geography'].isin(trade_only)].index\n hv_mix_ef = D_labels.loc[trade_only_mixes_hv]\n\n lv_mix_ef_comp = D_labels_comp[trade_only_mixes_lv] # low voltage mixes, not used\n hv_mix_ef_comp = D_labels_comp[trade_only_mixes_hv]\n\n trade_mixes_comp = lv_mix_ef_comp.join(hv_mix_ef_comp)\n\n labels.loc[labels['activityName'] == 'electricity, from municipal waste incineration to generic market for electricity, medium voltage']\n\n # ## Export results\n # Convert emission factors to g CO2-eq/kWh\n ef_countries = ef_countries * 1000\n lv_mix_ef = lv_mix_ef * 1000 # low voltage mixes, not used\n hv_mix_ef = hv_mix_ef * 1000\n trade_mixes_comp = trade_mixes_comp * 1000\n\n # Calculate mean technology footprints as quick check\n ef_aggregated.replace(0, np.nan).mean(axis=1)\n\n fp_results = os.path.join(os.path.curdir,'results')\n\n with pd.ExcelWriter(os.path.join(fp_results, 'hybrid_emission_factors_final_' + str(year) + '.xlsx')) as writer:\n ef_countries.to_excel(writer, sheet_name='country_emission_factors')\n no_ef.to_excel(writer, sheet_name='missing_emission_factors')\n lv_mix_ef.to_excel(writer, sheet_name='ecoinvent ef')\n hv_mix_ef.to_excel(writer, sheet_name='ecoinvent ef_hv')\n trade_mixes_comp.to_excel(writer, sheet_name='trade_mixes_from_ei')\n ei_tec_table.to_excel(writer, sheet_name='correspondence table')\n ef_aggregated.to_excel(writer, sheet_name='mean tech fps')\n\n # Export to .csv for use in BEV_footprints_calculations\n # append extra countries to file\n try:\n existing_tradeonly = pd.read_csv(os.path.join(fp_output, 'ecoinvent_ef_hv.csv'))['geography'].values\n add_ef_countries = set(hv_mix_ef.index.get_level_values('geography')) - set(existing_tradeonly) # countries not already in csv file\n if add_ef_countries:\n hv_mix_ef_exp = hv_mix_ef.loc[:,:,list(add_ef_countries),:]\n hv_mix_ef_exp.to_csv(os.path.join(fp_output, 'ecoinvent_ef_hv.csv'), mode='a', header=False) # used in BEV_footprints_calculations\n except FileNotFoundError:\n print('Previous ecoinvent file does not exist. Making file.')\n hv_mix_ef.to_csv(os.path.join(fp_output, 'ecoinvent_ef_hv.csv'))\n\n ef_countries.to_csv(os.path.join(fp_output, 'country_emission_factors.csv')) # used in clean_impact_factors\n no_ef.to_csv(os.path.join(fp_output, 'missing_emission_factors.csv')) # used in clean_impact_factors\n# lv_mix_ef.to_csv(os.path.join(fp_results, 'ecoinvent_ef_lv.csv'))\n\n return ef_countries, no_ef, countries_missing_ef\n\ndef clean_impact_factors(year, trade_only, calc_hybrid):\n entsoe_fp = os.path.join(fp_output, 'entsoe')\n with open(os.path.join(entsoe_fp, 'gen_final_' + str(year) + '.pkl'), 'rb') as handle:\n gen_df = pickle.load(handle)\n\n with open(os.path.join(entsoe_fp,'trade_final_' + str(year) + '.pkl'), 'rb') as handle:\n trade_df = pickle.load(handle)\n\n if calc_hybrid:\n try:\n print('\\n Calculating hybridized emission factors from pyLCAIO')\n # gen_df not modified in hybrid_emission_factors, just used to determine relevant labels\n ef, missing_factors, countries_missing_ef = hybrid_emission_factors(trade_only, year)\n except Exception as e:\n print('\\n Calculating from pyLCAIO failed. Importing previously calculated emission factors instead')\n print(e)\n # import ready-calculated emission factors if no access to pylcaio object\n ef = pd.read_csv(os.path.join(fp_output, 'country_emission_factors.csv'), index_col=[0])\n missing_factors = pd.read_csv(os.path.join(fp_output, 'missing_emission_factors.csv'), index_col=[0])\n else:\n print('\\n Loading previously calculated emission factors')\n ef = pd.read_csv(os.path.join(fp_output, 'country_emission_factors.csv'), index_col=[0])\n missing_factors = pd.read_csv(os.path.join(fp_output, 'missing_emission_factors.csv'), index_col=[0])\n\n countries_missing_ef = dict((k, list(v.dropna())) for k, v in missing_factors.iteritems()) # make dict of tec: [countries]\n countries_missing_ef = {key:value for key, value in countries_missing_ef.items() if len(value)} # remove entries with empty values\n\n \"\"\" Fix missing emission factors \"\"\"\n # Note that these disregard whether or not there is actual production\n ef['Fossil Oil shale'] = ef['Fossil Oil'] # Proxy shale oil with conventional oil\n ef['Waste'] = 0 # Allocate incineration emissions to waste treatment as per ecoinvent\n ef['Marine'] = 0\n\n # Put in proxy for missing regions and technologies\n missing_factors.dropna(how='all', axis=1, inplace=True)\n missing_factors_dict = {}\n # build dict of missing technology-country factors\n for tec, col in missing_factors.iteritems():\n missing_factors_dict[tec] = list(col.dropna(how='any', axis=0).values)\n\n # countries with no geo-specific factors\n missing_countries = list(set(gen_df.index) - set(ef.index))\n for country in missing_countries:\n ef = ef.append(pd.Series(name=country))\n\n temp_gen_df = gen_df.loc[missing_countries]\n temp_gen_df = temp_gen_df.replace(0, np.nan).dropna(how='all', axis=1)\n temp_dict = {}\n for tec, col in temp_gen_df.items():\n temp = temp_gen_df[tec] > 0\n temp_ind = temp.index\n temp_dict[tec] = temp_ind[temp.values].to_list()\n\n \"\"\" Merge dictionaries and keep values of common keys in list\"\"\"\n def mergeDict(dict1, dict2):\n dict3 = {**dict1, **dict2}\n for key, value in dict3.items():\n if key in dict1 and key in dict2:\n dict3[key] = (dict1[key] + dict2[key])\n return dict3\n\n # Merge dictionaries and add values of common keys in a list\n missing_factors_dict2 = mergeDict(missing_factors_dict, temp_dict)\n missing_factors_dict2\n\n # Use continental arithmetic average of same technology\n for key, countries in missing_factors_dict2.items():\n if not key=='Other' and not key=='Other renewable': # these are dealt with below\n ef[key].loc[countries] = ef[key].mean()\n\n # Make 'other' and 'other renewable' approximations\n renewable_dict = {'renewable': ['Biomass', 'Geothermal', 'Hydro Pumped Storage', 'Hydro Run-of-river and poundage',\n 'Hydro Water Reservoir','Solar','Waste','Wind Onshore', 'Wind Offshore','Marine'],\n 'non-renewable': ['Fossil Gas','Fossil Hard coal','Fossil Oil','Fossil Brown coal/Lignite','Nuclear','Fossil Coal-derived gas','Fossil Oil shale','Fossil Peat']}\n\n other_tec = gen_df.loc[:,renewable_dict['non-renewable']]\n other_wf = other_tec.div(other_tec.sum(axis=1), axis=0) # determine generation shares for each country\n\n other_renew = gen_df.loc[:,renewable_dict['renewable']]\n other_renew_wf = other_renew.div(other_renew.sum(axis=1), axis=0)\n\n ef['Other'] = (ef*other_wf).sum(axis=1)\n ef['Other renewable'] = (ef*other_renew_wf).sum(axis=1)\n\n\n # Sort the indices of production, trade and emission factor matrices before export\n def sort_indices(df):\n df.sort_index(axis=0, inplace=True)\n df.sort_index(axis=1, inplace=True)\n\n sort_indices(trade_df)\n sort_indices(gen_df)\n sort_indices(ef)\n\n # Export all data\n # .csv for use in BEV_footprints_calculations.py\n\n ef.to_csv(os.path.join(fp_output,'final_emission_factors_' + str(year) + '.csv'))\n\n with pd.ExcelWriter(os.path.join(fp_results, 'entsoe_export_final_' + str(year) + '.xlsx')) as writer:\n trade_df.to_excel(writer, 'trade')\n gen_df.to_excel(writer, 'generation')\n ef.to_excel(writer,'new ef')\n\n return countries_missing_ef", "meta": {"hexsha": "808461fecdae4e2d18cc57df872c1f6f94a4f642", "size": 22250, "ext": "py", "lang": "Python", "max_stars_repo_path": "hybridized_impact_factors.py", "max_stars_repo_name": "hungchristine/ReDyFEV", "max_stars_repo_head_hexsha": "b40d9df43c7b2611fba9f34501e69c2df6b5b5b2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hybridized_impact_factors.py", "max_issues_repo_name": "hungchristine/ReDyFEV", "max_issues_repo_head_hexsha": "b40d9df43c7b2611fba9f34501e69c2df6b5b5b2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hybridized_impact_factors.py", "max_forks_repo_name": "hungchristine/ReDyFEV", "max_forks_repo_head_hexsha": "b40d9df43c7b2611fba9f34501e69c2df6b5b5b2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.3695652174, "max_line_length": 254, "alphanum_fraction": 0.6807191011, "include": true, "reason": "import numpy", "num_tokens": 5609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.22815649166448124, "lm_q1q2_score": 0.14201813401497515}} {"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 23 16:44:22 2020\n\n@author: Administrator\n\"\"\"\n\nimport numpy as np\n#import tensorflow as tf \nimport tensorflow.compat.v1 as tf\ntf.disable_v2_behavior()\nimport os \nimport shutil\nimport random\nimport math\nimport scipy.io as sio\nimport time\nimport argparse\n#from im2mesh.utils import libmcubes\nimport trimesh\nfrom scipy.spatial import cKDTree\nfrom plyfile import PlyData\nfrom plyfile import PlyElement\nfrom skimage.measure import marching_cubes_lewiner\n\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--train',action='store_true', default=False)\nparser.add_argument('--finetune',action='store_true', default=False)\nparser.add_argument('--test',action='store_true', default=False)\nparser.add_argument(\"--save_idx\", type=int, default=-1)\nparser.add_argument('--input_ply_file', type=str, default=\"test.ply\")\nparser.add_argument('--data_dir', type=str, default=\"test.ply\")\nparser.add_argument('--CUDA', type=int, default=0)\nparser.add_argument('--OUTPUT_DIR_LOCAL', type=str, default=\"test.ply\")\nparser.add_argument('--OUTPUT_DIR_GLOBAL', type=str, default=\"test.ply\")\na = parser.parse_args()\n\ncuda_idx = str(a.CUDA)\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]= cuda_idx\n\nclass_idx = '03211117'\nname = 'totempole'\nBS = 1\nprimitives = 1\nPOINT_NUM = 400\nPOINT_NUM_GT = 10000\n\npart_vox_size = 6\nOUTPUT_DIR = a.OUTPUT_DIR_LOCAL\nOUTPUT_DIR_FINETUNE = a.OUTPUT_DIR_GLOBAL\nLR = 0.0001\nSTART = 0\nSHAPE_NUM = 8000\nBD_EMPTY = 0.05\nTRAIN = a.train\nbd = 0.55\n\nif(TRAIN):\n if os.path.exists(OUTPUT_DIR):\n shutil.rmtree(OUTPUT_DIR)\n print ('test_res_dir: deleted and then created!')\n os.makedirs(OUTPUT_DIR)\n if os.path.exists(OUTPUT_DIR_FINETUNE):\n shutil.rmtree(OUTPUT_DIR_FINETUNE)\n print ('test_res_dir: deleted and then created!')\n os.makedirs(OUTPUT_DIR_FINETUNE)\n\n\n\ndef normal_points(ps_gt, ps, translation = False):\n tt = 0\n if((np.max(ps_gt[:,0])-np.min(ps_gt[:,0])))>(np.max(ps_gt[:,1])-np.min(ps_gt[:,1])):\n tt = (np.max(ps_gt[:,0])-np.min(ps_gt[:,0]))\n else:\n tt = (np.max(ps_gt[:,1])-np.min(ps_gt[:,1]))\n if(tt < (np.max(ps_gt[:,2])-np.min(ps_gt[:,2]))):\n tt = (np.max(ps_gt[:,2])-np.min(ps_gt[:,2]))\n #print('tt:',tt)\n tt = 10/(10*tt)\n ps_gt = ps_gt*tt\n ps = ps*tt\n if(translation):\n t = np.mean(ps_gt,axis = 0)\n ps_gt = ps_gt - t\n ps = ps - t\n #print('normal_gt:',np.max(ps_gt),np.min(ps_gt))\n #print('normal:',np.max(ps),np.min(ps))\n return ps_gt, ps\n\ndef fully_connected(inputs,\n num_outputs,\n scope,\n use_xavier=True,\n stddev=1e-3,\n weight_decay=0.0,\n activation_fn=tf.nn.relu,\n bn=False,\n bn_decay=None,\n is_training=None):\n \"\"\" Fully connected layer with non-linear operation.\n \n Args:\n inputs: 2-D tensor BxN\n num_outputs: int\n \n Returns:\n Variable tensor of size B x num_outputs.\n \"\"\"\n with tf.variable_scope(scope) as sc:\n num_input_units = inputs.get_shape()[-1].value\n weights = _variable_with_weight_decay('weights',\n shape=[num_input_units, num_outputs],\n use_xavier=use_xavier,\n stddev=stddev,\n wd=weight_decay)\n outputs = tf.matmul(inputs, weights)\n biases = _variable_on_cpu('biases', [num_outputs],\n tf.constant_initializer(0.0))\n outputs = tf.nn.bias_add(outputs, biases)\n \n\n if activation_fn is not None:\n outputs = activation_fn(outputs)\n return outputs\ndef max_pool2d(inputs,\n kernel_size,\n scope,\n stride=[2, 2],\n padding='VALID'):\n \"\"\" 2D max pooling.\n\n Args:\n inputs: 4-D tensor BxHxWxC\n kernel_size: a list of 2 ints\n stride: a list of 2 ints\n \n Returns:\n Variable tensor\n \"\"\"\n with tf.variable_scope(scope) as sc:\n kernel_h, kernel_w = kernel_size\n stride_h, stride_w = stride\n outputs = tf.nn.max_pool(inputs,\n ksize=[1, kernel_h, kernel_w, 1],\n strides=[1, stride_h, stride_w, 1],\n padding=padding,\n name=sc.name)\n return outputs\ndef _variable_on_cpu(name, shape, initializer, use_fp16=False):\n \"\"\"Helper to create a Variable stored on CPU memory.\n Args:\n name: name of the variable\n shape: list of ints\n initializer: initializer for Variable\n Returns:\n Variable Tensor\n \"\"\"\n with tf.device('/cpu:0'):\n dtype = tf.float16 if use_fp16 else tf.float32\n var = tf.get_variable(name, shape, initializer=initializer, dtype=dtype)\n return var\n\ndef _variable_with_weight_decay(name, shape, stddev, wd, use_xavier=True):\n \"\"\"Helper to create an initialized Variable with weight decay.\n\n Note that the Variable is initialized with a truncated normal distribution.\n A weight decay is added only if one is specified.\n\n Args:\n name: name of the variable\n shape: list of ints\n stddev: standard deviation of a truncated Gaussian\n wd: add L2Loss weight decay multiplied by this float. If None, weight\n decay is not added for this Variable.\n use_xavier: bool, whether to use xavier initializer\n\n Returns:\n Variable Tensor\n \"\"\"\n if use_xavier:\n initializer = tf.contrib.layers.xavier_initializer()\n else:\n initializer = tf.truncated_normal_initializer(stddev=stddev)\n var = _variable_on_cpu(name, shape, initializer)\n if wd is not None:\n weight_decay = tf.multiply(tf.nn.l2_loss(var), wd, name='weight_loss')\n tf.add_to_collection('losses', weight_decay)\n return var\n\ndef conv2d(inputs,\n num_output_channels,\n kernel_size,\n scope,\n stride=[1, 1],\n padding='SAME',\n use_xavier=True,\n stddev=1e-3,\n weight_decay=0.0,\n activation_fn=tf.nn.relu,\n bn=False,\n bn_decay=None,\n is_training=None):\n \"\"\" 2D convolution with non-linear operation.\n\n Args:\n inputs: 4-D tensor variable BxHxWxC\n num_output_channels: int\n kernel_size: a list of 2 ints\n scope: string\n stride: a list of 2 ints\n padding: 'SAME' or 'VALID'\n use_xavier: bool, use xavier_initializer if true\n stddev: float, stddev for truncated_normal init\n weight_decay: float\n activation_fn: function\n bn: bool, whether to use batch norm\n bn_decay: float or float tensor variable in [0,1]\n is_training: bool Tensor variable\n\n Returns:\n Variable tensor\n \"\"\"\n with tf.variable_scope(scope) as sc:\n kernel_h, kernel_w = kernel_size\n num_in_channels = inputs.get_shape()[-1].value\n kernel_shape = [kernel_h, kernel_w,\n num_in_channels, num_output_channels]\n kernel = _variable_with_weight_decay('weights',\n shape=kernel_shape,\n use_xavier=use_xavier,\n stddev=stddev,\n wd=weight_decay)\n stride_h, stride_w = stride\n outputs = tf.nn.conv2d(inputs, kernel,\n [1, stride_h, stride_w, 1],\n padding=padding)\n biases = _variable_on_cpu('biases', [num_output_channels],\n tf.constant_initializer(0.0))\n outputs = tf.nn.bias_add(outputs, biases)\n\n\n if activation_fn is not None:\n outputs = activation_fn(outputs)\n return outputs\n\ndef distance_p2p(points_src, normals_src, points_tgt, normals_tgt):\n ''' Computes minimal distances of each point in points_src to points_tgt.\n\n Args:\n points_src (numpy array): source points\n normals_src (numpy array): source normals\n points_tgt (numpy array): target points\n normals_tgt (numpy array): target normals\n '''\n kdtree = KDTree(points_tgt)\n dist, idx = kdtree.query(points_src)\n\n if normals_src is not None and normals_tgt is not None:\n normals_src = \\\n normals_src / np.linalg.norm(normals_src, axis=-1, keepdims=True)\n normals_tgt = \\\n normals_tgt / np.linalg.norm(normals_tgt, axis=-1, keepdims=True)\n\n normals_dot_product = (normals_tgt[idx] * normals_src).sum(axis=-1)\n # Handle normals that point into wrong direction gracefully\n # (mostly due to mehtod not caring about this in generation)\n normals_dot_product = np.abs(normals_dot_product)\n else:\n normals_dot_product = np.array(\n [np.nan] * points_src.shape[0], dtype=np.float32)\n return dist, normals_dot_product\n\ndef eval_pointcloud(pointcloud, pointcloud_tgt,\n normals=None, normals_tgt=None):\n ''' Evaluates a point cloud.\n\n Args:\n pointcloud (numpy array): predicted point cloud\n pointcloud_tgt (numpy array): target point cloud\n normals (numpy array): predicted normals\n normals_tgt (numpy array): target normals\n '''\n # Return maximum losses if pointcloud is empty\n\n\n pointcloud = np.asarray(pointcloud)\n pointcloud_tgt = np.asarray(pointcloud_tgt)\n\n # Completeness: how far are the points of the target point cloud\n # from thre predicted point cloud\n completeness, completeness_normals = distance_p2p(\n pointcloud_tgt, normals_tgt, pointcloud, normals\n )\n completeness2 = completeness**2\n\n completeness = completeness.mean()\n completeness2 = completeness2.mean()\n completeness_normals = np.absolute(completeness_normals).mean()\n\n # Accuracy: how far are th points of the predicted pointcloud\n # from the target pointcloud\n accuracy, accuracy_normals = distance_p2p(\n pointcloud, normals, pointcloud_tgt, normals_tgt\n )\n \n accuracy2 = accuracy**2\n\n accuracy = accuracy.mean()\n accuracy2 = accuracy2.mean()\n accuracy_normals = np.absolute(accuracy_normals).mean()\n\n # Chamfer distance\n chamferL2 = 0.5 * (completeness2 + accuracy2)\n #print(completeness,accuracy,completeness2,accuracy2)\n #print('chamferL2:',chamferL2)\n normals_correctness = (\n 0.5 * completeness_normals + 0.5 * accuracy_normals\n )\n chamferL1 = 0.5 * (completeness + accuracy)\n print('chamferL2:',chamferL2,'accuracy:',accuracy,'normals_correctness:',normals_correctness,'chamferL1:',chamferL1)\n return normals_correctness, chamferL1, chamferL2\n \n\ndef safe_norm_np(x, epsilon=1e-12, axis=1):\n return np.sqrt(np.sum(x*x, axis=axis) + epsilon)\n\ndef safe_norm(x, epsilon=1e-12, axis=None):\n return tf.sqrt(tf.reduce_sum(x ** 2, axis=axis) + epsilon)\n #return tf.reduce_sum(x ** 2, axis=axis)\n\ndef boundingbox(x,y,z):\n return min(x),max(x),min(y),max(y),min(z),max(z)\n\n\ndef get_data_from_filename(filename):\n load_data = np.load(filename)\n point = np.asarray(load_data['sample_near']).reshape(-1,POINT_NUM,3)\n sample = np.asarray(load_data['sample']).reshape(-1,POINT_NUM,3)\n rt = random.randint(0,sample.shape[0]-1)\n #rt = random.randint(0,int((sample.shape[0]-1)/5))\n sample = sample[rt,:,:].reshape(BS, POINT_NUM, 3)\n point = point[rt,:,:].reshape(BS, POINT_NUM, 3)\n\n \n \n #print('input_points_bs:',filename)\n #print(input_points_bs)\n return point.astype(np.float32), sample.astype(np.float32)\n\ndef sample_query_points(input_ply_file):\n data = PlyData.read(a.data_dir + input_ply_file)\n v = data['vertex'].data\n v = np.asarray(v)\n print(v.shape)\n\n #rt = np.random.choice(v.shape, 50000, replace = False)\n\n points = []\n for i in range(v.shape[0]):\n points.append(np.array([v[i][0],v[i][1],v[i][2]]))\n points = np.asarray(points)\n pointcloud_s =points.astype(np.float32)\n print('pointcloud sparse:',pointcloud_s.shape[0])\n \n pointcloud_s_t = pointcloud_s - np.array([np.min(pointcloud_s[:,0]),np.min(pointcloud_s[:,1]),np.min(pointcloud_s[:,2])])\n pointcloud_s_t = pointcloud_s_t / (np.array([np.max(pointcloud_s[:,0]) - np.min(pointcloud_s[:,0]), np.max(pointcloud_s[:,0]) - np.min(pointcloud_s[:,0]), np.max(pointcloud_s[:,0]) - np.min(pointcloud_s[:,0])]))\n trans = np.array([np.min(pointcloud_s[:,0]),np.min(pointcloud_s[:,1]),np.min(pointcloud_s[:,2])])\n scal = np.array([np.max(pointcloud_s[:,0]) - np.min(pointcloud_s[:,0]), np.max(pointcloud_s[:,0]) - np.min(pointcloud_s[:,0]), np.max(pointcloud_s[:,0]) - np.min(pointcloud_s[:,0])])\n pointcloud_s = pointcloud_s_t\n \n print(np.min(pointcloud_s[:,0]), np.max(pointcloud_s[:,0]))\n print(np.min(pointcloud_s[:,1]), np.max(pointcloud_s[:,1]))\n print(np.min(pointcloud_s[:,2]), np.max(pointcloud_s[:,2]))\n \n sample = []\n sample_near = []\n sample_near_o = []\n sample_dis = []\n sample_vec = []\n gt_kd_tree = cKDTree(pointcloud_s)\n for i in range(int(500000/pointcloud_s.shape[0])):\n \n pnts = pointcloud_s\n ptree = cKDTree(pnts)\n i = 0\n sigmas = []\n for p in np.array_split(pnts,100,axis=0):\n d = ptree.query(p,51)\n sigmas.append(d[0][:,-1])\n \n i = i+1\n \n sigmas = np.concatenate(sigmas)\n sigmas_big = 0.2 * np.ones_like(sigmas)\n sigmas = sigmas\n \n #tt = pnts + 0.5*0.25*np.expand_dims(sigmas,-1) * np.random.normal(0.0, 1.0, size=pnts.shape)\n tt = pnts + 0.5*np.expand_dims(sigmas,-1) * np.random.normal(0.0, 1.0, size=pnts.shape)\n #tt = pnts + 1*np.expand_dims(sigmas_big,-1) * np.random.normal(0.0, 1.0, size=pnts.shape)\n sample.append(tt)\n distances, vertex_ids = gt_kd_tree.query(tt, p=2, k = 1)\n \n\n vertex_ids = np.asarray(vertex_ids)\n print('distances:',distances.shape)\n #print(vertex_ids)\n\n sample_near.append(pointcloud_s[vertex_ids].reshape(-1,3))\n for i in range(int(500000/pointcloud_s.shape[0])):\n \n pnts = pointcloud_s\n ptree = cKDTree(pnts)\n i = 0\n sigmas = []\n for p in np.array_split(pnts,100,axis=0):\n d = ptree.query(p,51)\n sigmas.append(d[0][:,-1])\n \n i = i+1\n \n sigmas = np.concatenate(sigmas)\n sigmas_big = 0.2 * np.ones_like(sigmas)\n sigmas = sigmas\n \n #tt = pnts + 0.5*0.25*np.expand_dims(sigmas,-1) * np.random.normal(0.0, 1.0, size=pnts.shape)\n tt = pnts + 1.0*np.expand_dims(sigmas,-1) * np.random.normal(0.0, 1.0, size=pnts.shape)\n #tt = pnts + 1*np.expand_dims(sigmas_big,-1) * np.random.normal(0.0, 1.0, size=pnts.shape)\n sample.append(tt)\n distances, vertex_ids = gt_kd_tree.query(tt, p=2, k = 1)\n \n\n vertex_ids = np.asarray(vertex_ids)\n print('distances:',distances.shape)\n #print(vertex_ids)\n\n sample_near.append(pointcloud_s[vertex_ids].reshape(-1,3))\n \n \n\n\n\n \n sample = np.asarray(sample).reshape(-1,3)\n sample_near = np.asarray(sample_near).reshape(-1,3)\n np.savez_compressed(a.data_dir + input_ply_file , sample = sample, sample_near=sample_near,pointcloud_s = pointcloud_s, trans = trans, scal = scal)\n sample_all = sample.reshape(-1,3)\n sample_near_all = sample_near.reshape(-1,3)\n sample_part = [[] for i in range(part_vox_size*part_vox_size*part_vox_size)]\n sample_near_part = [[] for i in range(part_vox_size*part_vox_size*part_vox_size)]\n bd_max_x = np.max(pointcloud_s[:,0])\n bd_max_y = np.max(pointcloud_s[:,1])\n bd_max_z = np.max(pointcloud_s[:,2])\n bd_min_x = np.min(pointcloud_s[:,0])\n bd_min_y = np.min(pointcloud_s[:,1])\n bd_min_z = np.min(pointcloud_s[:,2])\n for l in range(sample_near_all.shape[0]):\n ex = sample_near_all[l,0] - bd_min_x\n ix = int(math.floor(ex/((bd_max_x- bd_min_x)/(part_vox_size))))\n #print(ex,ix)\n ey = sample_near_all[l,1] - bd_min_y\n iy = int(math.floor(ey/((bd_max_y- bd_min_y)/(part_vox_size))))\n ez = sample_near_all[l,2] - bd_min_z\n iz = int(math.floor(ez/((bd_max_z- bd_min_z)/(part_vox_size))))\n ix = np.clip(ix,0,part_vox_size-1)\n iy = np.clip(iy,0,part_vox_size-1)\n iz = np.clip(iz,0,part_vox_size-1)\n #print(ix,iy,iz)\n sample_part[ix*(part_vox_size)*(part_vox_size)+iy*(part_vox_size)+iz].append(sample_all[l])\n sample_near_part[ix*(part_vox_size)*(part_vox_size)+iy*(part_vox_size)+iz].append(sample_near_all[l])\n \n \n for iv in range(len(sample_part)):\n #print(np.asarray(sample[iv]).shape)\n np.savez(a.data_dir + input_ply_file + '_' + str(iv), sample = sample_part[iv],sample_near = sample_near_part[iv])\nif(a.train):\n sample_query_points(a.input_ply_file)\nmm = 0\nfiles = []\nfiles_path = []\n\nfiles.append(a.input_ply_file)\nfiles_path.append(a.data_dir + a.input_ply_file)\n\n\n\npoints_all = []\nsamples_all = []\n\nif(a.train):\n for fi in range(len(files_path)):\n print(files_path[fi])\n for i in range(part_vox_size*part_vox_size*part_vox_size):\n #for i in range(100):\n if(os.path.exists(files_path[fi] + '_{}.npz'.format(i))):\n print(i)\n load_data = np.load(files_path[fi] + '_{}.npz'.format(i))\n sample_near = np.asarray(load_data['sample_near'])\n sampler = np.asarray(load_data['sample'])\n print(sample_near.shape[0])\n if(sample_near.shape[0]>=POINT_NUM):\n print(sample_near.shape[0])\n sample_near,sampler = normal_points(sample_near,sampler,True)\n tt = int(math.floor(sample_near.shape[0]*1.0/POINT_NUM))\n tt = (tt*POINT_NUM)\n #print(sample_near[0:tt,:].shape)\n points_all.append(sample_near[0:tt,:])\n samples_all.append(sampler[0:tt,:])\n #print(points_all[i].shape)\n \nSHAPE_NUM = len(files)\n#SHAPE_NUM = 26\nprint('SHAPE_NUM:',SHAPE_NUM)\n\n\npoints_target = tf.placeholder(tf.float32, shape=[BS,POINT_NUM,3])\ninput_points_3d = tf.placeholder(tf.float32, shape=[BS,POINT_NUM,3])\nnormal_gt = tf.placeholder(tf.float32, shape=[BS,None,3])\npoints_target_num = tf.placeholder(tf.int32, shape=[1,1])\npoints_input_num = tf.placeholder(tf.int32, shape=[1,1])\npoints_cd = tf.placeholder(tf.float32, shape=[BS,None,3])\n\ndef local_decoder(feature,input_points_3d):\n with tf.variable_scope('local', reuse=tf.AUTO_REUSE):\n feature_f = tf.nn.relu(tf.layers.dense(feature,512))\n net = tf.nn.relu(tf.layers.dense(input_points_3d, 512))\n net = tf.concat([net,feature_f],2)\n print('net:',net)\n with tf.variable_scope('decoder', reuse=tf.AUTO_REUSE):\n for i in range(8):\n with tf.variable_scope(\"resnetBlockFC_%d\" % i ):\n b_initializer=tf.constant_initializer(0.0)\n w_initializer = tf.random_normal_initializer(mean=0.0,stddev=np.sqrt(2) / np.sqrt(512))\n net = tf.layers.dense(tf.nn.relu(net),512,kernel_initializer=w_initializer,bias_initializer=b_initializer)\n \n b_initializer=tf.constant_initializer(-0.5)\n w_initializer = tf.random_normal_initializer(mean=2*np.sqrt(np.pi) / np.sqrt(512), stddev = 0.000001)\n print('net:',net)\n sdf = tf.layers.dense(tf.nn.relu(net),1,kernel_initializer=w_initializer,bias_initializer=b_initializer)\n print('sdf',sdf)\n \n grad = tf.gradients(ys=sdf, xs=input_points_3d) \n print('grad',grad)\n print(grad[0])\n normal_p_lenght = tf.expand_dims(safe_norm(grad[0],axis = -1),-1)\n print('normal_p_lenght',normal_p_lenght)\n grad_norm = grad[0]/normal_p_lenght\n print('grad_norm',grad_norm)\n return sdf,grad_norm\n\ninput_points_3d_global = tf.placeholder(tf.float32, shape=[BS,None,3])\npoints_target_global = tf.placeholder(tf.float32, shape=[BS,None,3])\nfeature_global = tf.placeholder(tf.float32, shape=[BS,None,SHAPE_NUM])\n#with tf.variable_scope('pointnet', reuse=tf.AUTO_REUSE):\n# input_image = tf.expand_dims(points_target_global,-1)\n# net = conv2d(input_image, 64, [1,3], padding='VALID', stride = [1,1], is_training = True, scope = 'conv1')\n# net = conv2d(input_image, 128, [1,3], padding='VALID', stride = [1,1], is_training = True, scope = 'conv2')\n# net = conv2d(input_image, 1024, [1,3], padding='VALID', stride = [1,1], is_training = True, scope = 'conv3')\n# net = max_pool2d(net,[POINT_NUM,1], padding = 'VALID', scope = 'maxpool')\n# net = tf.reshape(net,[1,-1])\n# net = fully_connected(net, 512, is_training = True, scope = 'fc1')\n# net = fully_connected(net, 256, is_training = True, scope = 'fc2')\n# feature_global = net\n#feature_global = tf.tile(tf.expand_dims(feature_global,1),[1,POINT_NUM,1]) \ndef global_decoder(feature_global_f,input_points_3d_global_f):\n with tf.variable_scope('global', reuse=tf.AUTO_REUSE):\n feature_g = tf.nn.relu(tf.layers.dense(feature_global_f,512))\n net_g = tf.nn.relu(tf.layers.dense(input_points_3d_global_f, 512))\n #print(net_g,feature_g)\n net_g = tf.concat([net_g,feature_g],2)\n for i in range(8):\n net_g = tf.layers.dense(tf.nn.relu(net_g),512)\n \n feature_output = tf.layers.dense(tf.nn.relu(net_g),SHAPE_NUM)\n d_output = tf.layers.dense(tf.nn.relu(net_g),3)\n sdf_g,grad_norm_g = local_decoder(feature_output,input_points_3d_global_f+d_output)\n g_points_g = input_points_3d_global_f - sdf_g * grad_norm_g\n return g_points_g, sdf_g\n\ng_points_g, sdf_g = global_decoder(feature_global,input_points_3d_global)\nloss_g = tf.reduce_mean(tf.norm((points_target_global-g_points_g), axis=-1))\n \n\n\n\nwith tf.variable_scope('pointnet', reuse=tf.AUTO_REUSE):\n input_image = tf.expand_dims(points_target,-1)\n net = conv2d(input_image, 64, [1,3], padding='VALID', stride = [1,1], is_training = True, scope = 'conv1')\n net = conv2d(input_image, 128, [1,3], padding='VALID', stride = [1,1], is_training = True, scope = 'conv2')\n net = conv2d(input_image, 1024, [1,3], padding='VALID', stride = [1,1], is_training = True, scope = 'conv3')\n net = max_pool2d(net,[POINT_NUM,1], padding = 'VALID', scope = 'maxpool')\n net = tf.reshape(net,[1,-1])\n net = fully_connected(net, 512, is_training = True, scope = 'fc1')\n net = fully_connected(net, 256, is_training = True, scope = 'fc2')\n feature = net\nfeature = tf.tile(tf.expand_dims(feature,1),[1,POINT_NUM,1]) \nsdf,grad_norm = local_decoder(feature,input_points_3d)\ng_points = input_points_3d - sdf * grad_norm\n\n\nloss = tf.reduce_mean(tf.norm((points_target, g_points), axis=-1))\n\nt_vars = tf.trainable_variables()\noptim = tf.train.AdamOptimizer(learning_rate=LR, beta1=0.9)\nloss_grads_and_vars = optim.compute_gradients(loss, var_list=t_vars)\nloss_optim = optim.apply_gradients(loss_grads_and_vars)\n\nglobal_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='global')\nloss_grads_and_vars_g = optim.compute_gradients(loss_g, var_list=global_vars)\n#loss_grads_and_vars_g = optim.compute_gradients(loss_g, var_list=t_vars)\nloss_optim_g = optim.apply_gradients(loss_grads_and_vars_g)\n\n\nconfig = tf.ConfigProto(allow_soft_placement=False) \nsaver_restore = tf.train.Saver(var_list=t_vars)\nsaver = tf.train.Saver(max_to_keep=2000000)\n\n\n\n\nwith tf.Session(config=config) as sess:\n feature_bs_all = []\n for i in range(SHAPE_NUM):\n tt = []\n for j in range(int(POINT_NUM)):\n t = np.zeros(SHAPE_NUM)\n \n t[i] = 1\n tt.append(t)\n feature_bs_all.append(tt)\n feature_bs_all = np.asarray(feature_bs_all)\n #print(feature_bs_all,feature_bs_all.shape)\n if(TRAIN):\n print('train start')\n sess.run(tf.global_variables_initializer())\n start_time = time.time()\n POINT_NUM_GT_bs = np.array(POINT_NUM_GT).reshape(1,1)\n points_input_num_bs = np.array(POINT_NUM).reshape(1,1)\n print('data shape:',len(points_all))\n for bi in range(500):\n epoch_index = np.random.choice(len(points_all)-1, len(points_all)-1, replace = False)\n for epoch in epoch_index:\n\n\n points = points_all[epoch].reshape(-1,POINT_NUM,3)\n samples = samples_all[epoch].reshape(-1,POINT_NUM,3)\n\n rt = random.randint(0,samples.shape[0]-1)\n sample = samples[rt,:].reshape(BS, POINT_NUM, 3)\n point = points[rt,:].reshape(BS, POINT_NUM, 3)\n \n _, loss_c,g_points_g_c = sess.run([loss_optim,loss,g_points],feed_dict={points_target_num:POINT_NUM_GT_bs,points_input_num:points_input_num_bs,\n points_target:point,input_points_3d:sample})\n \n if(bi%100 == 0):\n print('model:',bi,'epoch:',epoch,'loss:',loss_c)\n saver.save(sess, os.path.join(OUTPUT_DIR, \"model\"), global_step=bi)\n \n saver.save(sess, os.path.join(OUTPUT_DIR, \"model\"), global_step=bi)\n if(a.finetune):\n print('finuetune')\n POINT_NUM_GT_bs = np.array(POINT_NUM_GT).reshape(1,1)\n points_input_num_bs = np.array(POINT_NUM).reshape(1,1)\n points_all = []\n samples_all = []\n for epoch in range(1):\n print('epoch:',epoch)\n sess.run(tf.global_variables_initializer())\n start_time = time.time()\n checkpoint = tf.train.get_checkpoint_state(OUTPUT_DIR).all_model_checkpoint_paths\n print(checkpoint[a.save_idx])\n \n \n saver.restore(sess, checkpoint[a.save_idx])\n print(files_path[0] + '.npz') \n load_data = np.load(files_path[0] + '.npz')\n \n points = load_data['sample_near'].reshape(-1,3)\n samples = load_data['sample'].reshape(-1,3)\n SP_NUM = points.shape[0]\n for bi in range(100010):\n feature_bs = feature_bs_all[0]\n rt = np.random.choice(SP_NUM, POINT_NUM, replace = False) \n #rt = random.randint(0,samples.shape[0]-1)\n sample = samples[rt,:].reshape(BS, POINT_NUM, 3)\n point = points[rt,:].reshape(BS, POINT_NUM, 3)\n \n feature_bs_t = feature_bs.reshape(BS,POINT_NUM,SHAPE_NUM)\n _, loss_c = sess.run([loss_optim_g,loss_g],feed_dict={feature_global:feature_bs_t,points_target_num:POINT_NUM_GT_bs,points_input_num:points_input_num_bs,\n points_target_global:point,input_points_3d_global:sample})\n \n if(bi%100000 == 0):\n print('model:',bi,'epoch:',epoch,'loss:',loss_c)\n saver.save(sess, os.path.join(OUTPUT_DIR_FINETUNE, \"model\"), global_step=bi)\n #saver.save(sess, os.path.join(OUTPUT_DIR_FINETUNE, \"model\"), global_step=epoch)\n \n if(a.test):\n \"\"\" feature_bs = []\n for j in range(vox_size*vox_size):\n t = np.zeros(SHAPE_NUM)\n t[0] = 1\n feature_bs.append(t)\n feature_bs = np.asarray(feature_bs)\n sdf_c = sess.run([sdf_g],feed_dict={input_points_3d_global:input_points_2d_bs_t,feature_global:feature_bs_t,\n points_target_num:POINT_NUM_GT_bs,points_input_num:points_input_num_bs}) \"\"\"\n print('test start')\n \n \n s = np.arange(-bd,bd, (2*bd)/128)\n \n print(s.shape[0])\n vox_size = s.shape[0]\n POINT_NUM_GT_bs = np.array(vox_size).reshape(1,1)\n points_input_num_bs = np.array(POINT_NUM).reshape(1,1)\n \n \n \n \n POINT_NUM_GT_bs = np.array(vox_size*vox_size).reshape(1,1)\n\n sess.run(tf.global_variables_initializer())\n checkpoint = tf.train.get_checkpoint_state(OUTPUT_DIR_FINETUNE).all_model_checkpoint_paths\n print(checkpoint[a.save_idx])\n saver.restore(sess, checkpoint[a.save_idx])\n\n #saver.restore(sess, a.out_dir + 'model-0')\n \n point_sparse = np.load(a.data_dir + a.input_ply_file + '.npz')['pointcloud_s']\n \n\n \n input_points_2d_bs = []\n\n bd_max = [np.max(point_sparse[:,0]), np.max(point_sparse[:,1]), np.max(point_sparse[:,2])] \n bd_min = [np.min(point_sparse[:,0]), np.min(point_sparse[:,1]),np.min(point_sparse[:,2])] \n bd_max = np.asarray(bd_max) + 0.05\n bd_min = np.asarray(bd_min) - 0.05\n sx = np.arange(bd_min[0], bd_max[0], (bd_max[0] - bd_min[0])/vox_size)\n sy = np.arange(bd_min[1], bd_max[1], (bd_max[1] - bd_min[1])/vox_size)\n sz = np.arange(bd_min[2], bd_max[2], (bd_max[2] - bd_min[2])/vox_size)\n print(bd_max)\n print(bd_min)\n for i in sx:\n for j in sy:\n for k in sz:\n input_points_2d_bs.append(np.asarray([i,j,k]))\n input_points_2d_bs = np.asarray(input_points_2d_bs)\n input_points_2d_bs = input_points_2d_bs.reshape((vox_size,vox_size,vox_size,3))\n \n vox = []\n feature_bs = []\n for j in range(vox_size*vox_size):\n t = np.zeros(SHAPE_NUM)\n t[0] = 1\n feature_bs.append(t)\n feature_bs = np.asarray(feature_bs)\n for i in range(input_points_2d_bs.shape[0]):\n \n input_points_2d_bs_t = input_points_2d_bs[i,:,:,:]\n input_points_2d_bs_t = input_points_2d_bs_t.reshape(BS, vox_size*vox_size, 3)\n feature_bs_t = feature_bs.reshape(BS,vox_size*vox_size,SHAPE_NUM)\n sdf_c = sess.run([sdf_g],feed_dict={input_points_3d_global:input_points_2d_bs_t,feature_global:feature_bs_t,\n points_target_num:POINT_NUM_GT_bs,points_input_num:points_input_num_bs})\n vox.append(sdf_c)\n\n \n vox = np.asarray(vox)\n #vis_single_points(moved_points, 'moved_points.ply')\n #print('vox',np.min(vox),np.max(vox),np.mean(vox))\n vox = vox.reshape((vox_size,vox_size,vox_size))\n vox_max = np.max(vox.reshape((-1)))\n vox_min = np.min(vox.reshape((-1)))\n print('max_min:',vox_max,vox_min,np.mean(vox))\n \n #threshs = [0.001,0.0015,0.002,0.0025,0.005]\n threshs = [0.005]\n for thresh in threshs:\n print(np.sum(vox>thresh),np.sum(vox0.0)0.0)>np.sum(vox<0.0)):\n triangles_t = []\n for it in range(triangles.shape[0]):\n tt = np.array([triangles[it,2],triangles[it,1],triangles[it,0]])\n triangles_t.append(tt)\n triangles_t = np.asarray(triangles_t)\n else:\n triangles_t = triangles\n triangles_t = np.asarray(triangles_t)\n\n vertices -= 0.5\n # Undo padding\n vertices -= 1\n # Normalize to bounding box\n vertices /= np.array([vox_size-1, vox_size-1, vox_size-1])\n vertices = (bd_max-bd_min) * vertices + bd_min\n mesh = trimesh.Trimesh(vertices, triangles_t,\n vertex_normals=None,\n process=False)\n \n \n loc_data = np.load(a.data_dir + a.input_ply_file + '.npz')\n vertices = vertices * loc_data['scal'] + loc_data['trans']\n mesh = trimesh.Trimesh(vertices, triangles_t,\n vertex_normals=None,\n process=False)\n mesh.export(OUTPUT_DIR_FINETUNE + '/PCL_' + a.input_ply_file + '_'+ str(thresh) + '.off')\n \n \n \n\n \n ", "meta": {"hexsha": "c6323a311a7ea34f5fae721c8503eece8a9a61f2", "size": 32463, "ext": "py", "lang": "Python", "max_stars_repo_path": "pcp.py", "max_stars_repo_name": "mabaorui/PredictableContextPrior", "max_stars_repo_head_hexsha": "c8fc75f8087370953d1e4089283d520cd1af07a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-03-23T10:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:10:22.000Z", "max_issues_repo_path": "pcp.py", "max_issues_repo_name": "mabaorui/PredictiveContext", "max_issues_repo_head_hexsha": "ddcb036c8e3197cfd2cd19c22bdfbcdaf419b1ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcp.py", "max_forks_repo_name": "mabaorui/PredictiveContext", "max_forks_repo_head_hexsha": "ddcb036c8e3197cfd2cd19c22bdfbcdaf419b1ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5408038977, "max_line_length": 215, "alphanum_fraction": 0.616024397, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 8345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.27512972976675254, "lm_q1q2_score": 0.141862368075229}} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated: 2018\nAuthor: A. P. Naik\nDescription: 'data' submodule of spam package. See README for details and usage\nexamples.\n\nAttributes\n----------\nSPARCGalaxy : class\n Main object containing all relevant data for each SPARC galaxy.\nnames_full : list of strings, length 147\n List of names of SPARC galaxies in 'full' sample, i.e. 147 galaxies\n remaining after first 4 data cuts described in Naik et al. (2019).\nnames_standard : list of strings, length 85\n List of names of SPARC galaxies in 'standard' sample, i.e. 85 galaxies\n remaining after all data cuts described in Naik et al. (2019). Difference\n between 'standard' and 'full' samples are that in the 'standard' case,\n environmentally screened galaxies have additionally been cut from the\n sample.\n\"\"\"\nimport os as _os\nimport numpy as _np\nfrom scipy.constants import parsec as _pc\n\n# physical constants\n_kpc = 1e+3*_pc\n_Mpc = 1e+6*_pc\n_Msun = 1.989e+30\n\n\nclass SPARCGalaxy:\n \"\"\"\n Class containing all relevant data for a given galaxy. All data come from\n the SPARC database (http://astroweb.cwru.edu/SPARC/), with the following\n exceptions:\n\n - gas_radius : calculated in spam.data.fit_gas_disc.py\n - hernquist_radius : calculated in spam.data.fit_stellar_bulge.py\n - hernquist_rho_0 : ditto\n - stellar_expdisc_sigma_0 : calculated in spam.data.fit_stellar_disc.py\n - stellar_expdisc_R_d : ditto\n - ext_potential : calculated via the screening map of Desmond et al.\n - ext_potential_lower : ditto\n - ext_potential_upper : ditto\n\n Parameters\n ----------\n name : str\n Name of galaxy matching name in SPARC database, e.g. F574-1 or CamB.\n\n Attributes\n ----------\n name : str\n As above.\n hubble_type : str\n Hubble classification of galaxy.\n distance : float\n Distance to galaxy. UNITS: m\n distance_err : float\n Error on distance to galaxy. UNITS: m\n distance_method : int, {1, 2, 3, 4, 5}\n Method used to determine distance to galaxy (see SPARC database for\n meanings of numbers).\n inclination : float\n Inclination of galaxy. UNITS: degrees\n inclination_err : float\n Error on inclination. UNITS: degrees\n luminosity_tot : float\n Total luminosity of galaxy at 3.6mu. UNITS: 10^9 L_sun.\n luminosity_err : float\n Error on total luminosity. UNITS: 10^9 L_sun.\n disc_scale : float\n Scale length of disc fit to photometry data. UNITS: m\n disc_SB : float\n Central surface brightness of disc fit to photometry data. UNITS: m\n HI_mass : float\n Total mass of HI gas. UNITS: kg\n Q_flag : int\n Quality flag (see SPARC database).\n StellarBulge : bool\n Whether a bulge component is detected.\n R : 1D numpy.ndarray\n Radii of rotation curve measurements. UNITS: kpc\n v : 1D numpy.ndarray, shape same as R\n Rotation curve measurements. UNITS: km/s\n v_err : 1D numpy.ndarray, shape same as R\n Errors on rotation curve. UNITS: km/s\n v_gas : 1D numpy.ndarray, shape same as R\n Gas contribution to rotation curve. UNITS: km/s\n v_disc : 1D numpy.ndarray, shape same as R\n Stellar disc contribution to rotation curve, assuming mass-to-light\n ratio of 1 M_sun/L_sun. UNITS: km/s\n v_bul : 1D numpy.ndarray, shape same as R\n Stellar bulge contribution to rotation curve, assuming mass-to-light\n ratio of 1 M_sun/L_sun. Zero everywhere if StellarBulge is False.\n UNITS: km/s\n coords_RA : float\n Right ascension of galaxy. UNITS: degrees\n coords_DEC : float\n Declination of galaxy. UNITS: degrees\n gas_radius : float\n Best fit radius of gas disc, calculated in spam.data.fit_gas_disc.py.\n UNITS: m\n hernquist_radius : float\n Best fit radius of Hernquist bulge, calculated in\n spam.data.fit_stellar_bulge.py. UNITS: m\n hernquist_rho_0 : float\n Best fit central density of Hernquist bulge, calculated in\n spam.data.fit_stellar_bulge.py. UNITS: kg/m^3\n stellar_expdisc_sigma_0 : float\n Best fit central density of stellar disc, calculated in\n spam.data.fit_stellar_disc.py. UNITS: kg/m^2\n stellar_expdisc_R_d : float\n Best fit scale length of stellar disc, calculated in\n spam.data.fit_stellar_disc.py. UNITS: m\n ext_potential : float\n Maximum posterior external potential (specifically, log10(phi/c^2) )\n calculated via the screening map of Desmond et al. (see Naik et al.,\n 2019 for details and refs).\n ext_potential_lower : float\n 1 sigma lower bound on external potential.\n ext_potential_upper : ditto\n 1 sigma upper bound on external potential.\n \"\"\"\n def __init__(self, name):\n\n self.name = name\n datadir = _os.path.dirname(_os.path.realpath(__file__))+\"/SPARCData\"\n\n # loading metadata\n listfile = open(datadir+\"/metadata.txt\", 'r')\n data = listfile.readlines()\n listfile.close()\n\n names = []\n for i in range(len(data)):\n names.append(data[i].split()[0])\n ind = names.index(self.name)\n\n htypes = {0: 'S0', 1: 'Sa', 2: 'Sab', 3: 'Sb', 4: 'Sbc', 5: 'Sc',\n 6: 'Scd', 7: 'Sd', 8: 'Sdm', 9: 'Sm', 10: 'Im', 11: 'BCD'}\n self.hubble_type = htypes[int(data[ind].split()[1])]\n self.distance = float(data[ind].split()[2])*_Mpc # metres\n self.distance_err = float(data[ind].split()[3])*_Mpc # metres\n self.distance_method = int(data[ind].split()[4])\n self.inclination = float(data[ind].split()[5]) # degrees\n self.inclination_err = float(data[ind].split()[6]) # degrees\n self.luminosity_tot = float(data[ind].split()[7]) # 1e+9 Lsun\n self.luminosity_err = float(data[ind].split()[8]) # 1e+9 Lsun\n self.disc_scale = float(data[ind].split()[11])*_kpc # metres\n self.disc_SB = float(data[ind].split()[12])/_pc**2 # Lsun/m^2\n self.HI_mass = float(data[ind].split()[13])*1e+9*_Msun # kg\n self.Q_flag = int(data[ind].split()[17])\n\n # loading main SPARC data\n self.filename = datadir+\"/data/\"+name+\"_rotmod.dat\"\n gal_file = open(self.filename, 'r')\n data = gal_file.readlines()\n gal_file.close()\n self.R = _np.zeros((len(data[3:]),))\n self.v = _np.zeros((len(data[3:]),))\n self.v_err = _np.zeros((len(data[3:]),))\n self.v_gas = _np.zeros((len(data[3:]),))\n self.v_disc = _np.zeros((len(data[3:]),))\n self.v_bul = _np.zeros((len(data[3:]),))\n for i in range(len(data[3:])):\n self.R[i] = float(data[3:][i].split()[0])\n self.v[i] = float(data[3:][i].split()[1])\n self.v_err[i] = float(data[3:][i].split()[2])\n self.v_gas[i] = float(data[3:][i].split()[3])\n self.v_disc[i] = float(data[3:][i].split()[4])\n self.v_bul[i] = float(data[3:][i].split()[5])\n if (self.v_bul == 0).all():\n self.StellarBulge = False\n else:\n self.StellarBulge = True\n\n # loading coords\n coordfile = open(datadir+\"/coords.txt\", 'r')\n data = coordfile.readlines()[1:]\n coordfile.close()\n assert data[ind].split()[0] == self.name\n self.coords_RA = float(data[ind].split()[2])\n self.coords_DEC = float(data[ind].split()[3])\n\n # loading gas radius\n gasfile = open(datadir+\"/gas_radii.txt\", 'r')\n data = gasfile.readlines()\n gasfile.close()\n assert data[ind].split()[0] == self.name\n self.gas_radius = float(data[ind].split()[1])\n\n # loading hernquist parameters\n if self.StellarBulge:\n hernquistfile = open(datadir+\"/hernquist_parameters.txt\", 'r')\n data = hernquistfile.readlines()\n hernquistfile.close()\n assert data[ind].split()[0] == self.name\n self.hernquist_rho_0 = float(data[ind].split()[1])\n self.hernquist_radius = float(data[ind].split()[2])\n else:\n self.hernquist_rho_0 = None\n self.hernquist_radius = None\n\n # loading stellar disc fit parameters\n discparfile = open(datadir+\"/stellar_disc_parameters.txt\", 'r')\n data = discparfile.readlines()\n discparfile.close()\n assert data[ind].split()[0] == self.name\n self.stellar_expdisc_sigma_0 = float(data[ind].split()[1]) # kg/m^2\n self.stellar_expdisc_R_d = float(data[ind].split()[2]) # metres\n\n # loading external potential data\n potential_dir = datadir+\"/SPARC_potentials\"\n col1 = _np.array([], dtype=_np.float64)\n col2 = _np.array([], dtype=_np.float64)\n col3 = _np.array([], dtype=_np.float64)\n for i in range(20):\n file = open(potential_dir+\"/SPARC_screen_\"+str(i)+\".dat\", 'r')\n data = file.readlines()\n file.close()\n assert data[ind].split()[0] == self.name\n col1 = _np.append(col1, float(data[ind].split()[1]))\n col2 = _np.append(col2, float(data[ind].split()[2]))\n col3 = _np.append(col3, float(data[ind].split()[3]))\n self.ext_potential_lower = col1\n self.ext_potential = col2\n self.ext_potential_upper = col3\n\n return\n\n\n# getting list of galaxy names\nnames_full = []\nnames_standard = []\n_datadir = _os.path.dirname(_os.path.realpath(__file__))+\"/SPARCData\"\n_namefile = open(_datadir+\"/names_full.txt\", 'r')\n_data = _namefile.readlines()\n_namefile.close()\nnames_full = []\nfor _i in range(len(_data)):\n names_full.append(_data[_i].split()[0])\n_namefile = open(_datadir+\"/names_standard.txt\", 'r')\n_data = _namefile.readlines()\n_namefile.close()\nnames_standard = []\nfor _i in range(len(_data)):\n names_standard.append(_data[_i].split()[0])\n\n__all__ = ['SPARCGalaxy', 'names_full', 'names_standard']\n", "meta": {"hexsha": "74f406f4fba311e50df4182586053b725db96b99", "size": 9934, "ext": "py", "lang": "Python", "max_stars_repo_path": "data/__init__.py", "max_stars_repo_name": "aneeshnaik/spam", "max_stars_repo_head_hexsha": "f66212bf77d72c8528c1a0d6cbe814cd360794c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "data/__init__.py", "max_issues_repo_name": "aneeshnaik/spam", "max_issues_repo_head_hexsha": "f66212bf77d72c8528c1a0d6cbe814cd360794c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data/__init__.py", "max_forks_repo_name": "aneeshnaik/spam", "max_forks_repo_head_hexsha": "f66212bf77d72c8528c1a0d6cbe814cd360794c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2648221344, "max_line_length": 79, "alphanum_fraction": 0.6267364606, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.2689414330889797, "lm_q1q2_score": 0.14181726148919926}} {"text": "#!/usr/bin/env python\n# encoding: utf-8\n\nimport os,utils,re,sfhs,weight,collections,astro_filter_light\nimport numpy as np\n# more modules are loaded in ezgal.__init__()\n# they are split up this way so that ezgal_light doesn't have to import those modules\n__ver__ = '2.0'\n\nclass ezgal(object):\n \"\"\" model = ezgal.ezgal(model_file, is_ised=False, is_fits=False, is_ascii=False, has_masses=False, units='a', age_units='gyrs')\n \n Class for converting galaxy seds as a function of age to magnitudes as a function of redshift.\n Reads in bc03 ised files as well as ascii files, effectively replacing cm_evolution from the bc03 src files\n Specify a model file. It should be a bc03 ised file, an ascii file, or a model file created with this class (which are stored as fits).\n See ezgal._load_ascii for information on formatting/units for ascii files\n This will automatically try to dtermine which type of file you have passed it. If this fails, you can specify it manually with the is_* flags.\n \n units, age_units, and has_masses apply only for ascii files. See ezgal._load_ascii()\n \"\"\"\n\n # model information\n filename = '' # the name of the file\n nages = 0 # number of different aged SEDs\n ages = np.array([]) # array of ages (years)\n nvs = 0 # number of frequences in each SED\n vs = np.array([]) # array of frequences for SEDs\n nls = 0 # number of wavelengths in each SED (same as self.nvs)\n ls = np.array([]) # array of wavelengths for SEDs (angstroms)\n seds = np.array([]) # age/SED grid. Units need to be ergs/cm^2/s. Size is nvs x nages\n # normalization info\n norm = { 'norm': 0, 'z': 0, 'filter': '', 'vega': False, 'apparent': False }\n # mass info\n has_masses = False # whether or not masses have been set\n masses = np.array([]) # masses as a function of self.ages\n # sfh info\n has_sfh = False # whether or not a star formation history is set\n sfh = np.array([]) # star formation as a function of self.ages\n\n # cosmology related stuff\n cosmology_loaded = False # whether or not a cosmology has been loaded\n cosmo = None # cosmology object\n zfs = np.array([]) # formation redshifts for models\n nzfs = 0 # number of formation redshifts to model\n zs = np.array([]) # redshifts at which to project models\n nzs = 0 # number of redshifts models should calculated at\n\n # filter stuff.\n filters = {} # dictionary of astro_filter objects\n filter_order = [] # list of filter names (in order added)\n nfilters = 0 # number of filters\n current_filter = -1 # counter for iterator\n\n # info for interpolated model SEDs. The SEDs are interpolated to a regular grid for each formation redshift.\n # These interpolated models are stored to save time if needed again\n interp_seds = [] # interpolated seds - each list element is a dictionary with sed info\n interp_zfs = np.array([]) # list of formation redshifts for sed\n tol = 1e-8 # tolerance for determining whether a given zf matches a stored zf\n\n # additional data\n data_dir = '' # data directory for filters, models, and reference spectra\n filter_dir = False # user-set directory for filters\n model_dir = False # user-set directory for models\n has_vega = False # whether or not the vega spectrum is found and loaded\n vega = np.array([]) # vega spectrum (nu vs Fnu)\n vega_out = False # if True then retrieved mags will be in vega mags\n has_solar = False # whether or not the solar spectrum is found and loaded\n solar = np.array([]) # solar spectrum (nu vs Fnu)\n\n # meta data\n has_meta_data = False # whether or not any meta data has been set for this model\n meta_data = {} # meta data for this model\n\n # weight for adding together models\n model_weight = 1\n\n ##########\n ## init ##\n ##########\n def __init__(self, model_file='', is_ised=False, is_fits=False, is_ascii=False, has_masses=False, units='a', age_units='gyrs', skip_load=False):\n \"\"\" model = ezgal.ezgal(model_file, is_ised=False, is_fits=False, is_ascii=False, has_masses=False, units='a', age_units='gyrs')\n \n Class for converting galaxy seds as a function of age to magnitudes as a function of redshift.\n Reads in bc03 ised files as well as ascii files, effectively replacing cm_evolution from the bc03 src files\n Specify a model file. It should be a bc03 ised file, an ascii file, or a model file created with this class (which are stored as fits).\n See ezgal._load_ascii for information on formatting/units for ascii files\n This will automatically try to dtermine which type of file you have passed it. If this fails, you can specify it manually with the is_* flags.\n \n units, age_units, and has_masses apply only for ascii files. See ezgal._load_ascii()\n \"\"\"\n\n # load additional modules. Yes, this is strange. But this way ezgal_light can inherit ezgal.\n # this is necessary because ezgal_light is intended to work without any of these modules\n import cosmology\n import astro_filter\n import csp_integrator\n import pyfits\n import scipy.integrate as integrate\n global cosmology\n global pyfits\n global integrate\n global astro_filter\n global csp_integrator\n\n # load a default cosmology\n self.set_cosmology()\n\n # clear filter list etc\n self.filters = {}\n self.filter_order = []\n self.interp_seds = []\n self.inter_zs = np.array([])\n self.zfs = np.array([])\n self.zs = np.array([])\n self.norm = { 'norm': 0, 'z': 0, 'filter': '', 'vega': False, 'apparent': False }\n\n # save path to data folder: module directory/data\n self.data_dir = os.path.dirname(os.path.realpath(__file__)) + '/data/'\n\n # how about path to filter and model directories?\n self.filter_dir = False\n self.model_dir = False\n if os.environ.has_key('ezgal_filters'):\n self.filter_dir = os.environ['ezgal_filters']\n elif os.environ.has_key('EZGAL_FILTERS'):\n self.filter_dir = os.environ['EZGAL_FILTERS']\n if os.environ.has_key('ezgal_models'):\n self.model_dir = os.environ['ezgal_models']\n elif os.environ.has_key('EZGAL_MODELS'):\n self.model_dir = os.environ['EZGAL_MODELS']\n\n # make sure paths end with a slash\n if self.data_dir[-1] != os.sep: self.data_dir += os.sep\n if self.filter_dir and self.filter_dir[-1] != os.sep: self.filter_dir += os.sep\n if self.model_dir and self.model_dir[-1] != os.sep: self.model_dir += os.sep\n\n # attempt to load the vega spectrum\n vega_file = '%srefs/vega.fits' % self.data_dir\n if os.path.isfile(vega_file):\n fits = pyfits.open(vega_file)\n self.vega = np.column_stack((fits[1].data.field('freq'),fits[1].data.field('flux')))\n self.has_vega = True\n else:\n self.vega = np.array([])\n self.has_vega = False\n\n # attempt to load the solar spectrum\n solar_file = '%srefs/solar.fits' % self.data_dir\n if os.path.isfile(solar_file):\n fits = pyfits.open(solar_file)\n self.solar = np.column_stack((fits[1].data.field('freq'),fits[1].data.field('flux')))\n self.has_solar = True\n else:\n self.solar = np.array([])\n self.has_solar = False\n\n # load model\n if not skip_load: self._load(model_file, is_ised=is_ised, is_fits=is_fits, is_ascii=is_ascii, has_masses=has_masses, units=units, age_units=age_units)\n\n #####################\n ## return iterator ##\n #####################\n def __iter__(self):\n self.current_filter = -1\n return self\n\n #########################\n ## next() for iterator ##\n #########################\n def next(self):\n\n self.current_filter += 1\n if self.current_filter == len(self.filter_order): raise StopIteration\n\n filt = self.filter_order[self.current_filter]\n return (filt,self.filters[filt])\n\n #####################\n ## load model file ##\n #####################\n def _load(self, model_file, is_ised=False, is_fits=False, is_ascii=False, has_masses=False, units='a', age_units='gyrs'):\n\n # find the model file\n model_file = self._find_model_file(model_file)\n self.filename = model_file\n\n # Load input file depending on what type of file it is.\n\n # test for a bruzual-charlot binary ised file\n if model_file[len(model_file)-5:] == '.ised' or is_ised:\n self._load_ised(self.filename)\n else:\n # And then the rest.\n fp = open(model_file, 'r')\n start = fp.read(80)\n fp.close()\n if (re.search('SIMPLE\\s+=\\s+T', start, re.IGNORECASE) or is_fits) and not(is_ascii):\n self._load_model(model_file)\n elif (start[0:5] == 'EzGal'):\n self._load_ascii_model(model_file)\n else:\n self._load_ascii(model_file, has_masses=has_masses, units=units, age_units=age_units)\n\n # always include a t=0 SED to avoid out of age interpolation errors later\n # a t=0 SED is also assumed during CSP generation\n if self.nages and self.ages.min() > 0:\n self.ages = np.append(0, self.ages)\n self.seds = np.hstack((np.zeros((self.nvs,1)), self.seds))\n if self.has_masses: self.masses = np.append(0, self.masses)\n self.nages += 1\n\n ######################\n ## _find_model_file ##\n ######################\n def _find_model_file(self, file):\n\n # first check file path\n files = [file]\n\n # then model_dir if set in environment\n if self.model_dir: files.append('%s%s' % (self.model_dir,os.path.basename(file)))\n\n # finally model directory in data directory\n files.append('%smodels/%s' % (self.data_dir,os.path.basename(file)))\n\n # now loop through the different files\n for check in files:\n if os.path.isfile(check): return check\n\n raise ValueError('The specified model file, %s was not found!' % file)\n return False\n\n #####################\n ## set vega output ##\n #####################\n def set_vega_output(self):\n \"\"\" ezgal.set_vega_output()\n \n :Example:\n >>> import ezgal\n >>> model = ezgal.model('bc03_ssp_z_0.02_chab.model')\n >>> # AB mag for ch1, zf=3, z=1\n >>> model.get_absolute_mags(3.0, filters='ch1', zs=1.0)\n 5.6135203220610741\n >>> # set Vega output\n >>> model.set_vega_output()\n >>> # Vega mag for ch1, zf=3, z=1\n >>> model.get_absolute_mags(3.0, filters='ch1', zs=1.0)\n 2.8262012027987748\n \n Set the default output for the ezgal object to Vega mags for all methods that can return magnitudes in vega or AB units.\n \n .. note::\n By default all ``EzGal`` methods output AB magnitudes.\n \n \"\"\"\n\n if not self.has_vega: raise ValueError('Cannot output vega mags: vega spectrum is not loaded!')\n self.vega_out = True\n\n ###################\n ## set AB output ##\n ###################\n def set_ab_output(self):\n \"\"\" ezgal.set_ab_output()\n \n :Example:\n >>> import ezgal\n >>> model = ezgal.model('bc03_ssp_z_0.02_chab.model')\n >>> # AB mag for ch1, zf=3, z=1\n >>> model.get_absolute_mags(3.0, filters='ch1', zs=1.0)\n 5.6135203220610741\n >>> # set Vega output\n >>> model.set_vega_output()\n >>> # Vega mag for ch1, zf=3, z=1\n >>> model.get_absolute_mags(3.0, filters='ch1', zs=1.0)\n 2.8262012027987748\n >>> # and back to AB mags\n >>> model.set_ab_output()\n >>> model.get_absolute_mags(3.0, filters='ch1', zs=1.0)\n 5.6135203220610741\n \n Set the default output for the ezgal object to AB mags for all methods that can return magnitudes in vega or AB units.\n \n .. note::\n By default all ``EzGal`` methods output AB magnitudes.\n \"\"\"\n\n self.vega_out = False\n\n ################\n ## set masses ##\n ################\n def set_masses(self, ages, masses, age_units='gyrs', grid=True):\n \"\"\" ezgal.set_masses(ages, masses, age_units='gyrs', grid=True)\n \n :param ages: A list of ages\n :param masses: A list of corresponding masses\n :param age_units: The units that ``ages`` are in\n :type ages: list, array\n :type masses: list, array\n :type age_units: str\n \n Set the age-mass relationship for the model. Pass a list of ages, the corresponding masses, and the units the ages are in. Once the age-mass relationship is set, masses and mass-to-light ratios can be fetched using all the standard methods. Also, age-mass relationships will be stored for any CSPs generated from the ``EzGal`` object.\n \n .. note::\n Masses are stored in the ezgal object and are gridded for every filter and formation redshift. This is technically unnecessary since mass is independent of filter. However, this guarantees that interpolation is done for masses exactly as for luminosity, thus removing potential errors from the mass-to-light ratios. \"\"\"\n\n # sort by age\n sinds = ages.argsort()\n ages = ages[sinds]\n masses = masses[sinds]\n\n mass_ages = utils.convert_time(ages, incoming=age_units, outgoing='yrs')\n\n # is it exactly the same ages as stored in the SEDs? If not, then interpolate\n if (self.ages.size != mass_ages.size or np.abs(self.ages - mass_ages).max() != 0): masses = np.interp(self.ages, mass_ages, masses, left=0)\n\n # store mass information\n self.has_masses = True\n self.masses = masses\n\n # and grid the filters\n if grid:\n self._grid_filters(masses=True)\n\n #####################\n ## check cosmology ##\n #####################\n def check_cosmology(self):\n if not self.cosmology_loaded:\n self.set_cosmology()\n print 'Default cosmology loaded'\n\n ###################\n ## set cosmology ##\n ###################\n def set_cosmology(self, Om=0.272, Ol=0.728, h=0.704, w=-1):\n \"\"\" ezgal.set_cosmology(Om=0.272, Ol=0.728, h=0.704, w=-1)\n \n Set the cosmology. The default cosmology is from `WMAP 7 `_, Komatsu, et al. 2011, ApJS, 192, 18. If the cosmology changes, then all filters will be regrided and any stored evolution models will be discarded.\n \"\"\"\n\n # is the cosmology changing?\n if self.cosmology_loaded:\n # don't bother doing anything if the cosmology isn't actually changing\n if max(np.abs(self.cosmo.Om - Om), np.abs(self.cosmo.Ol - Ol), np.abs(self.cosmo.h - h), np.abs(self.cosmo.w - w)) < self.tol: return True\n\n self.cosmo = cosmology.Cosmology(Om=Om, Ol=Ol, h=h, w=w)\n self.cosmo.lookup_tol = self.tol\n self.cosmology_loaded = True\n\n # pass cosmology object to all the filter objects\n for filter in self.filter_order: self.filters[filter].set_cosmology(self.cosmo)\n\n # now clear all the stored information\n self.clear_cache()\n\n # now force a regrid, since the cosmology has changed\n self._grid_filters(force=True)\n return True\n\n #############################\n ## set formation redshifts ##\n #############################\n def set_zfs(self, zfs, grid=True):\n \"\"\" ezgal.set_zfs(zfs, grid=True)\n \n :param zfs: A list of formation redshifts\n :type zfs: list, array\n :returns: None\n \n Set a list of formation redshifts for the model. When filters are later added to the model, magnitude evolution will automatically be calculated for those filters at the set formation redshifts. Also, magnitude evolution will be calculated for any already added filters at the given formation redshifts unless ``grid=False``.\n \"\"\"\n\n zfs = np.asarray(zfs).ravel()\n if len(zfs.shape) == 0: zfs = np.array([zfs])\n if zfs.min() < 0: raise ValueError('Redshifts must be greater than zero!')\n\n self.zfs = zfs\n self.nzfs = self.zfs.size\n\n # build the iteration grid for all the filters\n if grid: self._grid_filters()\n\n self._set_zs()\n\n ##########################\n ## set redshift outputs ##\n ##########################\n def _set_zs(self, zf=None):\n \"\"\" ezgal._set_zs(zf=None)\n \n Set some default redshifts at which models should be evaluated.\n They will go out to z=zf. The maximum set zf will be used if not zf is passed. \"\"\"\n\n if zf is None and self.nzfs == 0: raise ValueError('Please set the formation redshifts with ezgal.set_zfs() before setting redshift outputs')\n if zf is None: zf = self.zfs.max()\n\n # always keep the most inclusive zs possible\n if self.nzs > 0:\n if zf < max(self.zs): return True\n\n self.zs = self.get_zs(zf)\n self.nzs = self.zs.size\n return True\n\n #############################\n ## get apparent magnitudes ##\n #############################\n def get_apparent_mags(self, zf, filters=None, zs=None, normalize=True, vega=None, ab=None, squeeze=True):\n \"\"\" mags = ezgal.get_apparent_mags(zf, filters=None, zs=None, normalize=True, vega=None, ab=None, squeeze=True)\n \n Same as :meth:`ezgal.ezgal.get_absolute_mags` excepts returns apparent magnitudes.\n \n .. note::\n This is equivalent to the apparent magnitude field ``m_AB_ev`` found in the output of the bruzual and charlot program ``cm_evolution``.\n .. seealso::\n :func:`ezgal.ezgal.get_absolute_mags`\n \"\"\"\n\n return self._get_mags(zf, kind='apparent', filters=filters, zs=zs, normalize=normalize, ab=ab, vega=vega, squeeze=squeeze)\n\n ######################################\n ## get observed absolute magnitudes ##\n ######################################\n def get_observed_absolute_mags(self, zf, filters=None, zs=None, normalize=True, vega=None, ab=None, squeeze=True):\n \"\"\" mags = ezgal.get_observed_absolute_mags(zf, filters=None, zs=None, normalize=True, vega=None, ab=None, squeeze=True)\n \n Same as :meth:`ezgal.ezgal.get_absolute_mags` excepts returns observed-frame absolute magnitudes. The observed-frame absolute magnitude is the absolute magnitude of the model after being redshifted to the given redshift.\n \n .. note::\n This is the equiavlent to ``M_AB_ev`` from the output of the bruzual and charlot program ``cm_evolution``\n .. seealso::\n :meth:`ezgal.ezgal.get_absolute_mags`, :meth:`ezgal.ezgal.set_normalization`, :meth:`ezgal.ezgal.set_vega_output`, :meth:`ezgal.ezgal.set_ab_output`\n \"\"\"\n\n return self._get_mags(zf, kind='obs_abs', filters=filters, zs=zs, normalize=normalize, ab=ab, vega=vega, squeeze=squeeze)\n\n #############################\n ## get absolute magnitudes ##\n #############################\n def get_absolute_mags(self, zf, filters=None, zs=None, normalize=True, ab=None, vega=None, squeeze=True):\n \"\"\" mags = ezgal.get_absolute_mags(zf, filters=None, zs=None, normalize=True, ab=None, vega=None, squeeze=True)\n \n :param zf: The formation redshift of the galaxy\n :param filters: A list of filters to calculate magnitudes for\n :param zs: A list of redshifts to calculate magnitudes at\n :param normalize: Whether or not to normalize the output\n :param ab: Whether or not to output in AB magnitues\n :param vega: Whether or not to output in Vega magnitudes\n :type zf: int, float\n :type filters: string, list of strings\n :type zs: int, float, list, array\n :type normalize: bool\n :type ab: bool\n :type vega: bool\n :returns: Array of magnitudes\n :rtype: array\n \n :Example:\n >>> import ezgal\n >>> model = ezgal.model('bc03_ssp_z_0.02_chab.model')\n >>> model.add_filter('ch1')\n >>> model.add_filter('ch2')\n >>> model.add_filter('ch3')\n >>> model.add_filter('ch4')\n >>> model.get_absolute_mags(3.0, zs=[0,1.0,2.0])\n array([[6.39000031 6.83946654 7.25469915 7.80111159]\n [5.61352032 6.07145866 6.49122232 7.04203427]\n [4.48814389 4.87218428 5.30970258 5.85536578]])\n >>> model.get_absolute_mags(3.0, filters=['ch1','ch2'], zs=[0,1.0,2.0])\n array([[6.39000031, 6.83946654],\n [5.61352032, 6.07145866],\n [4.48814389, 4.87218428]])\n >>> model.get_absolute_mags(3.0, filters='ch1', zs=[0,1.0,2.0])\n array([6.39000031 5.61352032 4.48814389])\n >>> model.get_absolute_mags(3.0, filters='ch1', zs=0)\n 6.39000030832\n \n \n Fetch the rest-frame absolute magnitudes for the given filter(s) at the given output redshifts (``zs``) for the given formation redshift (``zf``). If no filter is specified, then magnitudes will be fetched for all loaded filters. If the specified filters are not already loaded into ``EzGal``, it will attempt to load them automatically according to the rules in :meth:`ezgal.ezgal.add_filter`.\n \n If normalize=True then the returned magnitudes will be normalized if a normalization has been set with :meth:`ezgal.ezgal.set_normalization`.\n \n Returns an array of shape ``(len(zs),len(filters))`` with the absolute magnitudes. If there is only one filter, then it returns an array of shape ``(len(zs))``\n \n Call with vega=True or ab=True to specify ab or vega output. If neither is set it will output AB mags unless :meth:`ezgal.ezgal.set_vega_output` has been called.\n \n .. note::\n If no output redshifts are specified, then the redshifts in ezgal.zs will be used.\n .. note::\n This is the equiavlent to ``M_AB_ev - k_cor_ev`` from the output of the bruzual and charlot program ``cm_evolution``\n .. seealso::\n :func:`ezgal.ezgal.set_normalization`, :func:`ezgal.ezgal.set_vega_output`, :func:`ezgal.ezgal.set_ab_output`\n \"\"\"\n\n return self._get_mags(zf, kind='absolute', filters=filters, zs=zs, normalize=normalize, ab=ab, vega=vega, squeeze=squeeze)\n\n\n ###################\n ## get kcorrects ##\n ###################\n def get_kcorrects(self, zf, filters=None, zs=None, squeeze=True):\n \"\"\" mags = ezgal.get_kcorrects(zf, filters=None, zs=None, squeeze=True)\n \n Same as :meth:`ezgal.ezgal.get_ecorrects` but returns the kcorrections.\n \n .. note::\n This is the equiavlent to ``k_cor_ev`` from the output of the bruzual and charlot program ``cm_evolution``.\n .. seealso::\n :func:`ezgal.ezgal.get_ecorrects`\n \"\"\"\n\n return self._get_mags(zf, kind='kcorrect', filters=filters, zs=zs, normalize=False, squeeze=squeeze)\n\n ###################\n ## get ecorrects ##\n ###################\n def get_ecorrects(self, zf, filters=None, zs=None, squeeze=True):\n \"\"\" mags = ezgal.get_ecorrects(zf, filters=None, zs=None, squeeze=True)\n \n :param zf: The formation redshift\n :param filters: The filters to calculate e-corrections for\n :param zs: The redshifts to calculate e-corrections at\n :type zf: int, float\n :type filters: string, list of strings\n :type zs: int, float, list, array\n :returns: The ecorrections\n :rtype: array\n \n :Example:\n >>> import ezgal\n >>> model = ezgal.model('bc03_ssp_z_0.02_chab.model')\n >>> model.add_filter('ch1')\n >>> model.add_filter('ch2')\n >>> model.add_filter('ch3')\n >>> model.add_filter('ch4')\n >>> model.get_ecorrects(3.0, zs=[0,0.5,1.0])\n array([[0. , 0. , 0. , 0. ],\n [-0.34465634, -0.32867488, -0.32408269, -0.32054988],\n [-0.77647999, -0.76800788, -0.76347683, -0.75907732]])\n >>> model.get_ecorrects(3.0, filters=['ch1','ch2'], zs=[0,0.5,1.0])\n array([[0. , 0. ],\n [-0.34465634, -0.32867488],\n [-0.77647999, -0.76800788]])\n >>> model.get_ecorrects(3.0, filters='ch1', zs=[0,0.5,1.0])\n array([0. , -0.34465634, -0.77647999])\n >>> model.get_ecorrects(3.0, filters='ch1', zs=0)\n 0.0\n \n Fetch the e-corrections for the given filter(s) at the given output redshifts (``zs``) for the given formation redshift (``zf``). If no filter is specified, then magnitudes will be fetched for all loaded filters. If the specified filters are not already loaded into ``EzGal``, it will attempt to load them automatically according to the rules in :meth:`ezgal.ezgal.add_filter`.\n \n returns an array of shape ``(len(zs),len(filters))`` with the kcorrects. If there is only one filter, then it returns an array of shape ``(len(zs))``\n \n .. note::\n If no redshifts are specified, then the redshifts in ``ezgal.zs`` will be used. \"\"\"\n\n return self._get_mags(zf, kind='ecorrect', filters=filters, zs=zs, normalize=False, squeeze=squeeze)\n\n ###################\n ## get ecorrects ##\n ###################\n def get_ekcorrects(self, zf, filters=None, zs=None, squeeze=True):\n \"\"\" mags = ezgal.get_ecorrects(zf, filters=None, zs=None)\n \n Same as :meth:`ezgal.ezgal.get_ecorrects` but returns the e+k corrections.\n \n .. note::\n This is the equiavlent to ``e+k_cor`` from the output of the bruzual and charlot program ``cm_evolution``.\n .. seealso::\n :func:`ezgal.ezgal.get_ecorrects`\n \"\"\"\n\n return self._get_mags(zf, kind='ekcorrect', filters=filters, zs=zs, normalize=False, squeeze=squeeze)\n\n ##############\n ## get mags ##\n ##############\n def _get_mags(self, zf, kind='absolute', filters=None, zs=None, ab=None, vega=None, normalize=True, squeeze=True):\n \"\"\" mags = ezgal._get_mags(zf, kind='absolute', filters=None, zs=None, ab=None, vega=None, normalize=True)\n\n Fetch the given type of magnitude, using otherwise the same calling sequence as get_apparent_mags()\n \"\"\"\n\n # load default values\n zs = self._populate_zs(zs, zf=zf)\n filters = self._populate_filters(filters)\n vega_out = self._get_vega_out(ab=ab, vega=vega)\n\n # make sure this formation redshift/filter combination is gridded\n if not self._check_grid(filters=filters, zfs=zf): raise ValueError('Cannot calculate mags for given filter/zf combination because the seds have not been loaded!')\n\n # create data table for results\n mags = np.zeros((len(zs),len(filters)))\n\n # loop through filters one at a time.\n for (i,filter) in enumerate(filters):\n\n # now fetch the magnitudes\n if kind == 'absolute':\n mags[:,i] = self.filters[filter].get_absolute_mags(zf, zs, vega=vega_out)\n elif kind == 'obs_abs':\n mags[:,i] = self.filters[filter].get_observed_absolute_mags(zf, zs, vega=vega_out)\n elif kind == 'apparent':\n mags[:,i] = self.filters[filter].get_apparent_mags(zf, zs, vega=vega_out)\n elif kind == 'kcorrect':\n mags[:,i] = self.filters[filter].get_kcorrects(zf, zs)\n elif kind == 'ecorrect':\n mags[:,i] = self.filters[filter].get_ecorrects(zf, zs)\n elif kind == 'ekcorrect':\n mags[:,i] = self.filters[filter].get_ekcorrects(zf, zs)\n\n # normalize models\n if normalize and (kind == 'absolute' or kind == 'apparent'):\n mags += self.get_normalization(zf)\n\n # squeeze return value if requested\n if squeeze: return self._squeeze(mags, len(filters))\n return mags\n\n #########################\n ## get rest M/L ratios ##\n #########################\n def get_rest_ml_ratios(self, zf, filters=None, zs=None, squeeze=True):\n \"\"\" mls = ezgal.get_rest_ml_ratios(zf, filters=None, zs=None)\n \n Same as :meth:`ezgal.ezgal.get_observed_ml_ratios` excepts returns the rest-frame M/L ratios. Rest frame mass-to-light ratios are calculated using the rest-frame luminosity of the sun and the rest-frame luminosity of the model.\n \n .. seealso::\n :func:`ezgal.ezgal.get_observed_ml_ratios`\n .. warning::\n Only works if masses are set in the model.\n \"\"\"\n\n if not self.has_masses: raise ValueError('Cannot get mass-to-light ratios: masses were not found in the model file!')\n\n # load default values\n filters = self._populate_filters(filters)\n zs = self._populate_zs(zs)\n\n # fetch model magnitudes\n mags = self._get_mags(zf, kind='absolute', filters=filters, zs=zs, ab=True, normalize=False, squeeze=False)\n\n # calculate masses for these redshifts\n masses = self.get_masses(zf, zs, nfilters=len(filters), squeeze=False)\n\n # rest-frame absolute magnitude of sun\n solar_mags = self.get_solar_rest_mags(nzs=zs.size, filters=filters, ab=True, squeeze=False)\n\n # M/L ratio = mass/(L/Lsun) = mass/10**(-0.4*(M - Msun))\n mls = masses/10.0**(-0.4*(mags-solar_mags))\n\n # return squeezed array?\n return self._squeeze(mls, len(filters)) if squeeze else mls\n\n #############################\n ## get observed M/L ratios ##\n #############################\n def get_observed_ml_ratios(self, zf, filters=None, zs=None, squeeze=True):\n \"\"\" mls = ezgal.get_observed_ml_ratios(zf, filters=None, zs=None)\n \n :param zf: The formation redshift\n :param filters: The filters to calculate M/L ratios for\n :param zs: The redshifts to calculate M/L ratios at\n :type zf: int, float\n :type filters: string, list of strings\n :type zs: int, float, list, array\n :returns: The M/L ratios\n :rtype: array\n \n :Example:\n >>> import ezgal\n >>> model = ezgal.model('bc03_ssp_z_0.02_chab.model')\n >>> model.add_filter('sloan_u')\n >>> model.add_filter('sloan_i')\n >>> model.add_filter('ch1')\n >>> model.get_observed_ml_ratios(3.0, zs=[0,1.0,2.0])\n array([[7.64179498, 2.52235684, 0.6858418],\n [0.19372322, 2.24205801, 0.44824818],\n [ nan, 0.22833461, 0.28408678]])\n \n Returns the observed-frame mass-to-light ratios as a function of ``zf``, ``z``, and ``filters``. The observed-frame mass to light ratios is the stellar mass of the model given ``zf`` and ``z`` divided by the luminosity of the model in solar units. For observed-frame M/L ratios the observed-frame luminosity of the model and the observed-frame luminosity of the sun are used. The observed-frame luminosity of the sun is calculated by redshifting the solar spectrum to the given redshift and then projecting it through the filters. This returns an array of shape ``(len(zs),len(filters))`` with the observed-frame mass-to-light ratios. If there is only one filter, then it returns an array of shape ``(len(zs))``.\n \n .. note::\n Returns ``nan`` when the redshifted solar spectrum doesn't fully cover the filter.\n .. warning::\n Only works if masses are set in the model. \"\"\"\n\n if not self.has_masses: raise ValueError('Cannot get mass-to-light ratios: masses were not found in the model file!')\n\n # load default values\n filters = self._populate_filters(filters)\n zs = self._populate_zs(zs)\n\n # fetch model magnitudes\n mags = self._get_mags(zf, kind='obs_abs', filters=filters, zs=zs, ab=True, normalize=False, squeeze=False)\n\n # calculate masses for these redshifts\n masses = self.get_masses(zf, zs, nfilters=len(filters), squeeze=False)\n\n # observed-frame absolute magnitude of sun\n solar_mags = self.get_solar_observed_mags(zf, filters=filters, zs=zs, ab=True, squeeze=False)\n\n # M/L ratio = mass/(L/Lsun) = mass/10**(-0.4*(M - Msun))\n mls = masses/10.0**(-0.4*(mags-solar_mags))\n\n # return squeezed array?\n return self._squeeze(mls, len(filters)) if squeeze else mls\n\n #########################\n ## get solar rest mags ##\n #########################\n def get_solar_rest_mags(self, nzs=1, filters=None, ab=None, vega=None, squeeze=True):\n \"\"\" mags = ezgal.get_solar_rest_mags(nzs=None, filters=None, ab=None, vega=None)\n \n :param nzs: The number of redshifts to return solar rest-frame magnitudes for\n :param filters: The filters to calculate solar rest-frame magnitudes for\n :param zs: The redshifts to calculate M/L ratios at\n :param ab: Whether or not to output in AB magnitues\n :param vega: Whether or not to output in Vega magnitudes\n :type zf: int, float\n :type filters: string, list of strings\n :type zs: int, float, list, array\n :type ab: bool\n :type vega: bool\n :returns: Array of solar rest-frame magnitudes\n :rtype: array\n \n :Example:\n >>> import ezgal\n >>> model = ezgal.model('bc03_ssp_z_0.02_chab.model')\n >>> model.add_filter('ch1')\n >>> model.add_filter('ch2')\n >>> model.add_filter('ch3')\n >>> model.add_filter('ch4')\n >>> model.get_solar_rest_mags(nzs=3)\n array([[6.06644384, 6.56615057, 7.0455159 , 7.66857929],\n [6.06644384, 6.56615057, 7.0455159 , 7.66857929],\n [6.06644384, 6.56615057, 7.0455159 , 7.66857929]])\n >>> model.get_solar_rest_mags(nzs=3, filters=['ch1','ch2'])\n array([[6.06644384, 6.56615057],\n [6.06644384, 6.56615057],\n [6.06644384, 6.56615057]])\n >>> model.get_solar_rest_mags(nzs=1, filters='ch1')\n 6.0664438415489164\n \n Return the rest-frame absolute magnitude of the sun through the given filters. Specify the number of redshifts to return an array of size ``(nzs,len(filters))``. The solar rest-frame magnitude does not depend on redshift, so values are repeated in the column for each filter in the returned array. This is done to match the return type of other methods such as :meth:`ezgal.ezgal.get_solar_observed_mags`.\n \n If nzs is None then returns an array of size ``len(filters)``. If no filters are specified then it will calculate solar rest-frame magnitudes for all filters which have already been loaded into the model.\n \n Call with ``vega=True`` or ``ab=True`` to specify ab or vega output. If neither is set it will output AB mags unless :meth:`ezgal.ezgal.set_vega_output` has been called.\n \n .. note::\n Returns NaN for undefined solar magnitudes. \"\"\"\n\n # load default values\n filters = self._populate_filters(filters)\n vega_out = self._get_vega_out(ab=ab, vega=vega)\n\n mags = np.empty(len(filters))\n\n # fetch mags from filters\n for (i,filt) in enumerate(filters):\n # filter must be added\n if not self.filters.has_key(filt):\n self.add_filter(filt)\n if not self.filters.has_key(filt): raise ValueError('The filter %s could not be loaded!' % filt)\n\n if self.filters[filt].has_solar:\n mags[i] = self.filters[filt].solar\n if vega_out: mags[i] += self.filters[filt].to_vega\n else:\n mags[i] = np.nan\n\n # repeat nzs times\n mags = mags.reshape((len(filters),1)).repeat(nzs, axis=1).transpose()\n\n if not squeeze: return mags\n return self._squeeze(mags, len(filters))\n\n #############################\n ## get solar observed mags ##\n #############################\n def get_solar_observed_mags(self, zf, filters=None, zs=zs, ab=None, vega=None, squeeze=True):\n \"\"\" mags = ezgal.get_solar_observed_mags(zf, filters=None, zs=zs, ab=None, vega=None, squeeze=True)\n \n :param zf: The formation redshift of the galaxy\n :param filters: A list of filters to calculate magnitudes for\n :param zs: A list of redshifts to calculate magnitudes at\n :param ab: Whether or not to output in AB magnitues\n :param vega: Whether or not to output in Vega magnitudes\n :type zf: int, float\n :type filters: string, list of strings\n :type zs: int, float, list, array\n :type ab: bool\n :type vega: bool\n :returns: Array of solar observed-frame magnitudes\n :rtype: array\n \n :Example:\n >>> import ezgal\n >>> model = ezgal.model('bc03_ssp_z_0.02_chab.model')\n >>> model.add_filter('ch1')\n >>> model.add_filter('ch2')\n >>> model.add_filter('ch3')\n >>> model.add_filter('ch4')\n >>> model.get_solar_observed_mags(3.0, zs=[0,1.0,2.0])\n array([[6.06644384, 6.56615057, 7.0455159 , 7.66857929],\n [4.05625676, 4.44971653, 4.89681114, 5.50676563],\n [3.35937661, 3.43865068, 3.72883098, 4.27894184]])\n >>> model.get_solar_observed_mags(3.0, filters=['ch1','ch2'], zs=[0,1.0,2.0])\n array([[6.06644384, 6.56615057],\n [4.05625676, 4.44971653],\n [3.35937661, 3.43865068]])\n >>> model.get_solar_observed_mags(3.0, filters='ch1', zs=[0,1.0,2.0])\n array([6.06644384, 4.05625676, 3.35937661])\n >>> model.get_solar_observed_mags(3.0, filters='ch1', zs=0)\n 6.0664438415489164\n \n Return the observed-frame absolute magnitude of the sun given ``zf``, ``filters``, and ``zs``. Returns an array of size (zs.size,filters.size). The observed-frame magnitude of the sun is the absolute magnitude of the sun after being redshifted to the given redshift. As such the observed-frame solar magnitude of the sun does not actually depend on ``zf``. However, ``zf`` is currently included in the calling sequence for consistency with other similar functions, such as :meth:`ezgal.ezgal.get_absolute_mags`. Returns an array of shape ``(len(zs),len(filters))``. If there is only one filter, then it returns an array of shape ``(len(zs))``\n \n Call with ``vega=True`` or ``ab=True`` to specify ab or vega output. If neither is set it will output AB mags unless :meth:`ezgal.ezgal.set_vega_output` has been called.\n \n .. note::\n Returns NaN for undefined solar magnitudes.\n .. note::\n The solar observed-frame magnitude does not depend on ``zf``, but this is included for consistency with other similar functions.\n .. warning::\n Requires ``zf > zs`` \"\"\"\n\n # load default values\n zs = self._populate_zs(zs)\n filters = self._populate_filters(filters)\n vega_out = self._get_vega_out(ab=ab, vega=vega)\n\n # make sure this formation redshift/filter combination is gridded\n if not self._check_grid(filters=filters, zfs=zf, solar=True): raise ValueError('Cannot calculate mags for given filter/zf combination because the seds have not been loaded!')\n\n # create data table for results\n mags = np.zeros((len(zs),len(filters)))\n\n # loop through filters one at a time.\n for (i,filter) in enumerate(filters): mags[:,i] = self.filters[filter].get_solar_mags(zf, zs, vega=vega_out)\n\n if not squeeze: return mags\n return self._squeeze(mags, len(filters))\n\n ###################\n ## get kcorrects ##\n ###################\n def get_distance_moduli(self, zs=None, nfilters=None, squeeze=True):\n \"\"\" mags = ezgal.get_distance_moduli(zs=None, nfilters=None, squeeze=True)\n \n :param zs: The redshifts to return distance moduli for\n :param nfilters: The number of filters to return distance moduli for\n :type zs: int, float, list, array\n :type nfilters: int\n :returns: Distance Moduli\n :rtype: array\n \n :Example:\n >>> import ezgal\n >>> model = ezgal.model('bc03_ssp_z_0.02_chab.model')\n >>> print model.get_distance_moduli([0.1, 0.5, 1.0], nfilters=1)\n array([38.30736787, 42.27018553, 44.1248392])\n >>> print model.get_distance_moduli([0.1, 0.5, 1.0], nfilters=2)\n array([[38.30736787, 38.30736787],\n [42.27018553, 42.27018553],\n [44.1248392 , 44.1248392]])\n \n Fetch the distance moduli for the given redshifts. Specify the number of filters to return an array of size (len(zs),nfilters). If nfilters is None, then the number of filters will be taken to be the number of filters loaded in the object. If there is only one filter, then it returns an array of shape (len(zs)). The distance moduli does not depend on filter so values are repeated when ``nfilters>1``. This is done for consistency with the return values of methods like :meth:`ezgal.ezgal.get_apparent_mags`.\n \n .. note::\n If no output redshifts are specified, then the redshifts in ezgal.zs will be used.\n \"\"\"\n\n # load defaults\n zs = self._populate_zs(zs)\n if nfilters is None: nfilters = self.nfilters\n\n # calculate the distance moduli\n dms = np.empty(len(zs))\n for i in range(len(zs)): dms[i] = self.cosmo.DistMod(zs[i])\n\n dms = dms.reshape((len(zs),1)).repeat(nfilters, axis=1)\n\n if not squeeze: return dms\n return self._squeeze(dms, nfilters)\n\n ################\n ## get masses ##\n ################\n def get_masses(self, zf, zs=None, nfilters=None, squeeze=True):\n \"\"\" masses = ezgal.get_masses(zf, zs, nfilters=None, normalize=True, squeeze=True)\n \n :param zf: The formation redshift\n :param zs: Redshifts to calculate masses at\n :param nfilters: The number of filters to return masses for\n :param normalize: Whether or not to normalize the returned masses\n :type zf: int, float\n :type zs: int, float, list, array\n :type nfilters: int\n :type normalize: bool\n :returns: The mass in solar masses\n :rtype: array\n \n :Example:\n >>> import ezgal\n >>> model.add_filter('ch1')\n >>> model.add_filter('ch2')\n >>> model.add_filter('ch3')\n >>> model.add_filter('ch4')\n >>> model = ezgal.model('bc03_ssp_z_0.02_chab.model')\n >>> model.get_masses(3.0, zs=[0, 1, 2])\n array([[0.50909797, 0.50909797, 0.50909797, 0.50909797],\n [0.54490264, 0.54490264, 0.54490264, 0.54490264],\n [0.60169807, 0.60169807, 0.60169807, 0.60169807]])\n >>> model.get_masses(3.0, zs=[0, 1, 2], nfilters=2)\n array([[0.50909797, 0.50909797],\n [0.54490264, 0.54490264],\n [0.60169807, 0.60169807]])\n >>> model.get_masses(3.0, zs=[0, 1, 2], nfilters=1)\n array([0.50909797, 0.54490264, 0.60169807])\n >>> model.get_masses(3.0, zs=0, nfilters=1)\n 0.50909797135560608\n \n Get the stellar mass (in solar masses) as a function of ``zf`` and ``z``. Specify the number of filters to return an array of size ``(len(zs),nfilters)``. If ``nfilters`` is None, then the number of filters will be taken to be the number of filters loaded in the object. If there is only one filter, then it returns an array of shape ``(len(zs))``. The mass is independent of filter, so masses are repeated across filters. This is done for consistency with the return type of methods like :meth:`ezgal.ezgal.get_absolute_mags`.\n \n .. note::\n If no output redshifts are specified, then the redshifts in ezgal.zs will be used. \"\"\"\n\n # load defaults\n zs = self._populate_zs(zs)\n if nfilters is None: nfilters = self.nfilters\n if nfilters == 0: nfilters = 1\n \n # use the gridded astro filter info to get masses for consistency with how luminosities are calculated\n # since masses are filter independent, we can use any filter to do this. So just grab the first filter\n filt = self.filter_order[0]\n # make sure the masses are gridded\n if not self._check_grid(filters=self.filter_order[0], zfs=zf, masses=True): raise ValueError('Cannot calculate mags for given filter/zf combination because the seds have not been loaded!')\n \n # get the masses and reshape given nfilters\n masses = self.filters[filt].get_masses(zf, zs).reshape((len(zs),1)).repeat(nfilters, axis=1)\n \n if not squeeze: return masses\n return self._squeeze(masses, nfilters)\n\n ##################\n ## get vega out ##\n ##################\n def _get_vega_out(self, ab=None, vega=None):\n \"\"\" vega_out = ezgal._get_vega_out(ab=None, vega=None)\n \n Returns true or false to specify whether or not mags should be in vega \"\"\"\n\n if vega is None and ab is None:\n vega_out = True if self.vega_out else False\n elif vega is None:\n vega_out = False if ab else True\n else:\n vega_out = True if vega else False\n\n return vega_out\n\n #############\n ## squeeze ##\n #############\n def _squeeze(self, mags, nfilters):\n \"\"\" squeezed = ezgal._squeeze(mags, nfilters)\n \n Squeeze magnitude array according to number of filters \"\"\"\n\n # nothing to do for nfilters > 1\n if nfilters > 1: return mags\n\n # if nfilters == 1 then return a list and not an array\n # however, if there is only one element, then just return that as a float\n if mags.size == 1: return float(mags)\n\n # squeeze!\n return np.squeeze(mags)\n\n #######################\n ## set normalization ##\n #######################\n def set_normalization(self, filter, z, mag, vega=False, apparent=False):\n \"\"\" ezgal.set_normalization(filter, z, mag, vega=False, apparent=False)\n \n :param filter: The normalization filter\n :param z: The normalization redshift\n :param mag: The normalization magnitude\n :param vega: Whether or not the normalization is in Vega mags\n :param apparent: Whether or not the normalization is in apparent magnitudes\n :type filter: str\n :type z: int, float\n :type mag: float\n :type vega: bool\n :type apparent: bool\n :returns: None\n \n :Example:\n >>> import ezgal\n >>> model = ezgal.model('bc03_ssp_z_0.02_chab.model')\n >>> model.get_absolute_mags(3.0, filters=['ch1','ch2'], zs=0.24)\n array([[6.18394468, 6.63764649]])\n >>> # normalize to match a Dai et al. 2009 M* galaxy.\n >>> model.set_normalization('ch1', 0.24, -25.06, vega=True)\n >>> # also set Vega output, to match normalization\n >>> model.set_vega_output()\n >>> model.get_absolute_mags(3.0, filters=['ch1','ch2'], zs=0.24)\n array([[-25.06 , -25.07924584]])\n \n \n Set the model normalization, given the rest-frame magnitude of a galaxy in a given filter at a given redshift. Assumes AB magnitudes unless vega=True.\n Assumes rest-frame absolute mag unless apparent=True.\n \n .. note::\n Once set, the normalization can be unset by calling again with mag=0. \"\"\"\n\n if not mag:\n self.norm = { 'norm': 0, 'z': 0, 'filter': '', 'vega': False, 'apparent': False }\n return True\n\n if not self.filters.has_key(filter): self.add_filter(filter)\n\n self.norm = { 'norm': float(mag), 'z': float(z), 'filter': filter, 'vega': bool(vega), 'apparent': bool(apparent) }\n\n #######################\n ## get normalization ##\n #######################\n def get_normalization(self, zf, flux=False):\n \"\"\" normalization = ezgal.get_normalization(zf, flux=False)\n \n :param zf: The formation redshift to assume\n :param flux: Wheter or not to return a multiplicative factor\n :type zf: int, float\n :type flux: bool\n :returns: The normalization\n :rtype: float\n \n :Example:\n >>> import ezgal\n >>> model = ezgal.model('bc03_ssp_z_0.02_chab.model')\n >>> model.set_normalization('ch1', 0.24, -25.06, vega=True)\n >>> model.get_normalization(3.0)\n -28.45662555679969\n >>> # when set, normalizations are always applied by default\n >>> model.get_absolute_mags(3.0, filters='ch1', zs=1.0)\n -22.843105234738616\n >>> # manually apply normalization\n >>> model.get_absolute_mags(3.0, filters='ch1', zs=1.0, normalize=False) + model.get_normalization(3.0)\n -22.843105234738616\n >>> model.get_normalization(3.0, flux=True)\n 241351622492.22711\n >>> # calculate the mass (in solar masses) of the normalized galaxy at z=0.24 assuming zf=3.0\n >>> model.get_masses(3.0, 0.24, nfilters=1) * model.get_normalization(3.0, flux=True)\n 124886846296.74387\n \n Returns the model normalization given formation redshift. Returns normalization in units of magnitudes. Set flux=True to return a multiplicative factor for multiplying SEDs or masses. Returns 0 if no normalization has been set.\n \n .. seealso::\n :func:`ezgal.ezgal.set_normalization`\n \"\"\"\n\n # nothing to do if not normalized.\n if not self.norm['norm'] or not self.norm['z'] or not self.norm['filter']:\n return 1.0 if flux else 0.0\n\n # fetch the appropriate magnitude of a galaxy at the normalization redshift through the normalization filter.\n if self.norm['apparent']:\n mag = self._get_mags(zf, kind='apparent', filters=self.norm['filter'], zs=self.norm['z'], normalize=False, vega=self.norm['vega'])\n else:\n mag = self._get_mags(zf, kind='absolute', filters=self.norm['filter'], zs=self.norm['z'], normalize=False, vega=self.norm['vega'])\n\n # the difference between the normalization magnitude and the magnitude returned above is the normalization\n if not flux: return self.norm['norm'] - float(mag)\n\n # otherwise the normalization is that same difference converted to flux\n return 10.0**(-0.4*(self.norm['norm'] - float(mag)))\n\n ###########################\n ## get mass weighted age ##\n ###########################\n def get_mass_weighted_ages(self, zf, zs=None, units='gyrs'):\n \"\"\" ezgal.get_mass_weighted_ages(zf, zs=None, units='gyrs')\n \n :param zf: The formation redshift\n :param zs: The redshifts to calculate ages at\n :param units: The units to return ages in\n :type zf: int, float\n :type zs: int, float, list, array\n :type units: string\n :returns: The mass weighted ages\n :rtype: int, float, array\n \n :Example:\n >>> import ezgal\n >>> csp = ezgal.model('bc03_exp_10.0_z_0.02_chab.model')\n >>> csp.get_mass_weighted_ages(3.0, [0, 1.0, 2.0, 2.5])\n array([10.6436012 , 3.47012948, 1.079878 , 0.44172018])\n >>> # compare to the time between zf and zs:\n >>> csp.get_age(3.0, [0, 1.0, 2.0, 2.5])\n array([11.55546768, 3.76705514, 1.1586272 , 0.47989398])\n \n Returns the mass weighted age as a function of redshift and formation redshift. Set units of returned ages with ``units``\n \n .. warning::\n Only works for CSP models generated with ``EzGal``. \"\"\"\n\n if not self.has_sfh: raise ValueError('Mass weighted ages can only be calculated for models with a stored star formation history!')\n\n # populate\n zs = self._populate_zs(zs)\n\n # calculate age at each redshift\n incoming_ages = self.get_age(zf, zs, units='yrs')\n\n # array to store mean ages\n outgoing_ages = np.zeros(zs.size)\n\n # loop through redshifts\n for i in range(zs.size):\n\n # find everything in SFH with age>> import ezgal\n >>> model = ezgal.model('bc03_ssp_z_0.02_chab.model')\n >>> sed = model.get_sed(10, age_units='gyrs', units='Fl')\n >>> sed.size\n 6900\n >>> model.ls.size, model.vs.size\n (6900, 6900)\n \n Returns the rest-frame sed of the galaxy at a given age. See :func:`ezgal.utils.to_years` for the available age units. Returns an array of size (model.nvs). The frequencies (wavelengths) of each point in the returned array correspond to the frequencies (wavelengths) in model.vs (model.ls).\n \n Available output units are (case insensitive):\n \n ========== ====================\n Name Units\n ========== ====================\n Jy Jansky\n Fv ergs/s/cm^2/Hz\n Fl ergs/s/cm^2/Angstrom\n Flux ergs/s/cm^2\n Luminosity ergs/s\n ========== ====================\n \n .. note::\n Uses linear interpolation between two nearest age models.\n \"\"\"\n\n # don't interpolate outside of the age range\n minage = utils.to_years(self.ages[0], units=age_units, reverse=True)\n maxage = utils.to_years(self.ages[-1], units=age_units, reverse=True)\n if age < minage or age > maxage: raise ValueError('Age must be between %.2f and %.2f %s' % (minage,maxage,age_units))\n age_yr = utils.convert_time(age, incoming=age_units, outgoing='yrs')\n\n # simple two point interpolation\n # find the closest SED younger than the given age\n yind = np.abs(self.ages - age_yr).argmin()\n if self.ages[yind] > age_yr: yind -= 1\n # ind of closest SED older than the given age\n oind = yind + 1\n\n # are we at the borders of the age array? If so return\n if oind == self.nages: return self.seds[:,yind].copy()\n if yind < 0: return self.seds[:,oind].copy()\n\n # age of older and younger seds\n yage = self.ages[yind]\n oage = self.ages[oind]\n\n # now interpolate\n sed = self.seds[:,yind] + (self.seds[:,oind]-self.seds[:,yind])*(age_yr-yage)/(oage-yage)\n\n units = units.lower()\n if units == 'jy': return sed/1e-23\n if units == 'fv': return sed\n if units == 'fl': return sed*self.vs**2.0/utils.convert_length(utils.c, outgoing='a')\n sed *= self.vs\n if units == 'flux': return sed\n if units == 'luminosity': return sed*4.0*np.pi*utils.convert_length(10, incoming='pc', outgoing='cm')**2.0\n raise NameError('Units of %s are unrecognized!' % units)\n\n ###############################\n ## retrieve sed given zf & z ##\n ###############################\n def get_sed_z(self, zf, z, units='Fv', normalize=True, observed=False, return_frequencies=False):\n \"\"\" sed = ezgal.get_sed_z(zf, z, units='Fv', normalize=True, observed=False, return_frequencies=False)\n \n :param zf: The formation redshift for the output SED\n :param z: The redshift for the output SED\n :param units: The output units for the SED\n :param normalize: Whether or not to normalize the output SED\n :param observed: Whether or not to output the observed-frame SED\n :param return_frequencies: Whether or not to return the corresponding frequencies\n :type zf: int, float\n :type z: int, float\n :type units: string\n :type normalize: bool\n :type observed: bool\n :type return_frequencies: bool\n :returns: The SED\n :rtype: array\n \n :Example:\n >>> import ezgal\n >>> model = ezgal.model('bc03_ssp_z_0.02_chab.model')\n >>> sed = model.get_sed_z(3.0, 0.5, units='Fl')\n >>> sed.size\n 6900\n >>> model.ls.size, model.vs.size\n (6900, 6900)\n >>> (ls, sed) = model.get_sed_z(3.0, 0.5, units='Fl', return_frequencies=True)\n \n \n Returns the rest-frame sed for a galaxy given its formation redshift (``zf``) and current redshift (``z``). If ``normalize=True`` and a normalization has been set with :meth:`ezgal.ezgal.set_normalization`` then the sed will be normalized accordingly. If ``observed=True`` then the observed frame SED is returned. If ``return_frequencies=True`` then it also returns the frequencies of the points in the returned SED (or wavelength array in angstroms if ``units='Fl'``). In this case a tuple is returned, with the first element being the list of frequencies, and the second element the SED. Otherwise, the frequencies (wavelengths) of each point in the returned array correspond to the frequencies (wavelengths) in model.vs (model.ls).\n \n .. seealso::\n See ezgal.get_sed() for available output units.\n .. warning::\n The conversion to observed-frame has not been thoroughly tested, and I don't guarantee that I did it right. So please check it carefully before using. \"\"\"\n\n units = units.lower()\n\n # fetch sed\n sed = self.get_sed(self.get_age(zf, z), units=units)\n\n # and normalize\n if normalize: sed *= self.get_normalization(zf, flux=True)\n\n # copy out frequencies in case they are going to be returned\n vs = self.vs.copy()\n # reverse if units are Fl so that frequencies are increasing in wavelength\n if units == 'fl':\n vs = utils.to_lambda(vs[::-1], units='a')\n sed = sed[::-1]\n\n # all done if observed=False\n if not observed:\n if not return_frequencies: return sed\n if units == 'fl': return (vs, sed)\n return (self.vs, sed)\n\n # we need to do different things depending on the units\n if units == 'fv':\n vs /= (1.0+z)\n sed *= (1.0+z)\n if units == 'fl' or units == 'jy':\n vs = vs*(1.0+z)\n sed /= (1.0+z)\n\n # in addition, if units are not luminosity, then we must account for distance modulus\n if units != 'luminosity': sed *= 10.0**(-0.4*self.get_distance_moduli(z, nfilters=1))\n\n # and that should do it\n if return_frequencies: return (vs, sed)\n return sed\n\n ###############\n ## _get_seds ##\n ###############\n def _get_seds(self, zf):\n \"\"\" ezgal.get_seds(zf)\n \n Returns a list of SEDs and ages interpolated nicely in redshift space.\n Stores interpolated SEDs in object for quick retrieval later. \"\"\"\n\n # Has this zf already been interpolated?\n w = np.where(np.abs(self.interp_zfs - zf) < self.tol)[0]\n\n # It has! Return stored SEDs\n if w.size > 0:\n interped = self.interp_seds[w[0]]\n return (interped['zs'], interped['ages'], interped['seds'])\n\n # get regular redshift grid for this zf\n zs = np.append([0, 0.001], self.get_zs(zf))\n for (i,z) in enumerate(zs):\n # fetch age of sed at z given zf\n age = self.get_age(zf, z, units='yrs')\n # and fetch the SED\n sed = self.get_sed_z(zf, z, normalize=False).reshape((self.nvs,1))\n # generate SED grid\n if i == 0:\n ages = np.array([age])\n seds = sed\n age_zs = np.array([z])\n else:\n # append so that ages are monotonically increasing\n ages = np.append(age, ages)\n seds = np.hstack((sed, seds))\n age_zs = np.append(z, age_zs)\n\n # store in the object, reverse redshifts since ages are monotonically increasing\n self.interp_seds.append({'ages': ages, 'seds': seds, 'zs': age_zs})\n self.interp_zfs = np.append(self.interp_zfs, zf)\n\n # and now return\n return (age_zs, ages, seds)\n\n #############\n ## get age ##\n #############\n def get_age(self, z1, z2, units='gyrs'):\n \"\"\" age = ezgal.get_age(z1, z2, units='gyrs')\n \n :param z1: The first redshift\n :param z2: The second redshift\n :param units: The units to return the time in\n :type z1: int, float\n :type z2: int, float, list, array\n :type units: str\n :returns: Time between two redshifts\n :rtype: int, float, list, array\n \n :Example:\n >>> import ezgal\n >>> model = ezgal.model('bc03_ssp_z_0.02_chab.model')\n >>> print model.get_age(3.0, [0.0,0.5,1.0])\n [11.55546768 6.49725355 3.76705514]\n \n returns the time difference between z1 and z2. z2 can be a list or numpy array. Primarily used to get the age of a galaxy at redshift z2, given formation redshift z1. See :func:`ezgal.utils.to_years` for available age units.\n \"\"\"\n\n if type(z2) == type([]) or type(z2) == type(np.array([])):\n ages = np.empty(len(z2))\n for i in range(len(z2)):\n if np.abs(z2[i] - z1) < self.tol:\n ages[i] = 0\n else:\n ages[i] = utils.to_years(self.cosmo.Tl(z1, yr=True)-self.cosmo.Tl(z2[i], yr=True), units=units, reverse=True)\n return ages\n \n else:\n if np.abs(z2 - z1) < self.tol:\n return 0\n else:\n return utils.to_years(self.cosmo.Tl(z1, yr=True)-self.cosmo.Tl(z2, yr=True), units=units, reverse=True)\n\n #################\n ## clear cache ##\n #################\n def clear_cache(self):\n\n # reset the list of interpolated SEDs\n self.interp_seds = []\n self.interp_zfs = np.array([])\n\n # reset all stored evolution info in filter objects\n for (filt,filt_obj) in self: filt_obj.clear_cache()\n\n ####################################################\n ## get a redshift grid going out to some redshift ##\n ####################################################\n def get_zs(self, z):\n \"\"\" ezgal.get_zs(z)\n \n :param z: The redshift out which to return redshifts\n :type z: int, float\n :returns: An array of redshifts\n :rtype: array\n \n :Example:\n >>> import ezgal\n >>> model = ezgal.model('bc03_ssp_z_0.02_chab.model')\n >>> model.get_zs(0.1)\n array([0.005, 0.01 , 0.015, 0.02 , 0.025, 0.03 , 0.035, 0.04 ,\n 0.045, 0.05 , 0.055, 0.06 , 0.065, 0.07 , 0.075, 0.08 ,\n 0.085, 0.09 , 0.095])\n \n Fetch a redshift grid out to redshift ``z``. Returned redshifts stop just short of ``z``. Returns more closely spaced redshifts at low redhift.\"\"\"\n \n zs = np.arange(0.005, np.min([0.1, z]), 0.005)\n if z > 0.1: zs = np.concatenate((zs, np.arange(0.1, np.min([2.0, z]), 0.025)))\n if z > 2.0: zs = np.concatenate((zs, np.arange(2.0, z, 0.1)))\n return zs\n\n #####################\n ## extract filters ##\n #####################\n def extract_filters(self, filename, filters=None, grid=True):\n \"\"\" ezgal.extract_filters(filename, filters=None, grid=True)\n \n This will extract filter response curves saved in a binary fits file with an ezgal object.\n Pass a list of filters to extract - if no filters are passed, then all the filters found in the file will be added to the object.\n \n If grid is True, then the models will be generated for all filters at all formation redshifts.\n This can be a bit slow. If not done now, it will be done on the fly as needed. \"\"\"\n\n # load the file\n fits = pyfits.open(filename)\n\n # make sure it has some filters\n if fits[0].header['nfilters'] == 0: raise ValueError('Cannot extract filters from specified file because it has none!')\n\n nfilters = fits[0].header['nfilters']\n\n # where do the response curves start? If the file contains SEDs, then they start in extension index 3, otherwise 1\n start = 1\n if fits[0].header['has_seds']: start = 3\n\n # if we haven't asked for any filters then load up the list of filters from the file\n if filters is None:\n filters = []\n for i in range(nfilters): filters.append(fits[0].header['filter%d'%(i+1)])\n # make sure it is an array\n if type(filters) == type(''): filters = [filters]\n\n # now loop through all the filters in the file, and add the ones in our filter list\n for i in range(nfilters):\n ind = i + start\n name = fits[ind].header['name']\n\n # see if we are keeping this filter\n if not(name in filters): continue\n\n # add!\n self.add_filter(fits[ind].data, name=name, units='hz')\n\n ###############################\n ## add filter to filter list ##\n ###############################\n def add_filter(self, file, name=None, units='a', grid=True):\n \"\"\" ezgal.add_filter(file, name=None, units='a', grid=True)\n \n :param file: The filename containing the filter response curve\n :param name: The name to store the filter as\n :param units: The length units for the wavelengths in the file\n :param grid: Whether or not to calculate evolution information when first added\n :type file: string\n :type name: string\n :type units: string\n :type grid: bool\n \n Add a filter for calculating models. Specify the name of the file containing the filter transmission curve. If the file is not found then ``EzGal`` will search for it in the directory specified by the ``EZGAL_FILTERS`` environment variable, and then in the ``data/filters`` directory in the ``EzGal`` module directory.\n \n The filter file should have two columns (wavelength,transmission). Wavelengths are expected to be in angstroms unless specified otherwise with ``units``. See :func:`ezgal.utils.to_meters` for list of available units.\n \n Specify a name to refer to the filter as later. If no name is specified, the filename is used (excluding path information and extension)\n If a filter already exists with that name, the previous filter will be replaced.\n \n If grid is True, then models will be generated for this filter at all set formation redshifts.\n \n You can pass a numpy array directly, instead of a file, but if you do this you need to specify the name.\n \"\"\"\n\n if name is None:\n if type(file) != type(''): raise ValueError('You need to pass a file name or a numpy array and filter name!')\n name = os.path.basename(file)\n\n # if a file name was passed then search for the file in the various directories\n if type(file) == type(''):\n file = self._find_filter_file(file)\n\n self.filters[name] = astro_filter.astro_filter(file, units=units, cosmology=self.cosmo, vega=self.vega, solar=self.solar)\n self.filters[name].tol = self.tol\n # store its name in self.filter_order\n if not self.filter_order.count(name): self.filter_order.append(name)\n self.nfilters += 1\n\n if grid: self._grid_filters(name)\n\n #######################\n ## _find_filter_file ##\n #######################\n def _find_filter_file(self, file):\n\n # first check file path\n files = [file]\n\n # then filter_dir if set in environment\n if self.filter_dir: files.append('%s%s' % (self.filter_dir,os.path.basename(file)))\n\n # finally filter directory in data directory\n files.append('%sfilters/%s' % (self.data_dir,os.path.basename(file)))\n\n # now loop through the different files\n for file in files:\n if os.path.isfile(file): return file\n\n raise ValueError('The specified filter transmission file was not found!')\n return False\n\n ##########################\n ## save a model to fits ##\n ##########################\n def save_model(self, model_file, filter_info=True, filter_only=False):\n \"\"\" ezgal.save_model(output_file, filter_info=True, filter_only=False)\n \n :param model_file: Output filename\n :param filter_info: Whether or not to output calculated model evolution\n :param filter_only: If true, only output calculated model evolution.\n :type model_file: str\n :type filter_info: bool\n :type filter_only: bool\n :returns: None\n \n :Example:\n >>> import ezgal\n >>> model = ezgal.model('bc03_ssp_z_0.02_chab.model')\n >>> model.add_filter('ch1')\n >>> model.add_filter('ch2')\n >>> model.set_zfs([3,4,5])\n >>> model.save_model('bc03_ssp_z_0.02_chab_with_models.model')\n >>> new_model = ezgal.model('bc03_ssp_z_0.02_chab_with_models.model')\n >>> new_model.get_absolute_mags(3.0, zs=[0,1,2])\n array([[6.39000031, 6.83946654],\n [5.61352032, 6.07145866],\n [4.48814389, 4.87218428]])\n \n Saves the ``EzGal`` model to a multi-extensions fits file which can be read back in later.\n \n If ``filter_info=True`` then this fits file will also contain the calculated model evolution as a function of filter and formation redshift. This will be loaded back into the object later, so that you don't have to recalculate the models everytime.\n \n if ``filter_only=True`` then the SEDs will not be stored - just the calculated filter data. This can later be loaded and return observables as a function of z for any formation redshifts and filters already computed. These files are smaller because the model grid is not included, but ``EzGal`` will not be able to calculate observables for any new formation redshifts or filters.\n \"\"\"\n\n if not filter_only:\n # primary hdu - sed table\n primary_hdu = pyfits.PrimaryHDU(self.seds)\n primary_hdu.header.update('units', 'ergs/s/cm^2/Hz')\n primary_hdu.header.update('has_seds', True)\n\n # store the list of frequencies in a table\n vs_hdu = pyfits.new_table(pyfits.ColDefs([pyfits.Column(name='vs', array=self.vs, format='D', unit='hertz')]))\n\n # the list of ages\n cols = [pyfits.Column(name='ages', array=self.ages, format='D', unit='years')]\n\n # the list of masses (if present)\n if self.has_masses: cols.append(pyfits.Column(name='masses', array=self.masses, format='D', unit='m_sun'))\n # and the sfh (if present)\n if self.has_sfh: cols.append(pyfits.Column(name='sfh', array=self.sfh, format='D'))\n\n # generate fits HDU\n ages_hdu = pyfits.new_table(pyfits.ColDefs(cols))\n if self.has_masses: ages_hdu.header.update('has_mass', True)\n if self.has_sfh: ages_hdu.header.update('has_sfh', True)\n else:\n # we are only storing filter info, so use a blank primary hdu with some data in the header\n if self.nfilters == 0: raise ValueError('Cannot output only the filter information if there is no filter information!')\n primary_hdu = pyfits.PrimaryHDU()\n primary_hdu.header.update('has_seds', False)\n primary_hdu.header.update('units', '')\n\n # and some info that we always want...\n primary_hdu.header.update('nfilters', 0)\n primary_hdu.header.update('nzfs', 0)\n\n # and meta data if set\n self._save_meta_data(primary_hdu.header)\n\n # store filter information as well\n if filter_info or filter_only:\n # Store the number of filters in the primary hdu\n primary_hdu.header.update('nfilters', self.nfilters)\n # Also store the cosmology\n primary_hdu.header.update('Om', self.cosmo.Om)\n primary_hdu.header.update('Ol', self.cosmo.Ol)\n primary_hdu.header.update('w', self.cosmo.w)\n primary_hdu.header.update('h', self.cosmo.h)\n\n # Store the filter response curves, each in its own fits extension\n # as long as we're looping through, figure out all formation redshifts which have been used\n filter_hdus = []\n zfs = None\n for (i,filter) in enumerate(self.filter_order):\n image = pyfits.ImageHDU(np.column_stack((self.filters[filter].vs,self.filters[filter].tran)))\n image.header.update('name', filter)\n filter_hdus.append(image)\n zfs = self.filters[filter].extend_zf_list(zfs)\n\n # add the list of filter names to the header\n primary_hdu.header.update('filter%d' % (i+1), filter)\n\n # now loop through each formation redshift and store all necessary info for each filter\n if zfs is not None:\n zfs.sort()\n primary_hdu.header.update('nzfs', len(zfs))\n for zf in zfs:\n # loop through the filters and retrieve any stored info for this filter at this formation redshift\n count = 0\n for filter in self.filter_order:\n if not(self.filters[filter].has_zf(zf)): continue\n\n # fetch the grid object for this filter and formation redshift\n zf_grid = self.filters[filter].get_zf_grid(zf)\n\n # for the first filter, get the redshifts, ages, masses, and start the column definitions\n if count == 0:\n zs = zf_grid.zs\n cols = [pyfits.Column(name='zs', array=zs, format='D'),pyfits.Column(name='ages', array=zf_grid.ages, format='D')]\n if zf_grid.has_masses: cols.append(pyfits.Column(name='masses', array=zf_grid.masses, format='E'))\n\n # add the rest-frame and observed-frame mags to the list of table columns\n cols.extend([pyfits.Column(name=filter+'_rest', array=zf_grid.rest, format='E'),pyfits.Column(name=filter+'_obs', array=zf_grid.obs, format='E')])\n # add observed-frame solar mags if they exists\n if zf_grid.has_solar: cols.append(pyfits.Column(name=filter+'_solar', array=zf_grid.solar, format='E'))\n\n count += 1\n\n # now generate the table extension and add it to the list\n tbl = pyfits.new_table(pyfits.ColDefs(cols))\n tbl.header.update('zf', zf)\n filter_hdus.append(tbl)\n\n # join all the hdus together and write them out!\n hdus = [primary_hdu]\n if not filter_only: hdus.extend([vs_hdu,ages_hdu])\n if filter_info or filter_only: hdus.extend(filter_hdus)\n \n hdulist = pyfits.HDUList(hdus)\n hdulist.writeto(model_file, clobber=True)\n\n ############################\n ## load a model from fits ##\n ############################\n def _load_model(self, model_file):\n \"\"\" ezgal._load_model(model_file)\n \n loads a model from a fits file created with ezgal.save_model()\n Saves the model information in the model object \"\"\"\n\n if not(os.path.isfile(model_file)): raise ValueError('The specified model file was not found!')\n\n fits = pyfits.open(model_file)\n\n # was sed information included in this model file?\n if fits[0].header['has_seds']:\n self.seds = fits[0].data\n self.vs = fits[1].data.field('vs')\n self.ls = utils.to_lambda(self.vs)\n self.ages = fits[2].data.field('ages')\n self.nvs = self.vs.size\n self.nls = self.ls.size\n self.nages = self.ages.size\n start_filters = 3\n # how about masses?\n if 'has_mass' in fits[2].header and fits[2].header['has_mass']:\n self.set_masses(self.ages, fits[2].data.field('masses'), age_units='yrs', grid=False)\n # and sfh?\n if 'has_sfh' in fits[2].header and fits[2].header['has_sfh']:\n self.sfh = fits[2].data.field('sfh')\n self.has_sfh = True\n else:\n self.nvs = 0\n self.nls = 0\n self.nages = 0\n start_filters = 1\n\n # and meta info if set\n self.load_meta_data(fits[0].header)\n\n # was filter information included in this model file?\n # if so, load it and store it in the object\n if 'nfilters' not in fits[0].header: return True\n if fits[0].header['nfilters'] == 0: return True\n\n # set cosmology specified in the model file\n self.set_cosmology(Om=fits[0].header['Om'], Ol=fits[0].header['Ol'], h=fits[0].header['h'], w=fits[0].header['w'])\n\n for i in range(start_filters, start_filters+fits[0].header['nfilters']):\n name = fits[i].header['name']\n self.filters[name] = astro_filter.astro_filter(fits[i].data, units='hz', cosmology=self.cosmo, vega=self.vega, solar=self.solar)\n self.filter_order.append(name)\n self.nfilters += 1\n\n # load any stored models\n if 'nzfs' not in fits[0].header: return True\n\n st = start_filters + fits[0].header['nfilters']\n zfs = []\n for i in range(st, st+fits[0].header['nzfs']):\n data = fits[i].data\n zf = fits[i].header['zf']\n zs = data.field('zs')\n ages = data.field('ages')\n masses = None if not data.names.count('masses') else data.field('masses')\n\n zfs.append(zf)\n\n # now loop through filters\n for filter in self.filter_order:\n # check to see if this filter has info stored for this zf\n if data.names.count(filter+'_rest') == 0: continue\n\n # store the info in the filter object\n solar = None if not data.names.count(filter + '_solar') else data.field(filter + '_solar')\n self.filters[filter].store_grid(zf, zs, ages, data.field(filter+'_rest'), data.field(filter+'_obs'), solar=solar, masses=masses)\n\n self.set_zfs(zfs, grid=False)\n\n ######################\n ## save ascii model ##\n ######################\n def save_ascii_model(self, model_file):\n \"\"\" ezgal.save_ascii_model(model_file)\n \n Save the interpolated model information in an ascii file for later retrieval \"\"\"\n\n # open the output file\n fp = open(model_file, 'wb')\n\n # write out basic header info\n fp.write(\"EzGal ascii model file\\nOriginal file:\\n%s\\nNumber Filters, Number of zfs:\\n%d %d\\nCosmology (Om, Ol, w, h):\\n%.3f %.3f %.3f %.3f\\n\" % (self.filename,self.nfilters,self.nzfs,self.cosmo.Om,self.cosmo.Ol,self.cosmo.w,self.cosmo.h))\n\n # write out the filter names, vega-to-ab conversions, and solar magnitudes\n filters = []\n vegas = []\n solars = []\n for (i,filter) in enumerate(self.filter_order):\n filters.append(filter)\n vegas.append('%.4f' % self.filters[filter].to_vega)\n solars.append('%.4f' % self.filters[filter].solar)\n fp.write('%s\\n%s\\n%s\\n' % (' '.join(filters), ' '.join(vegas), ' '.join(solars)))\n\n # formation redshifts will be output in reverse order\n zfs = self.zfs.copy()\n zfs.sort()\n zfs = zfs[::-1]\n\n # write out the formation redshifts\n zf_strings = []\n for zf in zfs: zf_strings.append('%.3f' % zf)\n fp.write('%s\\n' % ' '.join(zf_strings))\n\n # fetch dm, zs from the highest zf point, using any filter\n grid = self.filters[self.filter_order[0]].get_zf_grid(self.zfs.max())\n zs = grid.zs\n dms = self.get_distance_moduli(zs, nfilters=1)\n\n # generate a data array to store rest-frame mag evolution, observed-frame mag evolution, and observed-frame solar mag as a function of filter, zf, and z\n # need age and mass as a function of zf and z\n # also use a mask to denote where there are actually values\n res = np.zeros((zs.size,2+self.nfilters*self.nzfs*3+2*self.nzfs))\n res[:,0] = zs\n res[:,1] = dms\n mask = np.zeros((zs.size,2+self.nfilters*self.nzfs*3+2*self.nzfs))\n mask[:,0] = 1\n mask[:,1] = 1\n\n # output formats\n formats = ['%7.4f','%7.4f']\n\n # loop through the zfs, then the filters\n for (zfind, zf) in enumerate(zfs):\n\n # fetch zs for this zf from any filter\n grid = self.filters[self.filter_order[0]].get_zf_grid(zf)\n my_zs = grid.zs\n\n # store age and mass\n age_ind = 2 + (zfind*self.nfilters)*3 + (zfind)*2\n res[0:my_zs.size,age_ind] = grid.ages\n res[0:my_zs.size,age_ind+1] = grid.masses\n mask[0:my_zs.size,age_ind] = 1\n mask[0:my_zs.size,age_ind+1] = 1\n formats.extend(['%14.8e','%12.6e'])\n\n # now store gridded filter information\n for (find, filter) in enumerate(self.filter_order):\n\n start = 2 + (zfind*self.nfilters+find)*3 + (zfind+1)*2\n zf_grid = self.filters[filter].get_zf_grid(zf)\n\n # store observed-frame, rest-frame, and solar evolution in grid\n res[0:my_zs.size,start] = zf_grid.obs\n res[0:my_zs.size,start+1] = zf_grid.rest\n res[0:my_zs.size,start+2] = zf_grid.solar\n mask[0:my_zs.size,start] = 1\n mask[0:my_zs.size,start+1] = 1\n mask[0:my_zs.size,start+2] = 1\n formats.extend(['%7.4f','%7.4f','%7.4f'])\n\n # okay, now we just need to output this huge data array...\n for i in range(zs.size):\n # array for storing string data\n data = []\n # find actual data\n w = np.where(mask[i,:] == 1)[0]\n # convert to string\n for j in range(len(w)): data.append(formats[w[j]] % res[i,w[j]])\n # and write out line\n fp.write(' '.join(data) + '\\n')\n\n # all done!\n fp.close()\n\n #######################\n ## _load_ascii_model ##\n #######################\n def _load_ascii_model(self, model_file):\n \"\"\" ezgal.load_ascii_model(model_file)\n \n Loads calculated model info outputted by ezgal to an ascii file. This does not allow calculation of new models. \"\"\"\n\n if not(os.path.isfile(model_file)): raise ValueError('The specified model file was not found!')\n\n fp = open(model_file, 'r')\n\n # no sed info\n self.nvs = 0\n self.nls = 0\n self.nages = 0\n\n # first two lines are junk\n j = fp.readline()\n j = fp.readline()\n\n # next line is filename\n self.filename = fp.readline().strip()\n\n # more junk, then number of filters and zfs\n j = fp.readline()\n (self.nfilters, self.nzfs) = fp.readline().strip().split()\n self.nfilters = int(self.nfilters)\n self.nzfs = int(self.nzfs)\n\n # cosmological parameters\n j = fp.readline()\n (om, ol, w, h) = fp.readline().strip().split()\n self.set_cosmology(Om=float(om), Ol=float(ol), h=float(h), w=float(w))\n\n # now read through and generate filter objects\n filters = fp.readline().strip().split()\n to_vegas = fp.readline().strip().split()\n solars = fp.readline().strip().split()\n for (filter, to_vega, solar) in zip(filters, to_vegas, solars):\n self.filters[filter] = astro_filter_light.astro_filter_light(None, cosmology=self.cosmo, vega=float(to_vega), solar=float(solar))\n self.filter_order.append(filter)\n\n # and formation redshifts\n self.zfs = np.array(fp.readline().strip().split()).astype('float')\n\n # okay, now start reading in the big data array\n zs = np.array([])\n dms = np.array([])\n c = 0\n while True:\n line = fp.readline()\n if line == '': break\n\n data = np.array(line.strip().split()).astype('float')\n # copy out redshift, distance moduli, and mag evolution\n zs = np.append(zs, data[0])\n dms = np.append(dms, data[1])\n evol = data[2:]\n\n # and store in data array\n # also keep mask to track what has data and what doesn't\n if c == 0:\n res = evol\n mask = np.ones(res.size)\n ncols = res.size\n else:\n this = np.zeros(ncols)\n this_mask = np.zeros(ncols)\n this[0:evol.size] = evol\n this_mask[0:evol.size] = 1\n res = np.vstack((res, this))\n mask = np.vstack((mask, this_mask))\n c += 1\n\n # now we can loop through data array by column and store evolution data in filters\n for (zfind,zf) in enumerate(self.zfs):\n\n # copy out age-mass relationship for this formation redshift\n age_ind = (zfind*self.nfilters)*3 + (zfind)*2\n\n # find good data\n w = np.where(mask[:,age_ind] > -1)[0]\n\n ages = res[w,age_ind]\n masses = res[w,age_ind+1]\n if zfind == 0: self.set_masses(ages, masses, age_units='yrs', grid=False)\n\n for (find,filter) in enumerate(self.filter_order):\n\n # index for data in array\n start = (zfind*self.nfilters+find)*3 + (zfind+1)*2\n # store in filter\n self.filters[filter].store_grid(zf, zs[w], ages, res[w,start+1], res[w,start], dms[w])\n zf_grid = self.filters[filter].get_zf_grid(zf)\n zf_grid.store_solar_mags(res[w,start+2])\n zf_grid.store_masses(masses)\n\n # all done!\n fp.close()\n\n ################################\n ## load model from ascii file ##\n ################################\n def _load_ascii(self, file, has_masses=False, units='a', age_units='gyrs'):\n \"\"\" ezgal._load_ascii(file, has_masses=False, units='a', age_units='gyrs')\n \n Load a model file in ascii format. The file should be a data array of size (nwavelengths+1,nages+1).\n The first row specifies the age of each column, and the first column specifies the wavelength of each row.\n This means the data value in the first row of the first column is ignored. However, it still must have SOME value ('0' is fine) as a placeholder\n You can include masses in the file by specifying the mass (in solar masses) for each age in the second row. If you do this then set has_masses=True\n It loads a bit slow, so you should save it as a fits - see ezgal.save_model() - if you are going to be using it more than once.\n \n Specify units for the age with 'age_units'. Default is gyrs. See ezgal.utils.to_years() for avaialable unit specifications\n Specify units for wavelength & flux with 'units'. Default is 'a' for Angstroms, with flux units of ergs/s/angstrom.\n Set units='hz' for frequency with flux units of 'ergs/s/hertz'\n You can also set the units as anything else found in ezgal.utils.to_meters() as long as the flux has units of ergs/s/(wavelength units)\n \"\"\"\n\n if not(os.path.isfile(file)): raise ValueError('The specified model file was not found!')\n\n model = utils.rascii(file)\n\n self.vs = model[1:,0]\n self.nvs = self.vs.size\n self.nls = self.nvs\n self.ages = model[0,1:]\n self.nages = self.ages.size\n\n if has_masses:\n self.set_masses(ages, model[1,1:], age_units=age_units)\n self.seds = model[1:,2:]\n else:\n self.seds = model[1:,1:]\n\n # convert to intermediate units (hz, ergs/s/hz)\n units = units.lower()\n age_units = age_units.lower()\n if units != 'hz':\n self.seds *= self.vs.reshape((self.nvs,1))**2.0/utils.convert_length(utils.c, outgoing=units)\n self.vs = utils.to_hertz(self.vs, units=units)\n\n self.ls = utils.to_lambda(self.vs)\n\n # convert from ergs/s/Hz to ergs/s/Hz/cm^2.0 @ 10pc\n self.seds /= 4.0*np.pi*utils.convert_length(10, incoming='pc', outgoing='cm')**2.0\n\n # convert ages to the proper units\n self.ages = utils.to_years(self.ages, units=age_units)\n\n # now sort it to make sure that age is increasing\n sind = self.ages.argsort()\n self.ages = self.ages[sind]\n self.seds = self.seds[:,sind]\n\n # the same for frequency\n sind = self.vs.argsort()\n self.vs = self.vs[sind]\n self.seds = self.seds[sind,:]\n\n ###############################\n ## load model from ised file ##\n ###############################\n def _load_ised(self, file):\n \"\"\" ezgal._load_ised(file)\n \n Load a bruzual and charlot binary ised file.\n Saves the model information in the model object \"\"\"\n\n # read ised file\n (seds, ages, vs) = utils.read_ised(file)\n\n # store ages\n self.ages = ages\n self.nages = ages.size\n\n # store frequencies/wavelengths\n self.nvs = vs.size\n self.nls = vs.size\n self.vs = vs\n self.ls = utils.to_lambda(self.vs)\n\n # store seds\n self.seds = seds\n\n ###################\n ## set meta data ##\n ###################\n def set_meta_data(self, data):\n \"\"\" ezgal.set_meta_data(data)\n \n :param data: A dictionary containing model information\n :type data: dict\n :returns: None\n \n :Example:\n >>> import ezgal\n >>> model = ezgal.model('bc03_ssp_z_0.02_chab.model')\n >>> model.set_meta_data({'model': 'BC03', 'sfh': 'SSP'})\n >>> model.meta_data\n {'model': 'BC03', 'sfh': 'SSP'}\n \n Pass a dictionary with key/value pairs containing model information. This information is stored along with the model data, and is restored when the model is loaded later. Mainly, this serves as a method for propogating model information throughout python sessions. It can also be used extensively with the ``Wrapper`` class for searching, sorting, and interpolating between models.\n \n .. warning::\n Meta data will be stored in the fits header so keep key length <= 8 characters. Keep value length <20 characters. \"\"\"\n\n if type(data) != type({}) or len(data.keys()) == 0: raise ValueError('Please pass a dictionary of meta data')\n\n self.has_meta_data = True\n self.meta_data = {}\n # copy to meta data dictionary\n for (key, val) in data.iteritems():\n if len(str(key)) > 8: raise ValueError('Meta data keys must be less than 9 characters long!')\n if len(str(val)) > 20: raise ValueError('Meta data values must be less than 21 characters long!')\n self.meta_data[str(key)] = str(val)\n\n ####################\n ## save meta data ##\n ####################\n def _save_meta_data(self, hdr):\n \"\"\" ezgal._save_meta_data(hdr)\n \n Stores the SPS model data in a fits header (if meta data is present) \"\"\"\n\n if not self.has_meta_data: return hdr\n\n hdr.update('has_meta', True)\n\n # store meta data in fits header\n for (key, val) in self.meta_data.iteritems():\n hdr.update(key, val, comment='meta data')\n\n return hdr\n\n ####################\n ## load meta data ##\n ####################\n def load_meta_data(self, hdr):\n \"\"\" ezgal.load_meta_data(hdr)\n \n Saves the meta data in the fits header into the ezgal object (if present) \"\"\"\n\n if 'has_meta' not in hdr or not hdr['has_meta']: return False\n\n # loop through all header cards in the header and look for ones with a comment that says 'meta data'\n self.meta_data = {}\n for card in hdr.ascardlist():\n if str(card).count('meta data'):\n self.meta_data[card.key.lower()] = card.value\n\n self.has_meta_data = True\n return True\n\n ##############\n ## make csp ##\n ##############\n def make_csp(self, sfh_function, args=(), dust_function=None, dust_args=(), break_points=None, meta_data={}, max_err=0.001, max_iter=200):\n \"\"\" new_model = model.make_csp(sfh_function, args=(), dust_function=None, dust_args=(), break_points=None, meta_data={}, max_err=0.001, max_iter=200)\n \n :param sfh_function: The star formation rate as a function of age\n :param args: A tuple with additional arguments to pass to sfh_function\n :param dust_function: The dust dimming factor as a function of age and wavelength\n :param dust_args: A tuple with additional arguments to pass to dust_function\n :param break_points: A list of discontinutites in the star formation history\n :param meta_data: A dictionary with meta information to be stored in the new model\n :param max_err: Maximum allowed integration error (in magnitudes)\n :param max_iter: Maximum number of interations allowed when trying to get errors below ``max_err``\n :type sfh_function: function or callable object\n :type args: tuple\n :type dust_function: function or callable object\n :type dust_args: tuple\n :type break_points: list, array\n :type meta_data: dict\n :type max_err: float\n :type max_iter: int\n :returns: ``EzGal`` model object for new CSP\n :rtype: ezgal object\n \n :Example:\n >>> import ezgal\n >>> import numpy as np\n >>> model = ezgal.model('bc03_ssp_z_0.02_chab.model')\n >>> def exponential(t, tau):\n >>> return np.exp(-1.0*t/tau)\n >>> # make a csp with a dust free exponentially decaying star formation history with tau=1.0 gyrs\n >>> exp_1gyr = model.make_csp(exponential, (1.0,))\n \n Returns a new EzGal object which is a composite stellar population generated from an arbitrary SFH. Pass a python function or callable object representing the star formation history (``sfh_function``). The star formation history function will be passed an age (in gyrs) and should return a corresponding weight (relative star formation rate). ``args`` is an optional tuple and is passed to sfh_function. The calling sequence for the star formation history function will be::\n \n weight = sfh_function(time, *args)\n \n `dust` is an optional parameter and can be any python function or callable object. It should represent the dust extinction and should accept a time (in gyrs) and an array of wavelengths (in Angstroms). It should return the dimming factor at all wavelengths in an array of size ``lambdas.size``. If a tuple is passed to dust_args then these will be passed to dust_function as extra arguments. The calling sequence for dust_function is::\n \n factor = dust_function(time, lambdas, *args)\n \n If the SFH history or dust function has discontinuities in time then the integral can be split up. Use ``break_points`` to pass a list of ages (in Gyrs) to split the integral at.\n \n For integration, the SEDs in the model will be interpolated onto a more finely spaced grid in age. Before integrating an iterative process is used at 3000, 8000, and 12000 angstroms to determine the proper level of age resampling. The full integral is completed for these wavelength with increasing age resampling and the process stops when the difference in magnitude at all wavelengths from one iteration to the next drops below ``max_err`` (in magnitudes) or until the iteration has run ``max_iter`` times.\n \n In general finer age sampling (and therefore longer calculation times) are required for star formation histories with sharp bursts (i.e. short bursts of star formation).\n \n .. seealso::\n See :meth:`ezgal.ezgal.set_meta_data` for information about meta data.\n .. note::\n ``break_points`` is intended to decrease the amount of age resampling required for models with discontinuities, making for shorter execution times. However, it is still under development and its utility is not yet established.\n .. warning::\n Discontinuties are always a source of trouble, and at the moment it is not clear whether or not ``make_csp`` is properly handling them. In fact, it seems not to be. ``break_points`` is my current attempt at dealing with this problem, but is still under development. If you do model a star formation history with discontinuities then expect ``make_csp`` to hit the maximum iteration limit, and expect your model to take a very long amount of time to calculate. Moreover, it still might not be correct. Test your results carefully. \"\"\"\n\n # basic check - only generate CSPs from SSPs\n if self.has_meta_data and self.meta_data.has_key('sfh') and self.meta_data['sfh'].lower() != 'ssp':\n raise ValueError('Defiantly refusing to generate CSPs from anything other than SSPs. Meta data says this model has an alternate SFH: %s' % self.meta_data['sfh'])\n\n # load up a CSP integrator object (all ages should be in units of Gyrs)\n integrator = csp_integrator.csp_integrator(self.seds, self.ls, self.ages/1e9, self.cosmo.Tu(gyr=True), break_points)\n\n # pass the star formation history stuff\n integrator.set_sfh(sfh_function, args)\n\n # the dust stuff\n if dust_function is not None: integrator.set_dust(dust_function, dust_args)\n\n # and the masses\n if self.has_masses: integrator.set_masses(self.masses)\n\n # calculate the amount of resampling needed\n resampling = integrator.find_resampling(max_err, max_iter)\n\n # integrate\n (seds, masses, sfh) = integrator.integrate(resampling)\n\n # and finally return the new model\n return self._return_new(seds, masses, sfh=sfh, meta_data=meta_data)\n\n ######################\n ## make exponential ##\n ######################\n def make_exponential(self, tau, dust_function=None, dust_args=(), max_err=0.001, max_iter=200):\n \"\"\" new_model = model.make_exponential(tau, dust_function=None, dust_args=(), max_err=0.001, max_iter=200)\n \n :param tau: Time scale for exponentially decaying burst of star formation (in gyrs).\n :param dust_function: The dust dimming factor as a function of age and wavelength\n :param dust_args: A tuple with additional arguments to pass to dust_function\n :param max_err: Maximum allowed integration error (in magnitudes)\n :param max_iter: Maximum number of interations allowed when trying to get errors below ``max_err``\n :type tau: float\n :type sfh_function: function or callable object\n :type args: tuple\n :type dust_function: function or callable object\n :type dust_args: tuple\n :type max_err: float\n :type max_iter: int\n :returns: ``EzGal`` model object for new CSP\n :rtype: ezgal object\n \n :Example:\n >>> import ezgal\n >>> import numpy as np\n >>> model = ezgal.model('bc03_ssp_z_0.02_chab.model')\n >>> # dust free exponentially decaying burst with tau=1 gyr\n >>> exp_1 = model.make_exponential(1.0)\n \n Returns a new EzGal object which exponentially decaying SFH with a timescale of ``tau``.\n \n .. seealso::\n See :meth:`ezgal.ezgal.make_csp` for description of other parameters.\n \"\"\"\n\n return self.make_csp(sfhs.exponential, args=(tau,), meta_data={'sfh': 'Exponential', 'tau': str(tau)}, dust_function=dust_function, dust_args=dust_args, max_err=max_err, max_iter=max_iter)\n\n ################\n ## make burst ##\n ################\n def make_burst(self, length, dust_function=None, dust_args=(), max_err=0.001, max_iter=200):\n \"\"\" new_model = model.make_burst(length, dust_function=None, dust_args=(), max_err=0.001, max_iter=200)\n \n :param length: Length of burst (in gyrs)\n :param dust_function: The dust dimming factor as a function of age and wavelength\n :param dust_args: A tuple with additional arguments to pass to dust_function\n :param max_err: Maximum allowed integration error (in magnitudes)\n :param max_iter: Maximum number of interations allowed when trying to get errors below ``max_err``\n :type length: float\n :type sfh_function: function or callable object\n :type args: tuple\n :type dust_function: function or callable object\n :type dust_args: tuple\n :type max_err: float\n :type max_iter: int\n :returns: ``EzGal`` model object for new CSP\n :rtype: ezgal object\n \n :Example:\n >>> import ezgal\n >>> import numpy as np\n >>> model = ezgal.model('bc03_ssp_z_0.02_chab.model')\n >>> # dust free 0.1 gyr constant burst\n >>> short_burst = model.make_burst(0.1)\n \n Returns a new EzGal object with a constant SFR from ``t=0`` to ``t=length``. Length should be in gyrs.\n \n .. seealso::\n See :meth:`ezgal.ezgal.make_csp` for description of other parameters.\n .. warning::\n A discontinuity is present for star formation histories which are a constant burst, as the star formation drops from some finite value to zero at the end of the burst. It is not yet clear if :meth:`ezgal.ezgal.make_csp` is properly handling discontinuities (see the warning there for more info), so test results from this method carefully before using them. \"\"\"\n\n return self.make_csp(sfhs.constant, args=(length,), dust_function=dust_function, dust_args=dust_args, break_points=length, meta_data={'sfh': 'Burst', 'length': str(length)}, max_err=max_err, max_iter=max_iter)\n\n ##################\n ## make numeric ##\n ##################\n def make_numeric(self, ages, sfr, age_units='gyrs', dust_function=None, dust_args=(), break_points=None, max_err=0.001, max_iter=200):\n \"\"\" new_model = model.make_numeric(ages, sfr, age_units='gyrs', dust_function=None, dust_args=(), break_points=None, max_err=0.001, max_iter=200)\n \n :param ages: A list of ages for the numeric star formation history.\n :param sfr: The star formation rate at each age in ``ages``.\n :param age_units: The age units for the ``ages`` array.\n :param dust_function: The dust dimming factor as a function of age and wavelength\n :param dust_args: A tuple with additional arguments to pass to dust_function\n :param max_err: Maximum allowed integration error (in magnitudes)\n :param max_iter: Maximum number of interations allowed when trying to get errors below ``max_err``\n :type ages: list, array\n :type sfr: list, array\n :type age_units: string\n :type sfh_function: function or callable object\n :type args: tuple\n :type dust_function: function or callable object\n :type dust_args: tuple\n :type max_err: float\n :type max_iter: int\n :returns: ``EzGal`` model object for new CSP\n :rtype: ezgal object\n \n :Example:\n >>> import ezgal\n >>> import numpy as np\n >>> model = ezgal.model('bc03_ssp_z_0.02_chab.model')\n >>> # some arbitrary SFH\n >>> ages = [0,1,2,5,10,12]\n >>> sfr = [0,2,5,8,20,0]\n >>> csp = model.make_numeric(ages, sfr, age_units='gyrs')\n \n Returns a new EzGal object with a SFH determined from an arbitrary numeric star formation history. ``ages`` should be an array of ages and ``sfr`` should be an array with the corresponding star formation rates as a function of time. Expects the ages to be in units of gyrs, if not specify units with ``age_units`` (see :func:`ezgal.utils.to_years` for full list of available age units). The star formation history does not have to be normalized.\n \n .. seealso::\n See :meth:`ezgal.ezgal.make_csp` for description of other parameters. \"\"\"\n\n ages = np.asarray(ages)\n sfr = np.asarray(sfr)\n sinds = ages.argsort()\n return self.make_csp(sfhs.numeric(utils.convert_time(ages[sinds], incoming=age_units, outgoing='gyrs'), sfr[sinds]), dust_function=dust_function, dust_args=dust_args, break_points=break_points, meta_data={'sfh': 'Numeric'}, max_err=max_err, max_iter=max_iter)\n\n ##################\n ## make delayed ##\n ##################\n def make_delayed(self, delay=0.0, age_units='gyrs'):\n \"\"\" new_model = model.make_delayed(delay, age_units='gyrs')\n \n :param delay: length of delay.\n :param age_units: units of delay.\n :type delay: int, float\n :type age_units: string\n :returns: ``EzGal`` model with delayed star formation history\n :rtype: ``EzGal`` model object.\n \n :Example:\n >>> import ezgal\n >>> import numpy as np\n >>> model = ezgal.model('bc03_ssp_z_0.02_chab.model')\n >>> delayed_ssp = model.make_delayed(1.0)\n \n Return a new model with a delay before the onset of star formation. Expects ``delay`` to be in units of ``age_units``. See :func:`ezgal.utils.to_years` for available age units.\n \n This is intended for generating CSPs with complicated star formation histories, as it allows you to add together bursts of star formation which begin at different times.\n \n .. note::\n Uses interpolation to add in delay.\n \"\"\"\n\n # generate arrays for holding new seds/masses/sfhs\n seds = np.zeros(self.seds.shape)\n masses = np.zeros(self.nages) if self.has_masses else None\n sfh = np.zeros(self.nages) if self.has_sfh else None\n\n # convert delay to years\n delay = utils.convert_time(delay, incoming=age_units, outgoing='yrs')\n # and check\n if delay < self.ages.min() or delay > self.ages.max():\n raise ValueError(\"Delay before onset of star formation must be between %f and %f gyrs\" % (self.ages.min()/1e9,self.ages.max()/1e9))\n\n # now generate new SEDs using interpolation\n w = np.where(self.ages > delay)[0]\n for ind in w:\n seds[:,ind] = self.get_sed(self.ages[ind]-delay, age_units='yrs')\n if self.has_masses: masses[ind] = np.interp(self.ages[ind]-delay, self.ages, self.masses)\n if self.has_sfh: sfh[ind] = np.interp(self.ages[ind]-delay, self.ages, self.sfh)\n\n return self._return_new(seds, masses, sfh, meta_data={'delay': utils.convert_time(delay, incoming='yrs', outgoing='gyrs')})\n\n #################\n ## _return_new ##\n #################\n def _return_new(self, seds, masses=None, sfh=None, meta_data=None, weight=1):\n \"\"\" new_model = model._return_new(seds, masses=None, sfh=None, meta_data=meta_data, weight=1)\n \n Return a new EzGal object with the given SEDs, masses, and sfh but with everything else the same.\n seds.shape must equal model.seds.shape. Does not maintain filter information or stored models. \"\"\"\n\n # generate a blank EzGal object to work with\n model = ezgal(skip_load=True)\n\n # store all SED info, and make sure to actually copy\n model.nages = self.nages\n model.nvs = self.nvs\n model.nls = self.nls\n model.ages = self.ages.copy()\n model.vs = self.vs.copy()\n model.ls = self.ls.copy()\n model.seds = seds\n\n # cosmology\n model.set_cosmology(Om=self.cosmo.Om, Ol=self.cosmo.Ol, h=self.cosmo.h, w=self.cosmo.w)\n\n # star formation history\n if sfh is not None:\n model.has_sfh = True\n model.sfh = sfh\n\n # masses\n if masses is not None:\n model.has_masses = True\n model.masses = masses\n\n # meta data\n items = []\n if self.has_meta_data: items += self.meta_data.items()\n # do new meta data last so that it overwrites old meta data\n if meta_data is not None and type(meta_data) == type({}): items += meta_data.items()\n if len(items): model.set_meta_data(dict(items))\n\n # weight\n model.model_weight = weight\n\n return model\n\n ##########\n ## copy ##\n ##########\n def copy(self):\n \"\"\" copy = model.copy()\n \n :returns: A copy of the model\n :rtype: ``EzGal`` model object\n \n :Example:\n >>> import ezgal\n >>> model = ezgal.model('bc03_ssp_z_0.02_chab.model')\n >>> model_copy = model.copy()\n \n Returns a copy of the ``EzGal`` object without any stored filter information.\"\"\"\n\n masses = self.masses.copy() if self.has_masses else None\n sfh = self.sfh.copy() if self.has_sfh else None\n\n return self._return_new(self.seds.copy(), masses, sfh, weight=self.model_weight)\n\n ############\n ## weight ##\n ############\n def weight(self, weight):\n \"\"\" new_model = model.weight(weight)\n \n :param weight: Weight to apply to model\n :type weight: int, float\n :returns: Weighted ``EzGal`` object\n :rtype: ``EzGal`` model object\n \n :Example:\n >>> import ezgal\n >>> model = ezgal.model('bc03_ssp_z_0.02_chab.model')\n >>> heavy = model.weight(2)\n >>> heavier = heavy.weight(4)\n >>> model.model_weight, heavy.model_weight, heavier.model_weight\n (1, 2, 8)\n \n Return a copy of the EzGal model weighted by an additional factor of ``weight``. \"\"\"\n\n new = self.copy()\n new.model_weight *= weight\n return new\n\n #############\n ## __mul__ ##\n #############\n def __mul__(self, obj):\n if type(obj) == type(self):\n return self.weight(obj.model_weight)\n elif type(obj) == type(weight.weight(1)):\n return self.weight(obj.weight)\n else:\n return self.weight(obj)\n\n ##############\n ## __imul__ ##\n ##############\n def __imul__(self, obj):\n if type(obj) == type(self):\n self.model_weight *= obj.model_weight\n elif type(obj) == type(weight.weight(1)):\n self.model_weight *= obj.weight\n else:\n self.model_weight *= obj\n return self\n\n #############\n ## __add__ ##\n #############\n def __add__(self, obj):\n new = self.copy()\n new += obj\n return new\n\n ##############\n ## __iadd__ ##\n ##############\n def __iadd__(self, obj):\n if type(obj) != type(self): raise TypeError('EzGal model objects can only be added with other EzGal model objects!')\n if self.seds.shape != obj.seds.shape or np.max(np.abs(self.ages - obj.ages)) > 0 or np.max(np.abs(self.vs - obj.vs)) > 0:\n raise TypeError('EzGal model objects can only be added if they have the same age/wavelength grid!')\n\n # add together SEDs\n tot_weight = self.model_weight + obj.model_weight\n self.seds *= self.model_weight\n self.seds += obj.model_weight*obj.seds\n self.seds /= tot_weight\n\n # add together masses\n if self.has_masses and obj.has_masses:\n self.masses *= self.model_weight\n self.masses += obj.model_weight*obj.masses\n self.masses /= tot_weight\n else:\n self.has_masses = False\n self.masses = []\n\n # and SFHs\n if self.has_sfh and obj.has_sfh:\n self.sfh *= self.model_weight\n self.sfh += obj.model_weight*obj.sfh\n self.sfh /= tot_weight\n else:\n self.has_sfh = False\n self.sfh = []\n\n # add together weights and return\n self.model_weight = tot_weight\n return self\n\ndef usage():\n print \"ezgal.py [-k -d -b -p --by_filter --prefix=prefix] model_file zf1 zf2 ... zfn filter1 filter2 ... filtern\"\n print \"\"\n print \"all command line flags must come first\"\n print \"pass the input model file, a list of formation redshifts, and a list of filter transmission curves (filenames)\"\n print \"specify an optional prefix for the output filenames\"\n print \"by default it outputs distance moduli, kcorrections, absolute mags, and apparent mags for each filter\"\n print \"use the -k, -b, -p, or -d options to have it output kcorrections, absolute mags, apparent mags, or distance moduli\"\n print \"If you specify the --by_filter flag, and are only outputting one column mag data (-k,-b,-p) then an output file will be created for each filter instead of each formation redshift\"\n print \"\"\n print \"Use these flags:\"\n print \"--norm=mag --norm_filter=filter --norm_z=z --norm_vega --norm_apparent\"\n print \"to set the normalization to be a magnitude of norm through filter norm_filter at redshift norm_z.\"\n print \"Normalization mags are assumed to be in absolute AB mags unless --norm_vega or --norm_apparent is set.\"\n\n################################\n## let's make this executable ##\n################################\nif __name__ == '__main__':\n import sys,getopt,re\n\n # check arguments\n try:\n (opts, args) = getopt.getopt(sys.argv[1:], 'fr:m:z:t:aVvwlhkbpd', ['by_filter','prefix=','norm=','norm_z=','norm_filter=','norm_apparent','norm_vega','vega','Om=','Ol=','h='])\n except getopt.GetoptError, err:\n print str(err)\n usage()\n sys.exit(2)\n\n if len(sys.argv) < 2:\n usage()\n sys.exit()\n\n # make sure the model file exists\n model_file = args[0]\n if not(os.path.isfile(model_file)):\n print 'The specified model file does not exist!'\n usage()\n sys.exit()\n\n # check flags\n norm = 0.0\n norm_z = 0.0\n norm_filter = ''\n norm_apparent = False\n group = 'zf'\n out = 'all'\n prefix = ''\n norm_vega = False\n vega = False\n om = 0.279\n ol = 0.721\n h = 0.701\n for (o, a) in opts:\n if o == '-f' or o == '--by_filter': group = 'filter'\n if o == '-k': out = 'kcor'\n if o == '-b': out = 'abs'\n if o == '-p': out = 'app'\n if o == '-d': out = 'dm'\n if o == '-r' or o == '--prefix': prefix = a\n if o == '-m' or o == '--norm': norm = float(a)\n if o == '-z' or o == '--norm_z': norm_z = float(a)\n if o == '-t' or o == '--norm_filter': norm_filter = a\n if o == '-a' or o == '--norm_apparent': norm_apparent = True\n if o == '-V' or o == '--norm_vega': norm_vega = True\n if o == '-v' or o == '--vega': vega=True\n if o == '-w' or o == '--Om': om = float(a)\n if o == '-l' or o == '--Ol': ol = float(a)\n if o == '-h' or o == '--h': h = float(a)\n\n # load the model\n model = ezgal(model_file)\n\n # set the cosmology\n model.set_cosmology(Om=om, Ol=ol, h=h)\n\n # loop through arguments and find formation redshifts/filters\n zfs_in = []\n filters = []\n nfilters = 0\n for arg in args[1:]:\n # are we still looking for formation redshifts?\n if nfilters == 0:\n # is this a number?\n if re.match('[\\-+]?\\d{1,}\\.?\\d{,}([eEdD]\\d+)?$', arg):\n zfs_in.append(arg)\n continue\n\n # if the filter isn't already in the model then make sure there is a file for it\n if not(model.filters.has_key(arg)) and not(os.path.isfile(arg)): raise ValueError('Could not load the filter %s!' % arg)\n filters.append(arg)\n nfilters += 1\n\n # convert to float and sort formation redshifts\n zfs = np.asarray(zfs_in).astype('float')\n sinds = zfs.argsort()\n zfs = zfs[sinds]\n zfs_in = np.asarray(zfs_in)[sinds]\n\n # time to actually do the calculations\n if len(zfs_in): model.set_zfs(zfs, grid=False)\n for filter in filters:\n if not(model.filters.has_key(filter)): model.add_filter(filter)\n\n # was normalization info passed?\n if norm and norm_z and norm_filter: model.set_normalization(norm_filter, norm_z, norm, vega=norm_vega, apparent=norm_apparent)\n\n # output vega mags?\n if vega: model.set_vega_output()\n\n # if no filters were passed, see if we can load them from the model\n if nfilters == 0:\n if model.nfilters == 0:\n usage()\n sys.exit()\n\n filters = model.filter_order\n nfilters = model.nfilters\n\n # if no zfs were passed, see if we can load them from the model\n if len(zfs_in) == 0:\n if model.nzfs == 0:\n usage()\n sys.exit()\n\n zfs = model.zfs\n zfs_in = ['']*zfs.size\n for i in range(zfs.size): zfs_in[i] = '%.3f' % zfs[i]\n\n system = 'vega' if vega else 'ab'\n\n # create an output file for each filter\n if group == 'filter' and out != 'all' and out != 'dm':\n # add a prefix if there isn't one, otherwise the filter files will be overwritten\n if prefix == '': prefix = 'ev_'\n\n for (find,filter) in enumerate(filters):\n # file header\n display = 'Apparent Mags'\n if out == 'kcor': display = 'Kcorrects'\n if out == 'abs': display = 'Absolute Mags'\n header = '# %s, filter = %s, Om = %.4f, Ol = %.4f, h = %.4f, w = %.4f\\n# input file = %s\\n# All mangitudes are on the %s system\\n# zf= ' % (display,filter,model.cosmo.Om,model.cosmo.Ol,model.cosmo.h,model.cosmo.w,model.filename,system)\n header += ' '.join('%7s' % zf for zf in zfs_in)\n\n # now load data\n output = np.empty((model.zs.size,zfs.size+1))\n output[:,0] = model.zs\n for (zfind,zf) in enumerate(zfs):\n if out == 'app': output[:,zfind+1] = model.get_apparent_mags(zf, filters=filter)\n if out == 'abs': output[:,zfind+1] = model.get_absolute_mags(zf, filters=filter)\n if out == 'kcor': output[:,zfind+1] = model.get_kcorrects(zf, filters=filter)\n\n # don't output stuff if everything is zero\n m = np.abs(output[:,1:]).max(axis=1) != 0\n\n # and output\n utils.wascii(output[m,:], '%s%s' % (prefix,filter), formats='%7.4f', header=header)\n\n else:\n if group == 'filter': print 'Ignoring group by filter specification - that only works for single column ouput!\\n';\n\n # create an output file for each formation redshift\n for (zfind,zf) in enumerate(zfs):\n header = '# zf = %s, Om = %.4f, Ol = %.4f, h = %.4f, w = %.4f\\n# input file = %s\\n# All magnitudes are on the %s system\\n# 1: z' % (zfs_in[zfind],model.cosmo.Om,model.cosmo.Ol,model.cosmo.h,model.cosmo.w,model.filename,system)\n zs = model.zs.reshape((model.nzs,1))\n \n # output apparent magnitudes\n if out == 'app':\n output = np.hstack((zs,model.get_apparent_mags(zf, filters=filters).reshape((model.nzs,len(filters)))))\n for (i,filter) in enumerate(model.filter_order): header += '\\n# %2d: Apparent Mag %s' % (i+2,filter)\n \n # output kcorrections\n if out == 'kcor':\n output = np.hstack((zs,model.get_kcorrects(zf, filters=filters).reshape((model.nzs,len(filters)))))\n for (i,filter) in enumerate(model.filter_order): header += '\\n# %2d: Kcorrect %s' % (i+2,filter)\n \n # output absolute mags\n if out == 'abs':\n output = np.hstack((zs,model.get_absolute_mags(zf, filters=filters).reshape((model.nzs,len(filters)))))\n for (i,filter) in enumerate(model.filter_order): header += '\\n# %2d: Absolute Mag %s' % (i+2,filter)\n \n # output distance moduli\n if out == 'dm' or out == 'all':\n output = np.hstack((zs,model.get_distance_moduli(nfilters=1).reshape((model.nzs,1))))\n header += '\\n# 2: Distance Modulus'\n \n if out == 'all':\n for (i,filter) in enumerate(filters):\n filter_dat = np.column_stack((model.get_kcorrects(zf, filters=filter),model.get_absolute_mags(zf, filters=filter),model.get_apparent_mags(zf, filters=filter)))\n output = np.hstack((output,filter_dat))\n header += '\\n# %2d: Kcorrect %s\\n# %2d: Absolute Mag %s\\n# %2d: Apparent Mag %s (2 + %d + %d)' % (i*3+3,filter,i*3+4,filter,i*3+5,filter,i*3+3,i*3+4)\n if i == 0: wgood = np.abs(filter_dat).max(axis=1) != 0\n else:\n # figure out what is outside the valid interpolation range\n wgood = np.abs(output[:,1:]).max(axis=1) != 0\n \n # now write out a file\n utils.wascii(output[wgood,:], prefix + 'zf_%s' % zfs_in[zfind], formats='%7.4f', header=header)\n", "meta": {"hexsha": "5a49a26b8482e9c94931f7450d31f72ecc54ed87", "size": 129894, "ext": "py", "lang": "Python", "max_stars_repo_path": "ezgal/ezgal.py", "max_stars_repo_name": "dpgettings/ezgal", "max_stars_repo_head_hexsha": "de4a58879eaee0bddbcdb42dddfa2b398dbc3ea9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-07-15T21:05:22.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-05T19:16:09.000Z", "max_issues_repo_path": "ezgal/ezgal.py", "max_issues_repo_name": "dpgettings/ezgal", "max_issues_repo_head_hexsha": "de4a58879eaee0bddbcdb42dddfa2b398dbc3ea9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-09-12T12:37:29.000Z", "max_issues_repo_issues_event_max_datetime": "2015-09-12T12:37:29.000Z", "max_forks_repo_path": "ezgal/ezgal.py", "max_forks_repo_name": "dpgettings/ezgal", "max_forks_repo_head_hexsha": "de4a58879eaee0bddbcdb42dddfa2b398dbc3ea9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-05-14T14:34:19.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-22T02:17:22.000Z", "avg_line_length": 46.0453739809, "max_line_length": 746, "alphanum_fraction": 0.5905969483, "include": true, "reason": "import numpy,import scipy", "num_tokens": 32534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.28140560140262283, "lm_q1q2_score": 0.1418020189682285}} {"text": "#!/bin/env python\nimport math\n#import simtk.openmm.app as soa\n#import simtk.unit as su\nimport sys,os\nimport numpy as np\nfrom .fhet import hetnames,cofactors\nimport copy\n\nMASS = {'O':15.999, 'N':14.010,\n 'C':12.010, 'H': 1.008,\n 'F':19.000,\n 'Na':22.99, 'NA':22.99,\n 'P':30.970, 'S':32.060,\n 'Cl':35.45, 'CL':35.45,\n 'Br':79.90, 'BR':79.90,\n 'CU':63.55,\n }\nATOM_NUM = {'O': 8, 'N': 7,\n 'C': 6, 'H': 1,\n 'F': 9,\n 'Na':11, 'NA':11,\n 'P':15, 'S':16,\n 'Cl':17, 'CL':17,\n 'Br':35, 'BR':35,\n 'CU':29,\n 'X':999\n }\n\nMAX = 99999\nTMPFILE = \"FPDB.SOA.TMPPDBFILE.PDB\"\nkJ_to_kcal = 1/4.184\nBIG_NUM = 1.e10\nHBOND_DISTANCE_CUTOFF = 3.5 # angstron\nHBOND_ANGLE_CUTOFF = 0.666667*math.pi # pi\n\nPROGS = { \"I-interpret\":\"/home/fuqy/Software/I-interpret/bin/I-interpret\" ,\n \"pdbconvert\":\"/opt/schrodinger2016-2/utilities/pdbconvert\",\n \"hetgrp_ffgen\":\"/opt/schrodinger2016-2/utilities/hetgrp_ffgen\",\n \"opls_to_gmx\":\"~/.ffallrain/fqy_scripts/opls2005_to_gmx.py\",\n }\n\nif True: ### residue names \n standard_protein_residues = ('ARG','LYS','HIS','HIP','HIE',\n 'HID','ASP','GLU',\n 'ASN','GLN','SER','THR','CYS','CYX','GLY','PRO','ALA',\n 'VAL','LEU','ILE','MET','PHE','TYR','TRP' )\n\n standard_ion_redsidues = ('FE','MN','NI','CA','ZN','MG',\"CL\",\"NA\")\n standard_water_residues = ('HOH','SOL','WAT')\n standard_residues = standard_protein_residues + standard_water_residues + standard_ion_redsidues\n\n protein_hbond_donors = (\n ('*','N','H'),\n ('*','N','HN'),\n ('ARG', 'NE','HE'),\n ('ARG','NH1','HH11'),\n ('ARG','NH1','HH12'),\n ('ARG','NH2','HH21'),\n ('ARG','NH2','HH22'),\n ('LYS', 'NZ', 'HZ1'),\n ('LYS', 'NZ', 'HZ2'),\n ('LYS', 'NZ', 'HZ3'),\n ('HIS','ND1', 'HD1'),\n ('HIS','NE2', 'HE2'),\n ('HIP','ND1', 'HD1'),\n ('HIP','NE2', 'HE2'),\n ('HID','ND1', 'HD1'),\n ('HIE','NE2', 'HE2'),\n ('ASN','ND2','HD21'),\n ('ASN','ND2','HD22'),\n ('GLN','NE2','HE22'),\n ('GLN','NE2','HE21'),\n ('SER','OG','HG'),\n ('THR','OG1','HG1'),\n ('CYS','SG','HG'),\n ('TYR','OH','HH'),\n ('TRP','NE1','HE1'),\n )\n\n one_letter_code = { \n 'ala'.upper() : 'A' , \n 'arg'.upper() : 'R' ,\n 'asn'.upper() : 'N' ,\n 'asp'.upper() : 'D' ,\n 'asx'.upper() : 'B' ,\n 'cys'.upper() : 'C' ,\n 'glu'.upper() : 'E' ,\n 'gln'.upper() : 'Q' ,\n 'glx'.upper() : 'Z' ,\n 'gly'.upper() : 'G' ,\n 'his'.upper() : 'H' ,\n 'ile'.upper() : 'I' ,\n 'leu'.upper() : 'L' ,\n 'lys'.upper() : 'K' ,\n 'met'.upper() : 'M' ,\n 'phe'.upper() : 'F' ,\n 'pro'.upper() : 'P' ,\n 'ser'.upper() : 'S' ,\n 'thr'.upper() : 'T' ,\n 'trp'.upper() : 'W' ,\n 'tyr'.upper() : 'Y' ,\n 'val'.upper() : 'V' ,\n }\n three_letter_code = dict()\n for key,value in list(one_letter_code.items()):\n three_letter_code[value] = key\n\n\nif True: ### Global varieties \n newnew = '/home/fuqiuyu/.ffallrain/newnew'\n TMPFILE = 'FIND_RING.PDB'\n TMPFILE_MOL2 = 'FIND_RING.mol2'\n babel = '/usr/bin/babel'\n\nclass fATOM():\n def __init__(self,atom_line = None):\n if atom_line == None:\n atom_line = \"ATOM 1 X DEF 1 0.000 0.000 0.000 1.00 0.00 X\" \n\n tmpname = atom_line[12:16]\n if tmpname[0] in \"0123456789\" and tmpname[3]!=\" \":\n tmpname = tmpname[1:] + tmpname[0]\n tmpname = tmpname.strip()\n self.name = tmpname\n try:\n if len(atom_line)>=78:\n self.element = atom_line[76:78].strip()\n else:\n self.element = tmpname[0]\n self.atom_num = ATOM_NUM[self.element]\n except:\n # print(\"DEBUG\",tmpname)\n self.element = tmpname[0] ### !!!! NOT FINISHED\n self.resi_name = atom_line[17:20].strip()\n try:\n self.resi_index = int(atom_line[22:26])\n except:\n self.resi_index = 0\n self.charge = None\n self.sig = None\n self.eps = None\n self.conf = atom_line[16]\n self.index = int(atom_line[6:11])\n x = float(atom_line[30:38])\n y = float(atom_line[38:46])\n z = float(atom_line[46:54])\n self.posi = [x,y,z]\n try:\n self.bf = float(atom_line[60:66])\n except:\n self.bf = 0\n try:\n self.occ = float(atom_line[54:60])\n except:\n self.occ = 0\n self.connect_count = 0 ## for bond\n self.bond = list()\n self.var1 = None\n self.var2 = None\n self.var3 = None\n\n def addparm(self,charge,sig,eps):\n self.charge = charge\n self.sig = sig\n self.eps = eps\n\n def _addconnect(self):\n self.connect_count += 1\n\n def _delconnect(self):\n self.connect_count -= 1\n if self.connect_count < 0 :\n sys.stderr.write(\"WARNING,BOND CONNECTION LESS THAN ZERO.\\n\")\n def addbond(self,bond):\n self.bond.append(bond)\n self._addconnect()\n def delbond(self,bond):\n self.bond.remove(bond)\n self._delconnect()\n\nclass fCHEMO():\n @staticmethod\n def _next_atom_line(resi_lines):\n for atom_line in resi_lines:\n if len(atom_line)>=6 and atom_line[:6] in ('HETATM','ATOM '):\n yield atom_line\n\n ### Did not finished !\n def addH(self,keep_current = False,nc = 0 ):\n sys.stderr.write(\"##### FPDB WARNING: Currently, using fCHEMO.addH will remove the names/indexes of the exist atoms !!\\n\")\n parameter_text = '''\n SP1_CUTOFF_ANGLE = 155.0\n SP2_CUTOFF_ANGLE = 115.0\n TORSION_RING_FIVE = 7.5\n TORSION_RING_SIX = 15.0\n FLAT_TORSION_ANGLE = 30.0\n\n CHARGED_CARBOXYL = YES\n ALIPHATIC_NITROGEN = YES\n CHARGED_GUANIDINIUM = YES\n ODD_RING_AROMATICITY = YES\n CONVERT_DATIVE_BONDS = YES\n\n LARGEST_SUBSTRUCTURE = NO\n ADD_HYDROGEN_ATOMS = YES\n HEAVY_ATOM_STATISTICS = NO\n '''\n ofp = open(\"parameter.txt\",'w')\n ofp.write(parameter_text)\n ofp.close()\n ofp = open(\"FPDB_TMPLIG.pdb\",'w')\n self.write_pdb(ofp)\n ofp.close()\n os.system(\"%s FPDB_TMPLIG.pdb FPDB_OUTLIG.pdb\"%PROGS[\"I-interpret\"])\n os.system(\"rm FPDB_TMPLIG.pdb parameter.txt\")\n lines = list()\n for line in open(\"FPDB_OUTLIG.pdb\"):\n if len(line)>=6 and line[:6] in (\"HETATM\",\"ATOM \"):\n lines.append(line)\n self._update(resi_lines = lines)\n for atom in self.atoms:\n atom.conf = ' '\n\n def _update(self,resi_lines):\n for line in resi_lines:\n H_index = 1\n tmp_atom = fATOM(line)\n exist_flag = False\n for atom in self.atoms:\n if dist_2(atom,tmp_atom)<0.1:\n exist_flag = True\n break\n if exist_flag:\n pass\n else:\n name = \"H%d\"%H_index\n while ( name in list(self.atoms_d.keys()) ):\n H_index += 1\n name = \"H%d\"%H_index\n tmp_atom.name = name\n self.atoms.append(tmp_atom)\n self.atoms_d[name] = tmp_atom\n \n def rename_atom(self):\n element_index = dict()\n for atom in self.atoms:\n if atom.element not in element_index:\n element_index[atom.element] = 0\n newname = atom.element+\"%d\"%element_index[atom.element]\n else:\n element_index[atom.element] += 1\n newname = atom.element+\"%d\"%element_index[atom.element]\n atom.name = newname\n self.atoms_d[atom.name] = atom\n\n def generate_OPLS_parameters(self, nc = 0, version = '2005', rename_atom = False):\n if rename_atom:\n self.rename_atom()\n\n self.removeH()\n self.addH( keep_current = False,nc = nc)\n resname = self.name.lower()\n self.write_pdb(\"%s.pdb\"%resname)\n os.system(\"%s -ipdb %s.pdb -omae %s.mae\"%(PROGS['pdbconvert'],resname,resname))\n os.system(\"%s %s %s.mae\"%(PROGS['hetgrp_ffgen'],version,resname))\n os.system(\"%s -f %s.pdb -o %s.top -p %s\"%(PROGS['opls_to_gmx'],resname,resname,resname)) \n os.system(\"mkdir %s_parameter\"%resname)\n os.system(\"mv %s %s.mae %s.pdb %s.top %s_nb.itp %s_parameter/\"%(resname,resname,resname,resname,resname,resname))\n sys.stdout.write(\">>>>> FPDB, parameters of compound %s generated. \\n\"%resname)\n\n # load parameters\n nb_itp = \"%s_parameter/%s_nb.itp\"%(resname,resname)\n top = \"%s_parameter/%s.top\"%(resname,resname)\n self.load_parameters_from_file(nb_itp,top)\n\n def load_parameters_from_file(self,nb_itp,top):\n try :\n # vdw\n flag = False \n for line in open(nb_itp):\n if \"atomtypes\" in line:\n flag = True\n continue\n if flag :\n if \"name\" not in line:\n if line.strip() != \"\":\n name = line.split()[0]\n sig = float(line.split()[5])\n eps = float(line.split()[6])\n self.atoms_d[name].sig = sig\n self.atoms_d[name].eps = eps\n # charge\n flag = False\n for line in open(top):\n if \"atoms\" in line:\n flag = True\n continue\n elif \"bonds\" in line:\n flag = False\n continue\n if flag :\n if line.strip() != \"\":\n if line.strip()[0] != \";\":\n name = line.split()[1]\n charge = float(line.split()[6])\n self.atoms_d[name].charge = charge\n except Exception as e:\n print((\"##### Load parameter Fail: %s\"%self.name))\n print((e.message))\n\n\n def __init__(self,resi_lines=None):\n if resi_lines == None:\n resi_lines = list()\n try:\n self.name = resi_lines[0][17:20].strip()\n self.index = int(resi_lines[0][22:26])\n self.chain = resi_lines[0][21]\n self.insertion = resi_lines[0][26]\n except:\n self.name = \"UND\"\n self.index = 0\n self.chain = \" \"\n self.insertion = \" \"\n\n self.atoms = list()\n self.index_shift = 0\n \n for atom_line in fRESIDUE._next_atom_line(resi_lines):\n self.atoms.append( fATOM(atom_line) )\n if len(self.atoms)>0:\n self.index_shift = self.atoms[0].index - 1\n else:\n self.index_shift = 0\n self.atoms_d = dict()\n for atom in self.atoms:\n self.atoms_d[atom.name] = atom\n self.var1 = None\n self.var2 = None\n self.var3 = None\n self.del_duplicate_atoms()\n\n def getCOM(self):\n mass = np.array([MASS[i.element] for i in self.atoms])\n coors = self.getxyzs\n return np.dot(mass, coors) / sum(mass)\n\n def getxyzs(self):\n return np.array([i.posi for i in self.atoms])\n\n def updatexyzs(self, xyzs):\n for i, xyz in zip(self.atoms, xyzs):\n i.posi = xyz \n\n def add_atom(self,atom):\n if hasattr(atom,'name'):\n self.atoms.append(atom)\n self.atoms_d[atom.name] = atom\n else :\n try:\n a = fATOM(atom)\n self.atoms.append( a )\n self.atoms_d[a.name] = a\n except:\n sys.stderr.write(\"##### Error, Error loading atom %s\"%atom)\n\n def remove_atom(self,atom):\n self.atoms.remove(atom)\n if atom.name in self.atoms_d:\n del(self.atoms_d[atom.name])\n\n def removeH(self):\n to_del = [ x for x in self.atoms if x.element == \"H\" ]\n for atom in to_del:\n self.remove_atom(atom)\n \n def find_atoms(self, name = None , index = None ):\n result = list()\n ignore_name = False\n ignore_index = False\n if name == None:\n ignore_name = True\n if index == None:\n ignore_index = True\n for atom in self.atoms:\n if ignore_name or atom.name in name:\n if ignore_index or atom.index in index:\n result.append(atom)\n return result\n\n def write_pdb(self,ofile=None):\n pdbstr = \"\"\n for atom in self.atoms:\n x,y,z = atom.posi\n \n tmpname = atom.name\n if len(tmpname) == 4:\n tmpname = tmpname[-1]+tmpname[:-1]\n else:\n tmpname = \" \"+tmpname+\" \"*(3-len(tmpname))\n \n line = 'ATOM %5d %4s%1s%-4s%1s%4d %8.3f%8.3f%8.3f%6.2f%6.2f%12s\\n'%(\n atom.index,tmpname,atom.conf,self.name,self.chain,self.index,\n x,y,z,atom.occ,atom.bf,atom.element)\n pdbstr += line\n if ofile is None:\n return pdbstr\n elif hasattr(ofile,'write'):\n ofile.write(pdbstr)\n else:\n ofp = open(ofile,'w')\n ofp.write(pdbstr)\n \n def write_pdb_plop(self,ofile=None):\n # make atomline : case if protein or metal\n if self.name in standard_protein_residues:\n atomline='ATOM %5d %-3s%1s%3s %1s%4d %8.3f%8.3f%8.3f 1.00 0.00\\n'\n else:\n atomline='HETATM%5d %-3s%1s%3s %1s%4d %8.3f%8.3f%8.3f 1.00 0.00\\n' # qiuyu Fu\n if self.name in standard_ion_redsidues:\n atomline='HETATM%5d %-4s%1s%3s %1s%4d %8.3f%8.3f%8.3f 1.00 0.00\\n'\n # Case: no ofp\n if ofile is None:\n ofp = str()\n if self.name not in standard_protein_residues: ofp +='TER\\n'\n for atom in self.atoms:\n x,y,z = atom.posi\n line = atomline%(atom.index,atom.name,atom.conf,self.name,self.chain,self.index,x,y,z)\n ofp += line\n if self.name not in standard_protein_residues: ofp +='TER\\n'\n return ofp\n # Case: file handle\n elif hasattr(ofile,'write'):\n ofp = ofile\n if self.name not in standard_protein_residues:ofp.write('TER\\n')\n for atom in self.atoms:\n pass\n if len(atom.name) != 4 :\n x,y,z = atom.posi\n line = atomline%(atom.index,atom.name,atom.conf,self.name,self.chain,self.index,x,y,z)\n ofp.write(line)\n else:\n tmpatomline='HETATM%5d %-4s%1s%3s %1s%4d %8.3f%8.3f%8.3f 1.00 0.00\\n' \n x,y,z = atom.posi\n line = tmpatomline%(atom.index,atom.name,atom.conf,self.name,self.chain,self.index,x,y,z)\n ofp.write(line)\n if self.name not in standard_protein_residues:ofp.write('TER\\n')\n # Case: String ( filename )\n else:\n ofp = open(ofile,'a')\n if self.name not in standard_protein_residues:ofp.write('TER\\n')\n for atom in self.atoms:\n pass\n if len(atom.name) != 4 :\n x,y,z = atom.posi\n line = atomline%(atom.index,atom.name,atom.conf,self.name,self.chain,self.index,x,y,z)\n ofp.write(line)\n else:\n tmpatomline='HETATM%5d %-4s%1s%3s %1s%4d %8.3f%8.3f%8.3f 1.00 0.00\\n' \n x,y,z = atom.posi\n line = tmpatomline%(atom.index,atom.name,atom.conf,self.name,self.chain,self.index,x,y,z)\n ofp.write(line)\n if self.name not in standard_protein_residues:ofp.write('TER\\n')\n ofp.close()\n\n def debug(self):\n print(('name',self.name))\n print(('index',self.index))\n print(('insertion',self.insertion))\n print('atoms:')\n for atom in self.atoms:\n print((atom.name,))\n print()\n\n def find_h(self):\n h_list = list()\n for atom in self.atoms:\n if atom.element == 'H':\n h_list.append(atom)\n #print \"DEBUG:\",h_list\n return h_list\n\n def _find_bond_atoms(self,atom,cutoff):\n cutoff_2 = cutoff ** 2\n a_list = list()\n for a in self.atoms:\n if a == atom:\n continue\n if dist_2(atom,a) < cutoff_2:\n a_list.append(a)\n return a_list\n\n def find_polar_h(self):\n polar_h_list = list()\n for atom in self.find_h():\n for a in self._find_bond_atoms(atom, 1.2): # bond length with H is usually < 1.0 A\n if a.element in (\"N\",\"O\",\"S\"): # currently only take O,N and S into account.\n polar_h_list.append(atom)\n return polar_h_list\n\n def find_hbond_acceptor(self):\n l = list()\n for atom in self.atoms:\n if atom.element in (\"N\",\"O\"):\n l.append(atom)\n return l\n\n def find_hbond_donar(self):\n donar = list()\n for atom in self.find_h():\n for a in self._find_bond_atoms(atom, 1.2): # bond length with H is usually < 1.0 A\n if a.element in (\"N\",\"O\",\"S\"): # currently only take O,N and S into account.\n donar.append( (a,atom) )\n \n return donar\n\n def find_hbond_with(self,resi): ## use three \n return self.find_hbond(resi)\n\n def find_hbond(self,resi): ## use three \n if not hasattr(resi,'atoms'):\n print(\"##### Error. Currently the only usage of find_h_bond() is : self.find_h_bond( another_residue ). Will stop \")\n sys.exit()\n if self == resi:\n print(\"##### Warning: find hbond between identical residues. Will return empty list.\")\n return list(),list()\n\n as_donar = list()\n for d,h in self.find_hbond_donar():\n for a in resi.find_hbond_acceptor():\n if fHbond.is_hydrogen_bond(d,h,a):\n as_donar.append( fHbond(d,h,a) )\n as_acceptor = list()\n for a in self.find_hbond_acceptor():\n for d,h in resi.find_hbond_donar():\n if fHbond.is_hydrogen_bond(d,h,a):\n as_acceptor.append( fHbond(d,h,a) )\n return as_donar,as_acceptor\n\n def del_duplicate_atoms(self):\n # \n names = set()\n tmp_atoms = list()\n for atom in self.atoms:\n if atom.name not in names:\n tmp_atoms.append(atom)\n names.add(atom.name)\n else:\n pass\n self.atom = tmp_atoms\n\nclass fSDF_MOL(fCHEMO):\n def __init__(self, sdf_frame):\n fCHEMO.__init__(self)\n n_atom = int(sdf_frame[3].split()[0])\n atomlines = sdf_frame[4:4+n_atom]\n self.name = \"___\"\n self.index = 0\n for atomline in atomlines:\n tmpatom = fATOM()\n items = atomline.split()\n x = float(items[0])\n y = float(items[1])\n z = float(items[2])\n name = items[3]\n tmpatom.posi = (x,y,z)\n tmpatom.index = 0 \n tmpatom.name = name\n tmpatom.element = name[0]\n self.add_atom(tmpatom)\n\nclass fRESIDUE(fCHEMO):\n pass\n\nclass fRING(fCHEMO):\n def __init__(self,atom_list):\n fCHEMO.__init__(self,[])\n for atom in atom_list:\n self.atom.append(atom)\n\nclass fHbond(fCHEMO):\n def __init__(self,d,h,a):\n fCHEMO.__init__(self)\n self.add_atom(d)\n self.add_atom(h)\n self.add_atom(a)\n self.d = d\n self.h = h\n self.a = a\n self.angle = angle(d,h,a)\n self.dist = dist(d,a)\n if self.angle < HBOND_ANGLE_CUTOFF:\n sys.stderr.write( \"##### Warning ! You registed a hydrogen bond, but angle(d,h,a) is smaller than HBOND_ANGLE_CUTOFF(%f)\\n\"%HBOND_ANGLE_CUTOFF )\n if self.dist > HBOND_DISTANCE_CUTOFF:\n sys.stderr.write( \"##### Warning ! You registed a hydrogen bond, but dist(d,a) is larger than HBOND_DISTANCE_CUTOFF(%f)\\n\"%HBOND_DISTANCE_CUTOFF )\n\n @staticmethod\n def is_hydrogen_bond(d,h,a):\n tmp_angle = angle(d,h,a)\n tmp_dist = dist(d,a)\n if tmp_angle >= HBOND_ANGLE_CUTOFF and tmp_dist <= HBOND_DISTANCE_CUTOFF:\n return True\n else:\n return False\n\nclass fBOND:\n def __init__(self,atoma,atomb):\n # print \"DEBUG ADD BOND BETWEEN\",atoma.name,'and',atomb.name\n if atoma.nameatomb.name:\n atoma.addbond(self)\n atomb.addbond(self)\n self._ = (atomb,atoma)\n else:\n pass\n sys.stderr.write(\"WARNING,INTENDED TO CONNECT BOND BETWEEN IDENTICAL ATOMS\\n\")\n def del_me(self):\n self._[0].delbond(self)\n self._[1].delbond(self)\n\nclass fCOMPOUND(fCHEMO):\n BOND_CUTOFF_H = 1.5 # Angstrom\n BOND_CUTOFF_H_2 = 2.25 # Angstrom\n BOND_CUTOFF = 2.0 # Angstrom\n BOND_CUTOFF_2 = 4.0 # Angstrom\n def __init__(self,compound_lines):\n fCHEMO.__init__(self,compound_lines)\n self._atom_classification()\n self._makebond()\n def _atom_classification(self):\n self.h_list = list()\n self.heavy_list = list()\n for atom in self.atoms:\n if len(atom.name)>=1 and atom.name[0] == 'H' :\n self.h_list.append(atom)\n else:\n self.heavy_list.append(atom)\n def _makebond(self):\n self.bonds = set()\n self._make_h_bond()\n self._make_heavy_bond()\n def _make_h_bond(self):\n for h in self.h_list:\n for heavy in self.heavy_list:\n if dist_2(h,heavy) <= self.BOND_CUTOFF_H_2:\n self.bonds.add(fBOND(h,heavy))\n break\n def _make_heavy_bond(self):\n for heavy_1 in self.heavy_list:\n for heavy_2 in self.heavy_list:\n if heavy_1.name < heavy_2.name :\n if dist_2(heavy_1,heavy_2) <= self.BOND_CUTOFF_2:\n self.bonds.add(fBOND(heavy_1,heavy_2))\n def truncate_leaf(self):\n while True:\n to_be_deleted = list()\n for atom in self.atoms:\n assert atom.connect_count > 0\n if atom.connect_count == 1:\n to_be_deleted.append(atom)\n if len(to_be_deleted) == 0 :\n break\n else:\n for atom in to_be_deleted:\n bonds = atom.bond\n for bond in bonds:\n bond.del_me()\n self.bonds.remove(bond)\n self.atoms.remove(atom)\n self._atom_classification()\n def find_ring(self):\n pass\n self.write_mol2(TMPFILE_MOL2)\n answer = os.popen(\"%s %s \"%(newnew,TMPFILE_MOL2)).readlines()\n os.remove(TMPFILE_MOL2)\n rings = list()\n for line in answer:\n tmpring = list()\n numbers = [ int(x)+self.index_shift for x in line.replace(',' , '').split()[2:] ]\n tmpring = self.find_atoms(index = numbers)\n rings.append(tmpring)\n self.rings = self._merge_ring(rings)\n return self.rings\n #analyze answer and tranlate to my class ( fRING class )\n def _merge_ring(self,rings):\n new_rings = list()\n for ring in rings:\n flag_keep = True\n for i in range(len(new_rings)):\n cp_ring = new_rings[i]\n if len(ring)+len(cp_ring)-len( set( ring + cp_ring )) >=2 :\n new_rings[i] = list( set(ring+cp_ring) )\n flag_keep = False\n break\n if flag_keep:\n new_rings.append(ring)\n return new_rings\n def write_mol2(self,ofile):\n self.write_pdb(TMPFILE)\n os.system(\"%s -ipdb %s -omol2 %s\"%(babel,TMPFILE,ofile))\n os.system(\"echo '@ATOM' >> %s\"%ofile)\n os.remove(TMPFILE)\n def list_connect_count(self):\n for atom in self.atoms:\n print((atom.name,atom.connect_count))\n def debug(self):\n fCHEMO.debug(self)\n print(\"Hydrogen atoms:\")\n for h in self.h_list:\n print((h.name))\n print(\"Heavy atoms:\")\n for heavy in self.heavy_list:\n print((heavy.name))\n print((\"Num of Bonds:\",len(self.bonds)))\n print(\"Atom index:\")\n for atom in self.atoms:\n print((atom.index,))\n print()\n \nclass fCHAIN():\n def __init__(self,chain_index = 'A'):\n self.residues = list()\n self.chain_name = chain_index\n def add_resi(self,resi):\n self.residues.append(resi)\n def delete_resi(self,resi):\n self.residues.remove(resi)\n\nclass fTOPOLOGY():\n @staticmethod\n def _next_resi_lines(lines):\n resi_lines = list()\n oldresindex = None\n for line in lines:\n if len(line)<6 or line[:6] not in ('ATOM ','HETATM'):\n continue\n else:\n resindex = line[22:26].strip()+line[21]\n if resindex == oldresindex or oldresindex == None:\n resi_lines.append(line)\n else:\n yield resi_lines\n resi_lines = list()\n resi_lines.append(line)\n oldresindex = resindex\n yield resi_lines\n\n def __init__(self,lines):\n self.residues = list()\n for resi_lines in fTOPOLOGY._next_resi_lines(lines):\n self.residues.append( fRESIDUE(resi_lines) )\n self.residues_d = dict()\n for resi in self.residues:\n self.residues_d[resi.index] = resi\n\n self.chains = dict()\n for resi in self.residues:\n if resi.chain in list(self.chains.keys()):\n self.chains[resi.chain].add_resi(resi)\n else:\n self.chains[resi.chain] = fCHAIN(resi.chain)\n self.chains[resi.chain].add_resi(resi)\n\n def add_residue(self, resi):\n self.residues.append(resi)\n self.residues_d[resi.index] = resi \n if resi.chain in list(self.chains.keys()):\n self.chains[resi.chain].add_resi(resi)\n else:\n self.chains[resi.chain] = fCHAIN(resi.chain)\n self.chains[resi.chain].add_resi(resi)\n def remove_residue(self,resi):\n self.residues.remove(resi)\n del(self.residues_d[resi.index])\n try:\n self.chains[resi.chain].delete_resi(resi)\n except Exception as e:\n print((e.message))\n \n\n def get_protein_residues(self):\n prot_residues = list()\n for resi in self.residues:\n if resi.name in standard_protein_residues:\n prot_residues.append(resi)\n return prot_residues\n\n def get_water_residues(self):\n water_residues = list()\n for resi in self.residues:\n if resi.name in standard_water_residues:\n water_residues.append(resi)\n return water_residues\n\n def find_residues(self, name = None , index = None ,atom_index = None ):\n result = list()\n ignore_name = False\n ignore_index = False\n ignore_atom_index = False\n if name == None:\n ignore_name = True\n if index == None:\n ignore_index = True\n if atom_index == None:\n ignore_atom_index = True\n for residue in self.residues:\n if ignore_name or residue.name in name:\n if ignore_index or residue.index in index:\n if ignore_atom_index or sum( [ atom_index.count(x.index) for x in residue.atoms] ) > 0:\n result.append(residue)\n return result\n\n def write_model(self,ofp):\n for residue in self.residues:\n residue.write_pdb(ofp)\n\nclass fPDB:\n def __init__(self,frame = None, fragmentation=False):\n lines = None\n if hasattr(frame,'isalpha'):\n lines = open(frame).readlines()\n elif frame == None:\n lines = list()\n else:\n lines = frame\n\n for line in lines:\n if len(line)>=6 and line[:6]==\"CRYST1\":\n x = float(line.split()[1])\n y = float(line.split()[2])\n z = float(line.split()[3])\n self.box = x,y,z\n break\n\n if not hasattr(self,'box'):\n self.box = 0,0,0\n\n self.model_n = 1\n for line in lines:\n if len(line)>=6 and line[:6]==\"MODEL \":\n try:\n if len(line.split())==2:\n self.model_n = int(line.split()[-1]) \n else:\n self.model_n = int(line[5:14])\n except:\n pass\n if fragmentation:\n from .frag import fFRAGTOPO\n self.topology = fFRAGTOPO(lines)\n else:\n self.topology = fTOPOLOGY(lines)\n\n @staticmethod\n def load_ff_param_resi(resi,gmxtop):\n resi_atoms = set( [ x.name for x in resi.atoms ] )\n gmx_resi_set = set(gmxtop.get_resilist())\n gmx_atoms = None\n\n if resi.name in standard_water_residues:\n tmpname = 'HOH'\n else:\n tmpname = resi.name\n \n if tmpname in gmx_resi_set:\n _ = dict()\n for x in gmxtop.get_resi(tmpname) :\n _[x[0]] = x \n # _ = { x[0]:x for x in gmxtop.get_resi(tmpname) }\n if resi_atoms == set(_.keys()):\n gmx_atoms = _\n else:\n gmx_atoms = None\n \n if gmx_atoms == None:\n for gmx_resi in gmx_resi_set:\n # _ = { x[0]:x for x in gmxtop.get_resi(gmx_resi) }\n _ = dict()\n for x in gmxtop.get_resi(gmx_resi):\n _[x[0]] = x \n if resi_atoms == set(_.keys()):\n # print(>>>>> Loading GMX parameters : %s\"%gmx_resi)\n if tmpname != gmx_resi :\n gmx_atoms = _\n pass\n if tmpname != 'HOH':\n sys.stderr.write(\"===== Warning : different residue names while loading parameters %s ( parameters: %s).\\n\"%(tmpname,gmx_resi))\n\n if gmx_atoms is not None:\n for atom in resi.atoms:\n gmx_atom = gmx_atoms[atom.name]\n atom.addparm( gmx_atom[3],gmx_atom[1],gmx_atom[2] )\n return \n\n # for gmx_resi in gmxtop.get_resilist_amber():\n # gmx_atoms = set( [ x[0] for x in gmxtop.get_resi_amber(gmx_resi) ] )\n\n # if resi_atoms == gmx_atoms:\n # pass\n # print(\">>>>> Loading AMBER parameters : %s\"%gmx_resi)\n # if resi.name != gmx_resi :\n # pass\n # print(\"##### Warning : Different residue names while loading parameters %s and %s\"%(resi.name,gmx_resi))\n # for atom in resi.atoms:\n # for gmx_atom in gmxtop.get_resi_amber(gmx_resi):\n # if atom.name == gmx_atom[0]:\n # atom.addparm( gmx_atom[3],gmx_atom[1],gmx_atom[2] )\n # return \n\n print((\"##### Warning : Error in loading residue parameters \",resi.name,resi.index, \" set all parameter within this residue to zero \"))\n for atom in resi.atoms:\n atom.addparm(0,0,0)\n # print(\"Error loading residue parameters\",resi.name,resi.index)\n return\n\n def load_ff_params(self, gmxtop ):\n residues = list(self.topology.residues)\n for resi in residues :\n fPDB.load_ff_param_resi(resi,gmxtop)\n\n def check_params(self):\n for resi in self.topology.residues:\n for atom in resi.atoms:\n print((atom.name,atom.charge,atom.sig,atom.eps))\n\n def find_protein_center(self):\n n = 0\n xs = 0.\n ys = 0.\n zs = 0.\n for residue in self.topology.residues:\n if residue.name in standard_protein_residues:\n for atom in residue.atoms:\n x,y,z = atom.posi\n xs += x\n ys += y\n zs += z\n n += 1\n if n == 0 :\n return 0,0,0\n else:\n return xs/n,ys/n,zs/n\n\n def center(self, center_posi = (0,0,0) ):\n for resi in self.topology.residues:\n for atom in resi.atoms:\n for i in range(3):\n if atom.posi[i] - center_posi[i] > 0:\n atom.posi[i] = atom.posi[i] - self.box[i]*int( ( atom.posi[i]-center_posi[i] )/self.box[i] + 0.5 )\n else :\n atom.posi[i] = atom.posi[i] + self.box[i]*int( ( - atom.posi[i] + center_posi[i] )/self.box[i] + 0.5 )\n\n def write_pdb(self,ofp):\n if hasattr(ofp,'write'):\n flag_is_handle = True\n flag_is_str = False\n else:\n ofp = open(ofp,'w')\n flag_is_handle = False\n flag_is_str = True\n\n ofp.write(\"MODEL %4d\\n\"%self.model_n)\n ofp.write(\"CRYST1%9.3f%9.3f%9.3f 90.00 90.00 90.00 P 65 2 2 12\\n\"%self.box)\n self.topology.write_model(ofp)\n ofp.write(\"ENDMDL\\n\")\n\n if flag_is_str:\n ofp.close()\n\n def optimize_lys_H(self):\n \"\"\" A specified method for proprocessing SPA graphic.pdb, fix three hydrogen postion on LYS NZ\"\"\"\n R_HN = 1.0\n for resi in self.topology.find_residues(name = (\"LYS\",) ):\n ce = resi.atoms_d['CE']\n nz = resi.atoms_d['NZ']\n h1 = resi.atoms_d['HZ1']\n h2 = resi.atoms_d['HZ2']\n h3 = resi.atoms_d['HZ3']\n r_tmp = dist(ce,nz)\n x = (nz.posi[0] - ce.posi[0])/r_tmp*R_HN\n y = (nz.posi[1] - ce.posi[1])/r_tmp*R_HN\n z = (nz.posi[2] - ce.posi[2])/r_tmp*R_HN\n from . import frotate \n matrix1 = frotate.build_matrix(h2.posi,h3.posi,-1.318)\n newcoord1 = frotate.rotate_atom( (x,y,z),(0,0,0),matrix1 )\n matrix2 = frotate.build_matrix(h3.posi,h1.posi,-1.318)\n newcoord2 = frotate.rotate_atom( (x,y,z),(0,0,0),matrix2 )\n matrix3 = frotate.build_matrix(h1.posi,h2.posi,-1.318)\n newcoord3 = frotate.rotate_atom( (x,y,z),(0,0,0),matrix3 )\n for i in (0,1,2):\n h1.posi[i] = newcoord1[i] + nz.posi[i]\n h2.posi[i] = newcoord2[i] + nz.posi[i]\n h3.posi[i] = newcoord3[i] + nz.posi[i]\n def choose_conformation(self,conf=None):\n if 'conf' == None:\n 'conf' == 'A'\n\n tmpdb = copy.deepcopy(self)\n tmpdb.topology = fTOPOLOGY(list())\n for resi in self.topology.residues:\n tmpresi = copy.deepcopy(resi)\n tmpresi.atoms = list()\n tmpresi.atoms_d = dict()\n for atom in resi.atoms :\n if atom.conf in (\" \",conf):\n tmpresi.add_atom(atom)\n tmpdb.topology.add_residue(tmpresi)\n \n return tmpdb\n \n###### Function to compute vdw\ndef calc_vdw(a,b,dist_2):\n sig1,eps1=a.sig,a.eps\n sig2,eps2=b.sig,b.eps\n sig = 0.5 * ( sig1 + sig2 )\n sig = sig * sig\n eps = math.sqrt(eps1*eps2)\n _dist = dist_2 / 100.\n _ = ( sig/_dist ) ** 3\n return 4 * eps * ( _ * _ - _ ) \n\n###### Function to compute charge\ndef calc_chg(a,b,dist_2):\n #f_charge = 138.935485\n charge1 = a.charge\n charge2 = b.charge\n return 138.935485*charge1*charge2/(math.sqrt(dist_2)/10.)\n\n###### Function to compute vdw\ndef atomicEF(a,b):\n k = 138.935485\n sig1,eps1=a.sig,a.eps\n sig2,eps2=b.sig,b.eps\n sig = 0.5 * ( sig1 + sig2 )\n sig = sig * sig\n sig6 = sig ** 3\n sig12 = sig6 * sig6\n eps = np.sqrt(eps1*eps2)\n x0 = np.array(a.posi)\n x1 = np.array(b.posi)\n x0 /= 10\n x1 /= 10\n r2 = sum((x1-x0)**2)\n r = np.sqrt(r2)\n r6 = r2**3\n r8 = r6 * r2\n r12 = r6 * r6\n r14 = r12 * r2\n Evdw = 4 * eps * (sig12/r12 - sig6/r6)\n Fvdw = 24 * eps * (sig6/r8 - 2*sig12/r14) * (x1-x0)\n chg1 = a.charge\n chg2 = b.charge\n Eelec = k*chg1*chg2/r\n Felec = - k*chg1*chg2*(x1-x0)/(r*r2)\n return (Evdw + Eelec)*kJ_to_kcal, (Fvdw + Felec)*kJ_to_kcal/10 # to A\n\n\n###### dist_2 atom atom\ndef dist_2(a,b):\n if hasattr(a,'posi'):\n x1,y1,z1 = a.posi\n else:\n x1,y1,z1 = a\n if hasattr(b,'posi'):\n x2,y2,z2 = b.posi\n else:\n x2,y2,z2 = b\n return (x1-x2)**2 + (y1-y2)**2 + (z1-z2)**2 \n\ndef dist(a,b):\n return math.sqrt( dist_2(a,b) )\ndef dist_resi_resi_2(a,b):\n assert len(a.atoms)>0 and len(b.atoms)>0\n dist = BIG_NUM\n for i in a.atoms:\n for j in b.atoms:\n tmp = dist_2(i,j)\n if tmp < dist:\n dist = tmp\n return dist\ndef dist_resi_resi(a,b):\n return math.sqrt(dist_resi_resi_2(a,b))\ndef dist_atom_resi_2(a,b):\n dist = BIG_NUM \n if hasattr(b,'atoms'):\n assert len(b.atoms)>0\n else:\n assert len(b) > 0\n if hasattr(b,'atoms'):\n for j in b.atoms:\n tmp = dist_2(a,j)\n if tmp< dist:\n dist = tmp\n else:\n for j in b:\n tmp = dist_2(a,j)\n if tmp< dist:\n dist = tmp\n return dist\n\ndef dist_atom_resi(a,b):\n return math.sqrt( dist_atom_resi_2(a,b) )\n\ndef angle( a1,b,a2):\n dist_a1_a2_2 = dist_2(a1,a2)\n dist_a1_b = dist(a1,b)\n dist_a2_b = dist(a2,b)\n cos_angle = ( - dist_a1_a2_2 + dist_a1_b**2 + dist_a2_b**2 )/( 2*dist_a1_b*dist_a2_b )\n angle = math.acos(cos_angle)\n return angle\n\ndef dihedral(a1,b1,b2,a2):\n \"Method at https://math.stackexchange.com/questions/47059/how-do-i-calculate-a-dihedral-angle-given-cartesian-coordinates\"\n \n vector_b1 = (np.array( b1.posi ) - np.array( a1.posi ))[:3]\n vector_b2 = (np.array( b2.posi ) - np.array( b1.posi ))[:3]\n vector_b3 = (np.array( a2.posi ) - np.array( b2.posi ))[:3]\n\n mod_b2 = np.sqrt( vector_b2.dot(vector_b2) )\n unit_b2 = vector_b2/mod_b2\n\n vector_n1 = np.cross(vector_b1,vector_b2)\n vector_n2 = np.cross(vector_b2,vector_b3)\n \n vector_m1 = np.cross( vector_n1, unit_b2 )\n\n x = vector_n1.dot(vector_n2)\n y = vector_m1.dot(vector_n2)\n \n angle = math.atan2(y,x)\n return angle\n \n\ndef potential_atom_atom( atoma,atomb ):\n d_2 = dist_2(atoma,atomb)\n vdw = calc_vdw(atoma,atomb,d_2) \n chg = calc_chg(atoma,atomb,d_2)\n return vdw*kJ_to_kcal,chg*kJ_to_kcal\n\ndef potential_resi( resia,resib ):\n if resia == resib:\n # sys.stderr.write(\"WARNING, YOU ARE ATTEMPING TO COMPUTE THE POTENTIAL BETWEEN IDENTICAL RESIDUES. THE FUNCTION WILL IGNORE IT AND RETURN ZERO.\\n\")\n return 0,0\n vdw = 0\n chg = 0\n for atoma in resia.atoms:\n for atomb in resib.atoms:\n v,c = potential_atom_atom(atoma,atomb)\n vdw += v\n chg += c \n return vdw, chg\n\ndef resiEFT( resia,resib ):\n if resia == resib:\n # sys.stderr.write(\"WARNING, YOU ARE ATTEMPING TO COMPUTE THE POTENTIAL BETWEEN IDENTICAL RESIDUES. THE FUNCTION WILL IGNORE IT AND RETURN ZERO.\\n\")\n return 0,0,0\n com1 = resib.getCOM() # not finish !!! jc\n E = 0\n F = np.zeros(3)\n T = np.zeros(3)\n for atoma in resia.atoms:\n for atomb in resib.atoms:\n e, f = atomicEF(atoma,atomb)\n E += e\n #f = -f # get negative for grid database. jc\n F += f # force a --> b\n x = (np.array(atomb.posi) - com1) # A\n T += np.cross(x, f)\n return E, F, T\n\ndef next_frame(filename):\n just_yield = True\n frame = list()\n for line in open(filename):\n if just_yield : # or ( len(line)>=6 and line[:6] in (\"MODEL \",\"TITLE \") ):\n frame = list()\n frame.append(line)\n just_yield = False\n elif len(line)>=3 and line[:3] == \"END\":\n frame.append(line)\n yield frame\n just_yield = True\n frame = list()\n else:\n frame.append(line)\n\ndef next_frame_sdf(filename):\n just_yield = True\n frame = list()\n for line in open(filename):\n if just_yield : # or ( len(line)>=6 and line[:6] in (\"MODEL \",\"TITLE \") ):\n frame = list()\n frame.append(line)\n just_yield = False\n elif \"$$$$\" in line:\n frame.append(line)\n yield frame\n just_yield = True\n frame = list()\n else:\n frame.append(line)\n\nif False:\n def dist_atom(a,b):\n return math.sqrt( (a[0]-b[0])**2 + (a[1]-b[1])**2 + (a[2]-b[2])**2 )\n\n def dist_atom_resi(atom, resi):\n assert len(atom)>=3\n assert len(resi)>0\n dist = MAX\n node = None\n for atomb in resi:\n tmp = dist_atom(atom,atomb)\n if tmp < dist:\n dist = tmp\n node = atomb\n assert node != None\n return dist,node\n\n# Test\nif __name__ == '__main__':\n pass\n \n", "meta": {"hexsha": "4600fb813f7f96738c701455b7f771b4171922dd", "size": 42133, "ext": "py", "lang": "Python", "max_stars_repo_path": "build/lib/fpdb/fpdb.py", "max_stars_repo_name": "yangjincai/fpdb", "max_stars_repo_head_hexsha": "e3ac5c13fa1a2d37420fc1496097c937a54a2870", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "build/lib/fpdb/fpdb.py", "max_issues_repo_name": "yangjincai/fpdb", "max_issues_repo_head_hexsha": "e3ac5c13fa1a2d37420fc1496097c937a54a2870", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-07-10T14:03:12.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-10T14:03:12.000Z", "max_forks_repo_path": "build/lib/fpdb/fpdb.py", "max_forks_repo_name": "yangjincai/fpdb", "max_forks_repo_head_hexsha": "e3ac5c13fa1a2d37420fc1496097c937a54a2870", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3102605863, "max_line_length": 158, "alphanum_fraction": 0.5125910806, "include": true, "reason": "import numpy", "num_tokens": 11604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.2538610013242243, "lm_q1q2_score": 0.14173744984832268}} {"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\" # 强制cpu计算\nimport tensorflow as tf\nimport mxnet as mx\nfrom sklearn.metrics import roc_curve, auc\nimport prettytable as pt\nfrom tqdm import tqdm\nimport numpy as np\nimport cv2\nimport pickle\nimport gc \nfrom verification import evaluate \n#\nPB_DIR = \"./mobilenet_arcface_optimized.pb\" \nVALID_DIR = \"./valid_dataset\"\nclass FACENET_PB:\n def __init__(self, model_path):\n graph = tf.Graph()\n with graph.as_default():\n with open(model_path, 'rb') as f:\n graph_def = tf.GraphDef.FromString(f.read())\n tf.import_graph_def(graph_def, name='')\n \n config = tf.ConfigProto(\n allow_soft_placement=True)\n self.sess = tf.Session(graph=graph, config=config)\n\n def get_embedding(self, images):\n feeds = {\n self.sess.graph.get_tensor_by_name(\"input_1:0\") : images, # 人脸抠图 4D float tensor with format [faceimg1,faceimg2 ....] 单张人脸faceimg1 112X112 像素,归一化[-1,1]之间,RGB通道\n }\n fetches = self.sess.graph.get_tensor_by_name(\"embeddings/l2_normalize:0\") # 抽取特征 2D float tensorflow [[1X512],....] 每行为单张人脸特征, 1X512\n\n embedding = self.sess.run(fetches, feed_dict=feeds)\n return embedding\n\n def free(self):\n self.sess.close()\n\n# model = FACENET_PB(PB_DIR)\n# img = cv2.imread('./img_0.jpg')\n# img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n#img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n# img = img - 127.5\n# img = img * 0.0078125\n# img = np.expand_dims(img,axis=0)\n# print(\"img:\",img.shape,img)\n# emb = model.get_embedding(img)\n# print(\"emb:\",emb)\n#\ndef predict_evaluate_data_PB(db_name, image_size , model, embedsize = 512): \n batch = 100\n bins, issame_list = pickle.load(open(os.path.join(db_name), 'rb'), encoding='bytes')\n datasets = np.zeros( (batch , image_size[0], image_size[1], 3))\n embedings = np.zeros((len(issame_list)*2, embedsize))\n count = 0\n \n for i in tqdm(range(len(issame_list)*2),desc=\"evalutaing %s ...\"%db_name) :\n _bin = bins[i]\n img = mx.image.imdecode(_bin).asnumpy()\n del _bin\n # img = cv2.imdecode(np.fromstring(_bin, np.uint8), -1)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n #img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n img = img - 127.5\n img = img * 0.0078125\n datasets[count, ...] = img \n count += 1\n i = i+1\n if i % batch == 0:\n count = 0\n # print('loading bin', i)\n bz_data = datasets[0:batch,...]\n bz_embedings = np.zeros([len(bz_data),512])\n for ii in range(len(bz_data)):\n em = model.get_embedding(np.expand_dims(bz_data[ii],axis = 0))\n bz_embedings[ii] = em\n embedings[i-batch:i,...] = bz_embedings\n else:\n ll = i % batch \n bz_embedings = np.zeros([ll,512])\n if ll !=0:\n ll_in = i // batch\n bz_data = datasets[0:ll,...]\n for ii in range(len(bz_data)): \n em = model.get_embedding(np.expand_dims(bz_data[ii],axis = 0))\n bz_embedings[ii] = em\n embedings[ll_in*batch : ll_in*batch+ll: ,...] = bz_embedings\n del bins \n gc.collect()\n return embedings, issame_list\n\ndef pb_model_test(model_dir): \n model = FACENET_PB(model_dir)\n img_size = 112 \n valid_dir = VALID_DIR \n datadirs = os.listdir(valid_dir)\n embedding_size = 512\n\n result = pt.PrettyTable( [\"data set\", \"AUC\", \"ACC\" ,\"VR @ FAR \", \"dist max\", \"dist min\"])\n val_all = []\n auc_all = []\n acc_all = []\n dist_all = []\n for i in range(len(datadirs)) : \n path = valid_dir + \"/\" + datadirs[i]\n embeddings, issamelab = predict_evaluate_data_PB(path, [img_size,img_size], model, embedding_size)\n \n embeddings1 = embeddings[0::2]\n embeddings2 = embeddings[1::2]\n diff = np.subtract(embeddings1, embeddings2)\n dist = np.sum(np.square(diff), 1)\n del embeddings1,embeddings2\n fpr, tpr,ths = roc_curve(np.asarray(issamelab).astype('int'),dist, pos_label=0 )\n auc_score = auc(fpr, tpr)\n if 0:\n plt.figure()\n lw = 2\n plt.plot(fpr, tpr, color='darkorange',\n lw=lw, label='ROC curve (area = %0.2f)' % auc_score)\n plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('Receiver operating characteristic example')\n plt.legend(loc=\"lower right\")\n # plt.show()\n plt.savefig(\"roc.png\")\n\n # print('-----10 folds------')\n tpr, fpr, accuracy, val, val_std, far = evaluate(embeddings, issamelab)\n del embeddings,issamelab\n gc.collect()\n result.add_row([datadirs[i] ,\n round(auc_score,2),\n \"%1.3f+-%1.3f\" % (np.mean(accuracy), np.std(accuracy)),\n \"%2.5f+-%2.5f @ FAR=%2.5f\" % (val, val_std, far),\n round(np.max(dist),2),\n round(np.min(dist),2),\n ])\n val_all.append(val)\n acc_all.append(accuracy)\n auc_all.append(auc_score)\n dist_all.append([np.max(dist),np.min(dist)])\n \n print(result)\n\n\n\npb_model_test(PB_DIR)\n\n", "meta": {"hexsha": "72c4a6b11c148078e48f18466f648afbe773d21b", "size": 5536, "ext": "py", "lang": "Python", "max_stars_repo_path": "pb_test.py", "max_stars_repo_name": "zhang-zsf/mobilenetV2-arcfaceloss-keras-tflite", "max_stars_repo_head_hexsha": "437725dbe62a9a5f5f8223e7aa910eaad0038b90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-02-24T00:08:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T07:55:30.000Z", "max_issues_repo_path": "pb_test.py", "max_issues_repo_name": "zhang-zsf/mobilenetV2-arcfaceloss-keras-tflite", "max_issues_repo_head_hexsha": "437725dbe62a9a5f5f8223e7aa910eaad0038b90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-09-25T22:33:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T23:41:35.000Z", "max_forks_repo_path": "pb_test.py", "max_forks_repo_name": "zhang-zsf/mobilenetV2-arcfaceloss-keras-tflite", "max_forks_repo_head_hexsha": "437725dbe62a9a5f5f8223e7aa910eaad0038b90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-04-27T02:22:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T06:56:30.000Z", "avg_line_length": 35.7161290323, "max_line_length": 175, "alphanum_fraction": 0.5690028902, "include": true, "reason": "import numpy", "num_tokens": 1556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.25683200276421697, "lm_q1q2_score": 0.14141359242714507}} {"text": "\"\"\"\nRPN:\ndata =\n {'data': [num_images, c, h, w],\n 'im_info': [num_images, 4] (optional)}\nlabel =\n {'gt_boxes': [num_boxes, 5] (optional),\n 'label': [batch_size, 1] <- [batch_size, num_anchors, feat_height, feat_width],\n 'bbox_target': [batch_size, num_anchors, feat_height, feat_width],\n 'bbox_weight': [batch_size, num_anchors, feat_height, feat_width]}\n\"\"\"\n\nfrom __future__ import print_function\nimport sys\nimport logging\nimport datetime\nimport numpy as np\nimport numpy.random as npr\n\nfrom ..logger import logger\nfrom ..config import config\nfrom .image import get_image, tensor_vstack, get_crop_image\nfrom ..processing.generate_anchor import generate_anchors, anchors_plane\nfrom ..processing.bbox_transform import bbox_overlaps, bbox_transform, landmark_transform\n\nSTAT = {0:0, 8:0, 16:0, 32:0}\n\ndef get_rpn_testbatch(roidb):\n \"\"\"\n return a dict of testbatch\n :param roidb: ['image', 'flipped']\n :return: data, label, im_info\n \"\"\"\n assert len(roidb) == 1, 'Single batch only'\n imgs, roidb = get_image(roidb)\n im_array = imgs[0]\n im_info = np.array([roidb[0]['im_info']], dtype=np.float32)\n\n data = {'data': im_array,\n 'im_info': im_info}\n label = {}\n\n return data, label, im_info\n\ndef get_rpn_batch(roidb):\n \"\"\"\n prototype for rpn batch: data, im_info, gt_boxes\n :param roidb: ['image', 'flipped'] + ['gt_boxes', 'boxes', 'gt_classes']\n :return: data, label\n \"\"\"\n assert len(roidb) == 1, 'Single batch only'\n imgs, roidb = get_image(roidb)\n im_array = imgs[0]\n im_info = np.array([roidb[0]['im_info']], dtype=np.float32)\n\n # gt boxes: (x1, y1, x2, y2, cls)\n if roidb[0]['gt_classes'].size > 0:\n gt_inds = np.where(roidb[0]['gt_classes'] != 0)[0]\n gt_boxes = np.empty((roidb[0]['boxes'].shape[0], 5), dtype=np.float32)\n gt_boxes[:, 0:4] = roidb[0]['boxes'][gt_inds, :]\n gt_boxes[:, 4] = roidb[0]['gt_classes'][gt_inds]\n else:\n gt_boxes = np.empty((0, 5), dtype=np.float32)\n\n data = {'data': im_array,\n 'im_info': im_info}\n label = {'gt_boxes': gt_boxes}\n\n return data, label\n\ndef get_crop_batch(roidb):\n \"\"\"\n prototype for rpn batch: data, im_info, gt_boxes\n :param roidb: ['image', 'flipped'] + ['gt_boxes', 'boxes', 'gt_classes']\n :return: data, label\n \"\"\"\n #assert len(roidb) == 1, 'Single batch only'\n data_list = []\n label_list = []\n imgs, roidb = get_crop_image(roidb)\n assert len(imgs)==len(roidb)\n for i in range(len(imgs)):\n im_array = imgs[i]\n im_info = np.array([roidb[i]['im_info']], dtype=np.float32)\n\n # gt boxes: (x1, y1, x2, y2, cls)\n if roidb[i]['gt_classes'].size > 0:\n gt_inds = np.where(roidb[i]['gt_classes'] != 0)[0]\n gt_boxes = np.empty((roidb[i]['boxes'].shape[0], 5), dtype=np.float32)\n gt_boxes[:, 0:4] = roidb[i]['boxes'][gt_inds, :]\n gt_boxes[:, 4] = roidb[i]['gt_classes'][gt_inds]\n if config.USE_BLUR:\n gt_blur = roidb[i]['blur']\n if config.FACE_LANDMARK:\n #gt_landmarks = np.empty((roidb[i]['landmarks'].shape[0], 11), dtype=np.float32)\n gt_landmarks = roidb[i]['landmarks'][gt_inds,:,:]\n if config.HEAD_BOX:\n gt_boxes_head = np.empty((roidb[i]['boxes_head'].shape[0], 5), dtype=np.float32)\n gt_boxes_head[:, 0:4] = roidb[i]['boxes_head'][gt_inds, :]\n gt_boxes_head[:, 4] = roidb[i]['gt_classes'][gt_inds]\n else:\n gt_boxes = np.empty((0, 5), dtype=np.float32)\n if config.USE_BLUR:\n gt_blur = np.empty((0,), dtype=np.float32)\n if config.FACE_LANDMARK:\n gt_landmarks = np.empty((0, 5, 3), dtype=np.float32)\n if config.HEAD_BOX:\n gt_boxes_head = np.empty((0, 5), dtype=np.float32)\n\n data = {'data': im_array,\n 'im_info': im_info}\n label = {'gt_boxes': gt_boxes}\n if config.USE_BLUR:\n label['gt_blur'] = gt_blur\n if config.FACE_LANDMARK:\n label['gt_landmarks'] = gt_landmarks\n if config.HEAD_BOX:\n label['gt_boxes_head'] = gt_boxes_head\n data_list.append(data)\n label_list.append(label)\n\n return data_list, label_list\n\ndef assign_anchor_fpn(feat_shape, gt_label, im_info, landmark=False, prefix='face', select_stride=0):\n \"\"\"\n assign ground truth boxes to anchor positions\n :param feat_shape: infer output shape\n :param gt_boxes: assign ground truth\n :param im_info: filter out anchors overlapped with edges\n :return: tuple\n labels: of shape (batch_size, 1) <- (batch_size, num_anchors, feat_height, feat_width)\n bbox_targets: of shape (batch_size, num_anchors * 4, feat_height, feat_width)\n bbox_weights: mark the assigned anchors\n \"\"\"\n def _unmap(data, count, inds, fill=0):\n \"\"\"\" unmap a subset inds of data into original data of size count \"\"\"\n if len(data.shape) == 1:\n ret = np.empty((count,), dtype=np.float32)\n ret.fill(fill)\n ret[inds] = data\n else:\n ret = np.empty((count,) + data.shape[1:], dtype=np.float32)\n ret.fill(fill)\n ret[inds, :] = data\n return ret\n\n global STAT\n DEBUG = False\n\n im_info = im_info[0]\n gt_boxes = gt_label['gt_boxes']\n # clean up boxes\n nonneg = np.where(gt_boxes[:, 4] != -1)[0]\n gt_boxes = gt_boxes[nonneg]\n if config.USE_BLUR:\n gt_blur = gt_label['gt_blur']\n gt_blur = gt_blur[nonneg]\n if landmark:\n gt_landmarks = gt_label['gt_landmarks']\n gt_landmarks = gt_landmarks[nonneg]\n assert gt_boxes.shape[0]==gt_landmarks.shape[0]\n #scales = np.array(scales, dtype=np.float32)\n feat_strides = config.RPN_FEAT_STRIDE\n bbox_pred_len = 4\n landmark_pred_len = 10\n if config.USE_BLUR:\n gt_boxes[:,4] = gt_blur\n bbox_pred_len = 5\n if config.USE_OCCLUSION:\n landmark_pred_len = 15\n\n anchors_list = []\n anchors_num_list = []\n inds_inside_list = []\n feat_infos = []\n A_list = []\n for i in range(len(feat_strides)):\n stride = feat_strides[i]\n sstride = str(stride)\n base_size = config.RPN_ANCHOR_CFG[sstride]['BASE_SIZE']\n allowed_border = config.RPN_ANCHOR_CFG[sstride]['ALLOWED_BORDER']\n ratios = config.RPN_ANCHOR_CFG[sstride]['RATIOS']\n scales = config.RPN_ANCHOR_CFG[sstride]['SCALES']\n base_anchors = generate_anchors(base_size=base_size, ratios=list(ratios), scales=np.array(scales, dtype=np.float32), stride = stride, dense_anchor = config.DENSE_ANCHOR)\n num_anchors = base_anchors.shape[0]\n feat_height, feat_width = feat_shape[i][-2:]\n feat_stride = feat_strides[i]\n feat_infos.append([feat_height, feat_width])\n\n A = num_anchors\n A_list.append(A)\n K = feat_height * feat_width\n\n all_anchors = anchors_plane(feat_height, feat_width, feat_stride, base_anchors)\n all_anchors = all_anchors.reshape((K * A, 4))\n #print('anchor0', stride, all_anchors[0])\n\n total_anchors = int(K * A)\n anchors_num_list.append(total_anchors)\n # only keep anchors inside the image\n inds_inside = np.where((all_anchors[:, 0] >= -allowed_border) &\n (all_anchors[:, 1] >= -allowed_border) &\n (all_anchors[:, 2] < im_info[1] + allowed_border) &\n (all_anchors[:, 3] < im_info[0] + allowed_border))[0]\n if DEBUG:\n print('total_anchors', total_anchors)\n print('inds_inside', len(inds_inside))\n\n # keep only inside anchors\n anchors = all_anchors[inds_inside, :]\n #print('AA', anchors.shape, len(inds_inside))\n\n anchors_list.append(anchors)\n inds_inside_list.append(inds_inside)\n\n # Concat anchors from each level\n anchors = np.concatenate(anchors_list)\n for i in range(1, len(inds_inside_list)):\n inds_inside_list[i] = inds_inside_list[i] + sum(anchors_num_list[:i])\n inds_inside = np.concatenate(inds_inside_list)\n total_anchors = sum(anchors_num_list)\n #print('total_anchors', anchors.shape[0], len(inds_inside), file=sys.stderr)\n\n # label: 1 is positive, 0 is negative, -1 is dont care\n labels = np.empty((len(inds_inside),), dtype=np.float32)\n labels.fill(-1)\n #print('BB', anchors.shape, len(inds_inside))\n #print('gt_boxes', gt_boxes.shape, file=sys.stderr)\n\n if gt_boxes.size > 0:\n # overlap between the anchors and the gt boxes\n # overlaps (ex, gt)\n overlaps = bbox_overlaps(anchors.astype(np.float), gt_boxes.astype(np.float))\n argmax_overlaps = overlaps.argmax(axis=1)\n #print('AAA', argmax_overlaps.shape)\n max_overlaps = overlaps[np.arange(len(inds_inside)), argmax_overlaps]\n gt_argmax_overlaps = overlaps.argmax(axis=0)\n gt_max_overlaps = overlaps[gt_argmax_overlaps, np.arange(overlaps.shape[1])]\n gt_argmax_overlaps = np.where(overlaps == gt_max_overlaps)[0]\n\n if not config.TRAIN.RPN_CLOBBER_POSITIVES:\n # assign bg labels first so that positive labels can clobber them\n labels[max_overlaps < config.TRAIN.RPN_NEGATIVE_OVERLAP] = 0\n\n # fg label: for each gt, anchor with highest overlap\n if config.TRAIN.RPN_FORCE_POSITIVE:\n labels[gt_argmax_overlaps] = 1\n\n # fg label: above threshold IoU\n labels[max_overlaps >= config.TRAIN.RPN_POSITIVE_OVERLAP] = 1\n\n if config.TRAIN.RPN_CLOBBER_POSITIVES:\n # assign bg labels last so that negative labels can clobber positives\n labels[max_overlaps < config.TRAIN.RPN_NEGATIVE_OVERLAP] = 0\n else:\n labels[:] = 0\n fg_inds = np.where(labels == 1)[0]\n #print('fg count', len(fg_inds))\n\n # subsample positive labels if we have too many\n if config.TRAIN.RPN_ENABLE_OHEM==0:\n fg_inds = np.where(labels == 1)[0]\n num_fg = int(config.TRAIN.RPN_FG_FRACTION * config.TRAIN.RPN_BATCH_SIZE)\n if len(fg_inds) > num_fg:\n disable_inds = npr.choice(fg_inds, size=(len(fg_inds) - num_fg), replace=False)\n if DEBUG:\n disable_inds = fg_inds[:(len(fg_inds) - num_fg)]\n labels[disable_inds] = -1\n\n # subsample negative labels if we have too many\n num_bg = config.TRAIN.RPN_BATCH_SIZE - np.sum(labels == 1)\n bg_inds = np.where(labels == 0)[0]\n if len(bg_inds) > num_bg:\n disable_inds = npr.choice(bg_inds, size=(len(bg_inds) - num_bg), replace=False)\n if DEBUG:\n disable_inds = bg_inds[:(len(bg_inds) - num_bg)]\n labels[disable_inds] = -1\n\n #fg_inds = np.where(labels == 1)[0]\n #num_fg = len(fg_inds)\n #num_bg = num_fg*int(1.0/config.TRAIN.RPN_FG_FRACTION-1)\n\n #bg_inds = np.where(labels == 0)[0]\n #if len(bg_inds) > num_bg:\n # disable_inds = npr.choice(bg_inds, size=(len(bg_inds) - num_bg), replace=False)\n # if DEBUG:\n # disable_inds = bg_inds[:(len(bg_inds) - num_bg)]\n # labels[disable_inds] = -1\n else:\n fg_inds = np.where(labels == 1)[0]\n num_fg = len(fg_inds)\n bg_inds = np.where(labels == 0)[0]\n num_bg = len(bg_inds)\n\n #print('anchor stat', num_fg, num_bg)\n\n\n bbox_targets = np.zeros((len(inds_inside), bbox_pred_len), dtype=np.float32)\n if gt_boxes.size > 0:\n #print('GT', gt_boxes.shape, gt_boxes[argmax_overlaps, :4].shape)\n bbox_targets[:,:] = bbox_transform(anchors, gt_boxes[argmax_overlaps, :])\n #bbox_targets[:,4] = gt_blur\n\n bbox_weights = np.zeros((len(inds_inside), bbox_pred_len), dtype=np.float32)\n #bbox_weights[labels == 1, :] = np.array(config.TRAIN.RPN_BBOX_WEIGHTS)\n bbox_weights[labels == 1, 0:4] = 1.0\n if bbox_pred_len>4:\n bbox_weights[labels == 1, 4:bbox_pred_len] = 0.1\n\n if landmark:\n landmark_targets = np.zeros((len(inds_inside), landmark_pred_len), dtype=np.float32)\n #landmark_weights = np.zeros((len(inds_inside), 10), dtype=np.float32)\n landmark_weights = np.zeros((len(inds_inside), landmark_pred_len), dtype=np.float32)\n #landmark_weights[labels == 1, :] = np.array(config.TRAIN.RPN_LANDMARK_WEIGHTS)\n if landmark_pred_len==10:\n landmark_weights[labels == 1, :] = 1.0\n elif landmark_pred_len==15:\n v = [1.0, 1.0, 0.1] * 5\n assert len(v)==15\n landmark_weights[labels == 1, :] = np.array(v)\n else:\n assert False\n #TODO here\n if gt_landmarks.size > 0:\n #print('AAA',argmax_overlaps)\n a_landmarks = gt_landmarks[argmax_overlaps,:,:]\n landmark_targets[:] = landmark_transform(anchors, a_landmarks)\n invalid = np.where(a_landmarks[:,0,2]<0.0)[0]\n #assert len(invalid)==0\n #landmark_weights[invalid, :] = np.array(config.TRAIN.RPN_INVALID_LANDMARK_WEIGHTS)\n landmark_weights[invalid, :] = 0.0\n\n #if DEBUG:\n # _sums = bbox_targets[labels == 1, :].sum(axis=0)\n # _squared_sums = (bbox_targets[labels == 1, :] ** 2).sum(axis=0)\n # _counts = np.sum(labels == 1)\n # means = _sums / (_counts + 1e-14)\n # stds = np.sqrt(_squared_sums / _counts - means ** 2)\n # print 'means', means\n # print 'stdevs', stds\n # map up to original set of anchors\n #print(labels.shape, total_anchors, inds_inside.shape, inds_inside[0], inds_inside[-1])\n labels = _unmap(labels, total_anchors, inds_inside, fill=-1)\n bbox_targets = _unmap(bbox_targets, total_anchors, inds_inside, fill=0)\n bbox_weights = _unmap(bbox_weights, total_anchors, inds_inside, fill=0)\n if landmark:\n landmark_targets = _unmap(landmark_targets, total_anchors, inds_inside, fill=0)\n landmark_weights = _unmap(landmark_weights, total_anchors, inds_inside, fill=0)\n #print('CC', anchors.shape, len(inds_inside))\n\n #if DEBUG:\n # if gt_boxes.size > 0:\n # print 'rpn: max max_overlaps', np.max(max_overlaps)\n # print 'rpn: num_positives', np.sum(labels == 1)\n # print 'rpn: num_negatives', np.sum(labels == 0)\n # _fg_sum = np.sum(labels == 1)\n # _bg_sum = np.sum(labels == 0)\n # _count = 1\n # print 'rpn: num_positive avg', _fg_sum / _count\n # print 'rpn: num_negative avg', _bg_sum / _count\n\n # resahpe\n label_list = list()\n bbox_target_list = list()\n bbox_weight_list = list()\n if landmark:\n landmark_target_list = list()\n landmark_weight_list = list()\n anchors_num_range = [0] + anchors_num_list\n label = {}\n for i in range(len(feat_strides)):\n stride = feat_strides[i]\n feat_height, feat_width = feat_infos[i]\n A = A_list[i]\n _label = labels[sum(anchors_num_range[:i+1]):sum(anchors_num_range[:i+1])+anchors_num_range[i+1]]\n if select_stride>0 and stride!=select_stride:\n #print('set', stride, select_stride)\n _label[:] = -1\n #print('_label', _label.shape, select_stride)\n #_fg_inds = np.where(_label == 1)[0]\n #n_fg = len(_fg_inds)\n #STAT[0]+=1\n #STAT[stride]+=n_fg\n #if STAT[0]%100==0:\n # print('rpn_stat', STAT, file=sys.stderr)\n bbox_target = bbox_targets[sum(anchors_num_range[:i+1]):sum(anchors_num_range[:i+1])+anchors_num_range[i+1]]\n bbox_weight = bbox_weights[sum(anchors_num_range[:i+1]):sum(anchors_num_range[:i+1])+anchors_num_range[i+1]]\n if landmark:\n landmark_target = landmark_targets[sum(anchors_num_range[:i+1]):sum(anchors_num_range[:i+1])+anchors_num_range[i+1]]\n landmark_weight = landmark_weights[sum(anchors_num_range[:i+1]):sum(anchors_num_range[:i+1])+anchors_num_range[i+1]]\n\n _label = _label.reshape((1, feat_height, feat_width, A)).transpose(0, 3, 1, 2)\n _label = _label.reshape((1, A * feat_height * feat_width))\n bbox_target = bbox_target.reshape((1, feat_height*feat_width, A * bbox_pred_len)).transpose(0, 2, 1)\n bbox_weight = bbox_weight.reshape((1, feat_height*feat_width, A * bbox_pred_len)).transpose((0, 2, 1))\n label['%s_label_stride%d'%(prefix, stride)] = _label\n label['%s_bbox_target_stride%d'%(prefix,stride)] = bbox_target\n label['%s_bbox_weight_stride%d'%(prefix,stride)] = bbox_weight\n if landmark:\n landmark_target = landmark_target.reshape((1, feat_height*feat_width, A * landmark_pred_len)).transpose(0, 2, 1)\n landmark_weight = landmark_weight.reshape((1, feat_height*feat_width, A * landmark_pred_len)).transpose((0, 2, 1))\n label['%s_landmark_target_stride%d'%(prefix,stride)] = landmark_target\n label['%s_landmark_weight_stride%d'%(prefix,stride)] = landmark_weight\n #print('in_rpn', stride,_label.shape, bbox_target.shape, bbox_weight.shape, file=sys.stderr)\n label_list.append(_label)\n #print('DD', _label.shape)\n bbox_target_list.append(bbox_target)\n bbox_weight_list.append(bbox_weight)\n if landmark:\n landmark_target_list.append(landmark_target)\n landmark_weight_list.append(landmark_weight)\n\n label_concat = np.concatenate(label_list, axis=1)\n bbox_target_concat = np.concatenate(bbox_target_list, axis=2)\n bbox_weight_concat = np.concatenate(bbox_weight_list, axis=2)\n #fg_inds = np.where(label_concat[0] == 1)[0]\n #print('fg_inds_in_rpn2', fg_inds, file=sys.stderr)\n\n label.update({'%s_label'%prefix: label_concat,\n '%s_bbox_target'%prefix: bbox_target_concat,\n '%s_bbox_weight'%prefix: bbox_weight_concat}\n )\n if landmark:\n landmark_target_concat = np.concatenate(landmark_target_list, axis=2)\n landmark_weight_concat = np.concatenate(landmark_weight_list, axis=2)\n label['%s_landmark_target'%prefix] = landmark_target_concat\n label['%s_landmark_weight'%prefix] = landmark_weight_concat\n return label\n\n\nclass AA:\n def __init__(self, feat_shape):\n self.feat_shape = feat_shape\n feat_strides = config.RPN_FEAT_STRIDE\n anchors_list = []\n anchors_num_list = []\n inds_inside_list = []\n feat_infos = []\n A_list = []\n DEBUG = False\n for i in range(len(feat_strides)):\n stride = feat_strides[i]\n sstride = str(stride)\n base_size = config.RPN_ANCHOR_CFG[sstride]['BASE_SIZE']\n allowed_border = config.RPN_ANCHOR_CFG[sstride]['ALLOWED_BORDER']\n ratios = config.RPN_ANCHOR_CFG[sstride]['RATIOS']\n scales = config.RPN_ANCHOR_CFG[sstride]['SCALES']\n base_anchors = generate_anchors(base_size=base_size, ratios=list(ratios), scales=np.array(scales, dtype=np.float32), stride = stride, dense_anchor = config.DENSE_ANCHOR)\n num_anchors = base_anchors.shape[0]\n feat_height, feat_width = feat_shape[i][-2:]\n feat_stride = feat_strides[i]\n feat_infos.append([feat_height, feat_width])\n\n A = num_anchors\n A_list.append(A)\n K = feat_height * feat_width\n\n all_anchors = anchors_plane(feat_height, feat_width, feat_stride, base_anchors)\n all_anchors = all_anchors.reshape((K * A, 4))\n #print('anchor0', stride, all_anchors[0])\n\n total_anchors = int(K * A)\n anchors_num_list.append(total_anchors)\n # only keep anchors inside the image\n inds_inside = np.where((all_anchors[:, 0] >= -allowed_border) &\n (all_anchors[:, 1] >= -allowed_border) &\n (all_anchors[:, 2] < config.SCALES[0][1] + allowed_border) &\n (all_anchors[:, 3] < config.SCALES[0][1] + allowed_border))[0]\n if DEBUG:\n print('total_anchors', total_anchors)\n print('inds_inside', len(inds_inside))\n\n # keep only inside anchors\n anchors = all_anchors[inds_inside, :]\n #print('AA', anchors.shape, len(inds_inside))\n\n anchors_list.append(anchors)\n inds_inside_list.append(inds_inside)\n anchors = np.concatenate(anchors_list)\n for i in range(1, len(inds_inside_list)):\n inds_inside_list[i] = inds_inside_list[i] + sum(anchors_num_list[:i])\n inds_inside = np.concatenate(inds_inside_list)\n #self.anchors_list = anchors_list\n #self.inds_inside_list = inds_inside_list\n self.anchors = anchors\n self.inds_inside = inds_inside\n self.anchors_num_list = anchors_num_list\n self.feat_infos = feat_infos\n self.A_list = A_list\n self._times = [0.0, 0.0, 0.0, 0.0]\n\n @staticmethod\n def _unmap(data, count, inds, fill=0):\n \"\"\"\" unmap a subset inds of data into original data of size count \"\"\"\n if len(data.shape) == 1:\n ret = np.empty((count,), dtype=np.float32)\n ret.fill(fill)\n ret[inds] = data\n else:\n ret = np.empty((count,) + data.shape[1:], dtype=np.float32)\n ret.fill(fill)\n ret[inds, :] = data\n return ret\n\n def assign_anchor_fpn(self, gt_label, im_info, landmark=False, prefix='face', select_stride=0):\n\n #ta = datetime.datetime.now()\n im_info = im_info[0]\n gt_boxes = gt_label['gt_boxes']\n # clean up boxes\n nonneg = np.where(gt_boxes[:, 4] != -1)[0]\n gt_boxes = gt_boxes[nonneg]\n if config.USE_BLUR:\n gt_blur = gt_label['gt_blur']\n gt_blur = gt_blur[nonneg]\n if landmark:\n gt_landmarks = gt_label['gt_landmarks']\n gt_landmarks = gt_landmarks[nonneg]\n assert gt_boxes.shape[0]==gt_landmarks.shape[0]\n #scales = np.array(scales, dtype=np.float32)\n feat_strides = config.RPN_FEAT_STRIDE\n bbox_pred_len = 4\n landmark_pred_len = 10\n if config.USE_BLUR:\n gt_boxes[:,4] = gt_blur\n bbox_pred_len = 5\n if config.USE_OCCLUSION:\n landmark_pred_len = 15\n\n #anchors_list = self.anchors_list\n #inds_inside_list = self.inds_inside_list\n anchors = self.anchors\n inds_inside = self.inds_inside\n anchors_num_list = self.anchors_num_list\n feat_infos = self.feat_infos\n A_list = self.A_list\n\n total_anchors = sum(anchors_num_list)\n #print('total_anchors', anchors.shape[0], len(inds_inside), file=sys.stderr)\n\n # label: 1 is positive, 0 is negative, -1 is dont care\n labels = np.empty((len(inds_inside),), dtype=np.float32)\n labels.fill(-1)\n #print('BB', anchors.shape, len(inds_inside))\n #print('gt_boxes', gt_boxes.shape, file=sys.stderr)\n #tb = datetime.datetime.now()\n #self._times[0] += (tb-ta).total_seconds()\n #ta = datetime.datetime.now()\n\n if gt_boxes.size > 0:\n # overlap between the anchors and the gt boxes\n # overlaps (ex, gt)\n overlaps = bbox_overlaps(anchors.astype(np.float), gt_boxes.astype(np.float))\n argmax_overlaps = overlaps.argmax(axis=1)\n #print('AAA', argmax_overlaps.shape)\n max_overlaps = overlaps[np.arange(len(inds_inside)), argmax_overlaps]\n gt_argmax_overlaps = overlaps.argmax(axis=0)\n gt_max_overlaps = overlaps[gt_argmax_overlaps, np.arange(overlaps.shape[1])]\n gt_argmax_overlaps = np.where(overlaps == gt_max_overlaps)[0]\n\n if not config.TRAIN.RPN_CLOBBER_POSITIVES:\n # assign bg labels first so that positive labels can clobber them\n labels[max_overlaps < config.TRAIN.RPN_NEGATIVE_OVERLAP] = 0\n\n # fg label: for each gt, anchor with highest overlap\n if config.TRAIN.RPN_FORCE_POSITIVE:\n labels[gt_argmax_overlaps] = 1\n\n # fg label: above threshold IoU\n labels[max_overlaps >= config.TRAIN.RPN_POSITIVE_OVERLAP] = 1\n\n if config.TRAIN.RPN_CLOBBER_POSITIVES:\n # assign bg labels last so that negative labels can clobber positives\n labels[max_overlaps < config.TRAIN.RPN_NEGATIVE_OVERLAP] = 0\n else:\n labels[:] = 0\n fg_inds = np.where(labels == 1)[0]\n #print('fg count', len(fg_inds))\n\n # subsample positive labels if we have too many\n if config.TRAIN.RPN_ENABLE_OHEM==0:\n fg_inds = np.where(labels == 1)[0]\n num_fg = int(config.TRAIN.RPN_FG_FRACTION * config.TRAIN.RPN_BATCH_SIZE)\n if len(fg_inds) > num_fg:\n disable_inds = npr.choice(fg_inds, size=(len(fg_inds) - num_fg), replace=False)\n if DEBUG:\n disable_inds = fg_inds[:(len(fg_inds) - num_fg)]\n labels[disable_inds] = -1\n\n # subsample negative labels if we have too many\n num_bg = config.TRAIN.RPN_BATCH_SIZE - np.sum(labels == 1)\n bg_inds = np.where(labels == 0)[0]\n if len(bg_inds) > num_bg:\n disable_inds = npr.choice(bg_inds, size=(len(bg_inds) - num_bg), replace=False)\n if DEBUG:\n disable_inds = bg_inds[:(len(bg_inds) - num_bg)]\n labels[disable_inds] = -1\n\n #fg_inds = np.where(labels == 1)[0]\n #num_fg = len(fg_inds)\n #num_bg = num_fg*int(1.0/config.TRAIN.RPN_FG_FRACTION-1)\n\n #bg_inds = np.where(labels == 0)[0]\n #if len(bg_inds) > num_bg:\n # disable_inds = npr.choice(bg_inds, size=(len(bg_inds) - num_bg), replace=False)\n # if DEBUG:\n # disable_inds = bg_inds[:(len(bg_inds) - num_bg)]\n # labels[disable_inds] = -1\n else:\n fg_inds = np.where(labels == 1)[0]\n num_fg = len(fg_inds)\n bg_inds = np.where(labels == 0)[0]\n num_bg = len(bg_inds)\n\n #print('anchor stat', num_fg, num_bg)\n\n\n bbox_targets = np.zeros((len(inds_inside), bbox_pred_len), dtype=np.float32)\n if gt_boxes.size > 0:\n #print('GT', gt_boxes.shape, gt_boxes[argmax_overlaps, :4].shape)\n bbox_targets[:,:] = bbox_transform(anchors, gt_boxes[argmax_overlaps, :])\n #bbox_targets[:,4] = gt_blur\n #tb = datetime.datetime.now()\n #self._times[1] += (tb-ta).total_seconds()\n #ta = datetime.datetime.now()\n\n bbox_weights = np.zeros((len(inds_inside), bbox_pred_len), dtype=np.float32)\n #bbox_weights[labels == 1, :] = np.array(config.TRAIN.RPN_BBOX_WEIGHTS)\n bbox_weights[labels == 1, 0:4] = 1.0\n if bbox_pred_len>4:\n bbox_weights[labels == 1, 4:bbox_pred_len] = 0.1\n\n if landmark:\n landmark_targets = np.zeros((len(inds_inside), landmark_pred_len), dtype=np.float32)\n #landmark_weights = np.zeros((len(inds_inside), 10), dtype=np.float32)\n landmark_weights = np.zeros((len(inds_inside), landmark_pred_len), dtype=np.float32)\n #landmark_weights[labels == 1, :] = np.array(config.TRAIN.RPN_LANDMARK_WEIGHTS)\n if landmark_pred_len==10:\n landmark_weights[labels == 1, :] = 1.0\n elif landmark_pred_len==15:\n v = [1.0, 1.0, 0.1] * 5\n assert len(v)==15\n landmark_weights[labels == 1, :] = np.array(v)\n else:\n assert False\n #TODO here\n if gt_landmarks.size > 0:\n #print('AAA',argmax_overlaps)\n a_landmarks = gt_landmarks[argmax_overlaps,:,:]\n landmark_targets[:] = landmark_transform(anchors, a_landmarks)\n # landmark 不存在就是0,存在为1\n invalid = np.where(a_landmarks[:,0,2]<=0.0)[0]\n #assert len(invalid)==0\n #landmark_weights[invalid, :] = np.array(config.TRAIN.RPN_INVALID_LANDMARK_WEIGHTS)\n landmark_weights[invalid, :] = 0.0\n #tb = datetime.datetime.now()\n #self._times[2] += (tb-ta).total_seconds()\n #ta = datetime.datetime.now()\n\n #if DEBUG:\n # _sums = bbox_targets[labels == 1, :].sum(axis=0)\n # _squared_sums = (bbox_targets[labels == 1, :] ** 2).sum(axis=0)\n # _counts = np.sum(labels == 1)\n # means = _sums / (_counts + 1e-14)\n # stds = np.sqrt(_squared_sums / _counts - means ** 2)\n # print 'means', means\n # print 'stdevs', stds\n # map up to original set of anchors\n #print(labels.shape, total_anchors, inds_inside.shape, inds_inside[0], inds_inside[-1])\n labels = AA._unmap(labels, total_anchors, inds_inside, fill=-1)\n bbox_targets = AA._unmap(bbox_targets, total_anchors, inds_inside, fill=0)\n bbox_weights = AA._unmap(bbox_weights, total_anchors, inds_inside, fill=0)\n if landmark:\n landmark_targets = AA._unmap(landmark_targets, total_anchors, inds_inside, fill=0)\n landmark_weights = AA._unmap(landmark_weights, total_anchors, inds_inside, fill=0)\n #print('CC', anchors.shape, len(inds_inside))\n\n #if DEBUG:\n # if gt_boxes.size > 0:\n # print 'rpn: max max_overlaps', np.max(max_overlaps)\n # print 'rpn: num_positives', np.sum(labels == 1)\n # print 'rpn: num_negatives', np.sum(labels == 0)\n # _fg_sum = np.sum(labels == 1)\n # _bg_sum = np.sum(labels == 0)\n # _count = 1\n # print 'rpn: num_positive avg', _fg_sum / _count\n # print 'rpn: num_negative avg', _bg_sum / _count\n\n # resahpe\n label_list = list()\n bbox_target_list = list()\n bbox_weight_list = list()\n if landmark:\n landmark_target_list = list()\n landmark_weight_list = list()\n anchors_num_range = [0] + anchors_num_list\n label = {}\n for i in range(len(feat_strides)):\n stride = feat_strides[i]\n feat_height, feat_width = feat_infos[i]\n A = A_list[i]\n _label = labels[sum(anchors_num_range[:i+1]):sum(anchors_num_range[:i+1])+anchors_num_range[i+1]]\n if select_stride>0 and stride!=select_stride:\n #print('set', stride, select_stride)\n _label[:] = -1\n #print('_label', _label.shape, select_stride)\n #_fg_inds = np.where(_label == 1)[0]\n #n_fg = len(_fg_inds)\n #STAT[0]+=1\n #STAT[stride]+=n_fg\n #if STAT[0]%100==0:\n # print('rpn_stat', STAT, file=sys.stderr)\n bbox_target = bbox_targets[sum(anchors_num_range[:i+1]):sum(anchors_num_range[:i+1])+anchors_num_range[i+1]]\n bbox_weight = bbox_weights[sum(anchors_num_range[:i+1]):sum(anchors_num_range[:i+1])+anchors_num_range[i+1]]\n if landmark:\n landmark_target = landmark_targets[sum(anchors_num_range[:i+1]):sum(anchors_num_range[:i+1])+anchors_num_range[i+1]]\n landmark_weight = landmark_weights[sum(anchors_num_range[:i+1]):sum(anchors_num_range[:i+1])+anchors_num_range[i+1]]\n\n _label = _label.reshape((1, feat_height, feat_width, A)).transpose(0, 3, 1, 2)\n _label = _label.reshape((1, A * feat_height * feat_width))\n bbox_target = bbox_target.reshape((1, feat_height*feat_width, A * bbox_pred_len)).transpose(0, 2, 1)\n bbox_weight = bbox_weight.reshape((1, feat_height*feat_width, A * bbox_pred_len)).transpose((0, 2, 1))\n label['%s_label_stride%d'%(prefix, stride)] = _label\n label['%s_bbox_target_stride%d'%(prefix,stride)] = bbox_target\n label['%s_bbox_weight_stride%d'%(prefix,stride)] = bbox_weight\n if landmark:\n landmark_target = landmark_target.reshape((1, feat_height*feat_width, A * landmark_pred_len)).transpose(0, 2, 1)\n landmark_weight = landmark_weight.reshape((1, feat_height*feat_width, A * landmark_pred_len)).transpose((0, 2, 1))\n label['%s_landmark_target_stride%d'%(prefix,stride)] = landmark_target\n label['%s_landmark_weight_stride%d'%(prefix,stride)] = landmark_weight\n #print('in_rpn', stride,_label.shape, bbox_target.shape, bbox_weight.shape, file=sys.stderr)\n label_list.append(_label)\n #print('DD', _label.shape)\n bbox_target_list.append(bbox_target)\n bbox_weight_list.append(bbox_weight)\n if landmark:\n landmark_target_list.append(landmark_target)\n landmark_weight_list.append(landmark_weight)\n\n label_concat = np.concatenate(label_list, axis=1)\n bbox_target_concat = np.concatenate(bbox_target_list, axis=2)\n bbox_weight_concat = np.concatenate(bbox_weight_list, axis=2)\n #fg_inds = np.where(label_concat[0] == 1)[0]\n #print('fg_inds_in_rpn2', fg_inds, file=sys.stderr)\n\n label.update({'%s_label'%prefix: label_concat,\n '%s_bbox_target'%prefix: bbox_target_concat,\n '%s_bbox_weight'%prefix: bbox_weight_concat}\n )\n if landmark:\n landmark_target_concat = np.concatenate(landmark_target_list, axis=2)\n landmark_weight_concat = np.concatenate(landmark_weight_list, axis=2)\n label['%s_landmark_target'%prefix] = landmark_target_concat\n label['%s_landmark_weight'%prefix] = landmark_weight_concat\n #tb = datetime.datetime.now()\n #self._times[3] += (tb-ta).total_seconds()\n #ta = datetime.datetime.now()\n #print(self._times)\n return label\n", "meta": {"hexsha": "82e3600ae96ef97cc4dc6c20ec1cf8cc20bc39e0", "size": 32232, "ext": "py", "lang": "Python", "max_stars_repo_path": "RetinaFace/rcnn/io/rpn.py", "max_stars_repo_name": "tensorflow-pool/insightface", "max_stars_repo_head_hexsha": "d27ad2d3e8b15a9abaddc86dc12c59437db6ee80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-02-19T09:53:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-19T09:53:11.000Z", "max_issues_repo_path": "RetinaFace/rcnn/io/rpn.py", "max_issues_repo_name": "tensorflow-pool/insightface", "max_issues_repo_head_hexsha": "d27ad2d3e8b15a9abaddc86dc12c59437db6ee80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RetinaFace/rcnn/io/rpn.py", "max_forks_repo_name": "tensorflow-pool/insightface", "max_forks_repo_head_hexsha": "d27ad2d3e8b15a9abaddc86dc12c59437db6ee80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.4105263158, "max_line_length": 177, "alphanum_fraction": 0.6417845619, "include": true, "reason": "import numpy", "num_tokens": 8976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.256831980010821, "lm_q1q2_score": 0.14141358368684603}} {"text": "#! /usr/bin/python\nimport math\nimport os\nimport string\nimport struct\nimport sys\nimport time\nimport csv\nimport numpy\n\n#functions including\n#1. simple classes to store all the information about each species and reaction.\n#2. Functions to read in the species and reaction file and check for sanity\n#3. Functions to write out files necessary for UCLCHEM\n\n\n##########################################################################################\n#1. simple classes to store all the information about each species and reaction.\n#largely just to make the other functions more readable.\n##########################################################################################\nclass Species:\n\tdef __init__(self, inputRow):\n\t\tself.name = inputRow[0]\n\t\tself.mass = inputRow[1]\n\t\tself.bindener = float(inputRow[2])\n\t\tself.solidFraction = float(inputRow[3])\n\t\tself.monoFraction = float(inputRow[4])\n\t\tself.volcFraction = float(inputRow[5])\n\t\tself.enthalpy = float(inputRow[6])\n\n\tdef is_grain_species(self):\n\t\treturn self.name[0] == '#'\n\n\tdef is_ion(self):\n\t\treturn (self.name[-1] == \"+\" or self.name[-1] == \"-\")\n\n\nclass Reaction:\n\tdef __init__(self, inputRow):\n\t\tself.reactants = [inputRow[0], inputRow[1], self.NANCheck(inputRow[2])]\n\t\tself.products = [inputRow[3], self.NANCheck(\n\t\t\tinputRow[4]), self.NANCheck(inputRow[5]), self.NANCheck(inputRow[6])]\n\t\tself.alpha = float(inputRow[7])\n\t\tself.beta = float(inputRow[8])\n\t\tself.gamma = float(inputRow[9])\n\t\tself.templow = inputRow[10]\n\t\tself.temphigh = inputRow[11]\n\n\tdef NANCheck(self, a):\n\t\taa = a if a else 'NAN'\n\t\treturn aa\n\n\n##########################################################################################\n#2. Functions to read in the species and reaction file and check for sanity\n##########################################################################################\n\n# Read the entries in the specified species file\ndef read_species_file(fileName):\n\tspeciesList = []\n\tf = open(fileName, 'rb')\n\treader = csv.reader(f, delimiter=',', quotechar='|')\n\tfor row in reader:\n\t\tif row[0] != \"NAME\" and \"!\" not in row[0]:\n\t\t\tspeciesList.append(Species(row))\n\tnSpecies = len(speciesList)\n\treturn nSpecies, speciesList\n\n# Read the entries in the specified reaction file and keep the reactions that involve the species in our species list\n\n\ndef read_reaction_file(fileName, speciesList, ftype):\n\treactions = []\n\tkeepList = []\n\t# keeplist includes the elements that ALL the reactions should be formed from\n\tkeepList.extend(['', 'NAN', '#', 'E-', 'e-', 'ELECTR', 'PHOTON', 'CRP', 'CRPHOT', 'FREEZE', 'CRH',\n 'PHOTD', 'THERM', 'XRAY', 'XRSEC', 'XRLYA', 'XRPHOT', 'DESOH2', 'DESCR', 'DEUVCR', \"CHEMDES\", \"DIFF\"])\n\tfor species in speciesList:\n\t\tkeepList.append(species.name)\n\tif ftype == 'UMIST': # if it is a umist database file\n\t\tf = open(fileName, 'rb')\n\t\treader = csv.reader(f, delimiter=':', quotechar='|')\n\t\tfor row in reader:\n\t\t\t# if all the reaction elements belong to the keeplist\n\t\t\tif all(x in keepList for x in [row[2], row[3], row[4], row[5], row[6], row[7]]):\n\t\t\t\t#umist file doesn't have third reactant so add space and has a note for how reactions there are so remove that\n\t\t\t\treactions.append(Reaction(row[2:4]+['']+row[4:8]+row[9:]))\n\tif ftype == 'UCL': # if it is a ucl made (grain?) reaction file\n\t\tf = open(fileName, 'rb')\n\t\treader = csv.reader(f, delimiter=',', quotechar='|')\n\t\tfor row in reader:\n\t\t\t# if all the reaction elements belong to the keeplist\n\t\t\tif all(x in keepList for x in row[0:7]):\n\t\t\t\trow[10] = 0.0\n\t\t\t\trow[11] = 10000.0\n\t\t\t\treactions.append(Reaction(row))\n\n\tnReactions = len(reactions)\n\treturn nReactions, reactions\n\n\ndef remove_duplicate_species(speciesList):\n\t\t#check for duplicate species\n\tduplicates = 0\n\tduplicate_list = []\n\tfor i in range(0, len(speciesList)):\n\t\tfor j in range(0, len(speciesList)):\n\t\t\tif speciesList[i].name == speciesList[j].name:\n\t\t\t\tif (j != i) and speciesList[i].name not in duplicate_list:\n\t\t\t\t\tprint \"\\t {0} appears twice in input species list\".format(speciesList[i].name)\n\t\t\t\t\tduplicate_list.append(speciesList[i].name)\n\n\tfor duplicate in duplicate_list:\n\t\tremoved = False\n\t\ti = 0\n\t\twhile not removed:\n\t\t\tif speciesList[i].name == duplicate:\n\t\t\t\tdel speciesList[i]\n\t\t\t\tprint \"\\tOne entry of {0} removed from list\".format(duplicate)\n\t\t\t\tremoved = True\n\t\t\telse:\n\t\t\t\ti += 1\n\treturn speciesList\n\n#Look for possibly incorrect parts of species list\n\n\ndef filter_species(speciesList, reactionList):\n\t#check for species not involved in any reactions\n\tlostSpecies = []\n\tfor species in speciesList:\n\t\tkeepFlag = False\n\t\tfor reaction in reactionList:\n\t\t\tif species.name in reaction.reactants or species.name in reaction.products:\n\t\t\t\tkeepFlag = True\n\t\tif not keepFlag:\n\t\t\tlostSpecies.append(species.name)\n\t\t\tspeciesList.remove(species)\n\n\tprint '\\tSpecies in input list that do not appear in final list:'\n\tprint '\\t', lostSpecies\n\tprint '\\n'\n\treturn speciesList\n\n#All species should freeze out at least as themselves and all grain species should desorb according to their binding energy\n#This function adds those reactions automatically to slim down the grain file\n\n\ndef add_desorb_reactions(speciesList, reactionList):\n\tfor species in speciesList:\n\t\tif species.is_grain_species():\n\t\t\tfor reacType in ['DESOH2', \"DESCR\", \"DEUVCR\"]:\n\t\t\t\tnewReaction = Reaction([species.name, reacType, 'NAN', species.name[1:],\n 'NAN', 'NAN', 'NAN', 1, 0, species.bindener, 0.0, 10000.0])\n\t\t\t\treactionList.append(newReaction)\n\treturn reactionList\n\n#check reactions to alert user of potential issues including repeat reactions\n#and multiple freeze out routes\n\n\ndef reaction_check(speciesList, reactionList, freeze_check=True):\n\n\t#first check for multiple freeze outs so user knows to do alphas\n\tprint \"\\tSpecies with multiple freeze outs, check alphas:\"\n\tfor spec in speciesList:\n\t\tfreezes = 0\n\t\tfor reaction in reactionList:\n\t\t\tif (spec.name in reaction.reactants and 'FREEZE' in reaction.reactants):\n\t\t\t\tfreezes += 1\n\t\tif (freezes > 1):\n\t\t\tprint \"\\t{0} freezes out through {1} routes\".format(spec.name, freezes)\n\t\tif freezes < 1 and not spec.is_grain_species() and freeze_check:\n\t\t\tprint \"\\t{0} does not freeze out\".format(spec.name, freezes)\n\t#now check for duplicate reactions\n\tduplicate_list = []\n\tprint \"\\n\\tPossible duplicate reactions for manual removal:\"\n\tduplicates = 0\n\tfor i, reaction1 in enumerate(reactionList):\n\t\tif i not in duplicate_list:\n\t\t\tfor j, reaction2 in enumerate(reactionList):\n\t\t\t\tif i != j:\n\t\t\t\t\tif set(reaction1.reactants) == set(reaction2.reactants):\n\t\t\t\t\t\tif set(reaction1.products) == set(reaction2.products):\n\t\t\t\t\t\t\tprint \"\\tReactions {0} and {1} are possible duplicates\".format(i+1, j+1)\n\t\t\t\t\t\t\tprint \"\\t\", str(i+1), reaction1.reactants, \"-->\", reaction1.products\n\t\t\t\t\t\t\tprint \"\\t\", str(j+1), reaction1.reactants, \"-->\", reaction2.products\n\t\t\t\t\t\t\tduplicates += 1\n\t\t\t\t\t\t\tduplicate_list.append(i)\n\t\t\t\t\t\t\tduplicate_list.append(j)\n\n\tif (duplicates == 0):\n\t\tprint \"\\tNone\"\n\n#capitalize files\n\n\ndef make_capitals(fileName):\n\ta = open(fileName).read()\n\toutput = open(fileName, mode='w')\n\toutput.write(a.upper())\n\toutput.close()\n\n\ndef find_constituents(speciesList):\n\telementList = ['H', 'D', 'HE', 'C', 'N', 'O', 'F',\n 'P', 'S', 'CL', 'LI', 'NA', 'MG', 'SI', 'PAH', '15N']\n\telementMass = [1, 2, 4, 12, 14, 16, 19, 31, 32, 35, 3, 23, 24, 28, 420, 15]\n\tsymbols = ['#', '+', '-', '(', ')']\n\n\tfor species in speciesList:\n\t\tspeciesName = species.name\n\t\ti = 0\n\t\tatoms = []\n\t\tbracket = False\n\t\tbracketContent = []\n\t\t#loop over characters in species name to work out what it is made of\n\t\twhile i < len(speciesName):\n\t\t\t#if character isn't a #,+ or - then check it otherwise move on\n\t\t\tif speciesName[i] not in symbols:\n\t\t\t\tif i+1 < len(speciesName):\n\t\t\t\t\t#if next two characters are (eg) 'MG' then atom is Mg not M and G\n\t\t\t\t\tif speciesName[i:i+3] in elementList:\n\t\t\t\t\t\tj = i+3\n\t\t\t\t\telif speciesName[i:i+2] in elementList:\n\t\t\t\t\t\tj = i+2\n\t\t\t\t\t#otherwise work out which element it is\n\t\t\t\t\telif speciesName[i] in elementList:\n\t\t\t\t\t\tj = i+1\n\n\t\t\t\t#if there aren't two characters left just try next one\n\t\t\t\telif speciesName[i] in elementList:\n\t\t\t\t\tj = i+1\n\t\t\t\t#if we've found a new element check for numbers otherwise print error\n\t\t\t\tif j > i:\n\t\t\t\t\tif bracket:\n\t\t\t\t\t\tbracketContent.append(speciesName[i:j])\n\t\t\t\t\telse:\n\t\t\t\t\t\tatoms.append(speciesName[i:j]) # add element to list\n\t\t\t\t\tif j < len(speciesName):\n\t\t\t\t\t\tif is_number(speciesName[j]):\n\t\t\t\t\t\t\tif int(speciesName[j]) > 1:\n\t\t\t\t\t\t\t\tfor k in range(1, int(speciesName[j])):\n\t\t\t\t\t\t\t\t\tif bracket:\n\t\t\t\t\t\t\t\t\t\tbracketContent.append(speciesName[i:j])\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tatoms.append(speciesName[i:j])\n\t\t\t\t\t\t\t\ti = j+1\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\ti = j\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ti = j\n\t\t\t\t\telse:\n\t\t\t\t\t\ti = j\n\t\t\t\telse:\n\t\t\t\t\tprint speciesName[i]\n\t\t\t\t\tprint\"\\t{0} contains elements not in element list:\".format(speciesName)\n\t\t\t\t\tprint elementList\n\t\t\telse:\n\t\t\t\t#if symbol is start of a bracketed part of molecule, keep track\n\t\t\t\tif (speciesName[i] == \"(\"):\n\t\t\t\t\tbracket = True\n\t\t\t\t\tbracketContent = []\n\t\t\t\t\ti += 1\n\t\t\t\t#if it's the end then add bracket contents to list\n\t\t\t\telif speciesName[i] == \")\":\n\t\t\t\t\tif is_number(speciesName[i+1]):\n\t\t\t\t\t\tfor k in range(0, int(speciesName[i+1])):\n\t\t\t\t\t\t\tatoms.extend(bracketContent)\n\t\t\t\t\t\ti += 2\n\t\t\t\t\telse:\n\t\t\t\t\t\tatoms.extend(bracketContent)\n\t\t\t\t\t\ti += 1\n\t\t\t\t#otherwise move on\n\t\t\t\telse:\n\t\t\t\t\ti += 1\n\n\t\tspecies.n_atoms = len(atoms)\n\t\tmass = 0\n\t\tfor atom in atoms:\n\t\t\tmass += elementMass[elementList.index(atom)]\n\t\tif mass != float(species.mass):\n\t\t\t#print \"\\tcalculated mass of {0} does not match input mass\".format(speciesName)\n\t\t\t#print \"\\tcalculated mass: {0} \\t input mass: {1}\\n\".format(mass,species.mass)\n\t\t\t#print \"\\tkeeping calculated mass\\n\"\n\t\t\tspecies.mass = str(mass)\n\treturn speciesList\n\n\ndef is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n return False\n##########################################################################################\n#3. Functions to write out files necessary for UCLCHEM\n##########################################################################################\n\n# Write the species file in the desired format\n\n\ndef write_species(fileName, speciesList):\n\tf = open(fileName, 'wb')\n\twriter = csv.writer(f, delimiter=',', quotechar='|',\n\t quoting=csv.QUOTE_MINIMAL, lineterminator='\\n')\n\tnSpecies = len(speciesList)\n\tfor species in speciesList:\n\t\twriter.writerow([species.name, species.mass, species.n_atoms])\n\n# Write the reaction file in the desired format\n\n\ndef write_reactions(fileName, reactionList):\n\tf = open(fileName, 'wb')\n\twriter = csv.writer(f, delimiter=',', quotechar='|',\n\t quoting=csv.QUOTE_MINIMAL, lineterminator='\\n')\n\tnReactions = len(reactionList)\n\tfor reaction in reactionList:\n\t\t#if statement changes beta for ion freeze out to 1. This is how ucl_chem recognises ions when calculating freeze out rate\n\t\tif ('FREEZE' in reaction.reactants and reaction.reactants[0][-1] == '+'):\n\t\t\treaction.beta = 1\n\t\twriter.writerow(reaction.reactants+reaction.products +\n\t\t [reaction.alpha, reaction.beta, reaction.gamma, reaction.templow, reaction.temphigh])\n\n\ndef write_odes_f90(fileName, speciesList, reactionList):\n\toutput = open(fileName, mode='w')\n\t#go through every species and build two strings, one with eq for all destruction routes and one for all formation\n\tydotString = build_ode_string(speciesList, reactionList)\n\toutput.write(ydotString)\n\toutput.close()\n\n\ndef build_ode_string(speciesList, reactionList):\n\todeString = \"\"\n\tnSpecies = len(speciesList)\n\tnReactions = len(reactionList)\n\n\tfor n, species in enumerate(speciesList):\n\t\tlossString = ''\n\t\tformString = ''\n\t\t#go through entire reaction list\n\t\tfor i, reaction in enumerate(reactionList):\n\n\t\t\t#if species appear in reactants, reaction is a destruction route\n\t\t\tif species.name in reaction.reactants:\n\t\t\t\tbodyCount = 0 # two or more bodies in a reaction mean we multiply rate by density so need to keep track\n\t\t\t\t#easy for h2 formation\n\t\t\t\tif is_H2_formation(reaction.reactants, reaction.products):\n\t\t\t\t\tlossString += '-2*RATE('+str(i+1)+')*D'\n\t\t\t\t\tcontinue\n\t\t\t\t#multiply string by number of time species appears in reaction. multiple() defined below\n\t\t\t\t#so far reaction string is rate(reaction_index) indexs are all +1 for fortran array indexing\n\t\t\t\tlossString += '-' + \\\n\t\t\t\t\tmultiple(reaction.reactants.count(species.name))+'RATE('+str(i+1)+')'\n\n\t\t\t\t#now add *Y(species_index) to string for every reactant\n\t\t\t\tfor reactant in set(reaction.reactants):\n\t\t\t\t\tn_appearances = reaction.reactants.count(reactant)\n\t\t\t\t\t#every species appears at least once in its loss reaction\n\t\t\t\t\t#so we multiply entire loss string by Y(species_index) at end\n\t\t\t\t\t#thus need one less Y(species_index) per reaction\n\t\t\t\t\tif reactant == species.name:\n\t\t\t\t\t\tbodyCount += n_appearances\n\t\t\t\t\t\tif n_appearances > 1:\n\t\t\t\t\t\t\tfor j, possibleReactants in enumerate(speciesList):\n\t\t\t\t\t\t\t\tif reactant == possibleReactants.name:\n\t\t\t\t\t\t\t\t\tfor appearance in range(1, n_appearances):\n\t\t\t\t\t\t\t\t\t\tlossString += '*Y('+str(j+1)+')'\n\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\telse:\n\t\t\t\t\t\t#look through species list and find reactant\n\t\t\t\t\t\tfor j, possibleReactants in enumerate(speciesList):\n\t\t\t\t\t\t\tif reactant == possibleReactants.name:\n\t\t\t\t\t\t\t\tfor appearance in range(n_appearances):\n\t\t\t\t\t\t\t\t\tlossString += '*Y('+str(j+1)+')'\n\t\t\t\t\t\t\t\t\tbodyCount += 1\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t#now string is rate(reac_index)*Y(species_index1)*Y(species_index2) may need *D if total rate is\n\t\t\t\t#proportional to density\n\t\t\t\tif reaction.reactants.count('FREEZE') > 0 or reaction.reactants.count('DESOH2') > 0:\n\t\t\t\t\tlossString += '*D'\n\t\t\t\tfor body in range(1, bodyCount):\n\t\t\t\t\tlossString += \"*D\"\n\n\t\t\t#same process as above but rate is positive for reactions where species is positive\n\t\t\tif species.name in reaction.products:\n\t\t\t\tbodyCount = 0 # two or more bodies in a reaction mean we multiply rate by density so need to keep track\n\n\t\t\t\tif is_H2_formation(reaction.reactants, reaction.products):\n\t\t\t\t\t#honestly H should be index 1 but lets check\n\t\t\t\t\tH_index = speciesList.index(\n\t\t\t\t\t\tnext((x for x in speciesList if x.name == 'H')))\n\t\t\t\t\tformString += '+RATE('+str(i+1)+')*Y('+str(H_index+1)+')*D'\n\t\t\t\t\tcontinue\n\n\t\t\t\t#multiply string by number of time species appears in reaction. multiple() defined below\n\t\t\t\t#so far reaction string is rate(reaction_index) indexs are all +1 for fortran array indexing\n\t\t\t\tformString += '+' + \\\n\t\t\t\t\tmultiple(reaction.products.count(species.name))+'RATE('+str(i+1)+')'\n\n\t\t\t\t#now add *Y(species_index) to string for every reactant\n\t\t\t\tfor reactant in set(reaction.reactants):\n\t\t\t\t\tn_appearances = reaction.reactants.count(reactant)\n\t\t\t\t\tfor j, possibleReactants in enumerate(speciesList):\n\t\t\t\t\t\tif reactant == possibleReactants.name:\n\t\t\t\t\t\t\tfor appearance in range(n_appearances):\n\t\t\t\t\t\t\t\tformString += '*Y('+str(j+1)+')'\n\t\t\t\t\t\t\t\tbodyCount += 1\n\t\t\t\t\t\t\tcontinue\n\n\t\t\t\t#now string is rate(reac_index)*Y(species_index1)*Y(species_index2) may need *D if total rate is\n\t\t\t\t#proportional to density\n\t\t\t\tif reaction.reactants.count('FREEZE') > 0 or reaction.reactants.count('DESOH2') > 0:\n\t\t\t\t\tformString += '*D'\n\t\t\t\tfor body in range(1, bodyCount):\n\t\t\t\t\tformString += \"*D\"\n\n\t\tif lossString != '':\n\t\t\tlossString = ' LOSS = '+lossString+'\\n'\n\t\t\tlossString = truncate_line(lossString)\n\t\t\todeString += lossString\n\t\tif formString != '':\n\t\t\tformString = ' PROD = '+formString+'\\n'\n\t\t\tformString = truncate_line(formString)\n\t\t\todeString += formString\n\n\t\t#start with empty string and add production and loss terms if they exists\n\t\tydotString = ''\n\t\tif formString != '':\n\t\t\tydotString += 'PROD'\n\t\t\tif lossString != '':\n\t\t\t\tydotString += '+'\n\t\tif lossString != '':\n\t\t\tydotString += 'Y('+str(n+1)+')*LOSS'\n\n\t\t#if we have prod and/or loss add ydotstring to odes\n\t\tif ydotString != '':\n\t\t\tydotString = ' YDOT('+str(n+1)+') = '+ydotString+\"\\n\"\n\t\t\tydotString = truncate_line(ydotString)\n\t\t\todeString += ydotString\n\t\telse:\n\t\t\tydotString = ' YDOT('+str(n+1)+') = 0.0\\n'\n\t\t\tydotString = truncate_line(ydotString)\n\t\t\todeString += ydotString\n\treturn odeString\n\n#create a file containing length of each list of moleculetypes and then the two lists (gas and grain) of species in each type\n#as well as fraction that evaporated in each type of event\n\n\ndef write_evap_lists(openFile, speciesList):\n\tgrainlist = []\n\tmgrainlist = []\n\tsolidList = []\n\tmonoList = []\n\tvolcList = []\n\tbindEnergyList = []\n\tenthalpyList = []\n\n\tfor i, species in enumerate(speciesList):\n\t\tif species.name[0] == '#':\n\t\t\t#find gas phase version of grain species. For #CO it looks for first species in list with just CO and then finds the index of that\n\t\t\ttry:\n\t\t\t\tj = speciesList.index(\n\t\t\t\t\tnext((x for x in speciesList if x.name == species.name[1:])))\n\t\t\texcept:\n\t\t\t\tprint \"\\n**************************************\\nWARNING\\n**************************************\"\n\t\t\t\tprint \"{0} has no gas phase equivalent in network. Every species should at least freeze out and desorb.\".format(species.name)\n\t\t\t\tprint \"ensure {0} is in the species list, and at least one reaction involving it exists and try again\".format(species.name[1:])\n\t\t\t\tprint \"Alternatively, provide the name of the gas phase species you would like {0} to evaporate as\".format(species.name)\n\t\t\t\tinput = raw_input(\n\t\t\t\t\t\"type x to quit Makerates or any species name to continue\\n\")\n\t\t\t\tif input.lower() == \"x\":\n\t\t\t\t\texit()\n\t\t\t\telse:\n\t\t\t\t\tj = speciesList.index(\n\t\t\t\t\t\tnext((x for x in speciesList if x.name == input.upper())))\n\n\t\t\t#plus ones as fortran and python label arrays differently\n\t\t\tmgrainlist.append(i+1)\n\t\t\tgrainlist.append(j+1)\n\t\t\tsolidList.append(species.solidFraction)\n\t\t\tmonoList.append(species.monoFraction)\n\t\t\tvolcList.append(species.volcFraction)\n\t\t\tbindEnergyList.append(species.bindener)\n\t\t\tenthalpyList.append(species.enthalpy)\n\n\topenFile.write(array_to_string(\"gasGrainList\", grainlist, type=\"int\"))\n\topenFile.write(array_to_string(\"grainList\", mgrainlist, type=\"int\"))\n\topenFile.write(array_to_string(\"solidFractions\", solidList, type=\"float\"))\n\topenFile.write(array_to_string(\"monoFractions\", monoList, type=\"float\"))\n\topenFile.write(array_to_string(\"volcanicFractions\", volcList, type=\"float\"))\n\topenFile.write(array_to_string(\n\t\t\"bindingEnergy\", bindEnergyList, type=\"float\", parameter=False))\n\topenFile.write(array_to_string(\n\t\t\"formationEnthalpy\", enthalpyList, type=\"float\"))\n\n\treturn len(grainlist)\n\n# Create the appropriate multiplication string for a given number\n\n\ndef multiple(number):\n if number == 1:\n \treturn ''\n else:\n \treturn str(number)+'*'\n\n\ndef truncate_line(input, codeFormat='F90', continuationCode=None):\n\tlineLength = 72\n\tmaxlines = 300\n\tlines = 0\n\tresult = ''\n\ti = 0\n\tj = 0\n\twhile i+j < len(input):\n\t\tj += 1\n\t\tif j > lineLength:\n\t\t\t#important not to break entries so split lines at ,s\n\t\t\ttry:\n\t\t\t\tk = input[i+j-16:i+j].index(\",\")\n\t\t\texcept:\n\t\t\t\ttry:\n\t\t\t\t\tk = input[i+j-16:i+j].index(\"*\")\n\t\t\t\texcept:\n\t\t\t\t\tk = input[i+j-16:i+j].index(\")\")\n\t\t\tj = j-16+k\n\t\t\tresult += input[i:i+j]+\"&\\n &\"\n\t\t\ti = i+j\n\t\t\tj = 0\n\tresult += input[i:i+j]\n\treturn result\n\n\ndef is_H2_formation(reactants, products):\n nReactants = len([species for species in reactants if species != ''])\n nProducts = len([species for species in products if species != ''])\n if nReactants == 2 and nProducts == 1:\n if reactants[0] == 'H' and reactants[1] == 'H' and products[0] == 'H2':\n \treturn True\n if nReactants == 3 and nProducts == 2:\n if reactants[0] == 'H' and reactants[1] == 'H' and reactants[2] == '#' and products[0] == 'H2' and products[1] == '#':\n \treturn True\n return False\n\n\ndef write_network_file(fileName, speciesList, reactionList):\n\topenFile = open(fileName, \"wb\")\n\topenFile.write(\"integer, parameter :: nSpec={0}, nReac={1}\\n\".format(\n\t\tlen(speciesList), len(reactionList)))\n\n\t#write arrays of all species stuff\n\tnames = []\n\tatoms = []\n\tmasses = []\n\tfor species in speciesList:\n\t\tnames.append(species.name)\n\t\tmasses.append(float(species.mass))\n\t\tatoms.append(species.n_atoms)\n\topenFile.write(array_to_string(\"specname\", names, type=\"string\"))\n\topenFile.write(array_to_string(\"mass\", masses, type=\"float\"))\n\topenFile.write(array_to_string(\"atomCounts\", atoms, type=\"int\"))\n\n\t#then write evaporation stuff\n\tnGrain = write_evap_lists(openFile, speciesList)\n\n\t#finally all reactions\n\treactant1 = []\n\treactant2 = []\n\treactant3 = []\n\tprod1 = []\n\tprod2 = []\n\tprod3 = []\n\tprod4 = []\n\talpha = []\n\tbeta = []\n\tgama = []\n\tfor reaction in reactionList:\n\t\treactant1.append(reaction.reactants[0])\n\t\treactant2.append(reaction.reactants[1])\n\t\treactant3.append(reaction.reactants[2])\n\t\tprod1.append(reaction.products[0])\n\t\tprod2.append(reaction.products[1])\n\t\tprod3.append(reaction.products[2])\n\t\tprod4.append(reaction.products[3])\n\t\talpha.append(reaction.alpha)\n\t\tbeta.append(reaction.beta)\n\t\tgama.append(reaction.gamma)\n\topenFile.write(array_to_string(\"re1\", reactant1, type=\"string\"))\n\topenFile.write(array_to_string(\"re2\", reactant2, type=\"string\"))\n\topenFile.write(array_to_string(\"re3\", reactant3, type=\"string\"))\n\topenFile.write(array_to_string(\"p1\", prod1, type=\"string\"))\n\topenFile.write(array_to_string(\"p2\", prod2, type=\"string\"))\n\topenFile.write(array_to_string(\"p3\", prod3, type=\"string\"))\n\topenFile.write(array_to_string(\"p4\", prod4, type=\"string\"))\n\topenFile.write(array_to_string(\"alpha\", alpha, type=\"float\", parameter=False))\n\topenFile.write(array_to_string(\"beta\", beta, type=\"float\", parameter=False))\n\topenFile.write(array_to_string(\"gama\", gama, type=\"float\", parameter=False))\n\n\ndef array_to_string(name, array, type=\"int\", parameter=True):\n\tif parameter:\n\t\toutString = \", parameter :: \"+name+\" ({0})=(/\".format(len(array))\n\telse:\n\t\toutString = \" :: \"+name+\" ({0})=(/\".format(len(array))\n\tif type == \"int\":\n\t\toutString = \"integer\"+outString\n\t\tfor value in array:\n\t\t\toutString += \"{0},\".format(value)\n\telif type == \"float\":\n\t\toutString = \"double precision\"+outString\n\t\tfor value in array:\n\t\t\toutString += \"{0:.4e},\".format(value)\n\telif type == \"string\":\n\t\toutString = \"character(Len=10)\"+outString\n\t\tfor value in array:\n\t\t\toutString += \"\\\"\"+value.ljust(10)+\"\\\",\"\n\telse:\n\t\tprint \"Not a valid type for array to string\"\n\toutString = outString[:-1]+\"/)\\n\"\n\toutString = truncate_line(outString)\n\treturn outString\n", "meta": {"hexsha": "37fa8d039b85a26a07bc5ec5ffc7e43f09d5a2ef", "size": 22216, "ext": "py", "lang": "Python", "max_stars_repo_path": "Makerates/Functions.py", "max_stars_repo_name": "tomasjames/UCLCHEM", "max_stars_repo_head_hexsha": "3a41a10200864227801a83b22b213d060d74c8e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Makerates/Functions.py", "max_issues_repo_name": "tomasjames/UCLCHEM", "max_issues_repo_head_hexsha": "3a41a10200864227801a83b22b213d060d74c8e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Makerates/Functions.py", "max_forks_repo_name": "tomasjames/UCLCHEM", "max_forks_repo_head_hexsha": "3a41a10200864227801a83b22b213d060d74c8e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4888178914, "max_line_length": 133, "alphanum_fraction": 0.6614151963, "include": true, "reason": "import numpy", "num_tokens": 5968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.27202454519235225, "lm_q1q2_score": 0.14132255132174767}} {"text": "from collections.abc import Mapping\nfrom collections import defaultdict\n\nimport numba\nfrom numba import generated_jit, types\nimport numpy as np\n\nfrom africanus.util.patterns import Multiton\nfrom africanus.experimental.rime.fused.arguments import ArgumentDependencies\nfrom africanus.experimental.rime.fused.intrinsics import IntrinsicFactory\nfrom africanus.experimental.rime.fused.specification import RimeSpecification\n\n\nDATASET_TYPES = []\n\ntry:\n from daskms.dataset import Dataset as dmsds\nexcept ImportError:\n pass\nelse:\n DATASET_TYPES.append(dmsds)\n\ntry:\n from xarray import Dataset as xrds\nexcept ImportError:\n pass\nelse:\n DATASET_TYPES.append(xrds)\n\n\ndef rime_impl_factory(terms, transformers, ncorr):\n @generated_jit(nopython=True, nogil=True, cache=True)\n def rime(names, *inargs):\n if len(inargs) != 1 or not isinstance(inargs[0], types.BaseTuple):\n raise TypeError(f\"{inargs[0]} must be be a Tuple\")\n\n if not isinstance(names, types.BaseTuple):\n raise TypeError(f\"{names} must be a Tuple of strings\")\n\n if len(names) != len(inargs[0]):\n raise ValueError(f\"len(names): {len(names)} \"\n f\"!= {len(inargs[0])}\")\n\n if not all(isinstance(n, types.Literal) for n in names):\n raise TypeError(f\"{names} must be a Tuple of strings\")\n\n if not all(n.literal_type is types.unicode_type for n in names):\n raise TypeError(f\"{names} must be a Tuple of strings\")\n\n # Get literal argument names\n names = tuple(n.literal_value for n in names)\n\n # Generate intrinsics\n argdeps = ArgumentDependencies(names, terms, transformers)\n factory = IntrinsicFactory(argdeps)\n out_names, pack_opts_indices = factory.pack_optionals_and_indices_fn()\n out_names, pack_transformed = factory.pack_transformed_fn(out_names)\n term_state = factory.term_state_fn(out_names)\n term_sampler = factory.term_sampler_fn()\n\n try:\n lm_i = out_names.index(\"lm\")\n uvw_i = out_names.index(\"uvw\")\n chan_freq_i = out_names.index(\"chan_freq\")\n except ValueError as e:\n raise ValueError(f\"{str(e)} is required\")\n\n def impl(names, *inargs):\n args_opt_idx = pack_opts_indices(inargs)\n args = pack_transformed(args_opt_idx)\n state = term_state(args)\n\n nsrc, _ = args[lm_i].shape\n nrow, _ = args[uvw_i].shape\n nchan, = args[chan_freq_i].shape\n\n vis = np.zeros((nrow, nchan, ncorr), np.complex128)\n # Kahan summation compensation\n compensation = np.zeros_like(vis)\n\n for s in range(nsrc):\n for r in range(nrow):\n t = state.time_index[r]\n a1 = state.antenna1[r]\n a2 = state.antenna2[r]\n f1 = state.feed1[r]\n f2 = state.feed2[r]\n\n for ch in range(nchan):\n X = term_sampler(state, s, r, t, f1, f2, a1, a2, ch)\n\n for c, value in enumerate(numba.literal_unroll(X)):\n # Kahan summation\n y = value - compensation[r, ch, c]\n current = vis[r, ch, c]\n x = current + y\n compensation[r, ch, c] = (x - current) - y\n vis[r, ch, c] = x\n\n return vis\n\n return impl\n\n return rime\n\n\nclass RimeFactory(metaclass=Multiton):\n REQUIRED_ARGS = ArgumentDependencies.REQUIRED_ARGS\n REQUIRED_ARGS_LITERAL = tuple(types.literal(n) for n in REQUIRED_ARGS)\n DEFAULT_SPEC = \"(Kpq, Bpq): [I, Q, U, V] -> [XX, XY, YX, YY]\"\n\n def __reduce__(self):\n return (RimeFactory, (self.rime_spec,))\n\n def __hash__(self):\n return hash(self.rime_spec)\n\n def __eq__(self, rhs):\n return (isinstance(rhs, RimeFactory) and\n self.rime_spec == rhs.rime_spec)\n\n def __init__(self, rime_spec=DEFAULT_SPEC):\n if isinstance(rime_spec, RimeSpecification):\n pass\n elif isinstance(rime_spec, (list, tuple)):\n rime_spec = RimeSpecification(*rime_spec)\n elif isinstance(rime_spec, str):\n rime_spec = RimeSpecification(rime_spec)\n\n self.rime_spec = rime_spec\n self.impl = rime_impl_factory(\n rime_spec.terms,\n rime_spec.transformers,\n len(rime_spec.corrs))\n\n def dask_blockwise_args(self, **kwargs):\n \"\"\" Get the dask schema \"\"\"\n argdeps = ArgumentDependencies(\n tuple(kwargs.keys()),\n self.rime_spec.terms,\n self.rime_spec.transformers)\n # Holds kwargs + any dummy outputs from transformations\n dummy_kw = kwargs.copy()\n\n dask_schema = defaultdict(list)\n for a in argdeps.REQUIRED_ARGS:\n dask_schema[a].append((\"internal\", (\"row\",)))\n\n POISON = object()\n\n for transformer in argdeps.can_create.values():\n kw = {}\n\n for a in transformer.ARGS:\n v = dummy_kw.get(a, None if a in argdeps.KEY_ARGS else POISON)\n kw[a] = v\n\n for a, d in transformer.KWARGS.items():\n kw[a] = dummy_kw.get(a, d)\n\n inputs, outputs = transformer.dask_schema(**kw)\n\n for k, schema in inputs.items():\n dask_schema[k].append((transformer, schema))\n\n dummy_kw.update(outputs)\n\n for term in self.rime_spec.terms:\n kw = {a: dummy_kw[a] for a in term.ALL_ARGS if a in dummy_kw}\n\n for k, v in term.dask_schema(**kw).items():\n dask_schema[k].append((term, v))\n\n merged_schema = {}\n\n for a, candidates in dask_schema.items():\n dims = set(pair[1] for pair in candidates)\n if len(dims) != 1:\n raise ValueError(\n f\"Multiple candidates provided conflicting \"\n f\"dimension definitions for {a}: {candidates}.\")\n\n merged_schema[a] = dims.pop()\n\n names = list(sorted(argdeps.valid_inputs & set(kwargs.keys())))\n blockwise_args = [e for n in names\n for e in (kwargs[n], merged_schema.get(n, None))]\n\n assert 2 * len(names) == len(blockwise_args)\n return names, blockwise_args\n\n def __call__(self, time, antenna1, antenna2, feed1, feed2, **kwargs):\n keys = (self.REQUIRED_ARGS_LITERAL +\n tuple(map(types.literal, kwargs.keys())))\n\n return self.impl(keys, time,\n antenna1, antenna2,\n feed1, feed2,\n *kwargs.values())\n\n\ndef consolidate_args(args, kw):\n mapping = {}\n oargs = []\n\n for element in args:\n if isinstance(element, tuple(DATASET_TYPES)):\n mapping.update((k.lower(), v.data) for k, v in element.items())\n elif isinstance(element, Mapping):\n mapping.update(element)\n else:\n oargs.append(element)\n\n mapping.update(zip(oargs, RimeFactory.REQUIRED_ARGS))\n mapping.update(kw)\n\n return mapping\n\n\ndef rime(rime_spec, *args, **kw):\n \"\"\"\n Evaluates the Radio Interferometer Measurement Equation (RIME), given\n the Specification of the RIME :code:`rime_spec`, as well as the\n inputs to the RIME given in :code:`*args` and :code:`**kwargs`.\n \"\"\"\n mapping = consolidate_args(args, kw)\n factory = RimeFactory(rime_spec=rime_spec)\n return factory(**mapping)\n", "meta": {"hexsha": "d23341dda5f9d99e772d8867299a657b5382a65a", "size": 7614, "ext": "py", "lang": "Python", "max_stars_repo_path": "africanus/experimental/rime/fused/core.py", "max_stars_repo_name": "ratt-ru/codex-africanus", "max_stars_repo_head_hexsha": "29c463c7e79eb8d2a2703d3381448d96c6840eb3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "africanus/experimental/rime/fused/core.py", "max_issues_repo_name": "ratt-ru/codex-africanus", "max_issues_repo_head_hexsha": "29c463c7e79eb8d2a2703d3381448d96c6840eb3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "africanus/experimental/rime/fused/core.py", "max_forks_repo_name": "ratt-ru/codex-africanus", "max_forks_repo_head_hexsha": "29c463c7e79eb8d2a2703d3381448d96c6840eb3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-26T15:02:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T15:02:59.000Z", "avg_line_length": 33.2489082969, "max_line_length": 78, "alphanum_fraction": 0.5876017862, "include": true, "reason": "import numpy,import numba,from numba", "num_tokens": 1736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2782568056728001, "lm_q1q2_score": 0.14130210723708092}} {"text": "# Generate primers of a specified length and annealing temperature,\n# with a specified distance from other primers.\n# Accept a random seed and starting position, to guarantee the results can be repeated.\n#import primer3\nimport ConfigParser\nimport sys\nimport os\nimport math\nimport numpy as np\nimport pandas as pd\nimport copy\nimport primer3\n\nDNA = ['A','C','G','T']\nDNA_C = {'A':'T', 'C':'G', 'G':'C', 'T':'A'}\nN_PROBS = [0.25, 0.25, 0.25, 0.25]\nMAX_NN_LENGTH = 60 # primer3 default\nPRIMER3_METHOD = 'santalucia' # primer3 default\nMAX_LOOP = 30 # primer3 default\n\ndef rc(seq):\n return(''.join([DNA_C[q] for q in seq])[::-1])\n\nclass primer_set(object):\n\n def __init__(self, cfg):\n params = dict(cfg.items('Params'))\n self.toe_anneal = float(params['toe_anneal'])\n self.toe_tolerance = float(params['toe_tolerance'])\n self.full_anneal = float(params['full_anneal'])\n self.full_tolerance = float(params['full_tolerance'])\n self.misprime_tolerance = float(params['misprime_tolerance'])\n self.evolve_iterations = int(params['evolve_iterations']) # number of iterations allowed for one call to 'evolve_new_seq' to get one new seq\n self.seqs = {'Toehold':[], 'Full':[]}\n self.seq_base = params['SEQ']\n self.base_probs = {'N': N_PROBS} # base probabilities for the toehold: include e.g. BsaI sites this way\n for q in self.seq_base:\n if not q in DNA and not q in self.base_probs.keys():\n x = [float(q) for q in params[q].strip().split(':')]\n self.base_probs[q] = x/sum(x)\n self.len_full_add = int(params['len_full_add'])# length of sequence to add to toehold to get something that anneals at self.full_anneal\n self.add_to_left = params['add_to_left'] == 'True'\n self.mv_conc = float(params['mv_conc']) # 50\n self.dv_conc = float(params['dv_conc']) # 0\n self.dntp_conc = float(params['dntp_conc']) # 0.8\n self.dna_conc = float(params['dna_conc']) # 50\n np.random.seed(int(params['random_seed']))\n\n # Get the annealing temperature of two sequences\n def melting_temp(self, seq):\n return( primer3.calcTm(seq, mv_conc=self.mv_conc, dv_conc=self.dv_conc, dntp_conc=self.dntp_conc,\n dna_conc=self.dna_conc, max_nn_length=MAX_NN_LENGTH, tm_method=PRIMER3_METHOD, salt_corrections_method=PRIMER3_METHOD) )\n\n # Find whether a concerning heterodimer exists between two sequences\n def get_misprime_tm(self, seq1, seq2, temp):\n tm_f1 = self.get_misprime_tm_inner(seq1, seq2, temp)\n tm_r1 = self.get_misprime_tm_inner(seq1, rc(seq2), temp)\n tm_f2 = self.get_misprime_tm_inner(seq2, seq1, temp)\n tm_r2 = self.get_misprime_tm_inner(seq2, rc(seq1), temp)\n return(max(tm_f1, tm_r1, tm_f2, tm_r2))\n\n def get_misprime_tm_inner(self, seq1, seq2, temp):\n heterodimer = primer3.calcHeterodimer(seq1, seq2,\n mv_conc=self.mv_conc, dv_conc=self.dv_conc, dntp_conc=self.dntp_conc, dna_conc=self.dna_conc, \n temp_c=temp, max_loop=MAX_LOOP)\n if not heterodimer.structure_found:\n return -100.\n return heterodimer.tm\n\n def true_if_no_misprime(self, seq1, seq2, temp):\n struct_tm = self.get_misprime_tm(seq1, seq2, temp)\n #if(struct_tm >= (temp - self.misprime_tolerance)):\n # raise Exception('oops!' + str(seq1) + ' ' + str(seq2) + ' ' + str(struct_tm))\n\n return struct_tm < (temp - self.misprime_tolerance) # e.g. if temp = 45, self.misprime_tolerance = 5, OK if t_anneal < 40; will be melted by 45\n\n # placeholder, for maybe rejecting e.g. hairpins\n def primer_passed_filter(self, seq):\n return True\n\n # generate a random sequence\n def get_random_seq(self, parent = None):\n if parent == None: # this is Python's fault\n parent = self.seq_base\n ans = []\n for b in parent:\n if b in DNA:\n ans.append(b)\n else:\n ans.append( np.random.choice(DNA, None, self.base_probs[b]) )\n return(''.join(ans))\n\n # get all variants of a random sequence, and find the one with Tm closest to some target\n # Compare to a template to see which bases aren't allowed to be changed\n def evolve_one_step(self, seq, template, target):\n assert(len(seq) == len(template))\n ans = seq\n err = abs( self.melting_temp(seq) - target )\n for i in range(len(seq)):\n if template[i] not in DNA:\n for b in DNA:\n if seq[i] != b:\n tmp = [q for q in seq]\n tmp[i] = b\n tmp = ''.join(tmp)\n new_err = abs(self.melting_temp(tmp) - target)\n if new_err < err and self.primer_passed_filter(tmp):\n err = new_err\n ans = tmp\n return(ans)\n\n def true_if_no_misprimes_to_seqs(self, seq):\n if len(self.seqs['Full']) == 0:\n return True\n return(all([self.true_if_no_misprime(seq, q, self.toe_anneal) for q in self.seqs['Full']]))\n\n # evolve a valid new toe first, then extend\n # 'self.evolve_iterations' available to get both tasks done.\n def evolve_new_seq_inner(self):\n seq = self.get_random_seq()\n is_full = False\n template = self.seq_base\n toe = None; full = None\n for i in range(self.evolve_iterations):\n if is_full: # get temperature targets based on what part of the process this is\n target = self.full_anneal\n target_low = target - self.full_tolerance; target_high = target + self.full_tolerance\n else:\n target = self.toe_anneal\n target_low = target - self.toe_tolerance; target_high = target + self.toe_tolerance\n tm = self.melting_temp(seq)\n if tm > target_low and tm < target_high:\n if not is_full:\n is_full = True; toe = seq\n new_pad = ''.join(['N']*self.len_full_add)\n if self.add_to_left:\n template = new_pad + seq\n seq = self.get_random_seq(template)\n else:\n template = seq + new_pad\n seq = self.get_random_seq(template)\n else:\n full = seq\n return(toe, full)\n seq = self.evolve_one_step(seq, template, target)\n return(None, None)\n\n def evolve_new_seq(self):\n toe, full = self.evolve_new_seq_inner()\n if full != None:\n if self.true_if_no_misprimes_to_seqs(full):\n self.seqs['Toehold'].append(toe)\n self.seqs['Full'].append(full)\n\ndef get_seqs(cfg):\n num_seqs = int(cfg.get('Params','num_seqs'))\n num_iters = int(cfg.get('Params','num_iters'))\n primers = primer_set(cfg)\n for i in range(num_iters):\n primers.evolve_new_seq()\n if len(primers.seqs['Full']) >= num_seqs:\n return(primers)\n if len(primers.seqs['Full']) < num_seqs:\n raise Exception(str(num_seqs) + ' primers desired, but ' + str(len(primers.seqs)) + ' found.')\n return(primers)\n\nif __name__ == '__main__':\n cfg = ConfigParser.RawConfigParser(allow_no_value=True); cfg.optionxform=str\n cfg.read(sys.argv[1])\n primers = get_seqs(cfg)\n for (toe, full) in zip(primers.seqs['Toehold'], primers.seqs['Full']):\n print('Full: ' + str(full))\n print('Toe: ' + str(toe))\n print('T_melt (toe): ' + str(primers.melting_temp(toe)))\n print('T_melt (full): ' + str(primers.melting_temp(full)))\n t_ann = float(cfg.get('Params','toe_anneal'))\n worst_seq = ''\n worst_t = -1000.\n for q in primers.seqs['Full']:\n if q != full:\n new_t = primers.get_misprime_tm(full, q, t_ann)\n if new_t > worst_t:\n worst_t = new_t; worst_seq = q\n\n print('T_misprime (max): ' + str(worst_t))\n print('Worst misprime sequence: ' + str(worst_seq))\n print('Sequences generated: ' + str(len(primers.seqs['Full'])))\n df_out = pd.DataFrame(primers.seqs)\n df_out.to_csv(os.path.expanduser(cfg.get('Files','out_fn')), index = False)\n", "meta": {"hexsha": "ba0d5c063ae5b09532c41eae7f689995e669e638", "size": 7620, "ext": "py", "lang": "Python", "max_stars_repo_path": "oligo_design/primer_gen.py", "max_stars_repo_name": "smolkelab/promoter_design", "max_stars_repo_head_hexsha": "c3a04bd7cabc52a04b21adc1d2629925e554bad7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-09-04T21:56:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T22:05:08.000Z", "max_issues_repo_path": "oligo_design/primer_gen.py", "max_issues_repo_name": "smolkelab/promoter_design", "max_issues_repo_head_hexsha": "c3a04bd7cabc52a04b21adc1d2629925e554bad7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-12-16T22:08:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T00:26:07.000Z", "max_forks_repo_path": "oligo_design/primer_gen.py", "max_forks_repo_name": "smolkelab/promoter_design", "max_forks_repo_head_hexsha": "c3a04bd7cabc52a04b21adc1d2629925e554bad7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-09-04T21:56:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T02:00:25.000Z", "avg_line_length": 40.1052631579, "max_line_length": 147, "alphanum_fraction": 0.6583989501, "include": true, "reason": "import numpy", "num_tokens": 2167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.2658804614657029, "lm_q1q2_score": 0.14123819332752116}} {"text": "# coding: utf-8\n#\n# Project: Azimuthal integration\n# https://github.com/silx-kit/pyFAI\n#\n# Copyright (C) 2015-2021 European Synchrotron Radiation Facility, Grenoble, France\n# Copyright (C) 2016 Synchrotron SOLEIL - L'Orme des Merisiers Saint-Aubin\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\"\"\"Module for treating simultaneously multiple detector configuration\nwithin a single integration\"\"\"\n\n__author__ = \"Jérôme Kieffer\"\n__contact__ = \"Jerome.Kieffer@ESRF.eu\"\n__license__ = \"MIT\"\n__copyright__ = \"European Synchrotron Radiation Facility, Grenoble, France\"\n__date__ = \"19/01/2021\"\n__status__ = \"stable\"\n__docformat__ = 'restructuredtext'\n\nimport collections\nimport logging\nlogger = logging.getLogger(__name__)\nfrom .azimuthalIntegrator import AzimuthalIntegrator\nfrom .containers import Integrate1dResult\nfrom .containers import Integrate2dResult\nfrom . import units\nimport threading\nimport numpy\nfrom .method_registry import IntegrationMethod\nerror = None\n\n\nclass MultiGeometry(object):\n \"\"\"This is an Azimuthal integrator containing multiple geometries,\n for example when the detector is on a goniometer arm\n \"\"\"\n\n def __init__(self, ais, unit=\"2th_deg\",\n radial_range=(0, 180), azimuth_range=(-180, 180),\n wavelength=None, empty=0.0, chi_disc=180):\n \"\"\"\n Constructor of the multi-geometry integrator\n :param ais: list of azimuthal integrators\n :param radial_range: common range for integration\n :param azimuthal_range: common range for integration\n :param empty: value for empty pixels\n :param chi_disc: if 0, set the chi_discontinuity at\n \"\"\"\n self._sem = threading.Semaphore()\n self.abolute_solid_angle = None\n self.ais = [ai if isinstance(ai, AzimuthalIntegrator)\n else AzimuthalIntegrator.sload(ai)\n for ai in ais]\n self.wavelength = None\n if wavelength:\n self.set_wavelength(wavelength)\n self.radial_range = tuple(radial_range[:2])\n self.azimuth_range = tuple(azimuth_range[:2])\n self.unit = units.to_unit(unit)\n self.abolute_solid_angle = None\n self.empty = empty\n if chi_disc == 0:\n for ai in self.ais:\n ai.setChiDiscAtZero()\n elif chi_disc == 180:\n for ai in self.ais:\n ai.setChiDiscAtPi()\n else:\n logger.warning(\"Unable to set the Chi discontinuity at %s\", chi_disc)\n\n def __repr__(self, *args, **kwargs):\n return \"MultiGeometry integrator with %s geometries on %s radial range (%s) and %s azimuthal range (deg)\" % \\\n (len(self.ais), self.radial_range, self.unit, self.azimuth_range)\n\n def integrate1d(self, lst_data, npt=1800,\n correctSolidAngle=True,\n lst_variance=None, error_model=None,\n polarization_factor=None,\n normalization_factor=None,\n lst_mask=None, lst_flat=None,\n method=\"splitpixel\"):\n \"\"\"Perform 1D azimuthal integration\n\n :param lst_data: list of numpy array\n :param npt: number of points int the integration\n :param correctSolidAngle: correct for solid angle (all processing are then done in absolute solid angle !)\n :param lst_variance: list of array containing the variance of the data. If not available, no error propagation is done\n :type lst_variance: list of ndarray\n :param error_model: When the variance is unknown, an error model can be given: \"poisson\" (variance = I), \"azimuthal\" (variance = (I-)^2)\n :type error_model: str\n :param polarization_factor: Apply polarization correction ? is None: not applies. Else provide a value from -1 to +1\n :param normalization_factor: normalization monitors value (list of floats)\n :param all: return a dict with all information in it (deprecated, please refer to the documentation of Integrate1dResult).\n :param lst_mask: numpy.Array or list of numpy.array which mask the lst_data.\n :param lst_flat: numpy.Array or list of numpy.array which flat the lst_data.\n :param method: integration method, a string or a registered method\n :return: 2th/I or a dict with everything depending on \"all\"\n :rtype: Integrate1dResult, dict\n \"\"\"\n method = IntegrationMethod.select_one_available(method, dim=1)\n\n if len(lst_data) == 0:\n raise RuntimeError(\"List of images cannot be empty\")\n if normalization_factor is None:\n normalization_factor = [1.0] * len(self.ais)\n elif not isinstance(normalization_factor, collections.Iterable):\n normalization_factor = [normalization_factor] * len(self.ais)\n if lst_variance is None:\n lst_variance = [None] * len(self.ais)\n if lst_mask is None:\n lst_mask = [None] * len(self.ais)\n elif isinstance(lst_mask, numpy.ndarray):\n lst_mask = [lst_mask] * len(self.ais)\n if lst_flat is None:\n lst_flat = [None] * len(self.ais)\n elif isinstance(lst_flat, numpy.ndarray):\n lst_flat = [lst_flat] * len(self.ais)\n signal = numpy.zeros(npt, dtype=numpy.float64)\n normalization = numpy.zeros_like(signal)\n count = numpy.zeros_like(signal)\n variance = None\n for ai, data, monitor, var, mask, flat in zip(self.ais, lst_data, normalization_factor, lst_variance, lst_mask, lst_flat):\n res = ai.integrate1d_ng(data, npt=npt,\n correctSolidAngle=correctSolidAngle,\n variance=var, error_model=error_model,\n polarization_factor=polarization_factor,\n radial_range=self.radial_range,\n azimuth_range=self.azimuth_range,\n method=method, unit=self.unit, safe=True,\n mask=mask, flat=flat, normalization_factor=monitor)\n sac = (ai.pixel1 * ai.pixel2 / ai.dist ** 2) if correctSolidAngle else 1.0\n count += res.count\n normalization += res.sum_normalization * sac\n signal += res.sum_signal\n if res.sigma is not None:\n if variance is None:\n variance = res.sum_variance.astype(dtype=numpy.float64) # explicit copy\n else:\n variance += res.sum_variance\n\n tiny = numpy.finfo(\"float32\").tiny\n norm = numpy.maximum(normalization, tiny)\n invalid = count <= 0.0\n I = signal / norm\n I[invalid] = self.empty\n\n if variance is not None:\n sigma = numpy.sqrt(variance) / norm\n sigma[invalid] = self.empty\n result = Integrate1dResult(res.radial, I, sigma)\n else:\n result = Integrate1dResult(res.radial, I)\n result._set_compute_engine(res.compute_engine)\n result._set_unit(self.unit)\n result._set_sum_signal(signal)\n result._set_sum_normalization(normalization)\n result._set_sum_variance(variance)\n result._set_count(count)\n return result\n\n def integrate2d(self, lst_data, npt_rad=1800, npt_azim=3600,\n correctSolidAngle=True,\n lst_variance=None, error_model=None,\n polarization_factor=None,\n normalization_factor=None, lst_mask=None,\n lst_flat=None, method=\"splitpixel\"):\n \"\"\"Performs 2D azimuthal integration of multiples frames, one for each geometry\n\n :param lst_data: list of numpy array\n :param npt: number of points int the integration\n :param correctSolidAngle: correct for solid angle (all processing are then done in absolute solid angle !)\n :param lst_variance: list of array containing the variance of the data. If not available, no error propagation is done\n :type lst_variance: list of ndarray\n :param error_model: When the variance is unknown, an error model can be given: \"poisson\" (variance = I), \"azimuthal\" (variance = (I-)^2)\n :type error_model: str\n :param polarization_factor: Apply polarization correction ? is None: not applies. Else provide a value from -1 to +1\n :param normalization_factor: normalization monitors value (list of floats)\n :param all: return a dict with all information in it (deprecated, please refer to the documentation of Integrate2dResult).\n :param lst_mask: numpy.Array or list of numpy.array which mask the lst_data.\n :param lst_flat: numpy.Array or list of numpy.array which flat the lst_data.\n :param method: integration method (or its name)\n :return: I/2th/chi or a dict with everything depending on \"all\"\n :rtype: Integrate2dResult, dict\n \"\"\"\n if len(lst_data) == 0:\n raise RuntimeError(\"List of images cannot be empty\")\n if normalization_factor is None:\n normalization_factor = [1.0] * len(self.ais)\n elif not isinstance(normalization_factor, collections.Iterable):\n normalization_factor = [normalization_factor] * len(self.ais)\n if lst_variance is None:\n lst_variance = [None] * len(self.ais)\n if lst_mask is None:\n lst_mask = [None] * len(self.ais)\n elif isinstance(lst_mask, numpy.ndarray):\n lst_mask = [lst_mask] * len(self.ais)\n if lst_flat is None:\n lst_flat = [None] * len(self.ais)\n elif isinstance(lst_flat, numpy.ndarray):\n lst_flat = [lst_flat] * len(self.ais)\n\n method = IntegrationMethod.select_one_available(method, dim=2)\n\n signal = numpy.zeros((npt_azim, npt_rad), dtype=numpy.float64)\n count = numpy.zeros_like(signal)\n normalization = numpy.zeros_like(signal)\n variance = None\n\n for ai, data, monitor, var, mask, flat in zip(self.ais, lst_data, normalization_factor, lst_variance, lst_mask, lst_flat):\n res = ai.integrate2d_ng(data, npt_rad=npt_rad, npt_azim=npt_azim,\n correctSolidAngle=correctSolidAngle,\n variance=var, error_model=error_model,\n polarization_factor=polarization_factor,\n radial_range=self.radial_range,\n azimuth_range=self.azimuth_range,\n method=method, unit=self.unit, safe=True,\n mask=mask, flat=flat, normalization_factor=monitor)\n sac = (ai.pixel1 * ai.pixel2 / ai.dist ** 2) if correctSolidAngle else 1.0\n count += res.count\n signal += res.sum_signal\n normalization += res.sum_normalization * sac\n if var is not None:\n if variance is None:\n variance = res.sum_variance.astype(numpy.float64) # explicit copy !\n else:\n variance += res.sum_variance\n\n tiny = numpy.finfo(\"float32\").tiny\n norm = numpy.maximum(normalization, tiny)\n invalid = count <= 0\n I = signal / norm\n I[invalid] = self.empty\n\n if variance is not None:\n sigma = numpy.sqrt(variance) / norm\n sigma[invalid] = self.empty\n result = Integrate2dResult(I, res.radial, res.azimuthal, sigma)\n else:\n result = Integrate2dResult(I, res.radial, res.azimuthal)\n result._set_sum(signal)\n result._set_compute_engine(res.compute_engine)\n result._set_unit(self.unit)\n result._set_sum_signal(signal)\n result._set_sum_normalization(normalization)\n result._set_sum_variance(variance)\n result._set_count(count)\n return result\n\n def set_wavelength(self, value):\n \"\"\"\n Changes the wavelength of a group of azimuthal integrators\n \"\"\"\n self.wavelength = float(value)\n for ai in self.ais:\n ai.set_wavelength(self.wavelength)\n", "meta": {"hexsha": "493acc02d54a5c47f6c147f524992ded6b2becde", "size": 13210, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyFAI/multi_geometry.py", "max_stars_repo_name": "tacaswell/pyFAI", "max_stars_repo_head_hexsha": "fd63c7d9ba35e687ef5c4ec717c01bf46564572a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45, "max_stars_repo_stars_event_min_datetime": "2016-07-16T19:43:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T16:53:47.000Z", "max_issues_repo_path": "pyFAI/multi_geometry.py", "max_issues_repo_name": "tacaswell/pyFAI", "max_issues_repo_head_hexsha": "fd63c7d9ba35e687ef5c4ec717c01bf46564572a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1125, "max_issues_repo_issues_event_min_datetime": "2016-06-09T07:47:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:34:00.000Z", "max_forks_repo_path": "pyFAI/multi_geometry.py", "max_forks_repo_name": "tacaswell/pyFAI", "max_forks_repo_head_hexsha": "fd63c7d9ba35e687ef5c4ec717c01bf46564572a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 52, "max_forks_repo_forks_event_min_datetime": "2016-06-09T07:30:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T08:25:11.000Z", "avg_line_length": 48.2116788321, "max_line_length": 147, "alphanum_fraction": 0.6370174111, "include": true, "reason": "import numpy", "num_tokens": 2914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.25091278688527247, "lm_q1q2_score": 0.14105727255866643}} {"text": "\"\"\"\nImplementation of BIMODAL to generate SMILES\n\"\"\"\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom bidir_lstm import BiDirLSTM\n\ntorch.manual_seed(1)\nnp.random.seed(5)\n\n\nclass BIMODAL():\n\n def __init__(self, molecule_size=7, encoding_dim=55, lr=.01, hidden_units=128):\n\n self._molecule_size = molecule_size\n self._input_dim = encoding_dim\n self._output_dim = encoding_dim\n self._layer = 2\n self._hidden_units = hidden_units\n\n # Learning rate\n self._lr = lr\n\n # Build new model\n self._lstm = BiDirLSTM(self._input_dim, self._hidden_units, self._layer)\n\n # Check availability of GPUs\n self._gpu = torch.cuda.is_available()\n self._device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n if torch.cuda.is_available():\n self._lstm = self._lstm.cuda()\n print('GPU available')\n\n # Adam optimizer\n self._optimizer = torch.optim.Adam(self._lstm.parameters(), lr=self._lr, betas=(0.9, 0.999))\n # Cross entropy loss\n self._loss = nn.CrossEntropyLoss(reduction='mean')\n\n def build(self, name=None):\n \"\"\"Build new model or load model by name\n :param name: model name\n \"\"\"\n\n if (name is None):\n self._lstm = BiDirLSTM(self._input_dim, self._hidden_units, self._layer)\n\n else:\n self._lstm = torch.load(name + '.dat', map_location=self._device)\n\n if torch.cuda.is_available():\n self._lstm = self._lstm.cuda()\n\n self._optimizer = torch.optim.Adam(self._lstm.parameters(), lr=self._lr, betas=(0.9, 0.999))\n\n def print_model(self):\n '''Print name and shape of all tensors'''\n for name, p in self._lstm.state_dict().items():\n print(name)\n print(p.shape)\n\n def train(self, data, label, epochs=1, batch_size=1):\n '''Train the model\n :param data: data array (n_samples, molecule_size, encoding_length)\n :param label: label array (n_samples, molecule_size)\n :param epochs: number of epochs for the training\n :param batch_size: batch size for the training\n :return statistic: array storing computed losses (epochs, batch size)\n '''\n\n # Number of samples\n n_samples = data.shape[0]\n\n # Change axes from (n_samples, molecule_size, encoding_dim) to (molecule_size, n_samples, encoding_dim)\n data = np.swapaxes(data, 0, 1)\n\n # Create tensor from label\n label = torch.from_numpy(label).to(self._device, dtype=torch.long)\n\n # Calculate number of batches per epoch\n if (n_samples % batch_size) is 0:\n n_iter = n_samples // batch_size\n else:\n n_iter = n_samples // batch_size + 1\n\n # To store losses\n statistic = np.zeros((epochs, n_iter))\n\n # Prepare model for training\n self._lstm.train()\n\n # Iteration over epochs\n for i in range(epochs):\n\n # Iteration over batches\n for n in range(n_iter):\n\n # Set gradient to zero for batch\n self._optimizer.zero_grad()\n\n # Store losses in list\n losses = []\n\n # Compute indices used as batch\n batch_start = n * batch_size\n batch_end = min((n + 1) * batch_size, n_samples)\n\n # Reset model with correct batch size\n self._lstm.new_sequence(batch_end - batch_start, self._device)\n\n # Current batch\n batch_data = torch.from_numpy(data[:, batch_start:batch_end, :].astype('float32')).to(self._device)\n\n # Initialize start and end position of sequence read by the model\n start = self._molecule_size // 2\n end = start + 1\n\n for j in range(self._molecule_size - 1):\n self._lstm.new_sequence(batch_end - batch_start, self._device)\n\n # Select direction for next prediction\n if j % 2 == 0:\n dir = 'right'\n else:\n dir = 'left'\n\n # Predict next token\n pred = self._lstm(batch_data[start:end], dir, self._device)\n\n # Compute loss and extend sequence read by the model\n if j % 2 == 0:\n loss = self._loss(pred, label[batch_start:batch_end, end])\n end += 1\n\n else:\n loss = self._loss(pred, label[batch_start:batch_end, start - 1])\n start -= 1\n\n # Append loss of current position\n losses.append(loss.item())\n\n # Accumulate gradients\n # (NOTE: This is more memory-efficient than summing the loss and computing the final gradient for the sum)\n loss.backward()\n\n # Store statistics: loss per token (middle token not included)\n statistic[i, n] = np.sum(losses) / (self._molecule_size - 1)\n\n # Perform optimization step\n self._optimizer.step()\n\n return statistic\n\n def validate(self, data, label, batch_size=128):\n ''' Validation of model and compute error\n :param data: test data (n_samples, molecule_size, encoding_size)\n :param label: label data (n_samples_molecules_size)\n :param batch_size: batch size for validation\n :return: mean loss over test data\n '''\n\n # Use train mode to get loss consistent with training\n self._lstm.train()\n\n # Gradient is not computed to reduce memory requirements\n with torch.no_grad():\n # Compute tensor of labels\n label = torch.from_numpy(label).to(self._device, dtype=torch.long)\n\n # Number of samples\n n_samples = data.shape[0]\n\n # Change axes from (n_samples, molecule_size, encoding_dim) to (molecule_size , n_samples, encoding_dim)\n data = np.swapaxes(data, 0, 1).astype('float32')\n\n # Initialize loss for complete validation set\n tot_loss = 0\n\n # Calculate number of batches per epoch\n if (n_samples % batch_size) is 0:\n n_iter = n_samples // batch_size\n else:\n n_iter = n_samples // batch_size + 1\n\n for n in range(n_iter):\n\n # Compute indices used as batch\n batch_start = n * batch_size\n batch_end = min((n + 1) * batch_size, n_samples)\n\n # Data used in this batch\n batch_data = torch.from_numpy(data[:, batch_start:batch_end, :].astype('float32')).to(self._device)\n\n # Initialize loss for molecule\n molecule_loss = 0\n\n # Reset model with correct batch size and device\n self._lstm.new_sequence(batch_end - batch_start, self._device)\n\n start = self._molecule_size // 2\n end = start + 1\n\n for j in range(self._molecule_size - 1):\n self._lstm.new_sequence(batch_end - batch_start, self._device)\n\n # Select direction for next prediction\n if j % 2 == 0:\n dir = 'right'\n if j % 2 == 1:\n dir = 'left'\n\n # Predict next token\n pred = self._lstm(batch_data[start:end], dir, self._device)\n\n # Extend reading of the sequence\n if j % 2 == 0:\n loss = self._loss(pred, label[batch_start:batch_end, end])\n end += 1\n\n if j % 2 == 1:\n loss = self._loss(pred, label[batch_start:batch_end, start - 1])\n start -= 1\n # Sum loss over molecule\n molecule_loss += loss.item()\n\n # Add loss per token to total loss (start token and end token not counted)\n tot_loss += molecule_loss / (self._molecule_size - 1)\n\n return tot_loss / n_iter\n\n def sample(self, middle_token, T=1):\n '''Generate new molecule\n :param middle_token: starting sequence\n :param T: sampling temperature\n :return molecule: newly generated molecule (molecule_length, encoding_length)\n '''\n\n # Prepare model\n self._lstm.eval()\n\n # Gradient is not compute to reduce memory requirements\n with torch.no_grad():\n # Output array with merged forward and backward directions\n\n # New sequence\n seq = np.zeros((self._molecule_size, 1, self._output_dim))\n seq[self._molecule_size // 2, 0] = middle_token\n\n # Create tensor for data and select correct device\n seq = torch.from_numpy(seq.astype('float32')).to(self._device)\n\n # Define start/end values for reading\n start = self._molecule_size // 2\n end = start + 1\n\n for j in range(self._molecule_size - 1):\n self._lstm.new_sequence(1, self._device)\n\n # Select direction for next prediction\n if j % 2 == 0:\n dir = 'right'\n if j % 2 == 1:\n dir = 'left'\n\n pred = self._lstm(seq[start:end], dir, self._device)\n\n # Compute new token\n token = self.sample_token(np.squeeze(pred.cpu().detach().numpy()), T)\n\n # Set new token within sequence\n if j % 2 == 0:\n seq[end, 0, token] = 1.0\n end += 1\n\n if j % 2 == 1:\n seq[start - 1, 0, token] = 1.0\n start -= 1\n\n return seq.cpu().numpy().reshape(1, self._molecule_size, self._output_dim)\n\n def sample_token(self, out, T=1.0):\n ''' Sample token\n :param out: output values from model\n :param T: sampling temperature\n :return: index of predicted token\n '''\n # Explicit conversion to float64 avoiding truncation errors\n out = out.astype('float64')\n\n # Compute probabilities with specific temperature\n out_T = out / T\n p = np.exp(out_T) / np.sum(np.exp(out_T))\n\n # Generate new token at random\n char = np.random.multinomial(1, p, size=1)\n return np.argmax(char)\n\n def save(self, name='test_model'):\n torch.save(self._lstm, name + '.dat')\n", "meta": {"hexsha": "9c82a9b54ff002b8744d2134a1d23236e3e8b74b", "size": 10675, "ext": "py", "lang": "Python", "max_stars_repo_path": "model/bimodal.py", "max_stars_repo_name": "ETHmodlab/de_novo_design_RNN", "max_stars_repo_head_hexsha": "622628317c2ee6545eea9643767216904a7d7415", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2022-01-02T12:49:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T17:10:48.000Z", "max_issues_repo_path": "model/bimodal.py", "max_issues_repo_name": "molML/de_novo_design_RNN", "max_issues_repo_head_hexsha": "e4e2dc1a791e0a7af92c8767cf6f12fb44f0f42c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model/bimodal.py", "max_forks_repo_name": "molML/de_novo_design_RNN", "max_forks_repo_head_hexsha": "e4e2dc1a791e0a7af92c8767cf6f12fb44f0f42c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-03-16T19:05:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-11T07:24:42.000Z", "avg_line_length": 35.3476821192, "max_line_length": 126, "alphanum_fraction": 0.5465105386, "include": true, "reason": "import numpy", "num_tokens": 2365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.2422056341953392, "lm_q1q2_score": 0.14079488021550002}} {"text": "# Copyright (c) 2009-2019 The Regents of the University of Michigan\n# This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.\n\n\nfrom hoomd import _hoomd\n#from hoomd.jit import _jit\nimport hoomd\nimport tempfile\nimport shutil\nimport subprocess\nimport os\n\nimport numpy as np\nfrom hoomd.swapmc import _swapmc as _plugin_patch\n#from hoomd.jit import patch\n\n#This python file faciltates the creation of relevant patch energies\n#we'll do shifted lennard jones and polydisperse's system for now\n#let's make different classes for different pair potentials. Of course, we'll let the user defined path energy to be available as well\nclass lj(object):\n R''' Define the patch energy of a lennard jones particle.\n\n Args:\n scaledr_cut (float): the scale of cutoff radius relative to particle center to center, beyond which all pair interactions are assumed 0.\n eps (float): uniform energetics\n llvm_ir_fname (str): File name of the llvm IR file to load.\n clang_exec (str): The Clang executable to use\n\n Patch energies define energetic interactions between pairs of shapes in :py:mod:`hpmc ` integrators.\n Shapes within a cutoff distance of *r_cut* are potentially interacting and the energy of interaction is a function\n the type and orientation of the particles and the vector pointing from the *i* particle to the *j* particle center.\n\n The :py:class:`user` patch energy takes C++ code, JIT compiles it at run time and executes the code natively\n in the MC loop at with full performance. It enables researchers to quickly and easily implement custom energetic\n interactions without the need to modify and recompile HOOMD.\n\n .. rubric:: C++ code\n\n Supply C++ code to the *code* argument and :py:class:`user` will compile the code and call it to evaluate\n patch energies. Compilation assumes that a recent ``clang`` installation is on your PATH. This is convenient\n when the energy evaluation is simple or needs to be modified in python. More complex code (i.e. code that\n requires auxiliary functions or initialization of static data arrays) should be compiled outside of HOOMD\n and provided via the *llvm_ir_file* input (see below).\n\n The text provided in *code* is the body of a function with the following signature:\n\n .. code::\n\n float eval(const vec3& r_ij,\n unsigned int type_i,\n const quat& q_i,\n float d_i,\n float charge_i,\n unsigned int type_j,\n const quat& q_j,\n float d_j,\n float charge_j)\n\n * ``vec3`` and ``quat`` are defined in HOOMDMath.h.\n * *r_ij* is a vector pointing from the center of particle *i* to the center of particle *j*.\n * *type_i* is the integer type of particle *i*\n * *q_i* is the quaternion orientation of particle *i*\n * *d_i* is the diameter of particle *i*\n * *charge_i* is the charge of particle *i*\n * *type_j* is the integer type of particle *j*\n * *q_j* is the quaternion orientation of particle *j*\n * *d_j* is the diameter of particle *j*\n * *charge_j* is the charge of particle *j*\n * Your code *must* return a value.\n * When \\|r_ij\\| is greater than *r_cut*, the energy *must* be 0. This *r_cut* is applied between\n the centers of the two particles: compute it accordingly based on the maximum range of the anisotropic\n interaction that you implement.\n\n Example:\n\n .. code-block:: python\n\n square_well = \"\"\"float rsq = dot(r_ij, r_ij);\n if (rsq < 1.21f)\n return -1.0f;\n else\n return 0.0f;\n \"\"\"\n patch = hoomd.jit.patch.user(mc=mc, r_cut=1.1, code=square_well)\n\n .. rubric:: LLVM IR code\n\n You can compile outside of HOOMD and provide a direct link\n to the LLVM IR file in *llvm_ir_file*. A compatible file contains an extern \"C\" eval function with this signature:\n\n .. code::\n\n float eval(const vec3& r_ij,\n unsigned int type_i,\n const quat& q_i,\n float d_i,\n float charge_i,\n unsigned int type_j,\n const quat& q_j,\n float d_j,\n float charge_j)\n\n ``vec3`` and ``quat`` are defined in HOOMDMath.h.\n\n Compile the file with clang: ``clang -O3 --std=c++11 -DHOOMD_LLVMJIT_BUILD -I /path/to/hoomd/include -S -emit-llvm code.cc`` to produce\n the LLVM IR in ``code.ll``.\n\n .. versionadded:: 2.3\n '''\n def __init__(self, mc, kT, scaledr_cut, eps, mode='shifted', llvm_ir_file=None, clang_exec=None):\n hoomd.util.print_status_line();\n #there is no need to write your own code. By definition, we're \n if (mode == 'truncated'):\n code = \"\"\"\n float rsq = dot(r_ij, r_ij);\n float sigma = 0.5*( d_i+d_j);\n float rcut = {}*sigma;\n if (rsq <= rcut*rcut)\n {{\n float eps = {};\n float sigmasq = sigma*sigma;\n float rsqinv = sigmasq / rsq;\n float r6inv = rsqinv*rsqinv*rsqinv;\n return 4.0f*eps*r6inv*(r6inv-1.0f);\n }}\n else\n {{\n return 0.0f;\n }}\n \"\"\".format(scaledr_cut,eps/kT);\n elif (mode == 'shifted'):\n code = \"\"\"\n float rsq = dot(r_ij, r_ij);\n float sigma = 0.5*( d_i+d_j);\n float rcut = {}*sigma;\n if (rsq <= rcut*rcut)\n {{\n float eps = {};\n float sigmasq = sigma*sigma;\n float rsqinv = sigmasq / rsq;\n float r6inv = rsqinv*rsqinv*rsqinv;\n \n float rsqinv_cut = sigmasq /(rcut*rcut);\n float r6inv_cut = rsqinv_cut*rsqinv_cut*rsqinv_cut;\n return 4.0f*eps*(r6inv*(r6inv-1.0f)-r6inv_cut*(r6inv_cut-1.0f));\n }}\n else\n {{\n return 0.0f;\n }}\n \"\"\".format(scaledr_cut,eps/kT);\n elif (mode == 'force-shift'):\n code = \"\"\"\n float rsq = dot(r_ij, r_ij);\n float sigma = 0.5*( d_i+d_j);\n float rcut = {}*sigma;\n if (rsq <= rcut*rcut)\n {{\n float eps = {};\n float sigmasq = sigma*sigma;\n float rsqinv = sigmasq / rsq;\n float r6inv = rsqinv*rsqinv*rsqinv;\n \n float rsqinv_cut = sigmasq /(rcut*rcut);\n float r6inv_cut = rsqinv_cut*rsqinv_cut*rsqinv_cut;\n return 4.0f*eps*( r6inv*(r6inv-1.0f)-r6inv_cut*(r6inv_cut-1.0f) +6*(sqrtf(rsq)/rcut-1.0f)*r6inv_cut*(2*r6inv_cut-1.0f) );\n }}\n else\n {{\n return 0.0f;\n }}\n \"\"\".format(scaledr_cut,eps/kT);\n # check if initialization has occurred\n if hoomd.context.exec_conf is None:\n raise RuntimeError('Error creating Lennard-Jones patch energy, call context.initialize() first');\n\n # raise an error if this run is on the GPU\n if hoomd.context.exec_conf.isCUDAEnabled():\n hoomd.context.msg.error(\"Patch energies are not supported on the GPU\\n\");\n raise RuntimeError(\"Error initializing patch energy\");\n\n # Find a clang executable if none is provided\n if clang_exec is not None:\n clang = clang_exec;\n else:\n clang = 'clang'\n\n if code is not None and llvm_ir_file is None:\n llvm_ir = self.compile_user(code, clang)\n else:\n # IR is a text file\n with open(llvm_ir_file,'r') as f:\n llvm_ir = f.read()\n\n self.compute_name = \"patch\"\n self.cpp_evaluator = _plugin_patch.PatchEnergyJITCustom(hoomd.context.exec_conf, llvm_ir, scaledr_cut);\n mc.set_PatchEnergyEvaluator(self);\n\n self.mc = mc\n self.enabled = True\n self.log = False\n\n def compile_user(self, code, clang_exec, fn=None):\n R'''Helper function to compile the provided code into an executable\n\n Args:\n code (str): C++ code to compile\n clang_exec (str): The Clang executable to use\n fn (str): If provided, the code will be written to a file.\n\n\n .. versionadded:: 2.3\n '''\n cpp_function = \"\"\"\n#include \"hoomd/HOOMDMath.h\"\n#include \"hoomd/VectorMath.h\"\n\nextern \"C\"\n{\nfloat eval(const vec3& r_ij,\n unsigned int type_i,\n const quat& q_i,\n float d_i,\n float charge_i,\n unsigned int type_j,\n const quat& q_j,\n float d_j,\n float charge_j)\n {\n\"\"\"\n cpp_function += code\n cpp_function += \"\"\"\n }\n}\n\"\"\"\n\n include_path = os.path.dirname(hoomd.__file__) + '/include';\n include_path_source = hoomd._hoomd.__hoomd_source_dir__;\n\n if clang_exec is not None:\n clang = clang_exec;\n else:\n clang = 'clang';\n\n if fn is not None:\n cmd = [clang, '-O3', '--std=c++11', '-DHOOMD_LLVMJIT_BUILD', '-I', include_path, '-I', include_path_source, '-S', '-emit-llvm','-x','c++', '-o',fn,'-']\n else:\n cmd = [clang, '-O3', '--std=c++11', '-DHOOMD_LLVMJIT_BUILD', '-I', include_path, '-I', include_path_source, '-S', '-emit-llvm','-x','c++', '-o','-','-']\n p = subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)\n\n # pass C++ function to stdin\n output = p.communicate(cpp_function.encode('utf-8'))\n llvm_ir = output[0].decode()\n\n f = open(\"llvm_ir_file\",'w')\n f.write(llvm_ir)\n f.close()\n \n if p.returncode != 0:\n hoomd.context.msg.error(\"Error compiling provided code\\n\");\n hoomd.context.msg.error(\"Command \"+' '.join(cmd)+\"\\n\");\n hoomd.context.msg.error(output[1].decode()+\"\\n\");\n raise RuntimeError(\"Error initializing patch energy\");\n\n return llvm_ir\n\n R''' Disable the patch energy and optionally enable it only for logging\n\n Args:\n log (bool): If true, only use patch energy as a log quantity\n\n '''\n def disable(self,log=None):\n hoomd.util.print_status_line();\n\n if log:\n # enable only for logging purposes\n self.mc.cpp_integrator.disablePatchEnergyLogOnly(log)\n self.log = True\n else:\n # disable completely\n self.mc.cpp_integrator.setPatchEnergy(None);\n self.log = False\n\n self.enabled = False\n\n R''' (Re-)Enable the patch energy\n\n '''\n def enable(self):\n hoomd.util.print_status_line()\n self.mc.cpp_integrator.setPatchEnergy(self.cpp_evaluator);\n\nclass softrepulsive(object):\n R''' Define the patch energy of a soft-repulsive particle.\n '''\n def __init__(self, mc, kT, scaledr_cut, eps, mode='shifted', llvm_ir_file=None, clang_exec=None):\n hoomd.util.print_status_line();\n #there is no need to write your own code. By definition, we're \n if (mode == 'truncated'):\n code = \"\"\"\n float rsq = dot(r_ij, r_ij);\n float sigma = 0.5*( d_i+d_j);\n float rcut = {}*sigma;\n if (rsq <= rcut*rcut)\n {{\n float eps = {};\n float sigmasq = sigma*sigma;\n float rsqinv = sigmasq / rsq;\n float r6inv = rsqinv*rsqinv*rsqinv;\n return 4.0f*eps*r6inv*r6inv;\n }}\n else\n {{\n return 0.0f;\n }}\n \"\"\".format(scaledr_cut,eps/kT);\n elif (mode == 'shifted'):\n code = \"\"\"\n float rsq = dot(r_ij, r_ij);\n float sigma = 0.5*( d_i+d_j);\n float rcut = {}*sigma;\n if (rsq <= rcut*rcut)\n {{\n float eps = {};\n float sigmasq = sigma*sigma;\n float rsqinv = sigmasq / rsq;\n float r6inv = rsqinv*rsqinv*rsqinv;\n \n float rsqinv_cut = sigmasq /(rcut*rcut);\n float r6inv_cut = rsqinv_cut*rsqinv_cut*rsqinv_cut;\n return 4.0f*eps*(r6inv*r6inv-r6inv_cut*r6inv_cut);\n }}\n else\n {{\n return 0.0f;\n }}\n \"\"\".format(scaledr_cut,eps/kT);\n elif (mode == 'force-shift'):\n code = \"\"\"\n float rsq = dot(r_ij, r_ij);\n float sigma = 0.5*( d_i+d_j);\n float rcut = {}*sigma;\n if (rsq <= rcut*rcut)\n {{\n float eps = {};\n float sigmasq = sigma*sigma;\n float rsqinv = sigmasq / rsq;\n float r6inv = rsqinv*rsqinv*rsqinv;\n \n float rsqinv_cut = sigmasq /(rcut*rcut);\n float r6inv_cut = rsqinv_cut*rsqinv_cut*rsqinv_cut;\n return 4.0f*eps*( r6inv*(r6inv)-r6inv_cut*(r6inv_cut) +6*(sqrtf(rsq)/rcut-1.0f)*r6inv_cut*(2*r6inv_cut) );\n }}\n else\n {{\n return 0.0f;\n }}\n \"\"\".format(scaledr_cut,eps/kT);\n # check if initialization has occurred\n if hoomd.context.exec_conf is None:\n raise RuntimeError('Error creating Lennard-Jones patch energy, call context.initialize() first');\n\n # raise an error if this run is on the GPU\n if hoomd.context.exec_conf.isCUDAEnabled():\n hoomd.context.msg.error(\"Patch energies are not supported on the GPU\\n\");\n raise RuntimeError(\"Error initializing patch energy\");\n\n # Find a clang executable if none is provided\n if clang_exec is not None:\n clang = clang_exec;\n else:\n clang = 'clang'\n\n if code is not None and llvm_ir_file is None:\n llvm_ir = self.compile_user(code, clang)\n else:\n # IR is a text file\n with open(llvm_ir_file,'r') as f:\n llvm_ir = f.read()\n\n \n self.compute_name = \"patch\"\n self.cpp_evaluator = _plugin_patch.PatchEnergyJITCustom(hoomd.context.exec_conf, llvm_ir, scaledr_cut);\n mc.set_PatchEnergyEvaluator(self);\n\n self.mc = mc\n self.enabled = True\n self.log = False\n\n def compile_user(self, code, clang_exec, fn=None):\n R'''Helper function to compile the provided code into an executable\n\n Args:\n code (str): C++ code to compile\n clang_exec (str): The Clang executable to use\n fn (str): If provided, the code will be written to a file.\n\n\n .. versionadded:: 2.3\n '''\n cpp_function = \"\"\"\n#include \"hoomd/HOOMDMath.h\"\n#include \"hoomd/VectorMath.h\"\n\nextern \"C\"\n{\nfloat eval(const vec3& r_ij,\n unsigned int type_i,\n const quat& q_i,\n float d_i,\n float charge_i,\n unsigned int type_j,\n const quat& q_j,\n float d_j,\n float charge_j)\n {\n\"\"\"\n cpp_function += code\n cpp_function += \"\"\"\n }\n}\n\"\"\"\n\n include_path = os.path.dirname(hoomd.__file__) + '/include';\n include_path_source = hoomd._hoomd.__hoomd_source_dir__;\n\n if clang_exec is not None:\n clang = clang_exec;\n else:\n clang = 'clang';\n\n if fn is not None:\n cmd = [clang, '-O3', '--std=c++11', '-DHOOMD_LLVMJIT_BUILD', '-I', include_path, '-I', include_path_source, '-S', '-emit-llvm','-x','c++', '-o',fn,'-']\n else:\n cmd = [clang, '-O3', '--std=c++11', '-DHOOMD_LLVMJIT_BUILD', '-I', include_path, '-I', include_path_source, '-S', '-emit-llvm','-x','c++', '-o','-','-']\n p = subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)\n\n # pass C++ function to stdin\n output = p.communicate(cpp_function.encode('utf-8'))\n llvm_ir = output[0].decode()\n\n f = open(\"llvm_ir_file\",'w')\n f.write(llvm_ir)\n f.close()\n \n if p.returncode != 0:\n hoomd.context.msg.error(\"Error compiling provided code\\n\");\n hoomd.context.msg.error(\"Command \"+' '.join(cmd)+\"\\n\");\n hoomd.context.msg.error(output[1].decode()+\"\\n\");\n raise RuntimeError(\"Error initializing patch energy\");\n\n return llvm_ir\n\n R''' Disable the patch energy and optionally enable it only for logging\n\n Args:\n log (bool): If true, only use patch energy as a log quantity\n\n '''\n def disable(self,log=None):\n hoomd.util.print_status_line();\n\n if log:\n # enable only for logging purposes\n self.mc.cpp_integrator.disablePatchEnergyLogOnly(log)\n self.log = True\n else:\n # disable completely\n self.mc.cpp_integrator.setPatchEnergy(None);\n self.log = False\n\n self.enabled = False\n\n R''' (Re-)Enable the patch energy\n\n '''\n def enable(self):\n hoomd.util.print_status_line()\n self.mc.cpp_integrator.setPatchEnergy(self.cpp_evaluator);\n\nclass polydisperse(object):\n R''' Define the patch energy of a polydisperse soft-repulsive\n '''\n def __init__(self, mc, kT, scaledr_cut, v0, eps, model, llvm_ir_file=None, clang_exec=None,kappa=3.0):\n hoomd.util.print_status_line();\n\n if (model == \"polydisperse12\"):\n a = scaledr_cut\n A = np.array([ [1,a**2,a**4],\n [0,2*a,4*a**3],\n [0,2,12*a**2]\n ])\n b = np.array([-v0/a**12,12*v0/a**13,-156*v0/a**14])\n c = np.linalg.solve(A,b)\n code = \"\"\"\n float rsq = dot(r_ij, r_ij);\n float sigma = 0.5*( d_i+d_j)*(1-{}*fabs(d_i-d_j) );\n float rcut = {}*(sigma);\n if (rsq <= rcut*rcut)\n {{\n float v0 = {};\n float c0 = {};\n float c1 = {};\n float c2 = {};\n float sigmasq = sigma*sigma;\n float rsqinv = sigmasq / rsq;\n float _rsq = rsq / sigmasq;\n float r6inv = rsqinv*rsqinv*rsqinv;\n return v0*r6inv*r6inv+c0+c1*_rsq+c2*_rsq*_rsq;\n }}\n else\n {{\n return 0.0f;\n }}\n \"\"\".format(eps,scaledr_cut,v0/kT,c[0]/kT,c[1]/kT,c[2]/kT);\n elif (model == \"lennardjones\"):\n a = scaledr_cut\n A = np.array([ [1,a**2,a**4],\n [0,2*a,4*a**3],\n [0,2,12*a**2]\n ])\n b = np.array([-v0*(1/a**12-1/a**6),v0*(12*v0/a**13-6/a**7),-v0*(156/a**14-42/a**8)])\n c = np.linalg.solve(A,b)\n code = \"\"\"\n float rsq = dot(r_ij, r_ij);\n float sigma = 0.5*( d_i+d_j)*(1-{}*fabs(d_i-d_j) );\n float rcut = {}*(sigma);\n if (rsq <= rcut*rcut)\n {{\n float v0 = {};\n float c0 = {};\n float c1 = {};\n float c2 = {};\n float sigmasq = sigma*sigma;\n float rsqinv = sigmasq / rsq;\n float _rsq = rsq / sigmasq;\n float r6inv = rsqinv*rsqinv*rsqinv;\n return v0*(r6inv*r6inv-r6inv)+c0+c1*_rsq+c2*_rsq*_rsq;\n }}\n else\n {{\n return 0.0f;\n }}\n \"\"\".format(eps,scaledr_cut,v0/kT,c[0]/kT,c[1]/kT,c[2]/kT);\n elif (model == \"polydisperse18\"):\n a = scaledr_cut\n A = np.array([ [1,a**2,a**4],\n [0,2*a,4*a**3],\n [0,2,12*a**2]\n ])\n b = np.array([-v0*(1/a**18),(18*v0/a**19),-v0*(342/a**20)])\n c = np.linalg.solve(A,b)\n code = \"\"\"\n float rsq = dot(r_ij, r_ij);\n float sigma = 0.5*( d_i+d_j)*(1-{}*fabs(d_i-d_j) );\n float rcut = {}*(sigma);\n if (rsq <= rcut*rcut)\n {{\n float v0 = {};\n float c0 = {};\n float c1 = {};\n float c2 = {};\n float sigmasq = sigma*sigma;\n float rsqinv = sigmasq / rsq;\n float _rsq = rsq / sigmasq;\n float r6inv = rsqinv*rsqinv*rsqinv;\n return v0*(r6inv*r6inv*r6inv)+c0+c1*_rsq+c2*_rsq*_rsq;\n }}\n else\n {{\n return 0.0f;\n }}\n \"\"\".format(eps,scaledr_cut,v0/kT,c[0]/kT,c[1]/kT,c[2]/kT);\n elif (model == \"polydisperse10\"):\n a = scaledr_cut\n c0 = -(56.0)*v0/(a**10);\n c1 = (140.0)*v0/(a**12);\n c2 = -(120.0)*v0/(a**14);\n c3 = (35.0)*v0/(a**16);\n code = \"\"\"\n float rsq = dot(r_ij, r_ij);\n float sigma = 0.5*( d_i+d_j)*(1-{}*fabs(d_i-d_j) );\n float rcut = {}*(sigma);\n if (rsq <= rcut*rcut)\n {{\n float v0 = {};\n float c0 = {};\n float c1 = {};\n float c2 = {};\n float c3 = {};\n float sigmasq = sigma*sigma;\n float rsqinv = sigmasq / rsq;\n float _rsq = rsq / sigmasq;\n float r10inv = rsqinv*rsqinv*rsqinv*rsqinv*rsqinv;\n return v0*r10inv+c0+c1*_rsq+c2*_rsq*_rsq+c3*_rsq*_rsq*_rsq;\n }}\n else\n {{\n return 0.0f;\n }}\n \"\"\".format(eps,scaledr_cut,v0/kT,c0/kT,c1/kT,c2/kT,c3/kT);\n elif (model == \"polydisperse106\"):\n a = scaledr_cut\n c0 = (-21 + 10*a**4)*v0/a**10\n c1 = -((5*(-7 + 3*a**4)*v0)/a**12)\n c2 = (3*(-5 + 2*a**4)*v0)/a**14\n code = \"\"\"\n float rsq = dot(r_ij, r_ij);\n float sigma = 0.5*( d_i+d_j)*(1-{}*fabs(d_i-d_j) );\n float rcut = {}*(sigma);\n if (rsq <= rcut*rcut)\n {{\n float v0 = {};\n float c0 = {};\n float c1 = {};\n float c2 = {};\n float sigmasq = sigma*sigma;\n float rsqinv = sigmasq / rsq;\n float _rsq = rsq / sigmasq;\n float r10inv = rsqinv*rsqinv*rsqinv*rsqinv*rsqinv;\n return v0*(r10inv-rsqinv*rsqinv*rsqinv)+c0+c1*_rsq + c2*_rsq*_rsq;\n }}\n else\n {{\n return 0.0f;\n }}\n \"\"\".format(eps,scaledr_cut,v0/kT,c0/kT,c1/kT,c2/kT);\n elif (model == \"polydisperseyukawa\"):\n a = scaledr_cut\n c0 = -((np.exp(-kappa*a)*(15 + 7*kappa*a + kappa**2*a**2)*v0)/(8*a))\n c1 = (np.exp(-kappa*a)*(5 + 5*kappa*a + kappa**2*a**2)*v0)/(4*a**3)\n c2 = -((np.exp(-kappa*a)*(3 + 3*kappa*a + kappa**2*a**2)*v0)/(8*a**5))\n code = \"\"\"\n float rsq = dot(r_ij, r_ij);\n float sigma = 0.5*( d_i+d_j)*(1-{}*fabs(d_i-d_j) );\n float rcut = {}*(sigma);\n if (rsq <= rcut*rcut)\n {{\n float v0 = {};\n float kappa = {};\n float c0 = {};\n float c1 = {};\n float c2 = {};\n float sigmasq = sigma*sigma;\n float rsqinv = sigmasq / rsq;\n float rinv = sqrtf(rsqinv);\n float _rsq = rsq / sigmasq;\n float _r = sqrtf(_rsq);\n float r10inv = rsqinv*rsqinv*rsqinv*rsqinv*rsqinv;\n return v0*exp(-_r*kappa)*rinv+c0+c1*_rsq + c2*_rsq*_rsq;\n }}\n else\n {{\n return 0.0f;\n }}\n \"\"\".format(eps,scaledr_cut,v0/kT,kappa,c0/kT,c1/kT,c2/kT);\n else:\n raise RuntimeError('Error creating Polydisperse patch energy. Not one of the available models. Perhaps theres a typo?');\n\n # check if initialization has occurred\n if hoomd.context.exec_conf is None:\n raise RuntimeError('Error creating Lennard-Jones patch energy, call context.initialize() first');\n\n # raise an error if this run is on the GPU\n if hoomd.context.exec_conf.isCUDAEnabled():\n hoomd.context.msg.error(\"Patch energies are not supported on the GPU\\n\");\n raise RuntimeError(\"Error initializing patch energy\");\n\n # Find a clang executable if none is provided\n if clang_exec is not None:\n clang = clang_exec;\n else:\n clang = 'clang'\n\n if code is not None and llvm_ir_file is None:\n llvm_ir = self.compile_user(code, clang)\n else:\n # IR is a text file\n with open(llvm_ir_file,'r') as f:\n llvm_ir = f.read()\n\n self.compute_name = \"patch\"\n self.cpp_evaluator = _plugin_patch.PatchEnergyJITCustom(hoomd.context.exec_conf, llvm_ir, scaledr_cut);\n mc.set_PatchEnergyEvaluator(self);\n\n self.mc = mc\n self.enabled = True\n self.log = False\n\n def compile_user(self, code, clang_exec, fn=None):\n R'''Helper function to compile the provided code into an executable\n\n Args:\n code (str): C++ code to compile\n clang_exec (str): The Clang executable to use\n fn (str): If provided, the code will be written to a file.\n\n\n .. versionadded:: 2.3\n '''\n cpp_function = \"\"\"\n#include \"hoomd/HOOMDMath.h\"\n#include \"hoomd/VectorMath.h\"\n\nextern \"C\"\n{\nfloat eval(const vec3& r_ij,\n unsigned int type_i,\n const quat& q_i,\n float d_i,\n float charge_i,\n unsigned int type_j,\n const quat& q_j,\n float d_j,\n float charge_j)\n {\n\"\"\"\n cpp_function += code\n cpp_function += \"\"\"\n }\n}\n\"\"\"\n\n include_path = os.path.dirname(hoomd.__file__) + '/include';\n include_path_source = hoomd._hoomd.__hoomd_source_dir__;\n\n if clang_exec is not None:\n clang = clang_exec;\n else:\n clang = 'clang';\n\n if fn is not None:\n cmd = [clang, '-O3', '--std=c++11', '-DHOOMD_LLVMJIT_BUILD', '-I', include_path, '-I', include_path_source, '-S', '-emit-llvm','-x','c++', '-o',fn,'-']\n else:\n cmd = [clang, '-O3', '--std=c++11', '-DHOOMD_LLVMJIT_BUILD', '-I', include_path, '-I', include_path_source, '-S', '-emit-llvm','-x','c++', '-o','-','-']\n p = subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)\n\n # pass C++ function to stdin\n output = p.communicate(cpp_function.encode('utf-8'))\n llvm_ir = output[0].decode()\n \n f = open(\"llvm_ir_file\",'w')\n f.write(llvm_ir)\n f.close()\n\n if p.returncode != 0:\n hoomd.context.msg.error(\"Error compiling provided code\\n\");\n hoomd.context.msg.error(\"Command \"+' '.join(cmd)+\"\\n\");\n hoomd.context.msg.error(output[1].decode()+\"\\n\");\n raise RuntimeError(\"Error initializing patch energy\");\n\n return llvm_ir\n\n R''' Disable the patch energy and optionally enable it only for logging\n\n Args:\n log (bool): If true, only use patch energy as a log quantity\n\n '''\n def disable(self,log=None):\n hoomd.util.print_status_line();\n\n if log:\n # enable only for logging purposes\n self.mc.cpp_integrator.disablePatchEnergyLogOnly(log)\n self.log = True\n else:\n # disable completely\n self.mc.cpp_integrator.setPatchEnergy(None);\n self.log = False\n\n self.enabled = False\n\n R''' (Re-)Enable the patch energy\n\n '''\n def enable(self):\n hoomd.util.print_status_line()\n self.mc.cpp_integrator.setPatchEnergy(self.cpp_evaluator);\n", "meta": {"hexsha": "db3a0dd6eedd6231e47223bdfc809d5aa9d665b7", "size": 31912, "ext": "py", "lang": "Python", "max_stars_repo_path": "swapmc/patch.py", "max_stars_repo_name": "muhammadhasyim/parallel-swap-mc", "max_stars_repo_head_hexsha": "0a9ac017d9a7046d4285034a01ec4a4d9361d28d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "swapmc/patch.py", "max_issues_repo_name": "muhammadhasyim/parallel-swap-mc", "max_issues_repo_head_hexsha": "0a9ac017d9a7046d4285034a01ec4a4d9361d28d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "swapmc/patch.py", "max_forks_repo_name": "muhammadhasyim/parallel-swap-mc", "max_forks_repo_head_hexsha": "0a9ac017d9a7046d4285034a01ec4a4d9361d28d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.8604353393, "max_line_length": 164, "alphanum_fraction": 0.4629293056, "include": true, "reason": "import numpy", "num_tokens": 7397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.2751297238231752, "lm_q1q2_score": 0.14078844812798993}} {"text": "# -*- coding: utf-8 -*-\n\n# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is\n# holder of all proprietary rights on this computer program.\n# You can only use this computer program if you have closed\n# a license agreement with MPG or you get the right to use the computer\n# program from someone who is authorized to grant you that right.\n# Any use of the computer program without a valid license is prohibited and\n# liable to prosecution.\n#\n# Copyright©2019 Max-Planck-Gesellschaft zur Förderung\n# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute\n# for Intelligent Systems. All rights reserved.\n#\n# Contact: ps-license@tuebingen.mpg.de\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport numpy as np\nimport cv2\nimport time\n# from numba import jit\n# import numba\n\nimport torch\nimport torch.nn.functional as F\n\nfrom .utils import rot_mat_to_euler\n\ndef find_dynamic_lmk_idx_and_bcoords_projective(vertices, neck_joint_loc, pose, dynamic_lmk_faces_idx,\n dynamic_lmk_b_coords,\n neck_kin_chain, dtype=torch.float32):\n batch_size = vertices.shape[0]\n # print('pose shape len')\n # print(len(pose.shape))\n if len(pose.shape) == 2:\n aa_pose = torch.index_select(pose.view(batch_size, -1, 3), 1,\n neck_kin_chain)\n rot_mats = batch_rodrigues(\n aa_pose.view(-1, 3), dtype=dtype).view(batch_size, -1, 3, 3)\n else:\n rot_mats = torch.index_select(pose.view(batch_size, -1, 3, 3), 1,\n neck_kin_chain)\n\n b = rot_mats.shape[0]\n\n rel_rot_mat = torch.eye(3, device=vertices.device,\n dtype=dtype).reshape(1, 3, 3).repeat(b, 1, 1)\n for idx in range(len(neck_kin_chain)):\n rel_rot_mat = torch.bmm(rot_mats[:, idx], rel_rot_mat)\n neck_cam_loc = -torch.bmm(torch.transpose(rel_rot_mat, 1, 2), neck_joint_loc.reshape(-1, 3, 1)).reshape(-1, 3)\n neck_cam_loc_len = torch.norm(neck_cam_loc, dim=1).reshape(-1, 1).repeat(1, 3)\n neck_cam_dir = neck_cam_loc / neck_cam_loc_len\n y_ang = -torch.atan2(neck_cam_dir[:, 0], neck_cam_dir[:, 2])\n\n # print('neck cam dir')\n # print(neck_cam_dir)\n\n y_rot_angle = torch.round(\n torch.clamp(y_ang * 180.0 / np.pi,\n max=39)).to(dtype=torch.long)\n\n # print('face cam ang')\n # print(y_rot_angle)\n\n neg_mask = y_rot_angle.lt(0).to(dtype=torch.long)\n mask = y_rot_angle.lt(-39).to(dtype=torch.long)\n neg_vals = mask * 78 + (1 - mask) * (39 - y_rot_angle)\n y_rot_angle = (neg_mask * neg_vals +\n (1 - neg_mask) * y_rot_angle)\n dyn_lmk_faces_idx = torch.index_select(dynamic_lmk_faces_idx,\n 0, y_rot_angle)\n dyn_lmk_b_coords = torch.index_select(dynamic_lmk_b_coords,\n 0, y_rot_angle)\n\n return dyn_lmk_faces_idx, dyn_lmk_b_coords\n\n\ndef find_dynamic_lmk_idx_and_bcoords(vertices, pose, dynamic_lmk_faces_idx,\n dynamic_lmk_b_coords,\n neck_kin_chain, dtype=torch.float32):\n ''' Compute the faces, barycentric coordinates for the dynamic landmarks\n\n\n To do so, we first compute the rotation of the neck around the y-axis\n and then use a pre-computed look-up table to find the faces and the\n barycentric coordinates that will be used.\n\n Special thanks to Soubhik Sanyal (soubhik.sanyal@tuebingen.mpg.de)\n for providing the original TensorFlow implementation and for the LUT.\n\n Parameters\n ----------\n vertices: torch.tensor BxVx3, dtype = torch.float32\n The tensor of input vertices\n pose: torch.tensor Bx(Jx3), dtype = torch.float32\n The current pose of the body model\n dynamic_lmk_faces_idx: torch.tensor L, dtype = torch.long\n The look-up table from neck rotation to faces\n dynamic_lmk_b_coords: torch.tensor Lx3, dtype = torch.float32\n The look-up table from neck rotation to barycentric coordinates\n neck_kin_chain: list\n A python list that contains the indices of the joints that form the\n kinematic chain of the neck.\n dtype: torch.dtype, optional\n\n Returns\n -------\n dyn_lmk_faces_idx: torch.tensor, dtype = torch.long\n A tensor of size BxL that contains the indices of the faces that\n will be used to compute the current dynamic landmarks.\n dyn_lmk_b_coords: torch.tensor, dtype = torch.float32\n A tensor of size BxL that contains the indices of the faces that\n will be used to compute the current dynamic landmarks.\n '''\n\n batch_size = vertices.shape[0]\n\n if len(pose.shape) == 2:\n aa_pose = torch.index_select(pose.view(batch_size, -1, 3), 1,\n neck_kin_chain)\n rot_mats = batch_rodrigues(\n aa_pose.view(-1, 3), dtype=dtype).view(batch_size, -1, 3, 3)\n else:\n rot_mats = torch.index_select(pose.view(batch_size, -1, 3, 3), 1,\n neck_kin_chain)\n\n b = rot_mats.shape[0]\n\n rel_rot_mat = torch.eye(3, device=vertices.device,\n dtype=dtype).reshape(1, 3, 3).repeat(b, 1, 1)\n for idx in range(len(neck_kin_chain)):\n rel_rot_mat = torch.bmm(rot_mats[:, idx], rel_rot_mat)\n\n y_rot_angle = torch.round(\n torch.clamp(-rot_mat_to_euler(rel_rot_mat) * 180.0 / np.pi,\n max=39)).to(dtype=torch.long)\n neg_mask = y_rot_angle.lt(0).to(dtype=torch.long)\n mask = y_rot_angle.lt(-39).to(dtype=torch.long)\n neg_vals = mask * 78 + (1 - mask) * (39 - y_rot_angle)\n y_rot_angle = (neg_mask * neg_vals +\n (1 - neg_mask) * y_rot_angle)\n# print('std yrot ang')\n# print(y_rot_angle)\n\n dyn_lmk_faces_idx = torch.index_select(dynamic_lmk_faces_idx,\n 0, y_rot_angle)\n dyn_lmk_b_coords = torch.index_select(dynamic_lmk_b_coords,\n 0, y_rot_angle)\n\n return dyn_lmk_faces_idx, dyn_lmk_b_coords\n\n\ndef vertices2landmarks(vertices, faces, lmk_faces_idx, lmk_bary_coords):\n ''' Calculates landmarks by barycentric interpolation\n\n Parameters\n ----------\n vertices: torch.tensor BxVx3, dtype = torch.float32\n The tensor of input vertices\n faces: torch.tensor Fx3, dtype = torch.long\n The faces of the mesh\n lmk_faces_idx: torch.tensor L, dtype = torch.long\n The tensor with the indices of the faces used to calculate the\n landmarks.\n lmk_bary_coords: torch.tensor Lx3, dtype = torch.float32\n The tensor of barycentric coordinates that are used to interpolate\n the landmarks\n\n Returns\n -------\n landmarks: torch.tensor BxLx3, dtype = torch.float32\n The coordinates of the landmarks for each mesh in the batch\n '''\n # Extract the indices of the vertices for each face\n # BxLx3\n batch_size, num_verts = vertices.shape[:2]\n device = vertices.device\n\n lmk_faces = torch.index_select(faces, 0, lmk_faces_idx.view(-1)).view(\n batch_size, -1, 3)\n\n lmk_faces += torch.arange(\n batch_size, dtype=torch.long, device=device).view(-1, 1, 1) * num_verts\n\n lmk_vertices = vertices.view(-1, 3)[lmk_faces].view(\n batch_size, -1, 3, 3)\n\n landmarks = torch.einsum('blfi,blf->bli', [lmk_vertices, lmk_bary_coords])\n return landmarks\n\n\ndef lbs(betas, pose, v_template, shapedirs, posedirs, J_regressor, parents,\n lbs_weights, pose2rot=True, dtype=torch.float32):\n ''' Performs Linear Blend Skinning with the given shape and pose parameters\n\n Parameters\n ----------\n betas : torch.tensor BxNB\n The tensor of shape parameters\n pose : torch.tensor Bx(J + 1) * 3\n The pose parameters in axis-angle format\n v_template torch.tensor BxVx3\n The template mesh that will be deformed\n shapedirs : torch.tensor 1xNB\n The tensor of PCA shape displacements\n posedirs : torch.tensor Px(V * 3)\n The pose PCA coefficients\n J_regressor : torch.tensor JxV\n The regressor array that is used to calculate the joints from\n the position of the vertices\n parents: torch.tensor J\n The array that describes the kinematic tree for the model\n lbs_weights: torch.tensor N x V x (J + 1)\n The linear blend skinning weights that represent how much the\n rotation matrix of each part affects each vertex\n pose2rot: bool, optional\n Flag on whether to convert the input pose tensor to rotation\n matrices. The default value is True. If False, then the pose tensor\n should already contain rotation matrices and have a size of\n Bx(J + 1)x9\n dtype: torch.dtype, optional\n\n Returns\n -------\n verts: torch.tensor BxVx3\n The vertices of the mesh after applying the shape and pose\n displacements.\n joints: torch.tensor BxJx3\n The joints of the model\n '''\n\n batch_size = max(betas.shape[0], pose.shape[0])\n device = betas.device\n\n # Add shape contribution\n v_shaped = v_template + blend_shapes(betas, shapedirs)\n\n # Get the joints\n # NxJx3 array\n J = vertices2joints(J_regressor, v_shaped)\n\n # print('j1t')\n # print(J[0][1])\n\n # 3. Add pose blend shapes\n # N x J x 3 x 3\n ident = torch.eye(3, dtype=dtype, device=device)\n if pose2rot:\n rot_mats = batch_rodrigues(\n pose.view(-1, 3), dtype=dtype).view([batch_size, -1, 3, 3])\n\n pose_feature = (rot_mats[:, 1:, :, :] - ident).view([batch_size, -1])\n # (N x P) x (P, V * 3) -> N x V x 3\n pose_offsets = torch.matmul(pose_feature, posedirs) \\\n .view(batch_size, -1, 3)\n else:\n pose_feature = pose[:, 1:].view(batch_size, -1, 3, 3) - ident\n rot_mats = pose.view(batch_size, -1, 3, 3)\n\n pose_offsets = torch.matmul(pose_feature.view(batch_size, -1),\n posedirs).view(batch_size, -1, 3)\n\n v_posed = pose_offsets + v_shaped\n # 4. Get the global joint location\n\n # print(rot_mats[0][1])\n\n J_transformed, A = batch_rigid_transform(rot_mats, J, parents, dtype=dtype)\n\n # 5. Do skinning:\n # W is N x V x (J + 1)\n W = lbs_weights.unsqueeze(dim=0).expand([batch_size, -1, -1])\n # (N x V x (J + 1)) x (N x (J + 1) x 16)\n num_joints = J_regressor.shape[0]\n T = torch.matmul(W, A.view(batch_size, num_joints, 16)) \\\n .view(batch_size, -1, 4, 4)\n\n homogen_coord = torch.ones([batch_size, v_posed.shape[1], 1],\n dtype=dtype, device=device)\n v_posed_homo = torch.cat([v_posed, homogen_coord], dim=2)\n v_homo = torch.matmul(T, torch.unsqueeze(v_posed_homo, dim=-1))\n\n verts = v_homo[:, :, :3, 0]\n\n return verts, J_transformed, A, J\n\n\ndef vertices2joints(J_regressor, vertices):\n ''' Calculates the 3D joint locations from the vertices\n\n Parameters\n ----------\n J_regressor : torch.tensor JxV\n The regressor array that is used to calculate the joints from the\n position of the vertices\n vertices : torch.tensor BxVx3\n The tensor of mesh vertices\n\n Returns\n -------\n torch.tensor BxJx3\n The location of the joints\n '''\n\n return torch.einsum('bik,ji->bjk', [vertices, J_regressor])\n\ndef vertices2joints_np(J_regressor_np, vertices_np):\n ''' Calculates the 3D joint locations from the vertices\n\n Parameters\n ----------\n J_regressor : torch.tensor JxV\n The regressor array that is used to calculate the joints from the\n position of the vertices\n vertices : torch.tensor BxVx3\n The tensor of mesh vertices\n\n Returns\n -------\n torch.tensor BxJx3\n The location of the joints\n '''\n n_j, n_v = J_regressor_np.shape\n b = vertices_np.shape[0]\n return np.matmul(np.tile(J_regressor_np.reshape(1, n_j, n_v), (b, 1, 1)), vertices_np)\n\n\ndef blend_shapes(betas, shape_disps):\n ''' Calculates the per vertex displacement due to the blend shapes\n\n\n Parameters\n ----------\n betas : torch.tensor Bx(num_betas)\n Blend shape coefficients\n shape_disps: torch.tensor Vx3x(num_betas)\n Blend shapes\n\n Returns\n -------\n torch.tensor BxVx3\n The per-vertex displacement due to shape deformation\n '''\n\n # Displacement[b, m, k] = sum_{l} betas[b, l] * shape_disps[m, k, l]\n # i.e. Multiply each shape displacement by its corresponding beta and\n # then sum them.\n blend_shape = torch.einsum('bl,mkl->bmk', [betas, shape_disps])\n return blend_shape\n\ndef blend_shapes_np(betas, shape_disps):\n ''' Calculates the per vertex displacement due to the blend shapes\n\n\n Parameters\n ----------\n betas : torch.tensor Bx(num_betas)\n Blend shape coefficients\n shape_disps: torch.tensor Vx3x(num_betas)\n Blend shapes\n\n Returns\n -------\n torch.tensor BxVx3\n The per-vertex displacement due to shape deformation\n '''\n\n # Displacement[b, m, k] = sum_{l} betas[b, l] * shape_disps[m, k, l]\n # i.e. Multiply each shape displacement by its corresponding beta and\n # then sum them.\n # blend_shape = betas, shape_disps\n b = betas.shape[0]\n m, k, l = shape_disps.shape\n shape_disps_r = np.tile(shape_disps.reshape(1, m, k, l), (b, 1, 1, 1))\n betas_r = np.tile(betas.reshape(b, 1, -1, 1), (1, m, 1, 1))\n blend_shape = np.matmul(shape_disps_r, betas_r)\n\n return blend_shape.reshape((b, m, 3))\n\ndef batch_rodrigues(rot_vecs, epsilon=1e-8, dtype=torch.float32):\n ''' Calculates the rotation matrices for a batch of rotation vectors\n Parameters\n ----------\n rot_vecs: torch.tensor Nx3\n array of N axis-angle vectors\n Returns\n -------\n R: torch.tensor Nx3x3\n The rotation matrices for the given axis-angle parameters\n '''\n\n batch_size = rot_vecs.shape[0]\n device = rot_vecs.device\n\n angle = torch.norm(rot_vecs + 1e-8, dim=1, keepdim=True)\n rot_dir = rot_vecs / angle\n\n cos = torch.unsqueeze(torch.cos(angle), dim=1)\n sin = torch.unsqueeze(torch.sin(angle), dim=1)\n\n # Bx1 arrays\n rx, ry, rz = torch.split(rot_dir, 1, dim=1)\n K = torch.zeros((batch_size, 3, 3), dtype=dtype, device=device)\n\n zeros = torch.zeros((batch_size, 1), dtype=dtype, device=device)\n K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1) \\\n .view((batch_size, 3, 3))\n\n ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0)\n rot_mat = ident + sin * K + (1 - cos) * torch.bmm(K, K)\n return rot_mat\n\ndef rodnumba(p):\n rot, jac = cv2.Rodrigues(p)\n return rot, jac\n\n\ndef batch_rodrigues_np(pose_body):\n ''' Calculates the rotation matrices for a batch of rotation vectors\n Parameters\n ----------\n rot_vecs: ndarray Nx3\n array of N axis-angle vectors\n Returns\n -------\n R: ndarray Nx3x3\n The rotation matrices for the given axis-angle parameters\n R_jac: ndarray Nx3x3x3\n Jacobians of the rotation matrices\n '''\n batch_size = pose_body.shape[0]\n n_j = int(pose_body.shape[1]/3)\n dt = pose_body.dtype\n rot_mats = np.zeros((batch_size, n_j, 3, 3), dtype=dt)\n rot_mats_jac = np.zeros((batch_size, n_j, 3, 3, 3), dtype=dt)\n for b in range(0, pose_body.shape[0]):\n for i in range(0, n_j):\n # rot, jac = cv2.Rodrigues(pose_body[b][3 * (i): 3 * (i + 1)].reshape(-1))\n rot, jac = rodnumba(pose_body[b][3 * (i): 3 * (i + 1)].reshape(-1))\n # print(numba.typeof(rot))\n # print(numba.typeof(jac))\n rot_mats[0, i] = rot\n rot_mats_jac[0, i] = jac.reshape(3, 3, 3)\n\n return rot_mats, rot_mats_jac\n\ndef transform_mat(R, t):\n ''' Creates a batch of transformation matrices\n Args:\n - R: Bx3x3 array of a batch of rotation matrices\n - t: Bx3x1 array of a batch of translation vectors\n Returns:\n - T: Bx4x4 Transformation matrix\n '''\n # No padding left or right, only add an extra row\n return torch.cat([F.pad(R, [0, 0, 0, 1]),\n F.pad(t, [0, 0, 0, 1], value=1)], dim=2)\n\ndef transform_mat_np(R, t):\n ''' Creates a batch of transformation matrices\n Args:\n - R: Bx3x3 array of a batch of rotation matrices\n - t: Bx3x1 array of a batch of translation vectors\n Returns:\n - T: Bx4x4 Transformation matrix\n '''\n # No padding left or right, only add an extra row\n b = R.shape[0]\n T = np.zeros((b, 4, 4), dtype=R.dtype)\n T[:, :3, :3] = R\n T[:, :3, 3] = t.reshape(b, 3)\n T[:, 3, 3] = 1\n return T\n\n\ndef batch_rigid_transform(rot_mats, joints, parents, dtype=torch.float32):\n \"\"\"\n Applies a batch of rigid transformations to the joints\n\n Parameters\n ----------\n rot_mats : torch.tensor BxNx3x3\n Tensor of rotation matrices\n joints : torch.tensor BxNx3\n Locations of joints\n parents : torch.tensor BxN\n The kinematic tree of each object\n dtype : torch.dtype, optional:\n The data type of the created tensors, the default is torch.float32\n\n Returns\n -------\n posed_joints : torch.tensor BxNx3\n The locations of the joints after applying the pose rotations\n rel_transforms : torch.tensor BxNx4x4\n The relative (with respect to the root joint) rigid transformations\n for all the joints\n \"\"\"\n\n joints = torch.unsqueeze(joints, dim=-1)\n\n rel_joints = joints.clone()\n rel_joints[:, 1:] -= joints[:, parents[1:]]\n\n transforms_mat = transform_mat(\n rot_mats.reshape(-1, 3, 3),\n rel_joints.reshape(-1, 3, 1)).reshape(-1, joints.shape[1], 4, 4)\n\n # print(transforms_mat[0][0])\n # print(transforms_mat[0][1])\n\n transform_chain = [transforms_mat[:, 0]]\n for i in range(1, parents.shape[0]):\n # Subtract the joint location at the rest pose\n # No need for rotation, since it's identity when at rest\n curr_res = torch.matmul(transform_chain[parents[i]],\n transforms_mat[:, i])\n transform_chain.append(curr_res)\n\n transforms = torch.stack(transform_chain, dim=1)\n\n # print(transforms[0][1])\n\n # The last column of the transformations contains the posed joints\n posed_joints = transforms[:, :, :3, 3]\n\n # The last column of the transformations contains the posed joints\n posed_joints = transforms[:, :, :3, 3]\n\n joints_homogen = F.pad(joints, [0, 0, 0, 1])\n\n rel_transforms = transforms - F.pad(\n torch.matmul(transforms, joints_homogen), [3, 0, 0, 0, 0, 0, 0, 0])\n\n return posed_joints, rel_transforms\n\n# @jit\ndef batch_rigid_transform_diff(rot_mats, rot_mats_jac, transform_jac_chain, joints, parents, is_jac=True):\n \"\"\"\n Applies a batch of rigid transformations to the joints\n\n Parameters\n ----------\n rot_mats : ndarray BxNx3x3\n Tensor of rotation matrices\n rot_mats_jac : ndarray BxNx3x3x3\n Tensor of rotation matrix Jacobians\n joints : ndarray BxNx3\n Locations of joints\n parents : ndarray BxN\n The kinematic tree of each object\n\n Returns\n -------\n posed_joints : ndarray BxNx3\n The locations of the joints after applying the pose rotations\n pose_joints_jac : ndarray BxNxNx3x3\n Jacobian of pose_joints w.r.t. pose\n rel_transforms : ndarray BxNx4x4\n The relative (with respect to the root joint) rigid transformations\n for all the joints\n rel_transforms_jac : jacobian w.r.t. pose\n \"\"\"\n # joints = joints.reshape()\n # joints = torch.unsqueeze(joints, dim=-1)\n\n t_0 = time.time()\n\n rel_joints = joints.copy()\n rel_joints[:, 1:] -= joints[:, parents[1:]]\n\n transforms_mat = transform_mat_np(\n rot_mats.reshape(-1, 3, 3),\n rel_joints.reshape(-1, 3, 1)).reshape(-1, joints.shape[1], 4, 4)\n\n b = joints.shape[0]\n n_j = joints.shape[1]\n\n t_1 = time.time()\n\n if is_jac:\n ainds = np.arange(0, parents.shape[0])\n transform_jac_chain.fill(0)\n transform_jac_chain[:, ainds, ainds, :, 0:3, 0:3] = rot_mats_jac[:, ainds]\n\n transform_chain = np.zeros((b, parents.shape[0], 4, 4), dtype=rot_mats.dtype)\n transform_chain[:, 0] = transforms_mat[:, 0]\n for i in range(1, parents.shape[0]):\n transform_chain[:, i] = np.matmul(transform_chain[:, parents[i]],\n transforms_mat[:, i])\n\n if is_jac:\n inds = np.arange(1, len(parents))\n trans_parent = transform_chain[:, parents[inds]].reshape(b, len(inds), 1, 1, 4, 4)\n trans_jac = transform_jac_chain[:, inds, inds, :].reshape(1, len(inds), 1, 3, 4, 4)\n transform_jac_chain[:, inds, inds, :] = np.matmul(trans_parent, trans_jac).reshape(len(inds), 3, 4, 4)\n\n m = np.eye(parents.shape[0], dtype=np.bool)\n b = transforms_mat.shape[0]\n for i in range(1, parents.shape[0]):\n m[i] = m[i] | m[parents[i]]\n # transform_jac_chain[:, i, :, :] += np.matmul(transform_jac_chain[:, parents[i], :, :], transforms_mat[:, i])\n tr_jac_ch_sel = transform_jac_chain[:, parents[i], m[i], :]\n transform_jac_chain[:, i, m[i], :] += np.matmul(tr_jac_ch_sel, transforms_mat[:, i]).reshape(b, -1, 3, 4, 4)\n\n t_2 = time.time()\n\n\n transforms = transform_chain\n posed_joints = transforms[:, :, :3, 3]\n joints_rot = np.matmul(transforms[:, :, 0:3, 0:3], joints.reshape(b, n_j, 3, 1)).reshape((b, n_j, 3))\n rel_transforms = transforms.copy()\n rel_transforms[:, :, 0:3, 3] = rel_transforms[:, :, 0:3, 3] - joints_rot\n if is_jac:\n transforms_jac = np.transpose(transform_jac_chain, (0, 2, 3, 1, 4, 5))\n posed_joints_jac = transforms_jac[:, :, :, :, :3, 3]\n tjhj = np.matmul(transforms_jac[:, :, :, :, 0:3, 0:3], joints.reshape((b, 1, 1, n_j, 3, 1))).reshape(\n (b, n_j, 3, n_j, 3))\n rel_transforms_jac = transforms_jac.copy()\n rel_transforms_jac[:, :, :, :, 0:3, 3] = rel_transforms_jac[:, :, :, :, 0:3, 3] - tjhj\n else:\n posed_joints_jac = None\n rel_transforms_jac = None\n t_3 = time.time()\n\n # print('brgd breakdown {} {} {} '.format(t_1-t_0, t_2-t_1, t_3-t_2))\n\n return posed_joints, posed_joints_jac, rel_transforms, rel_transforms_jac\n\ndef batch_rigid_transform_fast_diff(rot_mats, rot_mats_jac, joints, parents):\n \"\"\"\n Applies a batch of rigid transformations to the joints\n\n Parameters\n ----------\n rot_mats : ndarray BxNx3x3\n Tensor of rotation matrices\n rot_mats_jac : ndarray BxNx3x3x3\n Tensor of rotation matrix Jacobians\n joints : ndarray BxNx3\n Locations of joints\n parents : ndarray BxN\n The kinematic tree of each object\n\n Returns\n -------\n posed_joints : ndarray BxNx3\n The locations of the joints after applying the pose rotations\n pose_joints_jac : ndarray BxNxNx3x3\n Jacobian of pose_joints w.r.t. pose\n rel_transforms : ndarray BxNx4x4\n The relative (with respect to the root joint) rigid transformations\n for all the joints\n rel_transforms_jac : jacobian w.r.t. pose\n \"\"\"\n # joints = joints.reshape()\n # joints = torch.unsqueeze(joints, dim=-1)\n\n t_0 = time.time()\n\n rel_joints = joints.copy()\n rel_joints[:, 1:] -= joints[:, parents[1:]]\n\n transforms_mat = transform_mat_np(\n rot_mats.reshape(-1, 3, 3),\n rel_joints.reshape(-1, 3, 1)).reshape(-1, joints.shape[1], 4, 4)\n\n # print(transforms_mat[0][0])\n # print(transforms_mat[0][1])\n\n b = joints.shape[0]\n n_j = joints.shape[1]\n\n t_1 = time.time()\n\n # transform_jac = np.zeros((b, n_j, 3, 4, 4))\n # transform_jac[:, 0, :, 0:3, 0:3] = rot_mats_jac[:, 0]\n transform_jac_chain = np.zeros((b, n_j, 3, parents.shape[0], 4, 4))\n for i in range(0, parents.shape[0]):\n transform_jac_chain[:, i, :, i, 0:3, 0:3] = rot_mats_jac[:, i]\n\n transform_chain = np.copy(transforms_mat)\n for i in range(1, parents.shape[0]):\n t_curr = np.matmul(transform_chain[:, parents[i], 0:3, 0:3],\n transforms_mat[:, i, 0:3, 3].reshape(-1, 1, 3, 1)).reshape(-1, 1, 3)\n transform_chain[:, i, 0:3, 3] = t_curr + transform_chain[:, parents[i], 0:3, 3]\n t_i = np.tile(transforms_mat[:, i, 0:3, 3].reshape(-1, 1, 1, 3, 1), (1, n_j, 3, 1, 1))\n # print(transform_jac_chain[:, :, :, parents[i], 0:3, 0:3].shape)\n # print(t_i.shape)\n t_jac_curr = np.matmul(transform_jac_chain[:, :, :, parents[i], 0:3, 0:3], t_i)\n transform_jac_chain[:, :, :, i, 0:3, 3] = transform_jac_chain[:, :, :, parents[i], 0:3, 3] + \\\n t_jac_curr.reshape(-1, n_j, 3, 3)\n\n # transforms = np.stack(transform_chain, axis=1)\n transforms = transform_chain\n # transforms_jac = np.stack(transform_jac_chain, axis=3)\n transforms_jac = transform_jac_chain\n\n t_2 = time.time()\n # print(transforms[0][1])\n\n # The last column of the transformations contains the posed joints\n posed_joints = transforms[:, :, :3, 3]\n posed_joints_jac = transforms_jac[:, :, :, :, :3, 3]\n\n # joints_homogen = np.zeros((b, n_j, 4, 1))\n # joints_homogen[:, :, 0:3, 0] = joints\n\n joints_rot = np.matmul(transforms[:,:,0:3,0:3], joints.reshape(b, n_j, 3, 1)).reshape((b, n_j, 3))\n # jht = np.pad(np.matmul(transforms, joints_homogen), [(0, 0), (0, 0), (0, 0), (3,0)])\n # rel_transforms = transforms - jht\n rel_transforms = transforms.copy()\n rel_transforms[:, :, 0:3, 3] = rel_transforms[:, :, 0:3, 3] - joints_rot\n\n # jhtj = np.matmul(transforms_jac, joints_homogen.reshape((b, 1, 1, n_j, 4, 1)))\n # jhtj = np.pad(jhtj, [(0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (3, 0)])\n\n tjhj = np.matmul(transforms_jac[:,:,:,:,0:3,0:3], joints.reshape((b, 1, 1, n_j, 3, 1))).reshape((b, n_j, 3, n_j, 3))\n\n rel_transforms_jac = transforms_jac.copy()\n rel_transforms_jac[:, :, :, :, 0:3, 3] = rel_transforms_jac[:, :, :, :, 0:3, 3] - tjhj\n # rel_transforms_jac = transforms_jac - jhtj\n\n t_3 = time.time()\n\n print('brgd breakdown {} {} {} '.format(t_1-t_0, t_2-t_1, t_3-t_2))\n\n return posed_joints, posed_joints_jac, rel_transforms, rel_transforms_jac\n\ndef prepare_J(betas, v_template, shapedirs, J_regressor, n_v):\n # Add shape contribution\n v_shaped = v_template + blend_shapes_np(betas, shapedirs)\n\n # Get the joints\n # NxJx3 array\n J = vertices2joints_np(J_regressor, v_shaped)\n\n n_j = J_regressor.shape[0]\n\n batch_size = betas.shape[0]\n\n homogen_coord = np.ones((batch_size, n_v, 1), dtype=v_template.dtype)\n\n transform_jac_chain = np.zeros((batch_size, n_j, n_j, 3, 4, 4), dtype=v_template.dtype)\n\n return J, v_shaped, homogen_coord, transform_jac_chain\n\ndef rel_to_direct(pose, parents):\n\n rot_mats, rot_mat_jacs = batch_rodrigues_np(pose)\n\n b = pose.shape[0]\n\n rot_chain = np.zeros((b, parents.shape[0], 3, 3))\n rot_chain[:, 0] = rot_mats[:, 0]\n for i in range(1, parents.shape[0]):\n rot_chain[:, i] = np.matmul(rot_chain[:, parents[i]], rot_mats[:, i])\n\n pose_dir = np.zeros_like(pose)\n n_j = int(pose.shape[1]/3)\n for b in range(0, pose.shape[0]):\n for i in range(0, n_j):\n rv, jac = cv2.Rodrigues(rot_chain[b, i])\n pose_dir[b, 3*i : 3*(i+1)] = rv.reshape(-1)\n\n return pose_dir\n\n\n\ndef lbs_diff_fast(pose, parents,\n J, v_shaped, W, W_j, homogen_coord, v_inds=None):\n t_0 = time.time()\n\n batch_size = pose.shape[0]\n\n # print('j1:')\n # print(J[0][1])\n\n # 3. Add pose blend shapes\n # N x J x 3 x 3\n\n t_1 = time.time()\n\n rot_mats, rot_mat_jacs = batch_rodrigues_np(pose)\n # rot_mats = rot_mats.reshape((batch_size, -1, 3, 3))\n n_j = rot_mats.shape[1]\n\n if v_inds is not None:\n v_shaped = v_shaped[:, v_inds, :]\n\n n_v = v_shaped.shape[1]\n\n v_posed = v_shaped\n\n t_2 = time.time()\n\n J_transformed, J_transformed_jac, A, A_jac = batch_rigid_transform_fast_diff(rot_mats, rot_mat_jacs, J, parents)\n\n t_3 = time.time()\n\n t_3 = time.time()\n\n # 5. Do skinning:\n # W is N x V x (J + 1)\n # W = np.tile(lbs_weights.reshape(1, n_v, n_j), (batch_size, 1, 1))\n # (N x V x (J + 1)) x (N x (J + 1) x 16) = N x V x 16\n num_joints = n_j\n T = np.matmul(W, A.reshape(batch_size, num_joints, 16)) \\\n .reshape((batch_size, -1, 4, 4))\n\n # W_j = np.tile(W.reshape((batch_size, 1, 1, n_v, n_j)), (1, n_j, 3, 1, 1))\n\n A_jact = A_jac # .transpose(0, 2, 3, 1, 4, 5)\n T_jac = np.matmul(W_j, A_jact.reshape(batch_size, n_j, 3, n_j, -1))\n T_jac = T_jac.reshape((batch_size, n_j, 3, n_v, 4, 4))\n # N x n_j x 3 x V x 16\n\n v_posed_homo = np.concatenate([v_posed, homogen_coord], axis=2)\n\n v_homo = np.matmul(T, v_posed_homo.reshape((batch_size, n_v, 4, 1)))\n\n T_j = T.reshape((batch_size, 1, 1, n_v, 4, 4))\n\n v_posed_homo_j = v_posed_homo.reshape((batch_size, 1, 1, n_v, 4, 1))\n v_homo_jac2 = np.matmul(T_jac, v_posed_homo_j)\n\n verts = v_homo[:, :, :3, 0]\n\n v_homo_jac = v_homo_jac2[:, :, :, :, :3, :]\n\n verts_jac = v_homo_jac[:, :, :, :, :3, 0]\n\n t_4 = time.time()\n\n # print('breakdown b {} a {} rt {} f {}'.format(t_1-t_0, t_2-t_1, t_3-t_2, t_4-t_3))\n\n return verts, verts_jac, J_transformed, J_transformed_jac, A, A_jac, J # , v_posed, v_posed_jac\n\n# @jit\ndef lbs_diff(pose, posedirs, parents, J, v_shaped, lbs_weights, homogen_coord, transform_jac_chain, v_inds=None):\n ''' Performs Linear Blend Skinning with the given shape and pose parameters\n\n Parameters\n ----------\n betas : torch.tensor BxNB\n The tensor of shape parameters\n pose : ndarray Bx(J + 1) * 3\n The pose parameters in axis-angle format\n v_template ndarray BxVx3\n The template mesh that will be deformed\n shapedirs : torch.tensor 1xNB\n The tensor of PCA shape displacements\n posedirs : ndarray Px(V * 3)\n The pose PCA coefficients\n J_regressor : ndarray JxV\n The regressor array that is used to calculate the joints from\n the position of the vertices\n parents: ndarray J\n The array that describes the kinematic tree for the model\n lbs_weights: ndarray N x V x (J + 1)\n The linear blend skinning weights that represent how much the\n rotation matrix of each part affects each vertex\n vinds: ndarray - list of required vertex indices (if None, all vertices will be processed)\n\n Returns\n -------\n verts: ndarray BxVx3\n The vertices of the mesh after applying the shape and pose\n displacements.\n verts_jac: ndarray BxVx(J+1)x3x3\n joints: ndarray BxJx3\n The joints of the model\n joints_jac: ndarray BxJxJx3x3\n Jacobian of joints' coordinates\n '''\n\n t_0 = time.time()\n\n batch_size = pose.shape[0]\n\n if v_inds is not None:\n lbs_weights = lbs_weights[v_inds]\n n_v = len(v_inds)\n else:\n n_v = 0\n\n n_j = J.shape[1]\n\n W = np.tile(lbs_weights.reshape(1, n_v, n_j), (batch_size, 1, 1))\n # W_j = np.tile(W.reshape((batch_size, 1, 1, n_v, n_j)), (1, n_j, 3, 1, 1))\n W_j = W.reshape((batch_size, 1, 1, n_v, n_j))\n\n # print('j1:')\n # print(J[0][1])\n\n # 3. Add pose blend shapes\n # N x J x 3 x 3\n\n t_1 = time.time()\n\n rot_mats, rot_mat_jacs = batch_rodrigues_np(pose)\n # rot_mats = rot_mats.reshape((batch_size, -1, 3, 3))\n n_j = rot_mats.shape[1]\n pose_feature = (rot_mats[:, 1:, :, :] - np.tile(np.eye(3).reshape(1, 1, 3, 3), (batch_size, n_j-1, 1, 1)))\\\n .reshape((batch_size, -1))\n\n if v_inds is not None:\n v_shaped = v_shaped[:, v_inds, :]\n inds = np.stack([3*v_inds, 3*v_inds+1, 3*v_inds+2], axis=1).reshape(-1)\n posedirs = posedirs[:, inds]\n # lbs_weights = lbs_weights[v_inds]\n\n # (N x P) x (P, V * 3) -> N x V x 3\n pose_offsets = np.matmul(pose_feature, posedirs) \\\n .reshape((batch_size, -1, 3))\n\n n_v = v_shaped.shape[1]\n\n pose_offset_jacs = np.zeros((batch_size, n_j, 3, n_v, 3), dtype=pose.dtype)\n for i in range (1, n_j):\n pdi = np.matmul(rot_mat_jacs[:, i].reshape(-1, 9), posedirs[(i-1)*9 : i*9, :]).reshape((batch_size, 3, -1, 3))\n pose_offset_jacs[:, i] = pdi\n\n v_posed = pose_offsets + v_shaped\n\n #NxVxJ+1x3x3\n v_posed_jac = pose_offset_jacs\n\n # print(rot_mats[0][1])\n\n t_2 = time.time()\n\n J_transformed, J_transformed_jac, A, A_jac = batch_rigid_transform_diff(rot_mats, rot_mat_jacs, transform_jac_chain, J, parents)\n\n t_3 = time.time()\n\n # 5. Do skinning:\n # W is N x V x (J + 1)\n # W = np.tile(lbs_weights.reshape(1, n_v, n_j), (batch_size, 1, 1))\n # (N x V x (J + 1)) x (N x (J + 1) x 16) = N x V x 16\n num_joints = n_j\n T = np.matmul(W, A.reshape(batch_size, num_joints, 16)) \\\n .reshape((batch_size, -1, 4, 4))\n\n # W_j = np.tile(W.reshape((batch_size, 1, 1, n_v, n_j)), (1, n_j, 3, 1, 1))\n\n A_jact = A_jac #.transpose(0, 2, 3, 1, 4, 5)\n T_jac = np.matmul(W_j, A_jact.reshape(batch_size, n_j, 3, n_j, -1))\n T_jac = T_jac.reshape((batch_size, n_j, 3, n_v, 4, 4))\n #N x n_j x 3 x V x 16\n\n v_posed_homo = np.concatenate([v_posed, homogen_coord], axis=2)\n\n v_homo = np.matmul(T, v_posed_homo.reshape((batch_size, n_v, 4, 1)))\n\n # T_j = np.tile(T.reshape((batch_size, 1, 1, n_v, 4, 4)), (1, n_j, 3, 1, 1, 1))\n\n T_j = T.reshape((batch_size, 1, 1, n_v, 4, 4))\n\n # v_posed_jac_h = np.pad(v_posed_jac, ((0, 0), (0,0), (0,0), (0,0), (0,1))).reshape((batch_size, n_j, 3, n_v, 4, 1))\n # v_posed_jac_h = v_posed_jac_h.reshape((batch_size, n_j, 3, n_v, 4, 1))\n # v_homo_jac1 = np.matmul(T_j, v_posed_jac_h)\n\n v_homo_jac1 = np.matmul(T_j[:, :, :, :, 0:3, 0:3], v_posed_jac.reshape((batch_size, n_j, 3, n_v, 3, 1)))\n\n # v_posed_homo_j = np.tile(v_posed_homo.reshape((batch_size, 1, 1, n_v, 4, 1)), (1, n_j, 3, 1, 1, 1))\n v_posed_homo_j = v_posed_homo.reshape((batch_size, 1, 1, n_v, 4, 1))\n v_homo_jac2 = np.matmul(T_jac, v_posed_homo_j)\n # v_homo_jac2 = v_homo_jac2.transpose((0, 3, 1, 2, 4, 5))\n\n verts = v_homo[:, :, :3, 0]\n\n v_homo_jac = v_homo_jac1 + v_homo_jac2[:, :, :, :, :3, :]\n\n verts_jac = v_homo_jac[:, :, :, :, :3, 0]\n\n t_4 = time.time()\n\n # print('breakdown b {} a {} rt {} f {}'.format(t_1-t_0, t_2-t_1, t_3-t_2, t_4-t_3))\n\n return verts, verts_jac, J_transformed, J_transformed_jac, A, A_jac, J #, v_posed, v_posed_jac\n\n\ndef lbs_diff_nopd(pose, posedirs_face, parents, J, v_shaped, lbs_weights, homogen_coord, transform_jac_chain, v_inds=None,\n is_jac=True, bpm=None, face_expression=None, w_thr=0):\n ''' Performs Linear Blend Skinning with the given shape and pose parameters\n\n Parameters\n ----------\n betas : torch.tensor BxNB\n The tensor of shape parameters\n pose : ndarray Bx(J + 1) * 3\n The pose parameters in axis-angle format\n v_template ndarray BxVx3\n The template mesh that will be deformed\n shapedirs : torch.tensor 1xNB\n The tensor of PCA shape displacements\n posedirs : ndarray Px(V * 3)\n The pose PCA coefficients\n J_regressor : ndarray JxV\n The regressor array that is used to calculate the joints from\n the position of the vertices\n parents: ndarray J\n The array that describes the kinematic tree for the model\n lbs_weights: ndarray N x V x (J + 1)\n The linear blend skinning weights that represent how much the\n rotation matrix of each part affects each vertex\n vinds: ndarray - list of required vertex indices (if None, all vertices will be processed)\n\n Returns\n -------\n verts: ndarray BxVx3\n The vertices of the mesh after applying the shape and pose\n displacements.\n verts_jac: ndarray BxVx(J+1)x3x3\n joints: ndarray BxJx3\n The joints of the model\n joints_jac: ndarray BxJxJx3x3\n Jacobian of joints' coordinates\n '''\n\n t_0 = time.time()\n\n batch_size = pose.shape[0]\n if v_inds is not None:\n\n if bpm is None:\n w_arr = np.sum(lbs_weights[v_inds] ** 2, axis=0)/len(v_inds)\n bpm = w_arr > w_thr\n\n lbs_weights = lbs_weights[v_inds]\n\n # 3. Add pose blend shapes\n # N x J x 3 x 3\n\n t_1 = time.time()\n\n rot_mats, rot_mat_jacs = batch_rodrigues_np(pose)\n\n n_j = rot_mats.shape[1]\n\n if v_inds is not None:\n v_shaped = v_shaped[:, v_inds, :]\n\n if face_expression is not None:\n posedirs_face = posedirs_face[v_inds]\n n_v = len(v_inds)\n dv = np.matmul(posedirs_face.reshape(1, n_v, 3, 1, -1), np.tile(face_expression.reshape(1, 1, 1, -1, 1),\n (1, n_v, 3, 1, 1)))\n v_shaped += dv.reshape(1, -1, 3)\n dv_jac = np.transpose(posedirs_face.reshape(n_v, 3, -1), (2, 0, 1)).reshape(-1, 3 * n_v)\n\n n_v = v_shaped.shape[1]\n\n v_posed = v_shaped\n\n t_2 = time.time()\n\n J_transformed, J_transformed_jac, A, A_jac = batch_rigid_transform_diff(rot_mats, rot_mat_jacs, transform_jac_chain, J, parents, is_jac)\n\n t_3 = time.time()\n\n # 5. Do skinning:\n # W is N x V x (J + 1)\n # W = np.tile(lbs_weights.reshape(1, n_v, n_j), (batch_size, 1, 1))\n # (N x V x (J + 1)) x (N x (J + 1) x 16) = N x V x 16\n num_joints = n_j\n W = np.tile(lbs_weights.reshape(1, n_v, n_j), (batch_size, 1, 1))\n T = np.matmul(W, A.reshape(batch_size, num_joints, 16)) \\\n .reshape((batch_size, -1, 4, 4))\n v_posed_homo = np.concatenate([v_posed, homogen_coord], axis=2)\n v_homo = np.matmul(T, v_posed_homo.reshape((batch_size, n_v, 4, 1)))\n verts = v_homo[:, :, :3, 0]\n\n t_3_1 = time.time()\n\n if is_jac:\n\n Wred = W[:, :, bpm]\n n_bpm = Wred.shape[-1]\n W_j = Wred.reshape((batch_size, 1, 1, n_v, n_bpm))\n T_jac = np.matmul(W_j, A_jac.reshape(batch_size, n_j, 3, n_j, -1)[:, :, :, bpm])\n T_jac = T_jac.reshape((batch_size, n_j, 3, n_v, 4, 4))\n\n #N x n_j x 3 x V x 16\n\n t_3_2 = time.time()\n\n v_posed_homo_j = v_posed_homo.reshape((batch_size, 1, 1, n_v, 4, 1))\n v_homo_jac2 = np.matmul(T_jac, v_posed_homo_j)\n n_pars = pose.shape[1]\n verts_jac = v_homo_jac2[:, :, :, :, :3, 0].reshape(n_pars, -1)\n if face_expression is not None:\n n_fp = 10\n dv_jac = np.matmul(T[:, :, 0:3, 0:3], dv_jac.reshape(n_fp, -1, 3, 1)).reshape(n_fp, -1)\n # dv_jac = np.zeros_like(dv_jac)\n verts_jac = np.concatenate([verts_jac, dv_jac], axis=0)\n else:\n verts_jac = None\n\n t_4 = time.time()\n\n # print('breakdown b {} a {} rt {} f1 {} f2 {} f3 {}'.format(t_1-t_0, t_2-t_1, t_3-t_2, t_3_1 - t_3, t_3_2 - t_3_1, t_4-t_3_2))\n\n return verts, verts_jac, J_transformed, J_transformed_jac, A, A_jac, J, bpm #, v_posed, v_posed_jac", "meta": {"hexsha": "6b852134f7d806cd3813cc57ceade9bd9140a6d1", "size": 39552, "ext": "py", "lang": "Python", "max_stars_repo_path": "extern/patched_smplx/patched_smplx/lbs.py", "max_stars_repo_name": "wangxihao/rgbd-kinect-pose", "max_stars_repo_head_hexsha": "03180723c99759ba2500bcd42b5fe7a1d26eb507", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-07T06:12:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T06:12:26.000Z", "max_issues_repo_path": "extern/patched_smplx/patched_smplx/lbs.py", "max_issues_repo_name": "wangxihao/rgbd-kinect-pose", "max_issues_repo_head_hexsha": "03180723c99759ba2500bcd42b5fe7a1d26eb507", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extern/patched_smplx/patched_smplx/lbs.py", "max_forks_repo_name": "wangxihao/rgbd-kinect-pose", "max_forks_repo_head_hexsha": "03180723c99759ba2500bcd42b5fe7a1d26eb507", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6967509025, "max_line_length": 140, "alphanum_fraction": 0.6090716019, "include": true, "reason": "import numpy,import numba,from numba", "num_tokens": 12039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.2751297238231752, "lm_q1q2_score": 0.14078844812798988}} {"text": "from abc import abstractmethod\nfrom collections import OrderedDict\nfrom functools import partial\nfrom typing import List\n\nimport numpy as np\nimport pymc3 as pm\nimport theano as th\nimport theano.tensor as tt\nfrom pymc3.variational.updates import get_or_compute_grads\n\nfrom .. import types\nfrom ..io import io_commons\nfrom ..models.fancy_model import GeneralizedContinuousModel\n\n\nclass FancyStochasticOptimizer:\n \"\"\"The base class of stochastic optimizers equipped with the functionality of saving and loading the\n optimizer state to and from disk (e.g. for stateful optimizers such as ADAM and ADAMAX), and the\n possibility of utilizing the extra attributes of `GeneralizedContinuousModel` to perform structured\n parameter updates, e.g. updating only sample-specific variables while keeping global variables intact\n (see `FancyAdamax` for a concrete implementation).\n \"\"\"\n @abstractmethod\n def get_optimizer(self,\n model: GeneralizedContinuousModel=None,\n approx: pm.MeanField=None):\n \"\"\"\n\n Args:\n model: a generalized continuous PyMC3 model\n approx: an instance of PyMC3 mean-field approximation\n\n Returns:\n A callable function that upon providing `loss_or_grads` and `params`, returns an\n `OrderedDict` of shared theano tensor updates (for example, see `FancyAdamax.get_optimizer`).\n \"\"\"\n raise NotImplementedError\n\n @staticmethod\n def get_call_kwargs(_locals_):\n _locals_ = _locals_.copy()\n _locals_.pop('loss_or_grads')\n _locals_.pop('params')\n return _locals_\n\n @abstractmethod\n def save(self, output_path: str):\n raise NotImplementedError\n\n @abstractmethod\n def load(self, input_path: str):\n raise NotImplementedError\n\n\nclass FancyAdamax(FancyStochasticOptimizer):\n \"\"\"Adamax optimizer with saving/loading functionality and sample-specific-only update mode.\"\"\"\n def __init__(self,\n learning_rate: float = 0.002,\n beta1: float = 0.9,\n beta2: float = 0.999,\n epsilon: float = 1e-8,\n sample_specific_only: bool = False,\n disable_bias_correction: bool = False):\n \"\"\"Initializer.\n\n Args:\n learning_rate: learning rate\n beta1: first moment forgetting factor\n beta2: second moment forgetting factor\n epsilon: a small float for avoiding division-by-zero\n sample_specific_only: only update sample-specific variables (as specified in the generalized model)\n disable_bias_correction: disable moment estimation bias correction\n \"\"\"\n self.learning_rate = learning_rate\n self.beta1 = beta1\n self.beta2 = beta2\n self.epsilon = epsilon\n self.sample_specific_only = sample_specific_only\n self.disable_bias_correction = disable_bias_correction\n\n # placeholder for first (m) and second (u) moments\n # in mean-field type approximation, ``mu`` and ``rho`` each have their own tensors\n # the list elements correspond to ``mu`` and ``rho`` moments, respectively\n self.m_tensors: List[types.TensorSharedVariable] = []\n self.u_tensors: List[types.TensorSharedVariable] = []\n\n # placeholder for the state of moment estimation bias corrector\n self.res_tensor: types.TensorSharedVariable = None\n\n def _assert_shared_tensors_available(self):\n m_u_available = len(self.m_tensors) == 2 and len(self.u_tensors) == 2\n res_available = self.disable_bias_correction or self.res_tensor is not None\n assert m_u_available and res_available, \"Adamax tensors are not available yet\"\n\n def get_mu_m(self):\n self._assert_shared_tensors_available()\n return self.m_tensors[0]\n\n def get_rho_m(self):\n self._assert_shared_tensors_available()\n return self.m_tensors[1]\n\n def get_mu_u(self):\n self._assert_shared_tensors_available()\n return self.u_tensors[0]\n\n def get_rho_u(self):\n self._assert_shared_tensors_available()\n return self.u_tensors[1]\n\n def get_res_tensor(self):\n return self.res_tensor\n\n @staticmethod\n def structured_adamax(loss_or_grads=None,\n params=None,\n model: GeneralizedContinuousModel=None,\n approx: pm.MeanField=None,\n learning_rate=0.002, beta1=0.9,\n beta2=0.999, epsilon=1e-8,\n sample_specific_only=False,\n disable_bias_correction=False,\n base_class: 'FancyAdamax' = None):\n \"\"\"Adamax stochastic optimizer with partial sample-specific-only update functionality.\n\n Args:\n loss_or_grads: symbolic loss function or gradients\n params: variational parameter bundle\n model: an instance of generalized model\n approx: an instance of variational approximation for the model\n learning_rate: global learning rate\n beta1: first moment estimation forgetting factor\n beta2: second moment estimation forgetting factor\n epsilon: a small float to avoid division-by-zero\n sample_specific_only: only update parameters registered in the generalized model as sample-specific\n disable_bias_correction: disable moment estimation bias correction\n base_class: a reference to the base class to store a reference to the shared tensors (for I/O)\n\n Returns:\n returns the function itself if `loss_or_grads` and `params` are not given;\n otherwise, returns an ordered dict of shared tensor updates (to be used in pymc3 for compiling\n the step function)\n \"\"\"\n if loss_or_grads is None and params is None:\n return partial(FancyAdamax.structured_adamax,\n **FancyStochasticOptimizer.get_call_kwargs(locals()))\n elif loss_or_grads is None or params is None:\n raise ValueError('Please provide both `loss_or_grads` and `params` to get updates')\n assert model is not None, 'Please provide `model` to get updates'\n assert approx is not None, 'Please provide `approx` to get updates'\n\n all_grads = get_or_compute_grads(loss_or_grads, params)\n updates = OrderedDict()\n\n # indices of sample-specific vars\n if sample_specific_only:\n vmap_list = io_commons.get_var_map_list_from_meanfield_approx(approx)\n sample_specific_indices = []\n for vmap in vmap_list:\n if vmap.var in model.sample_specific_var_registry:\n sample_specific_indices += [idx for idx in range(vmap.slc.start, vmap.slc.stop)]\n update_indices = th.shared(np.asarray(sample_specific_indices, dtype=np.int))\n num_dof = len(sample_specific_indices)\n\n # Using theano constant to prevent upcasting of float32\n one = tt.constant(1)\n\n if disable_bias_correction:\n a_t = learning_rate\n else:\n res_prev = th.shared(pm.theanof.floatX(beta1))\n res = beta1 * res_prev\n a_t = learning_rate / (one - res)\n updates[res_prev] = res\n if base_class is not None:\n base_class.res_tensor = res_prev\n\n for param, g_t in zip(params, all_grads):\n if sample_specific_only:\n g_t_view = g_t[update_indices]\n m_prev = th.shared(np.zeros((num_dof,), dtype=types.floatX),\n broadcastable=(False,))\n u_prev = th.shared(np.zeros((num_dof,), dtype=types.floatX),\n broadcastable=(False,))\n else:\n g_t_view = g_t\n value = param.get_value(borrow=True)\n m_prev = th.shared(np.zeros(value.shape, dtype=types.floatX),\n broadcastable=(False,))\n u_prev = th.shared(np.zeros(value.shape, dtype=types.floatX),\n broadcastable=(False,))\n\n # save a reference to m and u in the base class\n if base_class is not None:\n base_class.m_tensors.append(m_prev)\n base_class.u_tensors.append(u_prev)\n\n m_t = beta1 * m_prev + (one - beta1) * g_t_view\n u_t = tt.maximum(beta2 * u_prev, abs(g_t_view))\n step = a_t * m_t / (u_t + epsilon)\n\n if sample_specific_only:\n new_param = tt.inc_subtensor(param[update_indices], -step)\n else:\n new_param = param - step\n\n updates[m_prev] = m_t\n updates[u_prev] = u_t\n updates[param] = new_param\n\n return updates\n\n def get_optimizer(self,\n model: GeneralizedContinuousModel=None,\n approx: pm.MeanField=None):\n return FancyAdamax.structured_adamax(\n model=model,\n approx=approx,\n beta1=self.beta1,\n beta2=self.beta2,\n learning_rate=self.learning_rate,\n epsilon=self.epsilon,\n sample_specific_only=self.sample_specific_only,\n disable_bias_correction=self.disable_bias_correction,\n base_class=self)\n\n def save(self, output_path: str) -> None:\n \"\"\"Saves the state of the optimizer to disk.\n\n Args:\n output_path: output path (must be writable directory)\n \"\"\"\n from ..io import io_adamax # lazy import to break import cycle\n io_adamax.AdamaxStateExporter(self, output_path)()\n\n def load(self, input_path: str):\n \"\"\"Loads the state of the optimizer from disk.\n\n Args:\n input_path: input path (must be a readable directory)\n \"\"\"\n from ..io import io_adamax # lazy import to break import cycle\n io_adamax.AdamaxStateImporter(self, input_path)()\n", "meta": {"hexsha": "c72bca41e68cb871dd4041998251af1b3af9460a", "size": 10089, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/main/python/org/broadinstitute/hellbender/gcnvkernel/inference/fancy_optimizers.py", "max_stars_repo_name": "raomohan89/GATK", "max_stars_repo_head_hexsha": "068b7fdd6d983cf0b7611b03bd0028d85de61bc2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main/python/org/broadinstitute/hellbender/gcnvkernel/inference/fancy_optimizers.py", "max_issues_repo_name": "raomohan89/GATK", "max_issues_repo_head_hexsha": "068b7fdd6d983cf0b7611b03bd0028d85de61bc2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main/python/org/broadinstitute/hellbender/gcnvkernel/inference/fancy_optimizers.py", "max_forks_repo_name": "raomohan89/GATK", "max_forks_repo_head_hexsha": "068b7fdd6d983cf0b7611b03bd0028d85de61bc2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1795918367, "max_line_length": 111, "alphanum_fraction": 0.6293983546, "include": true, "reason": "import numpy,import theano,import pymc3,from pymc3", "num_tokens": 2050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.26894141551050293, "lm_q1q2_score": 0.14076940954993636}} {"text": "#! /usr/bin/env python3\n\nimport numpy as np\nimport argparse\nimport json\nimport os\nfrom scipy.interpolate import interp1d\n\nparser = argparse.ArgumentParser(description=\"Compute log-likelihoods from light curve evaluations\")\nparser.add_argument(\"--interp-directory\", help=\"Directory containing the interpolator evaluations and index files\")\nparser.add_argument(\"--output-file\", help=\"Name of file to save posterior samples to\")\nparser.add_argument(\"--grid-file\", help=\"Location of the grid file\")\nparser.add_argument(\"--lc-file\", help=\"Location of the light curve JSON file\")\nparser.add_argument(\"--bands\", nargs=\"+\", help=\"Bands to use\")\nparser.add_argument(\"--distance\", type=float, help=\"Luminosity distance (in Mpc)\")\nargs = parser.parse_args()\n\n# Load the files containing the grid indices corresponding to each angle\nindices_fname_base = args.interp_directory + (\"/\" if args.interp_directory[-1] != \"/\" else \"\") + \"indices_\"\ninterp_angles = [0., 30., 45., 60., 75., 90.]\nindices = {_theta_interp:np.loadtxt(indices_fname_base + str(int(_theta_interp)) + \".dat\", ndmin=1).astype(int) for _theta_interp in interp_angles}\n\n# Load the grid\ngrid = np.loadtxt(args.grid_file)\ntheta_grid = grid[:,-1] # angle is the fifth column\n\n# Load the light curve data\nwith open(args.lc_file, \"r\") as fp:\n lc_data = json.load(fp)\nfor b in lc_data.keys():\n for key in lc_data[b].keys():\n lc_data[b][key] = np.array(lc_data[b][key]) # cast everything as a numpy array\n\ninterpolator_times = np.logspace(np.log10(0.125), np.log10(37.239195485411194), 264)\ninterpolator_times_str_to_float = {\"{:.3f}\".format(_t):_t for _t in interpolator_times} # this is useful since the times in the filenames are truncated to three decimal places\n\n# Set up a data structure to hold all the interpolated magnitudes.\n# This is a list with the following structure:\n# - Each element in the list corresponds to a row in the grid.\n# - This list element is a dictionary mapping (band, interpolator_angle) to *another* dictionary.\n# - This sub-dictionary maps the strings \"time\", \"mag\", and \"mag_err\" to lists containing those values\n# The point is to get all the interpolated magnitudes in one place, since they currently exist in many different files,\n# all while keeping track of which grid point each one corresponds to, its time, and its band, and to minimize lookup times going forward.\ninterp_data = [{} for _ in range(theta_grid.size)]\n\n# Fill this data structure with data loaded from the interpolated magnitude files\nfname_base = args.interp_directory + (\"/\" if args.interp_directory[-1] != \"/\" else \"\")\nfor fname in os.listdir(args.interp_directory):\n\n fname_split = fname.split(\"_\")\n\n # Determine whether it's a file we want or not\n if fname_split[0] != \"eval\":\n continue\n \n fname_split = fname_split[2:]\n \n # Get the time, angle, and band from the filename\n t_interp = interpolator_times_str_to_float[fname_split[0]] # convert from the truncated time in the filename to the full time value\n theta_interp = float(fname_split[1])\n band = fname_split[2][0]\n\n if band not in args.bands:\n continue\n\n if indices[theta_interp].size == 0:\n continue\n\n # Load the interpolated magnitude data\n data = np.loadtxt(fname_base + fname)\n \n # \"i\" is the index within this data file\n # \"grid_index\" is the row of the grid corresponding to this particular interpolator evaluation\n for i, grid_index in enumerate(indices[theta_interp]):\n # initialize things if needed\n if (band, theta_interp) not in interp_data[grid_index].keys():\n interp_data[grid_index][(band, theta_interp)] = {\"time\":[], \"mag\":[], \"mag_err\":[]}\n interp_data[grid_index][(band, theta_interp)][\"time\"].append(t_interp)\n interp_data[grid_index][(band, theta_interp)][\"mag\"].append(data[i][0])\n interp_data[grid_index][(band, theta_interp)][\"mag_err\"].append(data[i][1])\n\n# Go through and sort every array in interp_data by time (and also convert them to numpy arrays)\nfor i in range(theta_grid.size):\n for key in interp_data[i].keys():\n interp_data[i][key][\"time\"] = np.array(interp_data[i][key][\"time\"])\n interp_data[i][key][\"mag\"] = np.array(interp_data[i][key][\"mag\"])\n interp_data[i][key][\"mag_err\"] = np.array(interp_data[i][key][\"mag_err\"])\n sorted_indices = np.argsort(interp_data[i][key][\"time\"])\n interp_data[i][key][\"time\"] = interp_data[i][key][\"time\"][sorted_indices]\n interp_data[i][key][\"mag\"] = interp_data[i][key][\"mag\"][sorted_indices]\n interp_data[i][key][\"mag_err\"] = interp_data[i][key][\"mag_err\"][sorted_indices]\n\n# Now build a list of interpolators corresponding to each row in the grid for each band, where the interpolation over angle has been done\nlc_functions = []\nfor i, theta in enumerate(theta_grid):\n # Determine the angular bin\n for j in range(1, len(interp_angles)):\n if interp_angles[j] > theta:\n break\n theta_lower = interp_angles[j - 1]\n theta_upper = interp_angles[j]\n\n f_dict = {}\n for b in args.bands:\n # Get the interpolated values for this row in the grid\n t = interp_data[i][(b, theta_lower)][\"time\"]\n mag_lower = interp_data[i][(b, theta_lower)][\"mag\"]\n mag_err_lower = interp_data[i][(b, theta_lower)][\"mag_err\"]\n mag_upper = interp_data[i][(b, theta_upper)][\"mag\"]\n mag_err_upper = interp_data[i][(b, theta_upper)][\"mag_err\"]\n \n # Interpolate in angle\n mag = ((theta_upper - theta) / (theta_upper - theta_lower)) * mag_lower + ((theta - theta_lower) / (theta_upper - theta_lower)) * mag_upper\n mag_err = ((theta_upper - theta) / (theta_upper - theta_lower)) * mag_err_lower + ((theta - theta_lower) / (theta_upper - theta_lower)) * mag_err_upper\n\n # Interpolate in time and put the interpolators in the dictionary\n f_dict[b] = (interp1d(t, mag, fill_value=\"extrapolate\"), interp1d(t, mag_err, fill_value=\"extrapolate\"))\n\n lc_functions.append(f_dict)\n\n# Now, finally, compute the likelihoods\nlnL = np.zeros(theta_grid.size)\nfor i, f_dict in enumerate(lc_functions):\n for b in args.bands:\n mag_interpolator, mag_err_interpolator = f_dict[b]\n # make sure to account for the distance modulus when computing residuals\n residuals = mag_interpolator(lc_data[b][\"time\"]) + (5. * (np.log10(args.distance * 1.e6) - 1.)) - lc_data[b][\"mag\"]\n model_error = mag_err_interpolator(lc_data[b][\"time\"])\n lnL[i] += -0.5 * np.sum(residuals**2 / (model_error**2 + lc_data[b][\"mag_err\"]**2)\n + np.log(2. * np.pi * (model_error**2 + lc_data[b][\"mag_err\"]**2)))\n\ngrid[:,0] = lnL\n\n# Get the header for the posterior sample file from the grid file, then save\nwith open(args.grid_file, \"r\") as fp:\n header = fp.readline().strip()[2:] # strip off the \"# \" at the beginning and the \"\\n\" at the end\nnp.savetxt(args.output_file, grid, header=header)\n", "meta": {"hexsha": "37a732459383baddd6968254a422afed9d2c7337", "size": 6956, "ext": "py", "lang": "Python", "max_stars_repo_path": "bin/compute_posterior.py", "max_stars_repo_name": "liz-champion/lc_fit", "max_stars_repo_head_hexsha": "f86d28781252783240a33a4b8854e9ecefeab27c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bin/compute_posterior.py", "max_issues_repo_name": "liz-champion/lc_fit", "max_issues_repo_head_hexsha": "f86d28781252783240a33a4b8854e9ecefeab27c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bin/compute_posterior.py", "max_forks_repo_name": "liz-champion/lc_fit", "max_forks_repo_head_hexsha": "f86d28781252783240a33a4b8854e9ecefeab27c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.4057971014, "max_line_length": 175, "alphanum_fraction": 0.691920644, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.26894141551050293, "lm_q1q2_score": 0.14076940954993636}} {"text": "import smart\nimport numpy as np\nimport sys, os, os.path, time\nfrom astropy.table import Table\nfrom numpy.linalg import inv, det\nfrom ..utils.interpolations import trilinear_interpolation\n\n##############################################################################################################\n\n\ndef InterpModel(teff, logg=4, metal=0, alpha=0, modelset='marcs-apogee-dr15', instrument='nirspec', order=33):\n\n FULL_PATH = os.path.realpath(__file__)\n BASE, NAME = os.path.split(FULL_PATH)\n\n # Check the model set and instrument\n if instrument == 'nirspec':\n if modelset.lower() == 'btsettl08':\n path = BASE + '/../libraries/btsettl08/NIRSPEC-O%s-RAW/'%order\n Gridfile = BASE + '/../libraries/btsettl08/btsettl08_gridparams.csv'\n elif modelset.lower() == 'phoenix-aces-agss-cond-2011':\n path = BASE + '/../libraries/PHOENIX_ACES_AGSS_COND_2011/NIRSPEC-O%s-RAW/'%order\n Gridfile = BASE + '/../libraries/PHOENIX_ACES_AGSS_COND_2011/PHOENIX_ACES_AGSS_COND_2011_gridparams.csv'\n elif modelset.lower() == 'sonora-2018':\n path = BASE + '/../libraries/SONORA_2018/NIRSPEC-O%s-RAW/'%order\n Gridfile = BASE + '/../libraries/SONORA_2018/SONORA_2018_gridparams.csv'\n\n elif instrument == 'apogee':\n if modelset.lower() == 'btsettl08':\n path = BASE + '/../libraries/btsettl08/APOGEE-RAW/'\n Gridfile = BASE + '/../libraries/btsettl08/btsettl08_gridparams_apogee.csv'\n elif modelset.lower() == 'phoenix-btsettl-cifist2011-2015':\n path = BASE + '/../libraries/PHOENIX_BTSETTL_CIFIST2011_2015/APOGEE-RAW/'\n Gridfile = BASE + '/../libraries/PHOENIX_BTSETTL_CIFIST2011_2015/PHOENIX_BTSETTL_CIFIST2011_2015_gridparams_apogee.csv'\n elif modelset.lower() == 'phoenix-aces-agss-cond-2011' :\n path = BASE + '/../libraries/PHOENIX_ACES_AGSS_COND_2011/APOGEE-RAW/'\n Gridfile = BASE + '/../libraries/PHOENIX_ACES_AGSS_COND_2011/PHOENIX_ACES_AGSS_COND_2011_gridparams_apogee.csv'\n elif modelset.lower() == 'marcs-apogee-dr15' :\n path = BASE + '/../libraries/MARCS_APOGEE_DR15/APOGEE-RAW/'\n Gridfile = BASE + '/../libraries/MARCS_APOGEE_DR15/MARCS_APOGEE_DR15_gridparams_apogee.csv'\n\n # Read the grid file\n T1 = Table.read(Gridfile)\n\n ###################################################################################\n\n def GetModel(temp, wave=False, **kwargs):\n \n logg = kwargs.get('logg', 4.5)\n metal = kwargs.get('metal', 0)\n alpha = kwargs.get('alpha', 0)\n gridfile = kwargs.get('gridfile', None)\n instrument = kwargs.get('instrument', 'nirspec')\n order = kwargs.get('order', None)\n\n if gridfile is None:\n raise ValueError('Model gridfile must be provided.') \n\n if instrument == 'nirspec': \n if modelset.lower() == 'btsettl08': \n filename = 'btsettl08_t'+ str(int(temp.data[0])) + '_g' + '{0:.2f}'.format(float(logg)) + '_z-' + '{0:.2f}'.format(float(metal)) + '_en' + '{0:.2f}'.format(float(alpha)) + '_NIRSPEC-O' + str(order) + '-RAW.txt'\n elif modelset.lower() == 'phoenix-aces-agss-cond-2011':\n filename = 'PHOENIX_ACES_AGSS_COND_2011_t{0:03d}'.format(int(temp.data[0])) + '_g{0:.2f}'.format(float(logg)) + '_z{0:.2f}'.format(float(metal)) + '_alpha{0:.2f}'.format(float(alpha)) + '_NIRSPEC-O' + str(order) + '-RAW.txt'\n elif modelset.lower() == 'sonora-2018':\n filename = 'SONORA_2018_t{0:03d}'.format(int(temp.data[0])) + '_g{0:.2f}'.format(float(logg)) + '_FeH{0:.2f}'.format(0) + '_Y{0:.2f}'.format(0.28) + '_CO{0:.2f}'.format(1.00) + '_NIRSPEC-O' + str(order) + '-RAW.txt'\n\n if instrument == 'apogee':\n filename = gridfile['File'][np.where( (gridfile['Temp']==temp) & (gridfile['Logg']==logg) & (gridfile['Metal']==metal) & (gridfile['Alpha']==alpha) )].data[0]\n\n Tab = Table.read(path+filename, format='ascii.tab', names=['wave', 'flux'])\n\n if wave:\n return Tab['wave']\n else:\n return Tab['flux']\n\n ###################################################################################\n\n # Check if the model already exists (grid point)\n if modelset.lower() == 'sonora-2018':\n if (teff, logg) in zip(T1['Temp'], T1['Logg']):\n metal, ys = 0, 0.28\n index0 = np.where( (T1['Temp'] == teff) & (T1['Logg'] == logg) & (T1['FeH'] == metal) & (T1['Y'] == ys) )\n #flux2 = GetModel(T1['Temp'][index0], T1['Logg'][index0], T1['Metal'][index0], modelset=modelset )\n #waves2 = GetModel(T1['Temp'][index0], T1['Logg'][index0], T1['Metal'][index0], modelset=modelset, wave=True)\n flux2 = GetModel(T1['Temp'][index0], logg=T1['Logg'][index0], metal=T1['FeH'][index0], alpha=T1['Y'][index0], instrument=instrument, order=order, gridfile=T1)\n waves2 = GetModel(T1['Temp'][index0], logg=T1['Logg'][index0], metal=T1['FeH'][index0], alpha=T1['Y'][index0], instrument=instrument, order=order, gridfile=T1, wave=True)\n return waves2, flux2\n else:\n if (teff, logg, metal, alpha) in zip(T1['Temp'], T1['Logg'], T1['Metal'], T1['Alpha']): \n index0 = np.where( (T1['Temp'] == teff) & (T1['Logg'] == logg) & (T1['Metal'] == metal) & (T1['Alpha'] == alpha) )\n #flux2 = GetModel(T1['Temp'][index0], T1['Logg'][index0], T1['Metal'][index0], modelset=modelset )\n #waves2 = GetModel(T1['Temp'][index0], T1['Logg'][index0], T1['Metal'][index0], modelset=modelset, wave=True)\n flux2 = GetModel(T1['Temp'][index0], logg=T1['Logg'][index0], metal=T1['Metal'][index0], alpha=T1['Alpha'][index0], instrument=instrument, order=order, gridfile=T1)\n waves2 = GetModel(T1['Temp'][index0], logg=T1['Logg'][index0], metal=T1['Metal'][index0], alpha=T1['Alpha'][index0], instrument=instrument, order=order, gridfile=T1, wave=True)\n return waves2, flux2\n\n\n try:\n if modelset.lower() == 'sonora-2018':\n metal, alpha = 0, 0.28\n # Get the nearest models to the gridpoint (Temp)\n x0 = np.max(T1['Temp'][np.where(T1['Temp'] <= teff)])\n x1 = np.min(T1['Temp'][np.where(T1['Temp'] >= teff)])\n #print(x0, x1)\n \n # Get the nearest grid point to Logg\n y0 = np.max(list(set(T1['Logg'][np.where( (T1['Temp'] == x0) & (T1['Logg'] <= logg) )]) & \n set(T1['Logg'][np.where( (T1['Temp'] == x1) & (T1['Logg'] <= logg) )])))\n y1 = np.min(list(set(T1['Logg'][np.where( (T1['Temp'] == x0) & (T1['Logg'] >= logg) )]) & \n set(T1['Logg'][np.where( (T1['Temp'] == x1) & (T1['Logg'] >= logg) )])))\n #print(y0, y1)\n \n # Get the nearest grid point to [M/H]\n z0 = np.max(list(set(T1['FeH'][np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['FeH'] <= metal) )]) & \n set(T1['FeH'][np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['FeH'] <= metal) )])))\n z1 = np.min(list(set(T1['FeH'][np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['FeH'] >= metal) )]) & \n set(T1['FeH'][np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['FeH'] >= metal) )])))\n #print(z0, z1)\n \n # Get the nearest grid point to Alpha\n t0 = np.max(list(set(T1['Y'][np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['FeH'] == z0) & (T1['Y'] <= alpha) )]) & \n set(T1['Y'][np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['FeH'] == z1) & (T1['Y'] <= alpha) )])))\n t1 = np.min(list(set(T1['Y'][np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['FeH'] == z0) & (T1['Y'] >= alpha) )]) & \n set(T1['Y'][np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['FeH'] == z1) & (T1['Y'] >= alpha) )])))\n #print(t0, t1)\n \n else:\n # Get the nearest models to the gridpoint (Temp)\n x0 = np.max(T1['Temp'][np.where(T1['Temp'] <= teff)])\n x1 = np.min(T1['Temp'][np.where(T1['Temp'] >= teff)])\n #print('teff:', x0, teff, x1)\n # Get the nearest grid point to Logg\n y0 = np.max(list(set(T1['Logg'][np.where( (T1['Temp'] == x0) & (T1['Logg'] <= logg) )]) & \n set(T1['Logg'][np.where( (T1['Temp'] == x1) & (T1['Logg'] <= logg) )])))\n y1 = np.min(list(set(T1['Logg'][np.where( (T1['Temp'] == x0) & (T1['Logg'] >= logg) )]) & \n set(T1['Logg'][np.where( (T1['Temp'] == x1) & (T1['Logg'] >= logg) )])))\n #print('logg:', y0, logg, y1)\n # Get the nearest grid point to [M/H]\n #print(metal)\n #print(list(set(T1['Metal'][np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) )])))\n #print(list(set(T1['Metal'][np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) )])))\n #print(list(set(T1['Metal'][np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['Metal'] <= metal))])))\n #print(list(set(T1['Metal'][np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['Metal'] <= metal))])))\n #print(list(set(T1['Metal'][np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['Metal'] >= metal))])))\n #print(list(set(T1['Metal'][np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['Metal'] >= metal))])))\n z0 = np.max(list(set(T1['Metal'][np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['Metal'] <= metal) )]) & \n set(T1['Metal'][np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['Metal'] <= metal) )])))\n z1 = np.min(list(set(T1['Metal'][np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['Metal'] >= metal) )]) & \n set(T1['Metal'][np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['Metal'] >= metal) )])))\n #print('metal:', z0, metal, z1)\n # Get the nearest grid point to Alpha\n #print(list(set(T1['Alpha'][np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['Metal'] == z0) )])))\n #print(list(set(T1['Alpha'][np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['Metal'] == z1) )])))\n #print(list(set(T1['Alpha'][np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['Metal'] == z0) & (T1['Alpha'] <= alpha) )])))\n #print(list(set(T1['Alpha'][np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['Metal'] == z1) & (T1['Alpha'] <= alpha) )])))\n #print(list(set(T1['Alpha'][np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['Metal'] == z0) & (T1['Alpha'] >= alpha) )])))\n #print(list(set(T1['Alpha'][np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['Metal'] == z1) & (T1['Alpha'] >= alpha) )])))\n t0 = np.max(list(set(T1['Alpha'][np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['Metal'] == z0) & (T1['Alpha'] <= alpha) )]) & \n set(T1['Alpha'][np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['Metal'] == z1) & (T1['Alpha'] <= alpha) )])))\n t1 = np.min(list(set(T1['Alpha'][np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['Metal'] == z0) & (T1['Alpha'] >= alpha) )]) & \n set(T1['Alpha'][np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['Metal'] == z1) & (T1['Alpha'] >= alpha) )])))\n #print('alpha:', z0, alpha, z1)\n except:\n raise ValueError('Model Parameters Teff: %0.3f, Logg: %0.3f, [M/H]: %0.3f, Alpha: %0.3f are outside the model grid.'%(teff, logg, metal, alpha))\n\n\n if modelset.lower() == 'sonora-2018':\n # Get the 16 points\n ind0000 = np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['FeH'] == z0) & (T1['Y'] == t0) ) # 0000\n ind1000 = np.where( (T1['Temp'] == x1) & (T1['Logg'] == y0) & (T1['FeH'] == z0) & (T1['Y'] == t0) ) # 1000\n ind0100 = np.where( (T1['Temp'] == x0) & (T1['Logg'] == y1) & (T1['FeH'] == z0) & (T1['Y'] == t0) ) # 0100\n ind0010 = np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['FeH'] == z1) & (T1['Y'] == t0) ) # 0010\n ind0001 = np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['FeH'] == z0) & (T1['Y'] == t1) ) # 0001\n ind1001 = np.where( (T1['Temp'] == x1) & (T1['Logg'] == y0) & (T1['FeH'] == z0) & (T1['Y'] == t1) ) # 1001\n ind0101 = np.where( (T1['Temp'] == x0) & (T1['Logg'] == y1) & (T1['FeH'] == z0) & (T1['Y'] == t1) ) # 0101\n ind0011 = np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['FeH'] == z1) & (T1['Y'] == t1) ) # 0011\n ind1011 = np.where( (T1['Temp'] == x1) & (T1['Logg'] == y0) & (T1['FeH'] == z1) & (T1['Y'] == t1) ) # 1011\n ind0111 = np.where( (T1['Temp'] == x0) & (T1['Logg'] == y1) & (T1['FeH'] == z1) & (T1['Y'] == t1) ) # 0111\n ind1111 = np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['FeH'] == z1) & (T1['Y'] == t1) ) # 1111\n ind0110 = np.where( (T1['Temp'] == x0) & (T1['Logg'] == y1) & (T1['FeH'] == z1) & (T1['Y'] == t0) ) # 0110\n ind1010 = np.where( (T1['Temp'] == x1) & (T1['Logg'] == y0) & (T1['FeH'] == z1) & (T1['Y'] == t0) ) # 1010\n ind1100 = np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['FeH'] == z0) & (T1['Y'] == t0) ) # 1100\n ind1101 = np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['FeH'] == z0) & (T1['Y'] == t1) ) # 1101\n ind1110 = np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['FeH'] == z1) & (T1['Y'] == t0) ) # 1110\n Points = [ [np.log10(T1['Temp'][ind0000]), T1['Logg'][ind0000], T1['FeH'][ind0000], T1['Y'][ind0000], \n np.log10(GetModel(T1['Temp'][ind0000], logg=T1['Logg'][ind0000], metal=T1['FeH'][ind0000], alpha=T1['Y'][ind0000], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind1000]), T1['Logg'][ind1000], T1['FeH'][ind1000], T1['Y'][ind1000], \n np.log10(GetModel(T1['Temp'][ind1000], logg=T1['Logg'][ind1000], metal=T1['FeH'][ind1000], alpha=T1['Y'][ind1000], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind0100]), T1['Logg'][ind0100], T1['FeH'][ind0100], T1['Y'][ind0100], \n np.log10(GetModel(T1['Temp'][ind0100], logg=T1['Logg'][ind0100], metal=T1['FeH'][ind0100], alpha=T1['Y'][ind0100], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind0010]), T1['Logg'][ind0010], T1['FeH'][ind0010], T1['Y'][ind0010], \n np.log10(GetModel(T1['Temp'][ind0010], logg=T1['Logg'][ind0010], metal=T1['FeH'][ind0010], alpha=T1['Y'][ind0010], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind0001]), T1['Logg'][ind0001], T1['FeH'][ind0001], T1['Y'][ind0001], \n np.log10(GetModel(T1['Temp'][ind0001], logg=T1['Logg'][ind0001], metal=T1['FeH'][ind0001], alpha=T1['Y'][ind0001], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind1001]), T1['Logg'][ind1001], T1['FeH'][ind1001], T1['Y'][ind1001], \n np.log10(GetModel(T1['Temp'][ind1001], logg=T1['Logg'][ind1001], metal=T1['FeH'][ind1001], alpha=T1['Y'][ind1001], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind0101]), T1['Logg'][ind0101], T1['FeH'][ind0101], T1['Y'][ind0101], \n np.log10(GetModel(T1['Temp'][ind0101], logg=T1['Logg'][ind0101], metal=T1['FeH'][ind0101], alpha=T1['Y'][ind0101], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind0011]), T1['Logg'][ind0011], T1['FeH'][ind0011], T1['Y'][ind0011], \n np.log10(GetModel(T1['Temp'][ind0011], logg=T1['Logg'][ind0011], metal=T1['FeH'][ind0011], alpha=T1['Y'][ind0011], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind1011]), T1['Logg'][ind1011], T1['FeH'][ind1011], T1['Y'][ind1011], \n np.log10(GetModel(T1['Temp'][ind1011], logg=T1['Logg'][ind1011], metal=T1['FeH'][ind1011], alpha=T1['Y'][ind1011], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind0111]), T1['Logg'][ind0111], T1['FeH'][ind0111], T1['Y'][ind0111], \n np.log10(GetModel(T1['Temp'][ind0111], logg=T1['Logg'][ind0111], metal=T1['FeH'][ind0111], alpha=T1['Y'][ind0111], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind1111]), T1['Logg'][ind1111], T1['FeH'][ind1111], T1['Y'][ind1111], \n np.log10(GetModel(T1['Temp'][ind1111], logg=T1['Logg'][ind1111], metal=T1['FeH'][ind1111], alpha=T1['Y'][ind1111], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind0110]), T1['Logg'][ind0110], T1['FeH'][ind0110], T1['Y'][ind0110], \n np.log10(GetModel(T1['Temp'][ind0110], logg=T1['Logg'][ind0110], metal=T1['FeH'][ind0110], alpha=T1['Y'][ind0110], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind1010]), T1['Logg'][ind1010], T1['FeH'][ind1010], T1['Y'][ind1010], \n np.log10(GetModel(T1['Temp'][ind1010], logg=T1['Logg'][ind1010], metal=T1['FeH'][ind1010], alpha=T1['Y'][ind1010], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind1100]), T1['Logg'][ind1100], T1['FeH'][ind1100], T1['Y'][ind1100], \n np.log10(GetModel(T1['Temp'][ind1100], logg=T1['Logg'][ind1100], metal=T1['FeH'][ind1100], alpha=T1['Y'][ind1100], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind1101]), T1['Logg'][ind1101], T1['FeH'][ind1101], T1['Y'][ind1101], \n np.log10(GetModel(T1['Temp'][ind1101], logg=T1['Logg'][ind1101], metal=T1['FeH'][ind1101], alpha=T1['Y'][ind1101], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind1110]), T1['Logg'][ind1110], T1['FeH'][ind1110], T1['Y'][ind1110], \n np.log10(GetModel(T1['Temp'][ind1110], logg=T1['Logg'][ind1110], metal=T1['FeH'][ind1110], alpha=T1['Y'][ind1110], instrument=instrument, order=order, gridfile=T1))],\n ]\n #print(Points)\n waves2 = GetModel(T1['Temp'][ind1111], logg=T1['Logg'][ind1111], metal=T1['FeH'][ind1111], alpha=T1['Y'][ind1111], instrument=instrument, order=order, gridfile=T1, wave=True)\n else:\n # Get the 16 points\n ind0000 = np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['Metal'] == z0) & (T1['Alpha'] == t0) ) # 0000\n ind1000 = np.where( (T1['Temp'] == x1) & (T1['Logg'] == y0) & (T1['Metal'] == z0) & (T1['Alpha'] == t0) ) # 1000\n ind0100 = np.where( (T1['Temp'] == x0) & (T1['Logg'] == y1) & (T1['Metal'] == z0) & (T1['Alpha'] == t0) ) # 0100\n ind0010 = np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['Metal'] == z1) & (T1['Alpha'] == t0) ) # 0010\n ind0001 = np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['Metal'] == z0) & (T1['Alpha'] == t1) ) # 0001\n ind1001 = np.where( (T1['Temp'] == x1) & (T1['Logg'] == y0) & (T1['Metal'] == z0) & (T1['Alpha'] == t1) ) # 1001\n ind0101 = np.where( (T1['Temp'] == x0) & (T1['Logg'] == y1) & (T1['Metal'] == z0) & (T1['Alpha'] == t1) ) # 0101\n ind0011 = np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['Metal'] == z1) & (T1['Alpha'] == t1) ) # 0011\n ind1011 = np.where( (T1['Temp'] == x1) & (T1['Logg'] == y0) & (T1['Metal'] == z1) & (T1['Alpha'] == t1) ) # 1011\n ind0111 = np.where( (T1['Temp'] == x0) & (T1['Logg'] == y1) & (T1['Metal'] == z1) & (T1['Alpha'] == t1) ) # 0111\n ind1111 = np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['Metal'] == z1) & (T1['Alpha'] == t1) ) # 1111\n ind0110 = np.where( (T1['Temp'] == x0) & (T1['Logg'] == y1) & (T1['Metal'] == z1) & (T1['Alpha'] == t0) ) # 0110\n ind1010 = np.where( (T1['Temp'] == x1) & (T1['Logg'] == y0) & (T1['Metal'] == z1) & (T1['Alpha'] == t0) ) # 1010\n ind1100 = np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['Metal'] == z0) & (T1['Alpha'] == t0) ) # 1100\n ind1101 = np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['Metal'] == z0) & (T1['Alpha'] == t1) ) # 1101\n ind1110 = np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['Metal'] == z1) & (T1['Alpha'] == t0) ) # 1110\n Points = [ [np.log10(T1['Temp'][ind0000]), T1['Logg'][ind0000], T1['Metal'][ind0000], T1['Alpha'][ind0000], \n np.log10(GetModel(T1['Temp'][ind0000], logg=T1['Logg'][ind0000], metal=T1['Metal'][ind0000], alpha=T1['Alpha'][ind0000], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind1000]), T1['Logg'][ind1000], T1['Metal'][ind1000], T1['Alpha'][ind1000], \n np.log10(GetModel(T1['Temp'][ind1000], logg=T1['Logg'][ind1000], metal=T1['Metal'][ind1000], alpha=T1['Alpha'][ind1000], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind0100]), T1['Logg'][ind0100], T1['Metal'][ind0100], T1['Alpha'][ind0100], \n np.log10(GetModel(T1['Temp'][ind0100], logg=T1['Logg'][ind0100], metal=T1['Metal'][ind0100], alpha=T1['Alpha'][ind0100], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind0010]), T1['Logg'][ind0010], T1['Metal'][ind0010], T1['Alpha'][ind0010], \n np.log10(GetModel(T1['Temp'][ind0010], logg=T1['Logg'][ind0010], metal=T1['Metal'][ind0010], alpha=T1['Alpha'][ind0010], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind0001]), T1['Logg'][ind0001], T1['Metal'][ind0001], T1['Alpha'][ind0001], \n np.log10(GetModel(T1['Temp'][ind0001], logg=T1['Logg'][ind0001], metal=T1['Metal'][ind0001], alpha=T1['Alpha'][ind0001], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind1001]), T1['Logg'][ind1001], T1['Metal'][ind1001], T1['Alpha'][ind1001], \n np.log10(GetModel(T1['Temp'][ind1001], logg=T1['Logg'][ind1001], metal=T1['Metal'][ind1001], alpha=T1['Alpha'][ind1001], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind0101]), T1['Logg'][ind0101], T1['Metal'][ind0101], T1['Alpha'][ind0101], \n np.log10(GetModel(T1['Temp'][ind0101], logg=T1['Logg'][ind0101], metal=T1['Metal'][ind0101], alpha=T1['Alpha'][ind0101], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind0011]), T1['Logg'][ind0011], T1['Metal'][ind0011], T1['Alpha'][ind0011], \n np.log10(GetModel(T1['Temp'][ind0011], logg=T1['Logg'][ind0011], metal=T1['Metal'][ind0011], alpha=T1['Alpha'][ind0011], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind1011]), T1['Logg'][ind1011], T1['Metal'][ind1011], T1['Alpha'][ind1011], \n np.log10(GetModel(T1['Temp'][ind1011], logg=T1['Logg'][ind1011], metal=T1['Metal'][ind1011], alpha=T1['Alpha'][ind1011], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind0111]), T1['Logg'][ind0111], T1['Metal'][ind0111], T1['Alpha'][ind0111], \n np.log10(GetModel(T1['Temp'][ind0111], logg=T1['Logg'][ind0111], metal=T1['Metal'][ind0111], alpha=T1['Alpha'][ind0111], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind1111]), T1['Logg'][ind1111], T1['Metal'][ind1111], T1['Alpha'][ind1111], \n np.log10(GetModel(T1['Temp'][ind1111], logg=T1['Logg'][ind1111], metal=T1['Metal'][ind1111], alpha=T1['Alpha'][ind1111], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind0110]), T1['Logg'][ind0110], T1['Metal'][ind0110], T1['Alpha'][ind0110], \n np.log10(GetModel(T1['Temp'][ind0110], logg=T1['Logg'][ind0110], metal=T1['Metal'][ind0110], alpha=T1['Alpha'][ind0110], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind1010]), T1['Logg'][ind1010], T1['Metal'][ind1010], T1['Alpha'][ind1010], \n np.log10(GetModel(T1['Temp'][ind1010], logg=T1['Logg'][ind1010], metal=T1['Metal'][ind1010], alpha=T1['Alpha'][ind1010], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind1100]), T1['Logg'][ind1100], T1['Metal'][ind1100], T1['Alpha'][ind1100], \n np.log10(GetModel(T1['Temp'][ind1100], logg=T1['Logg'][ind1100], metal=T1['Metal'][ind1100], alpha=T1['Alpha'][ind1100], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind1101]), T1['Logg'][ind1101], T1['Metal'][ind1101], T1['Alpha'][ind1101], \n np.log10(GetModel(T1['Temp'][ind1101], logg=T1['Logg'][ind1101], metal=T1['Metal'][ind1101], alpha=T1['Alpha'][ind1101], instrument=instrument, order=order, gridfile=T1))],\n [np.log10(T1['Temp'][ind1110]), T1['Logg'][ind1110], T1['Metal'][ind1110], T1['Alpha'][ind1110], \n np.log10(GetModel(T1['Temp'][ind1110], logg=T1['Logg'][ind1110], metal=T1['Metal'][ind1110], alpha=T1['Alpha'][ind1110], instrument=instrument, order=order, gridfile=T1))],\n ]\n #print(Points)\n waves2 = GetModel(T1['Temp'][ind1111], logg=T1['Logg'][ind1111], metal=T1['Metal'][ind1111], alpha=T1['Alpha'][ind1111], instrument=instrument, order=order, gridfile=T1, wave=True)\n\n return waves2, smart.utils.interpolations.quadlinear_interpolation(np.log10(teff), logg, metal, alpha, Points)\n\n################################################################################################################################################################################################\n\n\ndef InterpModel_3D(Teff, Logg, Metal, modelset='marcs-apogee-dr15', instrument='nirspec', order=33):\n Alpha = 0.0\n FULL_PATH = os.path.realpath(__file__)\n BASE, NAME = os.path.split(FULL_PATH)\n\n # Check the model set\n if instrument == 'nirspec':\n\n if modelset.lower() == 'btsettl08':\n path = BASE + '/../libraries/btsettl08/NIRSPEC-O%s-RAW/'%order\n\n elif modelset.lower() == 'phoenixaces' :\n path = BASE + '/../libraries/phoenixaces/NIRSPEC-O%s-RAW/'%order\n\n elif instrument == 'apogee':\n\n if modelset.lower() == 'btsettl08':\n path = BASE + '/../libraries/btsettl08/APOGEE-RAW/'\n\n elif modelset.lower() == 'phoenix-btsettl-cifist2011-2015':\n path = BASE + '/../libraries/PHOENIX_BTSETTL_CIFIST2011_2015/APOGEE-RAW/'\n \n elif modelset.lower() == 'phoenix-aces-agss-cond-2011' :\n path = BASE + '/../libraries/PHOENIX_ACES_AGSS_COND_2011/APOGEE-RAW/'\n\n elif modelset.lower() == 'marcs-apogee-dr15' :\n path = BASE + '/../libraries/MARCS_APOGEE_DR15/APOGEE-RAW_3D/'\n\n def GetModel(temp, logg, metal, modelset='marcs-apogee-dr15', wave=False):\n en = 0.00\n if instrument == 'nirspec':\n\n if modelset.lower() == 'btsettl08':\n # alpha enhancement correction\n if metal == -0.5:\n en = 0.2\n elif (metal == -1.0) or (metal == -1.5) or (metal == -2.0) or (metal == -2.5):\n en = 0.4\n\n if metal == 0.0:\n filename = 'btsettl08_t'+ str(int(temp.data[0])) + '_g' + '{0:.2f}'.format(float(logg)) + '_z-' + '{0:.2f}'.format(float(metal)) + '_en' + '{0:.2f}'.format(float(en)) + '_NIRSPEC-O' + str(order) + '-RAW.txt'\n elif metal == 0.5:\n filename = 'btsettl08_t'+ str(int(temp.data[0])) + '_g' + '{0:.2f}'.format(float(logg)) + '_z' + '{0:.2f}'.format(float(metal)) + '_en' + '{0:.2f}'.format(float(en)) + '_NIRSPEC-O' + str(order) + '-RAW.txt'\n else:\n filename = 'btsettl08_t'+ str(int(temp.data[0])) + '_g' + '{0:.2f}'.format(float(logg)) + '_z' + '{0:.2f}'.format(float(metal)) + '_en' + '{0:.2f}'.format(float(en)) + '_NIRSPEC-O' + str(order) + '-RAW.txt'\n \n elif modelset.lower() == 'phoenixaces':\n filename = 'phoenixaces_t{0:03d}'.format(int(temp.data[0])) + '_g{0:.2f}'.format(float(logg)) + '_z-{0:.2f}'.format(float(metal)) + '_en{0:.2f}'.format(float(en)) + '_NIRSPEC-O' + str(order) + '-RAW.txt'\n \n elif instrument == 'apogee':\n if modelset.lower() == 'btsettl08':\n # alpha enhancement correction\n if metal == -0.5:\n en = 0.2\n elif (metal == -1.0) or (metal == -1.5) or (metal == -2.0) or (metal == -2.5):\n en = 0.4\n\n if metal == 0.0:\n filename = 'btsettl08_t'+ str(int(temp.data[0])) + '_g' + '{0:.2f}'.format(float(logg)) + '_z-' + '{0:.2f}'.format(float(metal)) + '_en' + '{0:.2f}'.format(float(en)) + '_APOGEE-RAW.txt'\n elif metal > 0.0:\n filename = 'btsettl08_t'+ str(int(temp.data[0])) + '_g' + '{0:.2f}'.format(float(logg)) + '_z' + '{0:.2f}'.format(float(metal)) + '_en' + '{0:.2f}'.format(float(en)) + '_APOGEE-RAW.txt'\n else:\n filename = 'btsettl08_t'+ str(int(temp.data[0])) + '_g' + '{0:.2f}'.format(float(logg)) + '_z' + '{0:.2f}'.format(float(metal)) + '_en' + '{0:.2f}'.format(float(en)) + '_APOGEE-RAW.txt'\n \n elif modelset.lower() == 'phoenix-btsettl-cifist2011-2015':\n filename = 'PHOENIX_BTSETTL_CIFIST2011_2015_t{0:03d}'.format(int(temp.data[0])) + '_g{0:.2f}'.format(float(logg)) + '_z{0:.2f}'.format(float(metal)) + '_en{0:.2f}'.format(float(en)) + '_APOGEE-RAW.txt'\n\n elif modelset.lower() == 'phoenix-aces-agss-cond-2011':\n filename = 'PHOENIX_ACES_AGSS_COND_2011_t{0:03d}'.format(int(temp.data[0])) + '_g{0:.2f}'.format(float(logg)) + '_z{0:.2f}'.format(float(metal)) + '_en{0:.2f}'.format(float(en)) + '_APOGEE-RAW.txt'\n \n elif modelset.lower() == 'marcs-apogee-dr15':\n filename = 'MARCS_APOGEE_DR15_t{0:03d}'.format(int(temp.data[0])) + '_g{0:.2f}'.format(float(logg)) + '_z{0:.2f}'.format(float(metal)) + '_en{0:.2f}'.format(float(en)) + '_APOGEE-RAW.txt'\n\n Tab = Table.read(path+filename, format='ascii.tab', names=['wave', 'flux'])\n\n if wave:\n return Tab['wave']\n else:\n return Tab['flux']\n\n \n\n if instrument == 'nirspec':\n\n if modelset.lower() == 'btsettl08':\n Gridfile = BASE + '/../libraries/btsettl08/btsettl08_gridparams.csv'\n\n elif modelset.lower() == 'phoenixaces':\n Gridfile = BASE + '/../libraries/phoenixaces/phoenixaces_gridparams.csv'\n\n elif instrument == 'apogee':\n\n if modelset.lower() == 'btsettl08':\n Gridfile = BASE + '/../libraries/btsettl08/btsettl08_gridparams_apogee.csv'\n\n elif modelset.lower() == 'phoenix-btsettl-cifist2011-2015':\n Gridfile = BASE + '/../libraries/PHOENIX_BTSETTL_CIFIST2011_2015/PHOENIX_BTSETTL_CIFIST2011_2015_gridparams_apogee.csv'\n\n elif modelset.lower() == 'phoenix-aces-agss-cond-2011':\n Gridfile = BASE + '/../libraries/PHOENIX_ACES_AGSS_COND_2011/PHOENIX_ACES_AGSS_COND_2011_gridparams_apogee.csv'\n\n elif modelset.lower() == 'marcs-apogee-dr15':\n Gridfile = BASE + '/../libraries/MARCS_APOGEE_DR15/MARCS_APOGEE_DR15_3D_gridparams_apogee.csv'\n\n T1 = Table.read(Gridfile)\n # Check if the model already exists (grid point)\n if (Teff, Logg, Metal) in zip(T1['Temp'], T1['Logg'], T1['Metal']):\n if modelset.lower() == 'btsettl08':\n if Metal == -0.5:\n Alpha = 0.2\n elif (Metal == -1.0) or (Metal == -1.5) or (Metal == -2.0) or (Metal == -2.5):\n Alpha = 0.4\n index0 = np.where( (T1['Temp'] == Teff) & (T1['Logg'] == Logg) & (T1['Metal'] == Metal) & (T1['Alpha'] == Alpha) )\n flux2 = GetModel(T1['Temp'][index0], T1['Logg'][index0], T1['Metal'][index0], modelset=modelset )\n waves2 = GetModel(T1['Temp'][index0], T1['Logg'][index0], T1['Metal'][index0], modelset=modelset, wave=True)\n return waves2, flux2\n\n # Get the nearest models to the gridpoint (Temp)\n x0 = np.max(T1['Temp'][np.where(T1['Temp'] <= Teff)])\n x1 = np.min(T1['Temp'][np.where(T1['Temp'] >= Teff)])\n #print(x0, Teff, x1)\n #y0 = T1['Logg'][np.where( ( (T1['Temp'] == x0) | (T1['Temp'] == x1) ) & (T1['Logg'] <= Logg) )][-1]\n #y1 = T1['Logg'][np.where( ( (T1['Temp'] == x0) | (T1['Temp'] == x1) ) & (T1['Logg'] >= Logg) )][0]\n #print(x0, list(set(T1['Logg'][np.where( ( (T1['Temp'] == x0) & (T1['Logg'] <= Logg) ) )])))\n #print(x1, list(set(T1['Logg'][np.where( ( (T1['Temp'] == x1) & (T1['Logg'] <= Logg) ) )])))\n #print(x0, list(set(T1['Logg'][np.where( ( (T1['Temp'] == x0) & (T1['Logg'] >= Logg) ) )])))\n #print(x1, list(set(T1['Logg'][np.where( ( (T1['Temp'] == x1) & (T1['Logg'] >= Logg) ) )])))\n y0 = np.max(list(set(T1['Logg'][np.where( ( (T1['Temp'] == x0) & (T1['Logg'] <= Logg) ) )]) & set(T1['Logg'][np.where( ( (T1['Temp'] == x1) & (T1['Logg'] <= Logg) ) )])))\n y1 = np.min(list(set(T1['Logg'][np.where( ( (T1['Temp'] == x0) & (T1['Logg'] >= Logg) ) )]) & set(T1['Logg'][np.where( ( (T1['Temp'] == x1) & (T1['Logg'] >= Logg) ) )])))\n #print(y0, Logg, y1)\n #z0 = T1['pgs'][np.where( ( (T1['Temp'] == x0) | (T1['Temp'] == x1) ) & ( (T1['Logg'] == y0) | (T1['Logg'] == y1) ) & (T1['pgs'] <= PGS) )][-1]\n #z1 = T1['pgs'][np.where( ( (T1['Temp'] == x0) | (T1['Temp'] == x1) ) & ( (T1['Logg'] == y0) | (T1['Logg'] == y1) ) & (T1['pgs'] >= PGS) )][0]\n #print(x0, y0, list(set(T1['pgs'][np.where( ( (T1['Temp'] == x0) & (T1['Logg'] == y0) ) & (T1['pgs'] <= PGS))])))\n #print(x1, y1, list(set(T1['pgs'][np.where( ( (T1['Temp'] == x1) & (T1['Logg'] == y1) ) & (T1['pgs'] <= PGS))])))\n #print(x0, y0, list(set(T1['pgs'][np.where( ( (T1['Temp'] == x0) & (T1['Logg'] == y0) ) & (T1['pgs'] >= PGS))])))\n #print(x1, y1, list(set(T1['pgs'][np.where( ( (T1['Temp'] == x1) & (T1['Logg'] == y1) ) & (T1['pgs'] >= PGS))])))\n z0 = np.max(list(set(T1['Metal'][np.where( ( (T1['Temp'] == x0) & (T1['Logg'] == y0) ) & (T1['Metal'] <= Metal) )]) & set(T1['Metal'][np.where( ( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['Metal'] <= Metal)) )])))\n z1 = np.min(list(set(T1['Metal'][np.where( ( (T1['Temp'] == x0) & (T1['Logg'] == y0) ) & (T1['Metal'] >= Metal) )]) & set(T1['Metal'][np.where( ( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['Metal'] >= Metal)) )])))\n #print(z0, PGS, z1)\n\n # Check if the gridpoint exists within the model ranges\n for x in [x0, x1]:\n for y in [y0, y1]:\n for z in [z0, z1]:\n if (x, y, z) not in zip(T1['Temp'], T1['Logg'], T1['Metal']):\n print('No Model', x, y, z)\n return 1\n '''\n print(np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1)))\n print(np.where( (T1['Temp'] == x1) & (T1['Logg'] == y2)))\n print(np.where( (T1['Temp'] == x2) & (T1['Logg'] == y1)))\n print(np.where( (T1['Temp'] == x2) & (T1['Logg'] == y2)))\n print(np.log10(T1['Temp'][np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1))]), np.log10(T1['Logg'][np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1))]))\n print(np.log10(T1['Temp'][np.where( (T1['Temp'] == x1) & (T1['Logg'] == y2))]), np.log10(T1['Logg'][np.where( (T1['Temp'] == x1) & (T1['Logg'] == y2))]))\n print(np.log10(T1['Temp'][np.where( (T1['Temp'] == x2) & (T1['Logg'] == y1))]), np.log10(T1['Logg'][np.where( (T1['Temp'] == x2) & (T1['Logg'] == y1))]))\n print(np.log10(T1['Temp'][np.where( (T1['Temp'] == x2) & (T1['Logg'] == y2))]), np.log10(T1['Logg'][np.where( (T1['Temp'] == x2) & (T1['Logg'] == y2))]))\n '''\n # Get the 16 points\n if modelset.lower() == 'btsettl08':\n if z0 == -0.5:\n Alpha0 = 0.2\n elif (z0 == -1.0) or (z0 == -1.5) or (z0 == -2.0) or (z0 == -2.5):\n Alpha0 = 0.4\n else:\n Alpha0 = 0.0\n if z1 == -0.5:\n Alpha1 = 0.2\n elif (z1 == -1.0) or (z1 == -1.5) or (z1 == -2.0) or (z1 == -2.5):\n Alpha1 = 0.4\n else:\n Alpha1 = 0.0\n ind000 = np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['Metal'] == z0) & (T1['Alpha'] == Alpha0) ) # 000\n ind100 = np.where( (T1['Temp'] == x1) & (T1['Logg'] == y0) & (T1['Metal'] == z0) & (T1['Alpha'] == Alpha0) ) # 100\n ind010 = np.where( (T1['Temp'] == x0) & (T1['Logg'] == y1) & (T1['Metal'] == z0) & (T1['Alpha'] == Alpha0) ) # 010\n ind110 = np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['Metal'] == z0) & (T1['Alpha'] == Alpha0) ) # 110\n ind001 = np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['Metal'] == z1) & (T1['Alpha'] == Alpha1) ) # 001\n ind101 = np.where( (T1['Temp'] == x1) & (T1['Logg'] == y0) & (T1['Metal'] == z1) & (T1['Alpha'] == Alpha1) ) # 101\n ind011 = np.where( (T1['Temp'] == x0) & (T1['Logg'] == y1) & (T1['Metal'] == z1) & (T1['Alpha'] == Alpha1) ) # 011\n ind111 = np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['Metal'] == z1) & (T1['Alpha'] == Alpha1) ) # 111\n\n else:\n ind000 = np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['Metal'] == z0) & (T1['Alpha'] == Alpha) ) # 000\n ind100 = np.where( (T1['Temp'] == x1) & (T1['Logg'] == y0) & (T1['Metal'] == z0) & (T1['Alpha'] == Alpha) ) # 100\n ind010 = np.where( (T1['Temp'] == x0) & (T1['Logg'] == y1) & (T1['Metal'] == z0) & (T1['Alpha'] == Alpha) ) # 010\n ind110 = np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['Metal'] == z0) & (T1['Alpha'] == Alpha) ) # 110\n ind001 = np.where( (T1['Temp'] == x0) & (T1['Logg'] == y0) & (T1['Metal'] == z1) & (T1['Alpha'] == Alpha) ) # 001\n ind101 = np.where( (T1['Temp'] == x1) & (T1['Logg'] == y0) & (T1['Metal'] == z1) & (T1['Alpha'] == Alpha) ) # 101\n ind011 = np.where( (T1['Temp'] == x0) & (T1['Logg'] == y1) & (T1['Metal'] == z1) & (T1['Alpha'] == Alpha) ) # 011\n ind111 = np.where( (T1['Temp'] == x1) & (T1['Logg'] == y1) & (T1['Metal'] == z1) & (T1['Alpha'] == Alpha) ) # 111\n\n Points = [ [np.log10(T1['Temp'][ind000]), T1['Logg'][ind000], T1['Metal'][ind000], \n np.log10(GetModel(T1['Temp'][ind000], T1['Logg'][ind000], T1['Metal'][ind000], modelset=modelset))],\n [np.log10(T1['Temp'][ind100]), T1['Logg'][ind100], T1['Metal'][ind100], \n np.log10(GetModel(T1['Temp'][ind100], T1['Logg'][ind100], T1['Metal'][ind100], modelset=modelset))],\n [np.log10(T1['Temp'][ind010]), T1['Logg'][ind010], T1['Metal'][ind010], \n np.log10(GetModel(T1['Temp'][ind010], T1['Logg'][ind010], T1['Metal'][ind010], modelset=modelset))],\n [np.log10(T1['Temp'][ind110]), T1['Logg'][ind110], T1['Metal'][ind110], \n np.log10(GetModel(T1['Temp'][ind110], T1['Logg'][ind110], T1['Metal'][ind110], modelset=modelset))],\n [np.log10(T1['Temp'][ind001]), T1['Logg'][ind001], T1['Metal'][ind001], \n np.log10(GetModel(T1['Temp'][ind001], T1['Logg'][ind001], T1['Metal'][ind001], modelset=modelset))],\n [np.log10(T1['Temp'][ind101]), T1['Logg'][ind101], T1['Metal'][ind101], \n np.log10(GetModel(T1['Temp'][ind101], T1['Logg'][ind101], T1['Metal'][ind101], modelset=modelset))],\n [np.log10(T1['Temp'][ind011]), T1['Logg'][ind011], T1['Metal'][ind011], \n np.log10(GetModel(T1['Temp'][ind011], T1['Logg'][ind011], T1['Metal'][ind011], modelset=modelset))],\n [np.log10(T1['Temp'][ind111]), T1['Logg'][ind111], T1['Metal'][ind111], \n np.log10(GetModel(T1['Temp'][ind111], T1['Logg'][ind111], T1['Metal'][ind111], modelset=modelset))],\n ]\n #print(Points)\n waves2 = GetModel(T1['Temp'][ind000], T1['Logg'][ind000], T1['Metal'][ind000], wave=True, modelset=modelset)\n\n return waves2, trilinear_interpolation(np.log10(Teff), Logg, Metal, Points)\n\n\n\n ################################################################################################\n", "meta": {"hexsha": "34035fa59c24ce4f4a3bd38e72b74542bbee0e74", "size": 40678, "ext": "py", "lang": "Python", "max_stars_repo_path": "smart/forward_model/InterpolateModel_txt.py", "max_stars_repo_name": "Lingfeng-Wei/smart", "max_stars_repo_head_hexsha": "2316e50bfb6f050d5dcdd0ee1e5eab6831e8a669", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-01-21T09:09:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T18:24:02.000Z", "max_issues_repo_path": "smart/forward_model/InterpolateModel_txt.py", "max_issues_repo_name": "Lingfeng-Wei/smart", "max_issues_repo_head_hexsha": "2316e50bfb6f050d5dcdd0ee1e5eab6831e8a669", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-02-07T19:03:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T01:21:56.000Z", "max_forks_repo_path": "smart/forward_model/InterpolateModel_txt.py", "max_forks_repo_name": "Lingfeng-Wei/smart", "max_forks_repo_head_hexsha": "2316e50bfb6f050d5dcdd0ee1e5eab6831e8a669", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-22T21:54:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-11T05:16:53.000Z", "avg_line_length": 82.1777777778, "max_line_length": 240, "alphanum_fraction": 0.5121933232, "include": true, "reason": "import numpy,from numpy,from astropy", "num_tokens": 14771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.26894141551050293, "lm_q1q2_score": 0.14076940954993636}} {"text": "\nimport ROOT\nimport numpy as np\nfrom collections import defaultdict\nfrom gna import datapath\nimport gna.parameters.ibd\nimport gna.parameters.oscillation\nimport itertools\nfrom gna.exp import baseexp\nfrom gna.env import env\nimport gna.constructors as C\n\n\nyear=365*24*60*60.0\n\nspectrumfiles = {\n 'Pu239': 'reactor_anu_spectra/Huber/Huber_smooth_extrap_Pu239_13MeV0.01MeVbin.dat',\n 'Pu241': 'reactor_anu_spectra/Huber/Huber_smooth_extrap_Pu241_13MeV0.01MeVbin.dat',\n 'U235': 'reactor_anu_spectra/Huber/Huber_smooth_extrap_U235_13MeV0.01MeVbin.dat',\n 'U238': 'reactor_anu_spectra/Mueller/Mueller_smooth_extrap_U238_13MeV0.01MeVbin.dat',\n}\n\neperfission = {\n 'Pu239': (209.99, 0.60),\n 'Pu241': (213.60, 0.65),\n 'U235': (201.92, 0.46),\n 'U238': (205.52, 0.96),\n}\n\ngeo_flux_files = {\n 'U238': 'AntineutrinoSpectrum_238U.knt',\n 'Th232': 'AntineutrinoSpectrum_232Th.knt',\n}\n\ngeo_flux_normalizations = {\n 'U238': (2.7e3/5, 0.3),\n 'Th232': (0.8e3/5, 0.3),\n}\n\nclass Reactor(object):\n def __init__(self, name, location, fission_fractions,\n power=None, power_rate=None):\n self.name = name\n self.location = location\n\n self.power = power\n\n self.power_rate = power_rate\n\n self.fission_fractions = {isoname: frac\n for isoname, frac in fission_fractions.items()}\n\n def assign(self, ns):\n self.ns = ns(\"reactors\")(self.name)\n self.ns.reqparameter(\"ThermalPower\", central=self.power, sigma=0)\n\n def calcdistance(self, detector):\n return np.sqrt(np.sum((np.array(self.location) - np.array(detector.location))**2))\n\n def initdistance(self, ns, detector):\n dist = self.calcdistance(detector)\n pair_ns = detector.ns(self.name)\n pair_ns.reqparameter(\"L_{0}\".format(self.name), central=dist, sigma=0)\n pair_ns.defparameter(\"L\", target=pair_ns.ref(\"L_{0}\".format(self.name)))\n\nclass ReactorGroup(object):\n def __init__(self, name, reactors):\n self.name = name\n self.reactors = reactors\n\n self.power = 1\n self.power_rate = reactors[0].power_rate\n\n self.fission_fractions = reactors[0].fission_fractions\n\n def assign(self, ns):\n self.ns = ns(\"reactorgroups\")(self.name)\n\n def initdistance(self, ns, detector):\n pair_ns = detector.ns(self.name)\n bindings = {}\n for i, reactor in enumerate(self.reactors):\n bindings[\"L_{0}\".format(i)] = detector.ns(reactor.name)[\"L\"]\n bindings[\"P_{0}\".format(i)] = reactor.ns[\"ThermalPower\"]\n ROOT.ReactorGroup(len(self.reactors), ns=pair_ns, bindings=bindings)\n\n pair_ns.defparameter(\"L\", target=pair_ns.ref(\"Lavg\"))\n pair_ns.defparameter(\"ThermalPower\", target=pair_ns.ref(\"Pavg\"))\n\nclass Detector(object):\n def __init__(self, name, edges, location,\n orders=None, protons=None, livetime=None, edges_final=None):\n self.name = name\n self.edges = edges\n self.edges_final = edges_final\n self.orders = orders\n\n self.location = location\n\n self.protons = protons\n\n self.livetime = livetime\n\n self.unoscillated = None\n self.components = defaultdict(lambda: defaultdict(ROOT.Sum))\n self.backgrounds = defaultdict(ROOT.Sum)\n self.intermediates = {}\n self.intermediates_bkg = {}\n self.hists = defaultdict(dict)\n self.back_hists = defaultdict(dict)\n\n def assign(self, ns):\n self.ns = ns(\"detectors\")(self.name)\n\n if self.protons is not None:\n self.ns.defparameter(\"TargetProtons\", central=self.protons, relsigma=0.01)\n\n self.ns.reqparameter(\"Eres_a\", central=0.0, sigma=0)\n self.ns.reqparameter(\"Eres_b\", central=0.03, sigma=0)\n self.ns.reqparameter(\"Eres_c\", central=0.0, sigma=0)\n self.ns.reqparameter(\"rho_C14\", central=1e-16, sigma=1e-19)\n self.ns.reqparameter(\"CoincidenceWindow\", central=300, sigma=1)\n\nclass GeoNeutrinoIsotope(object):\n def __init__(self, name):\n self.name = name\n\n try:\n Es_keV, self.ys = np.loadtxt(datapath(geo_flux_files[name]), unpack=True, skiprows=5)\n except OSError:\n raise Exception(\"Failed to load spectrum of {0} geo isotope from {1}\".format(name, geo_flux_files[name]))\n self.Es = Es_keV*1e-3\n self.spectrum = ROOT.LinearInterpolator(len(self.Es), self.Es.copy(), self.ys.copy(), \"use_zero\")\n\nclass Isotope(object):\n def __init__(self, ns, name):\n self.ns = ns(\"isotopes\")(name)\n self.name = name\n\n try:\n self.Es, self.ys = np.loadtxt(datapath(spectrumfiles[name]), unpack=True)\n except OSError:\n raise Exception(\"Failed to load spectrum of {0} reactor isotope from {1}\".format(name, datapath(spectrumfiles[name])))\n\n self.spectrum = ROOT.LinearInterpolator(len(self.Es), self.Es.copy(), self.ys.copy(), \"use_zero\")\n\nclass ReactorExperimentModel(baseexp):\n oscprob_classes = {\n 'standard': ROOT.OscProbPMNS,\n 'decoh': ROOT.OscProbPMNSDecoh,\n }\n\n @classmethod\n def initparser(self, parser, env):\n \"\"\"Initializes arguments parser with args common to all reactor experiments\"\"\"\n # def OscProb(name):\n # return {\n # 'standard': ROOT.OscProbPMNS,\n # 'decoh': ROOT.OscProbPMNSDecoh,\n # }[name]\n parser.add_argument('--name', required=True)\n parser.add_argument('--ibd', choices=['zero', 'first'], default='zero')\n parser.add_argument('--backgrounds', choices=['geo'], action='append',\n default=[], help='Choose backgrounds you want to add')\n parser.add_argument('--oscprob', choices=self.oscprob_classes.keys(),\n default='standard')\n parser.add_argument('--binning', nargs=4, metavar=('DETECTOR', 'EMIN', 'EMAX', 'NBINS'), action='append', default=[])\n parser.add_argument('--binning-final', nargs=6, metavar=('DETECTOR', 'EMIN', 'E0', 'E1', 'NBINS01', 'EMAX'), action='append', default=[])\n parser.add_argument('--integration-order', type=int, default=4)\n parser.add_argument('--no-reactor-groups', action='store_true')\n parser.add_argument('--with-C14', action='store_true')\n\n def __init__(self, opts, ns=None, reactors=None, detectors=None):\n \"\"\"Initialize a reactor experiment\n\n opts -- object with parsed common arguments returned by argparse\n ns -- namespace where experiment will create missing parameters, if is not provided ``opts.name`` will be used\n reactors -- iterable over Reactor objects, self.makereactors() will be called if None\n detectors -- iterable over Detector objects, self.makedetoctrs() will be called if None\n \"\"\"\n super(ReactorExperimentModel, self).__init__(None, opts)\n self._oscprobs = {}\n self._oscprobcls = self.oscprob_classes[self.opts.oscprob]\n self._isotopes = defaultdict(list)\n self._Enu_inputs = defaultdict(set)\n self.oscprobs_comps = defaultdict(dict)\n self._geo_isotopes = defaultdict(list)\n\n self.ns = ns or env.ns(opts.name)\n self.reqparameters(self.ns)\n\n self.detectors = list(detectors if detectors is not None else self.makedetectors())\n for binopt in self.opts.binning:\n for det in self.detectors:\n if det.name == binopt[0]:\n break\n else:\n raise Exception(\"can't find detector {}\".format(binopt[0]))\n det.edges = np.linspace(float(binopt[1]), float(binopt[2]), int(binopt[3]))\n for (detname, emin, e0, e1, ne, emax) in self.opts.binning_final:\n for det in self.detectors:\n if det.name == detname:\n break\n else:\n raise Exception(\"can't find detector {}\".format(detname))\n det.edges_final = np.concatenate(([float(emin)],\n np.linspace(float(e0), float(e1), int(ne)),\n [float(emax)]))\n for det in self.detectors:\n det.assign(self.ns)\n if det.orders is None:\n det.orders = np.full(len(det.edges)-1, self.opts.integration_order, int)\n\n self.reactors = list(reactors if reactors is not None else self.makereactors())\n for reactor in self.reactors:\n reactor.assign(self.ns)\n\n self.linkpairs(self.reactors, self.detectors)\n\n for detector in self.detectors:\n self.make_backgrounds(detector, opts.backgrounds)\n self.setibd(detector, opts.ibd)\n self.setupobservations(detector)\n\n def make_backgrounds(self, detector, background_list):\n \"\"\"Produce backgrounds and store them to detector components,\n currently only geoneutrino flux. Normalize it latter in makeibd\"\"\"\n\n # pass\n for bkg in background_list:\n if bkg == 'geo':\n for iso_name in geo_flux_files.keys():\n geo_isotope = GeoNeutrinoIsotope(iso_name)\n self._isotopes[\"geo_\"+iso_name].append(geo_isotope)\n self._Enu_inputs[detector].add(geo_isotope.spectrum.f.inputs.x)\n detector.intermediates_bkg['geo_flux_{}'.format(iso_name)] = geo_isotope.spectrum\n\n\n\n def _getoscprobcls(self, reactor, detector):\n \"\"\"Returns oscillation probability class for given (reactor, detector) pair\"\"\"\n if isinstance(reactor, ReactorGroup):\n return (ROOT.OscProbPMNSMult, ROOT.OscProbPMNS)\n keys = [frozenset([reactor, detector]), reactor, detector, None]\n for key in keys:\n try:\n return (self._oscprobs[key], self._oscprobs[key])\n except KeyError:\n pass\n return (self._oscprobcls, self._oscprobcls)\n\n def _getnormtype(self, reactor, detector):\n \"\"\"Returns normalization type applicable for given reactor and detector\n\n if power, power rate, protons and livetime are provided, 'calc' is returned to calculate normalization\n otherwise 'manual' is returned meaning that normalization should be done by the caller with external Norm parameters\n \"\"\"\n if all(x is not None for x in [reactor.power, reactor.power_rate, detector.protons, detector.livetime]):\n return 'calc'\n return 'manual'\n\n def groupreactors(self, reactors, detector, precision=1e-2):\n \"\"\"Merges some Reactors of reactors to ReactorGroup if their distances to detector are similar enough\n\n Faster approximated formula is used. Only reactors with standard OscProbPMNS formula are considered for grouping.\n Approximation of the probability is of the order of order precision**3.\n \"\"\"\n groups = [[reactor] for reactor in reactors]\n groupable = []\n if not self.opts.no_reactor_groups:\n for reactor in reactors:\n if self._getoscprobcls(reactor, detector)[0] is ROOT.OscProbPMNS:\n if self._getnormtype(reactor, detector) == 'calc':\n groupable.append(reactor)\n groups.remove([reactor])\n if not groupable:\n return reactors\n groups.append([])\n for reactor in sorted(groupable, key=lambda r: r.calcdistance(detector)):\n groups[-1].append(reactor)\n L = np.array([r.calcdistance(detector) for r in groups[-1]])\n P = np.array([r.power for r in groups[-1]])\n Lavg = sum(P/L)/sum(P/L**2)\n if not all(abs(L/Lavg-1) < precision):\n groups.append([groups[-1].pop()])\n grouped = []\n cnt = 0\n for group in groups:\n if len(group) > 1:\n rgroup = ReactorGroup(\"group{}\".format(cnt), group)\n rgroup.assign(self.ns)\n rgroup.initdistance(self.ns, detector)\n grouped.append(rgroup)\n cnt += 1\n else:\n grouped.append(group[0])\n return grouped\n\n def normalization(self, reactor, detector, normtype):\n \"\"\"Returns normalization object for given reactor/detector pair and norm type\"\"\"\n def vec(lst):\n v = ROOT.vector(\"std::string\")()\n for s in lst:\n v.push_back(s)\n return v\n\n if normtype == 'calc':\n bindings = {}\n for isoname in reactor.fission_fractions:\n bindings[\"EnergyPerFission_{0}\".format(isoname)] = self.ns(\"isotopes\")(isoname)[\"EnergyPerFission\"]\n norm = ROOT.ReactorNorm(vec(reactor.fission_fractions.keys()), bindings=bindings)\n lt=C.Points(detector.livetime)\n lt.points.setLabel('livetime: | '+detector.name)\n norm.isotopes.livetime(lt)\n pr=C.Points(reactor.power_rate)\n pr.points.setLabel('power: | '+reactor.name)\n norm.isotopes.power_rate(pr)\n norm.isotopes.setLabel('norm: | {} to {}'.format(reactor.name, detector.name))\n for isoname, frac in reactor.fission_fractions.items():\n ff=C.Points(frac)\n ff.points.setLabel('fission frac: | {} at {}'.format(isoname, reactor.name))\n norm.isotopes['fission_fraction_{0}'.format(isoname)](ff)\n elif normtype == 'manual':\n norm = ROOT.ReactorNormAbsolute(vec(reactor.fission_fractions.keys()))\n for isoname, frac in reactor.fission_fractions.items():\n norm.isotopes['fission_fraction_{0}'.format(isoname)](frac)\n return norm\n\n def linkpairs(self, reactors, detectors):\n \"\"\"Setup oscillations and normalizations of all reactors and detectors.\n\n Resulting components are stored in detector.components.\n \"\"\"\n for reactor, detector in itertools.product(reactors, detectors):\n reactor.initdistance(self.ns, detector)\n\n for detector in detectors:\n detector.unoscillated = ROOT.Sum()\n detector.unoscillated.sum.setLabel('unosc flux: | '+detector.name)\n grouped = self.groupreactors(reactors, detector)\n for rgroup in grouped:\n pair_ns = detector.ns(rgroup.name)\n normtype = self._getnormtype(rgroup, detector)\n with detector.ns, rgroup.ns, pair_ns:\n norm = self.norm = self.normalization(rgroup, detector, normtype)\n oscprobcls, weightscls = self._getoscprobcls(rgroup, detector)\n with self.ns(\"oscillation\"):\n oscprob = oscprobcls(ROOT.Neutrino.ae(), ROOT.Neutrino.ae())\n\n normedflux = ROOT.Sum()\n normedflux.sum.setLabel('normed flux: | {}'.format(rgroup.name))\n\n for isoname in rgroup.fission_fractions.keys():\n isotope = Isotope(self.ns, isoname)\n isotope.spectrum.f.setLabel('spectrum: | {} at {}'.format(isoname, rgroup.name))\n self._isotopes[(detector, rgroup)].append(isotope)\n self._Enu_inputs[detector].add(isotope.spectrum.f.inputs.x)\n subflux = ROOT.Product()\n subflux.product.setLabel('flux | {}'.format(isoname))\n subflux.multiply(isotope.spectrum)\n subflux.multiply(norm.isotopes['norm_{0}'.format(isoname)])\n detector.intermediates['flux_{}'.format(isoname)] = subflux\n normedflux.add(subflux)\n detector.intermediates['flux'] = normedflux\n\n\n compnames = set(oscprob.probsum.inputs)\n\n detector.unoscillated.add(normedflux)\n if 'comp0' in compnames:\n csum = detector.components['rate'][(weightscls, 'comp0')]\n csum.add(normedflux)\n csum.sum.setLabel('normed flux | comp0 at '+detector.name)\n ones = ROOT.FillLike(1.0)\n ones.fill.setLabel('1: comp0')\n ones.fill.inputs(normedflux)\n opsum=detector.components['oscprob'][(weightscls, 'comp0')]\n opsum.add(ones)\n opsum.sum.setLabel('osc flux | {} at {}'.format('comp0', detector.name))\n self.oscprobs_comps[(detector, rgroup)][(weightscls, 'comp0')] = ones\n compnames.remove('comp0')\n for osccomps in oscprob.transformations.values():\n osccomps.setLabel('oscprob {} | {}-\\\\>{}'.format(osccomps.label(), rgroup.name, detector.name))\n for compname, osccomp in osccomps.outputs.items():\n if compname not in compnames:\n continue\n product = ROOT.Product()\n product.product.setLabel('osc flux: | {} from {}'.format(compname, rgroup.name))\n product.multiply(normedflux)\n product.multiply(osccomp)\n csum=detector.components['rate'][(weightscls, compname)]\n csum.add(product)\n csum.sum.setLabel('normed flux | {} at {}'.format(compname, detector.name))\n opsum=detector.components['oscprob'][(weightscls, compname)]\n opsum.add(osccomp)\n opsum.sum.setLabel('osc flux | {} at {}'.format(compname, detector.name))\n self.oscprobs_comps[(detector, rgroup)][(weightscls, compname)] = osccomp\n if compname not in compnames:\n raise Exception(\"overriden component {}\".format(compname))\n compnames.remove(compname)\n\n if 'Enu' in osccomps.inputs:\n self._Enu_inputs[detector].add(osccomps.inputs.Enu)\n if compnames:\n raise Exception(\"components not found: {}\".format(compnames))\n\n\n\n def setibd(self, detector, ibdtype):\n \"\"\"Setup input energy values, integration and IBD calculation object for the given detector according to the ibdtype .\n ibdtype may be 'zero' or 'first' for the corresponding order.\n Resulting components are stored in detector.components.\n The backgrounds histos are also constructed here for now.\n \"\"\"\n Evis_edges = detector.edges\n orders = detector.orders\n with self.ns(\"ibd\"):\n econv = self.econv = ROOT.EvisToEe()\n if ibdtype == 'zero':\n with self.ns(\"ibd\"):\n ibd = self.ibd = ROOT.IbdZeroOrder()\n integrator = self.integrator = ROOT.GaussLegendre(Evis_edges, orders, len(orders))\n integrator.points.setLabel('integrator 1d')\n histcls = ROOT.GaussLegendreHist\n econv.Ee.Evis(integrator.points.x)\n ibd.xsec.Ee(econv.Ee.Ee)\n ibd.Enu.Ee(econv.Ee.Ee)\n eventsparts = [ibd.xsec]\n elif ibdtype == 'first':\n with self.ns(\"ibd\"):\n ibd = self.ibd = ROOT.IbdFirstOrder()\n integrator = self.integrator = ROOT.GaussLegendre2d(Evis_edges, orders, len(orders), -1.0, 1.0, 5)\n integrator.points.setLabel('integrator 2d')\n histcls = ROOT.GaussLegendre2dHist\n econv.Ee.Evis(integrator.points.x)\n ibd.Enu.Ee(econv.Ee.Ee)\n ibd.Enu.ctheta(integrator.points.y)\n detector.intermediates['ctheta'] = integrator.points.y\n ibd.xsec.Enu(ibd.Enu)\n ibd.xsec.ctheta(integrator.points.y)\n ibd.jacobian.Enu(ibd.Enu)\n # ibd.jacobian.Ee(integrator.points.x) # legacy: incorrect. X is Evis, not Ee\n ibd.jacobian.Ee(econv.Ee.Ee)\n ibd.jacobian.ctheta(integrator.points.y)\n eventsparts = [ibd.xsec, ibd.jacobian]\n else:\n raise Exception(\"unknown ibd type {0!r}\".format(ibdtype))\n ibd.xsec.setLabel('IBD xsec')\n\n detector.intermediates['Enu'] = ibd.Enu\n detector.intermediates['xsec'] = ibd.xsec\n for inp in self._Enu_inputs.get(detector, []):\n inp.connect(ibd.Enu.Enu)\n\n for detector in self.detectors:\n for resname, comps in detector.components.items():\n for compid, comp in comps.items():\n res = None\n if resname == 'rate':\n res = ROOT.Product()\n res.product.setLabel('count rate: | {} at {}'.format(compid[1], detector.name))\n res.multiply(comp)\n for part in eventsparts:\n res.multiply(part)\n elif resname == 'oscprob':\n res = comp\n hist = detector.hists[resname][compid] = histcls(integrator)\n hist.hist.setLabel('{} hist: | {} at {}'.format(resname, compid[1], detector.name))\n detector.hists[resname][compid].hist.inputs(res)\n\n # Below we construct backgrounds histos\n if self.opts.backgrounds:\n bkg_summary = ROOT.Sum()\n bkg_summary.sum.setLabel('bkg: | '+detector.name)\n for bkg_name, bkg in detector.intermediates_bkg.items():\n prod = ROOT.Product()\n prod.product.setLabel('bkg: | '+detector.name)\n prod.multiply(bkg)\n unosc_bkg_name = 'unosc_' + bkg_name\n for part in eventsparts:\n prod.multiply(part)\n hist = detector.back_hists[unosc_bkg_name] = histcls(integrator)\n hist.hist.setLabel('bkg hist: | '+detector.name)\n detector.back_hists[unosc_bkg_name].hist.inputs(prod)\n\n # normalize isotope flux now\n iso_name = bkg_name.split('_')[-1]\n with self.ns(\"geo_isotopes\")(iso_name):\n norm_geo = ROOT.GeoNeutrinoFluxNormed(detector.livetime[0]/year)\n norm_geo.flux_norm.flux(detector.back_hists[unosc_bkg_name].hist)\n\n with self.ns(\"oscillation\"):\n aver_oscprob = ROOT.OscProbAveraged(ROOT.Neutrino.ae(), ROOT.Neutrino.ae())\n aver_oscprob.average_oscillations.inputs(norm_geo.flux_norm)\n detector.back_hists['geo_'+iso_name] = norm_geo.flux_norm.normed_flux\n bkg_summary.add(aver_oscprob.average_oscillations.flux_averaged_osc)\n\n\n\n\n detector.unoscillated_hist = histcls(integrator)\n res = ROOT.Product()\n res.product.setLabel('unosc IBD: | '+detector.name)\n detector.unoscillated_hist.hist.setLabel('unoscillated hist: | '+detector.name)\n res.multiply(detector.unoscillated)\n for part in eventsparts:\n res.multiply(part)\n detector.unoscillated_hist.hist.inputs(res)\n\n if self.opts.backgrounds:\n detector.unoscillated_with_bkg = ROOT.Sum()\n detector.unoscillated_with_bkg.sum.setLabel('noosc+bkg | '+detector.name)\n detector.unoscillated_with_bkg.add(bkg_summary)\n detector.unoscillated_with_bkg.add(detector.unoscillated_hist)\n detector.back_hists['sum_bkg'] = bkg_summary\n\n def _sumcomponents(self, components, name):\n oscprobs = {}\n for oscprobcls, compname in components.keys():\n if oscprobcls in oscprobs:\n continue\n with self.ns(\"oscillation\"):\n oscprob = oscprobcls(ROOT.Neutrino.ae(), ROOT.Neutrino.ae(),\n freevars=['L'])\n oscprobs[oscprobcls] = oscprob\n\n for compid, comp in components.items():\n ps = oscprobs[compid[0]].probsum\n ps.setLabel('osc prob: | '+name)\n ps[compid[1]](comp)\n\n probsums = [oscprob.probsum for oscprob in oscprobs.values()]\n if len(probsums) > 1:\n finalsum = ROOT.Sum()\n finalsum.sum.setLabel('finalsum | '+name)\n for probsum in probsums:\n finalsum.add(probsum)\n return finalsum\n else:\n return probsums[0]\n\n def setupobservations(self, detector):\n \"\"\"Sum over the components and setup the observables to namespace\"\"\"\n\n self.ns.addobservable(\"{0}_unoscillated\".format(detector.name), detector.unoscillated_hist.hist, export=False)\n if self.opts.backgrounds:\n self.ns.addobservable(\"{0}_unoscillated_with_bkg\".format(detector.name),\n detector.unoscillated_with_bkg, export=False)\n\n sums = {resname: self._sumcomponents(detector.hists[resname], detector.name)\n for resname in detector.hists}\n\n if 'oscprob' in sums:\n detector.intermediates[\"oscprob\"] = sums['oscprob']\n if 'rate' in sums:\n inter_sum = ROOT.Sum()\n inter_sum.sum.setLabel('Observed IBD: | '+detector.name)\n sum_without_bkg = sums['rate']\n inter_sum.add(sum_without_bkg)\n if self.opts.backgrounds:\n inter_sum.add(detector.back_hists['sum_bkg'])\n\n self.ns.addobservable(\"{0}_noeffects\".format(detector.name), inter_sum, export=False)\n\n if self.opts.with_C14:\n with self.ns('ibd'), detector.ns:\n detector.c14 = ROOT.C14Spectrum(8, 5)\n detector.c14.smear.inputs(inter_sum)\n finalsum = detector.c14.smear\n\n self.ns.addobservable(\"{0}_c14\".format(detector.name),\n finalsum, export=True)\n else:\n finalsum = inter_sum\n\n with detector.ns:\n detector.eres = ROOT.EnergyResolution()\n detector.eres.matrix.Edges(self.integrator.points.xhist)\n detector.eres.smear.setLabel('Eres')\n detector.eres.smear.Ntrue(finalsum)\n finalsum = detector.eres.smear\n\n if detector.edges_final is not None:\n self.ns.addobservable(\"{0}_fine\".format(detector.name), finalsum)\n\n detector.rebin = C.Rebin(detector.edges_final, 6)\n finalsum >> detector.rebin\n finalsum = detector.rebin\n self.ns.addobservable(\"{0}\".format(detector.name), finalsum.single())\n else:\n self.ns.addobservable(\"{0}\".format(detector.name), finalsum)\n\n det_ns = self.ns(\"detectors\")(detector.name)\n\n for name in detector.intermediates:\n det_ns.addobservable(name, detector.intermediates[name], export=False)\n\n for name, bkg in detector.back_hists.items():\n det_ns.addobservable(\"bkg_{}\".format(name), bkg, export=False)\n\n for pair, comps in self.oscprobs_comps.items():\n pair_ns = det_ns(pair[1].name)\n pair_ns.addobservable('oscprob', self._sumcomponents(comps, detector.name), export=False)\n\n @classmethod\n def reqparameters(cls, ns):\n \"\"\"Setup the parameters\"\"\"\n gna.parameters.ibd.reqparameters(ns(\"ibd\"))\n gna.parameters.oscillation.reqparameters(ns(\"oscillation\"))\n\n for isoname, (central, sigma) in eperfission.items():\n isons = ns(\"isotopes\")(isoname)\n isons.reqparameter(\"EnergyPerFission\", central=central, sigma=sigma)\n for geo_isoname, (central, relsigma) in geo_flux_normalizations.items():\n geo_isons = ns(\"geo_isotopes\")(geo_isoname)\n geo_isons.reqparameter(\"FluxNorm\", central=central, relsigma=sigma)\n", "meta": {"hexsha": "bee6a0873cd32aeac824b48bd94d9c15e8cf356e", "size": 27869, "ext": "py", "lang": "Python", "max_stars_repo_path": "pylib/gna/exp/reactor.py", "max_stars_repo_name": "gnafit/gna", "max_stars_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T16:33:06.000Z", "max_issues_repo_path": "pylib/gna/exp/reactor.py", "max_issues_repo_name": "gnafit/gna", "max_issues_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pylib/gna/exp/reactor.py", "max_forks_repo_name": "gnafit/gna", "max_forks_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.1685575365, "max_line_length": 145, "alphanum_fraction": 0.5908356956, "include": true, "reason": "import numpy", "num_tokens": 6480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.2720245392906821, "lm_q1q2_score": 0.14026127002365366}} {"text": "#!/usr/bin/env python\n\"\"\"Minimises the energy or the gap penalty function of a molecule in a cluster.\n\nTemplate files are needed as well as an xyz file for the molecule and another\none for the surrounding molecules. Overall the use of subprocess is ugly as it\nis repeated 3 or 4 times but it was found to handle memory better than Pool\nwhen interfacing with Gaussian.\n\nEnergy units are Hartree inside the program but are printed in eV. Distances are\nkept as Angstrom throughout and are converted from Bohr if necessary before\nreaching this module\n\n\"\"\"\nimport numpy as np\nimport subprocess\nimport os\nfrom datetime import datetime\nfrom scipy.optimize import minimize\n\nfrom fromage.io import read_file as rf\nfrom fromage.utils import array_operations as ao\nfrom fromage.utils import calc\nfrom fromage.io.parse_config_file import bool_cast\n\n\ndef sequence(in_pos):\n \"\"\"\n Run Gaussian calculations in parallel and write and return results\n\n This function is designed to work with the scipy.optimise.minimize function.\n This is why it can only receive one array of floats as input and return two\n arrays of floats. As a result some variables in this function are defined\n elsewhere in the module which is a necessary evil.\n\n Parameters\n ----------\n in_pos : list of floats\n Input coordinates in array form\n Returns\n -------\n en_out : float\n Combined energy or penalty function value in Hartree\n gr_out : list of floats\n Gradients of en_out in Hartree/Angstrom\n\n References\n ----------\n Levine, B. G., Coe, J. D. & Martinez, T. J. Optimizing conical intersections\n without derivative coupling vectors: Application to multistate\n multireference second-order perturbation theory (MS-CASPT2).\n J. Phys. Chem. B 112, 405-413 (2008).\n\n \"\"\"\n # initialise calculation objects\n rl = calc.setup_calc(\"rl\", low_level)\n ml = calc.setup_calc(\"ml\", low_level)\n mh = calc.setup_calc(\"mh\", high_level)\n if bool_ci:\n mg = calc.setup_calc(\"mg\", high_level)\n\n # Run the calculations as subprocesses with a maximum of 2 simultameous ones\n # at the same time. This order is optimised for the mh calculation being\n # the longest\n mh_proc = mh.run(ao.array2atom(mol_atoms, in_pos))\n if bool_ci and high_level != \"gaussian_cas\":\n mg_proc = mg.run(ao.array2atom(mol_atoms, in_pos))\n rl_proc = rl.run(ao.array2atom(mol_atoms, in_pos))\n rl_proc.wait()\n ml_proc = ml.run(ao.array2atom(mol_atoms, in_pos))\n ml_proc.wait()\n mh_proc.wait()\n if bool_ci and high_level != \"gaussian_cas\":\n mg_proc.wait()\n\n # read results. Each x_en_gr is a tuple (energy,gradients,scf_energy)\n rl_en_gr = rl.read_out(in_pos, mol_atoms, shell_atoms)\n ml_en_gr = ml.read_out(in_pos)\n\n if high_level == \"gaussian_cas\":\n mh_en_gr = mh.read_out(in_pos)[0:3]\n if bool_ci:\n mg_en_gr = (mh.read_out(in_pos)[2], mh.read_out(\n in_pos)[3], mh.read_out(in_pos)[2])\n elif high_level == \"molcas\":\n mh_en_gr = mh.read_out(in_pos)\n if bool_ci:\n # in molcas the first read out is S_1, gr, S_0 even if the target\n # state is 0\n mg_en_gr = mg.read_out(in_pos)[::-1]\n else:\n mh_en_gr = mh.read_out(in_pos)\n if bool_ci:\n mg_en_gr = mg.read_out(in_pos)\n\n # combine results\n en_combo = rl_en_gr[0] - ml_en_gr[0] + mh_en_gr[0]\n gr_combo = rl_en_gr[1] - ml_en_gr[1] + mh_en_gr[1]\n scf_combo = rl_en_gr[2] - ml_en_gr[2] + mh_en_gr[2]\n\n if bool_ci:\n # corresponding ground state energy and gradients\n en_combo_g = rl_en_gr[0] - ml_en_gr[0] + mg_en_gr[0]\n gr_combo_g = rl_en_gr[1] - ml_en_gr[1] + mg_en_gr[1]\n\n # Penalty function parameters and calculation\n alpha = 0.02\n e_mean = (en_combo + en_combo_g) / 2\n e_diff = en_combo - en_combo_g\n g_ij = e_diff**2 / (e_diff + alpha)\n en_out = e_mean + sigma * g_ij\n gr_out = 0.5 * (gr_combo + gr_combo_g) + sigma * ((e_diff**2 + 2 *\n alpha * e_diff) / (e_diff + alpha)**2) * (gr_combo - gr_combo_g)\n else:\n en_out = en_combo\n gr_out = gr_combo\n\n # print some updates in the output\n out_file.write(\"------------------------------\\n\")\n global iteration\n iteration += 1\n out_file.write(\"Iteration: \" + str(iteration) + \"\\n\")\n out_file.write(\"Real low energy: {:>30.8f} eV\\n\".format(\n rl_en_gr[0] * evconv))\n out_file.write(\"Model low energy: {:>29.8f} eV\\n\".format(\n ml_en_gr[0] * evconv))\n out_file.write(\"Model high energy: {:>28.8f} eV\\n\".format(\n mh_en_gr[0] * evconv))\n out_file.write(\n \"ONIOM Total energy: {:>27.8f} eV\\n\".format(en_combo * evconv))\n out_file.write(\n \"ONIOM SCF energy: {:>29.8f} eV\\n\".format(scf_combo * evconv))\n out_file.write(\n \"Energy grad. norm: {:>28.8f} eV/A\\n\".format(np.linalg.norm(gr_combo * evconv)))\n if bool_ci:\n out_file.write(\n \"Penalty function value: {:>23.8f} eV\\n\".format(en_out * evconv))\n out_file.write(\"Penalty function grad. norm: {:>18.8f} eV\\n\".format(\n np.linalg.norm(gr_out * evconv)))\n\n out_file.write(\"Gap: {:>42.8f} eV\\n\".format(\n (en_combo - scf_combo) * evconv))\n out_file.flush()\n return (en_out, gr_out)\n\nif __name__ == '__main__':\n\n evconv = 27.2114 # Something in Hartree * evconv = Something in eV\n\n # default settings\n\n def_inputs = {\n \"mol_file\": \"mol.init.xyz\",\n \"shell_file\": \"shell.xyz\",\n \"out_file\": \"fromage.out\",\n \"bool_ci\": \"0\",\n \"high_level\": \"gaussian\",\n \"low_level\": \"gaussian\",\n \"sigma\": \"3.5\",\n \"gtol\": 1e-5,\n \"single_point\": \"0\"}\n\n inputs = def_inputs.copy()\n\n # read user inputs\n if os.path.isfile(\"fromage.in\"):\n new_inputs = rf.read_config(\"fromage.in\")\n inputs.update(new_inputs)\n\n mol_file = inputs[\"mol_file\"]\n shell_file = inputs[\"shell_file\"]\n out_file = inputs[\"out_file\"]\n bool_ci = bool_cast(inputs[\"bool_ci\"])\n high_level = inputs[\"high_level\"]\n low_level = inputs[\"low_level\"]\n gtol = inputs[\"gtol\"]\n single_point = bool_cast(inputs[\"single_point\"])\n # sigma is called lambda in some papers but that is a bad variable name\n # in Python\n sigma = float(inputs[\"sigma\"])\n # output\n out_file = open(out_file, \"w\", 1)\n # print start time\n start_time = datetime.now()\n out_file.write(\"STARTING TIME: \" + str(start_time) + \"\\n\")\n\n iteration = 0\n\n # clean up the last output\n if os.path.exists(\"geom_mol.xyz\"):\n subprocess.call(\"rm geom_mol.xyz\", shell=True)\n if os.path.exists(\"geom_cluster.xyz\"):\n subprocess.call(\"rm geom_cluster.xyz\", shell=True)\n\n # read initial coordniates\n mol_atoms = rf.read_xyz(mol_file)[0]\n\n # read shell atoms\n shell_atoms = rf.read_xyz(shell_file)[0]\n\n # make the initial coordinates into a flat list\n atoms_array = []\n for atom in mol_atoms:\n atoms_array.append(atom.x)\n atoms_array.append(atom.y)\n atoms_array.append(atom.z)\n\n # make the list into an array\n atoms_array = np.array(atoms_array)\n if single_point:\n sequence(atoms_array)\n else:\n res = minimize(sequence, atoms_array, jac=True,\n options={'disp': True, 'gtol': gtol})\n\n out_file.write(\"DONE\\n\")\n end_time = datetime.now()\n out_file.write(\"ELAPSED TIME: \" + str(end_time - start_time) + \"\\n\")\n out_file.write(\"ENDING TIME: \" + str(end_time) + \"\\n\")\n out_file.close()\n", "meta": {"hexsha": "aa09d5841fb793e15d313b3dbdf5e5bd8480e866", "size": 7644, "ext": "py", "lang": "Python", "max_stars_repo_path": "fromage/scripts/fro_run.py", "max_stars_repo_name": "Yulin832/fromage", "max_stars_repo_head_hexsha": "f6c84d5684ca5abfcc979540bb97cc8f105f963d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-11-19T09:36:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-12T13:46:20.000Z", "max_issues_repo_path": "fromage/scripts/fro_run.py", "max_issues_repo_name": "Yulin832/fromage", "max_issues_repo_head_hexsha": "f6c84d5684ca5abfcc979540bb97cc8f105f963d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-01-22T17:26:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-21T14:23:52.000Z", "max_forks_repo_path": "fromage/scripts/fro_run.py", "max_forks_repo_name": "Yulin832/fromage", "max_forks_repo_head_hexsha": "f6c84d5684ca5abfcc979540bb97cc8f105f963d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-04-22T14:56:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T13:30:58.000Z", "avg_line_length": 34.7454545455, "max_line_length": 123, "alphanum_fraction": 0.6369701727, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.2782567877172032, "lm_q1q2_score": 0.14021531232229914}} {"text": "#!/usr/bin/env python\nfrom scipy import *\nimport struct, sys, re\nfrom scipy import linalg\nimport optparse\nimport rdU\nfrom utils import W2kEnvironment, Ry_in_eV\nimport indmffile\nimport copy\n\nclass Struct:\n def __init__(self, case):\n self.case = case\n self.extn = 'struct'\n self.parse()\n\n def parse(self):\n '''The file is structured for reading by fortran code,\n so data is positioned by line and by column.'''\n f = open(self.case + '.' + self.extn, 'r')\n self.title = f.next().strip()\n\n line = f.next()\n self.lattice = line[0:4].strip()\n self.nat = int(line[27:30])\n self.latticename = line[30:].strip()\n\n self.mode = f.next()[13:17]\n\n line = f.next()\n self.a, self.b, self.c, self.alpha, self.beta, self.gamma = [float(line[i:i+10]) for i in range(0,60,10)]\n\n self.iatom = []\n self.mult = []\n self.isplit = []\n self.aname = []\n self.npt = []\n self.r0 = []\n self.rmt = []\n self.Znuc = []\n self.pos = []\n self.rotloc = []\n\n for iat in range(self.nat):\n line = f.next()\n self.iatom.append( int(line[4:8]) )\n pos = [[float(line[col:col+10]) for col in 12+13*arange(3)]]\n \n line = f.next()\n mult = int(line[15:17])\n self.mult.append(mult)\n\n self.isplit.append( int(line[34:37]) )\n\n for mu in range(mult-1):\n line = f.next()\n pos.append( [float(line[col:col+10]) for col in 12+13*arange(3)] )\n\n self.pos.append(pos)\n \n line = f.next()\n self.aname.append( line[0:10].strip() )\n self.npt.append( int(line[15:20]) )\n self.r0.append( float(line[25:35]) )\n self.rmt.append( float(line[40:50]) )\n self.Znuc.append( int(float(line[55:65])) )\n\n rt=[]\n for i in range(3):\n line = f.next()\n rt.append( [float(line[col:col+10]) for col in 20+10*arange(3)] )\n self.rotloc.append(rt)\n\n self.Ng = int(f.next().split()[0])\n self.iz=[]\n self.tau=[]\n for i in range(self.Ng):\n tiz=zeros((3,3), dtype=float)\n ttau=zeros(3, dtype=float)\n for j in range(3):\n line = f.next()\n tiz[j,:] = array([int(line[0:2]), int(line[2:4]), int(line[4:6])])\n ttau[j] = float(line[6:16])\n self.iz.append(tiz)\n self.tau.append(ttau)\n f.next()\n #print self.iz\n \n f.close()\n\n def debugprint(self, f=sys.stdout):\n print >> f, '***** Structure File Contents *****'\n print >> f, 'title =', self.title\n print >> f, 'Number of sorts, nat =', self.nat\n print >> f, 'unit cell parameters (a,b,c) =', self.a, self.b, self.c\n print >> f, 'angles (alpha, beta, gamma) =', self.alpha, self.beta, self.gamma\n\n\n printlist = [\n (self.aname, 'Atom name, aname ='),\n (self.iatom, 'Atom index, iatom ='),\n (self.mult, 'Number of atoms of this type, mult ='),\n (self.isplit, 'Symmetry of the atom, isplit ='),\n (self.npt, 'Number of radial points, npt ='),\n (self.r0, 'First point in radial mesh, r0 ='),\n (self.rmt, 'Muffin tin radius, rmt ='),\n (self.Znuc, 'Atomic number, Znuc ='),\n ]\n\n for i in range(self.nat):\n print >> f, '---------- atom type', i, '------------'\n\n for var,docstr in printlist:\n print >> f, docstr, var[i]\n\n print >> f, 'Position(s) inside the unit cell:'\n for m in range(self.mult[i]):\n print >> f, ' pos =', self.pos[i][m]\n\n print >> f, 'Local rotation matrix:'\n for row in self.rotloc[i]:\n print >> f, row\n\n print >> f, '***********************************'\n\n def flat(self, notflat):\n '''Return a flat view of given data as a list.\n Example: if w.mult = [2,4] and w.aname = ['V', 'O']\n w.flatten(w.aname) -> ['V', 'V', 'O', 'O', 'O', 'O']'''\n if notflat is self.pos:\n listoflists = self.pos\n else:\n listoflists = [[elem]*mult for elem,mult in zip(notflat, self.mult)]\n return reduce(operator.add, listoflists)\n\n\ndef DirectVectors(BR,RN):\n #v0 = cross(BR[1],BR[2])\n #v1 = cross(BR[2],BR[0])\n #v2 = cross(BR[0],BR[1])\n #vol = dot(v0,BR[0])\n #array([v0/vol,v1/vol,v2/vol])\n return dot(RN, linalg.inv(BR).transpose() )\n \ndef Print(fh, R, tHr):\n R0 = R # dot(DVinv,R)\n Rs=[]\n for i in range(3):\n if abs(round(R0[i])-R0[i])<1e-3:\n Rs.append( \"%d\" % int(round(R0[i])) )\n else:\n Rs.append(\"%.1f\" % R0[i])\n\n print >> fh, 'Hopping[(%s,%s,%s)]=[' % tuple(Rs)\n for l1 in range(shape(tHr)[0]):\n print >> fh, '[',\n for l2 in range(shape(tHr)[1]):\n print >> fh, \"%8.4f+%8.4fj,\" % (tHr[l1,l2].real, tHr[l1,l2].imag),\n print >> fh, '],'\n print >> fh, ']'\n\n\ndef ReadBRs(case):\n \"reads BR1 and BR2 from case.rotlm\"\n fr = open(case+'.rotlm') \n BR = zeros((2,3,3), dtype=float)\n for ii in range(2):\n fr.next()\n for i in range(3):\n BR[ii,:,i] = map(float,fr.next().split())\n \n BRX = array(linalg.inv(BR[1]) * matrix(BR[0]))\n return (BR,BRX)\n\n\ndef FindMaxMinBand(Ek, Emin, Emax):\n \"Finds minimum and maximum band to be used in downfolding\"\n\n istart=None\n iend=None\n for i in range(len(Ek)):\n if Ek[i]>Emin:\n istart = i\n break\n \n for i in range(istart,len(Ek)):\n if Ek[i]>Emax:\n iend = i\n break\n return array([istart, iend])\n \ndef TryAddBands(Nse_global, Ek, Emin, Emax, SmearN, SmearX):\n \n Nse = Nse_global[:]\n \n Em = Ek[Nse[0]-1] # closest energy below the cutoff\n Ep = Ek[Nse[1]] # closest energy above the cutoff\n \n print Em, Ep\n\n EmCanAdd, EpCanAdd = False, False\n \n if Emin-Em < SmearN : EmCanAdd = True\n if Ep-Emax < SmearX : EpCanAdd = True\n\n Succ = True\n \n if EmCanAdd and EpCanAdd:\n if Emin-Em < Ep-Emax:\n Nse[0]-=1\n print 'Both could be added. Adding below.'\n else:\n Nse[1]+=1\n print 'Both could be added. Adding above.' \n elif EmCanAdd :\n Nse[0]-=1\n print 'Can add below'\n elif EpCanAdd :\n Nse[1]+=1\n print 'Can add above'\n else:\n print 'Can not find enough bands in your interval. Increase Emin, Emax or smearings'\n Succ = False\n \n print Nse\n \n return (Nse, Succ)\n\n\n# RS = (i0,i1,i2)*DV[:,:]\n# RS*DV^-1 = (i0,i1,i2)\n\ndef GiveRs(div, DV):\n \"Gives real space vectors\"\n Rs=[]\n for i0 in range(div[0]/2,-div[0]/2,-1):\n for i1 in range(div[1]/2,-div[1]/2,-1):\n for i2 in range(div[2]/2,-div[2]/2,-1):\n Rs.append(DV[0]*i0 + DV[1]*i1 + DV[2]*i2)\n return Rs\n\n\n \n\nif __name__ == '__main__':\n \"\"\" Takes the DMFT projector Udmft.0 and LDA eigenvalues (case.energy) to produces downfolding hopping parameters.\n It also requires two parameters specifying the bands used in downfolding. The lower cutoff is determined by energy\n '--Emin' (counted from EF in eV), while the upped cutoff is determined by the number of bands '--nbnd'.\n \"\"\"\n\n usage = \"\"\"usage: %prog [ options ]\n \n The script takes the DMFT projector Udmft.0 and LDA eigenvalues (case.energy)\n and produces downfolded hopping parameters. It requires parameters\n specifying bands used in downfolding. The lower/upper cutoff is determined\n by energy '--Emin' or '-N' /'--Emax' or '-X' (counted from EF in eV).\n Additional bands are added if needed in the interval\n '--SmearN' or '-n' / '--SmerX' or '-x'\n\n -------------------- Emax+SmearX\n added if needed\n --------------------- Emax\n\n bands always used in downfolding\n\n --------------------- Emin\n added if needed\n --------------------- Emin-SmearN\n \"\"\"\n \n # Finds what is case\n w2k = W2kEnvironment()\n\n \n parser = optparse.OptionParser(usage)\n parser.add_option(\"-N\", \"--Emin\", dest=\"Emin\", type=\"float\", default=None, help=\"Bands above Emin (counted from EF in eV) will be consider in downfolding.\")\n parser.add_option(\"-X\", \"--Emax\", dest=\"Emax\", type=\"float\", default=None, help=\"Bands below Emax (counted from EF in eV) will be consider in downfolding.\")\n parser.add_option(\"-n\", \"--SmearN\", dest=\"SmearN\", type=\"float\", default=1., help=\"When determining Emin cutoff, we use smearing in eV if needed\")\n parser.add_option(\"-x\", \"--SmearX\", dest=\"SmearX\", type=\"float\", default=1., help=\"When determining Emax cutoff, we use smearing in eV if needed\")\n parser.add_option(\"-s\", \"--smalls\", dest=\"smalls\", type=\"float\", default=0.1, help=\"The smallest acceptable singular value\")\n # Next, parse the arguments\n (options, args) = parser.parse_args()\n \n if options.Emin is None:\n print 'You have to specify minimum band energy! Option -E or --Emin'\n sys.exit(1)\n if options.Emax is None:\n print 'You have to specify maximum band energy! Option -M or --Emax'\n sys.exit(1)\n \n print 'case=%s Emin=%s, Emax=%s SmearN=%s SmearX=%s' % (w2k.case, options.Emin, options.Emax, options.SmearN, options.SmearX)\n\n # File handlers to exchange files with Fortran\n # These numbers are not relevant, but need to be set\n fhp = 233\n fhe = 60\n Ntry=10 \n \n # Reads indmf-file\n inl = indmffile.Indmfl(w2k.case)\n inl.read()\n EF = inl.EF\n print 'Fermi energy is ', EF\n # atoms in the projection for downfolding\n\n atms = inl.atoms.keys()\n print 'atoms in the projection for downfolding=', atms\n # Finds actual positions of these atoms\n pos = [] # zeros((max(atms),3),dtype=float)\n fi = open(w2k.case+'.outputdmfu','r')\n for line in fi:\n m = re.search('Actual position of atom *(\\d+)',line)\n if m is not None:\n if int(m.group(1)) in atms:\n atom = int(m.group(1))\n\n print 'ATOM', atom, ' in atms=', atms\n \n m = re.search('Actual position of atom *(\\d+) *is: (.*)',line)\n #pos[atom-1,:] = map(float,m.group(2).split())\n pos.append( map(float,m.group(2).split()) )\n pos=array(pos)\n print 'Actual position of atoms for downfolding=', pos.tolist()\n \n strc = Struct(w2k.case)\n strc.parse()\n \n # reads BR1 and BR2 from case.rotlm\n (BR,BRX) = ReadBRs(w2k.case)\n # Computes direct vectors, knowing the reciprocal basis\n DV = DirectVectors(BR[1],BR[0])\n \n print 'Direct vectors:'\n for i in range(3):\n print (\"%7.3f \"*3) % tuple(DV[i])\n\n print 'Please enter the direct vectors for large Brillouin zone'\n DVn = zeros(1)\n while shape(DVn) != (3,3):\n DVn = array(eval(sys.stdin.readline()))\n #DVn = array([[0.5,0.5,0],[0.5,-0.5,0],[0,0,1]])\n print 'But switching to direct vectors of the one atom unit cell:'\n for i in range(3):\n print (\"%7.3f \"*3) % tuple(DVn[i])\n \n # Reads div from case.klist\n firstline = open(w2k.case+'.klist').next()\n m = re.search('div: *\\((\\s*\\d+\\s*\\d+\\s*\\d+)\\)', firstline)\n if m is not None:\n div = map(int,m.groups()[0].split())\n\n Rs = GiveRs(div, DVn)\n print 'Real space vectors used in the Fourier transform to tigh-binding:'\n for i,R in enumerate(Rs):\n print \"%3d\"%i, \"%7.3f %7.3f %7.3f\" % tuple(R)\n\n # Read Udmft\n filename = 'Udmft.0'\n (nkp, nsymop, norbitals) = rdU.fopen(fhp, filename)\n \n nindo = rdU.read1(fhp, norbitals)\n\n print 'nkp=', nkp, 'nsymop=', nsymop, 'norbitals=', norbitals, 'nindo=', nindo\n\n\n delta_A_B = pos[1]-pos[0]\n print 'delta_A_B=', delta_A_B\n \n rdU.feopen(fhe, w2k.case+'.energy', strc.nat)\n \n Hk=[]\n kps=[]\n wgh=[]\n for ikp in range(nkp):\n \n (iikp, nbands, tmaxdim2, tnorbitals, nemin) = rdU.read2(fhp)\n (k, kname, wg, ios, nen) = rdU.feread1(fhe)\n\n print 'delta*k=', delta_A_B*k\n \n if ios!=0:\n print 'Number of k-points in case.energy is smaller then in Udfmt.0'\n break\n \n # Read LDA energies from case.energy\n Ek = rdU.feread2(fhe, nen) * Ry_in_eV - EF\n \n # finds minimum and maximum band for downfolding\n #(bnd_s, bnd_e) = FindMaxMinBand(Ek, options.Emin, nemin, options.nbnd, options.dnbnd)\n #e = Ek[nemin+bnd_s-1:nemin+bnd_e-1]\n #print 'bnd_s=', bnd_s, 'bnd_e=', bnd_e, 'Emm=', e[0], e[-1]\n #print 'k=', k\n \n for isym in range(nsymop):\n \n kn = dot(strc.iz[isym],k)\n k_nat = [sum(BRX[i,:]*kn) for i in range(3)]\n \n kps.append(kn)\n wgh.append(wg)\n \n iisym = rdU.read3(fhp)\n if iisym!=isym+1:\n print 'ERROR: isym!=iisym', isym, iisym\n \n for iorb in range(norbitals):\n \n U = []\n for ind in range(nindo[iorb]):\n Udat = rdU.read4(fhp, nbands)\n U.append( Udat )\n U = array(U)\n \n if iorb==0:\n Utot = U\n else:\n Utot = vstack((Utot,U))\n\n # finds minimum and maximum band for downfolding\n Nse = FindMaxMinBand(Ek, options.Emin, options.Emax)\n\n print 'len(Utot)=', len(Utot)\n\n while (Nse[1]-Nse[0] < len(Utot) ):\n print 'Warning: Number of bands in the interval is ', Nse[1]-Nse[0], 'while number of orbitals is ', len(Utot)\n (Nse, Succ) = TryAddBands(Nse, Ek, options.Emin, options.Emax, options.SmearN, options.SmearX)\n if not Succ: sys.exit(1)\n\n NsingularValues=0\n while (NsingularValuesoptions.smalls, s))\n print 'NsingularValues=', NsingularValues\n\n if (NsingularValues> fh, '# Tighbinding Hamiltonian with entries: ', inl.legends\n print >> fh\n #print >> fh, \"lattice_unit=[\", tuple(DVn[0]), ',', tuple(DVn[1]), ',', tuple(DVn[2]), \"]\"\n print >> fh, \"lattice_unit=\", identity(3).tolist()\n\n print >> fh, \"orbital_positions=\",zeros((3,3)).tolist()\n print >> fh\n #print '['\n #for atm in inl.siginds.keys():\n # for i in range(len(inl.siginds[atm])):\n # print >> fh, pos[atm-1].tolist(),','\n #print \n #print >> fh, ']\\n'\n\n\n # sorting such that first come larger hoppings\n for irm,R in enumerate(Rs):\n if sum(abs(Rs[irm]))<1e-10: break\n \n ir_index = range(len(Rs))\n ir_index.sort( lambda a,b: cmp(sum(abs(Hr[b])), sum(abs(Hr[a]))) )\n ir0 = ir_index.index(irm)\n ir_index = [irm] + ir_index[:ir0] + ir_index[ir0+1:]\n \n #print ir_index\n \n DVn_inv = linalg.inv(DVn)\n print >> fh, 'Hopping={}'\n for ir in ir_index :\n # RS*DV^-1 = (i0,i1,i2)\n Rn = dot(Rs[ir] ,DVn_inv)\n Print(fh, Rn, Hr[ir])\n print >> fh\n \n fh.close()\n", "meta": {"hexsha": "4388c064d07b90b4b370684bb6a57fb85652c509", "size": 17166, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/downfold/downfold_2_to_1.py", "max_stars_repo_name": "dmft-wien2k/dmft-wien2k-v2", "max_stars_repo_head_hexsha": "83481be27e8a9ff14b9635d6cc1cd9d96f053487", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-04-03T06:37:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T11:44:06.000Z", "max_issues_repo_path": "src/downfold/downfold_2_to_1.py", "max_issues_repo_name": "dmft-wien2k/dmft-wien2k-v2", "max_issues_repo_head_hexsha": "83481be27e8a9ff14b9635d6cc1cd9d96f053487", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-07-12T21:37:53.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-12T21:42:01.000Z", "max_forks_repo_path": "src/downfold/downfold_2_to_1.py", "max_forks_repo_name": "dmft-wien2k/dmft-wien2k", "max_forks_repo_head_hexsha": "83481be27e8a9ff14b9635d6cc1cd9d96f053487", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-10-27T20:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-13T13:54:11.000Z", "avg_line_length": 33.0115384615, "max_line_length": 161, "alphanum_fraction": 0.5197483397, "include": true, "reason": "from scipy", "num_tokens": 5131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.27825678173200435, "lm_q1q2_score": 0.1402153093063205}} {"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\"\"\"Model an instrument response for spectroscopic simulations.\n\nAn instrument model is usually initialized from a configuration used to create\na simulator and then accessible via its ``instrument`` attribute, for example:\n\n >>> import specsim.simulator\n >>> simulator = specsim.simulator.Simulator('test') # doctest: +IGNORE_OUTPUT\n >>> print(np.round(simulator.instrument.fiber_diameter, 1))\n 107.0 um\n\nSee :doc:`/api` for examples of changing model parameters defined in the\nconfiguration. No attributes can be changed after a simulator has\nbeen created. File a github issue if you would like to change this.\n\nAn :class:`Instrument` includes one or more\n:class:`Cameras `.\n\"\"\"\nfrom __future__ import print_function, division\n\nimport numpy as np\nimport os.path\nimport scipy.interpolate\nimport scipy.integrate\n\nimport astropy.constants\nimport astropy.units as u\n\nimport specsim.camera\nimport specsim.fastfiberacceptance\nimport specsim.config\n\nclass Instrument(object):\n \"\"\"Model the instrument response of a fiber spectrograph.\n\n A spectrograph can have multiple :mod:`cameras ` with\n different wavelength coverages. Objects representing each camera are\n contained in a list accessible from our ``cameras`` attribute, which will\n be in order of increasing effective wavelength.\n\n No instrument attributes can be changed after an instrument has been\n created. Create a github issue if you would like to change this.\n\n Parameters\n ----------\n name : str\n Descriptive name of this instrument.\n wavelength : astropy.units.Quantity\n Array of wavelength bin centers where the instrument response is\n calculated, with units.\n fiberloss_method : str\n Must be \"table\" or \"galsim\" or \"fastsim\". Specifies how fiber acceptance fractions\n will be loaded or calculated.\n fiber_acceptance_dict : dict or None\n Dictionary of fiber acceptance fractions tabulated for different\n source models, with keys corresponding to source model names.\n Ignored when fiberloss_method is \"galsim\".\n fast_fiber_acceptance : specsim.fastfiberacceptance.FastFiberAcceptance or None\n Initialized instance to use when fiberloss_method is \"fastsim\".\n Ignored for other values of fiberloss_method.\n fiberloss_num_wlen : int\n Number of wavelengths where the fiberloss fraction should be tabulated\n for interpolation. Ignored when fiberloss_method is not \"galsim\".\n fiberloss_num_pixels : int\n Number of pixels used to subdivide the fiber diameter for\n numerical convolution and integration calculations.\n Ignored when fiberloss_method is not \"galsim\".\n blur_function : callable\n Function of field angle and wavelength that returns the corresponding\n RMS blur in length units (e.g., microns).\n offset_function : callable\n Function of focal-plane position (x,y) in angular units and wavelength\n that returns the corresponding radial centroid offset in length\n units (e.g., microns).\n cameras : list\n List of :class:`specsim.camera.Camera` instances representing the\n camera(s) of this instrument.\n primary_mirror_diameter : astropy.units.Quantity\n Diameter of the primary mirror, with units.\n obscuration_diameter : astropy.units.Quantity\n Diameter of a central obscuration of the primary mirror, with units.\n support_width : astropy.units.Quantity\n Width of the obscuring supports, with units.\n fiber_diameter : astropy.units.Quantity\n Physical diameter of the simulated fibers, with units of length.\n Converted to an on-sky diameter using the plate scale.\n field_radius : astropy.units.Quantity\n Maximum radius of the field of view in length units measured at\n the focal plane. Converted to an angular field of view using the\n plate scale.\n radial_scale : callable\n Callable function that returns the plate scale in the radial\n (meridional) direction (with appropriate units) as a function of\n focal-plane distance (with length units) from the boresight.\n azimuthal_scale : callable\n Callable function that returns the plate scale in the azimuthal\n (sagittal) direction (with appropriate units) as a function of\n focal-plane distance (with length units) from the boresight.\n \"\"\"\n def __init__(self, name, wavelength, fiberloss_method,\n fiber_acceptance_dict, fast_fiber_acceptance, fiberloss_num_wlen,\n fiberloss_num_pixels, blur_function, offset_function, cameras,\n primary_mirror_diameter, obscuration_diameter, support_width,\n fiber_diameter, field_radius, radial_scale, azimuthal_scale):\n self.name = name\n self._wavelength = wavelength\n self.fiber_acceptance_dict = fiber_acceptance_dict\n self.fast_fiber_acceptance = fast_fiber_acceptance\n # Both fiber_acceptance_dict and fast_fiber_acceptance must be initialized\n # before assigning to fiberloss_method (since its setter checks their values).\n self.fiberloss_method = fiberloss_method\n self.fiberloss_num_wlen = fiberloss_num_wlen\n self.fiberloss_num_pixels = fiberloss_num_pixels\n self._blur_function = blur_function\n self._offset_function = offset_function\n self.cameras = cameras\n self.primary_mirror_diameter = primary_mirror_diameter\n self.obscuration_diameter = obscuration_diameter\n self.support_width = support_width\n self.fiber_diameter = fiber_diameter\n self.field_radius = field_radius\n self.radial_scale = radial_scale\n self.azimuthal_scale = azimuthal_scale\n\n # Calculate the effective area of the primary mirror.\n D = self.primary_mirror_diameter\n obs = self.obscuration_diameter\n support_area = 0.5*(D - obs) * self.support_width\n self.effective_area = (\n np.pi * ((0.5 * D) ** 2 - (0.5 * obs) ** 2) - 4 * support_area)\n\n # Tabulate the mapping between focal plane radius and boresight\n # opening angle by integrating the radial plate scale.\n # Use mm and radians as the canonical units.\n self._radius_unit, self._angle_unit = u.mm, u.rad\n radius = np.linspace(\n 0., self.field_radius.to(self._radius_unit).value, 1000)\n dradius_dangle = self.radial_scale(radius * self._radius_unit).to(\n self._radius_unit / self._angle_unit).value\n angle = scipy.integrate.cumtrapz(\n 1. / dradius_dangle, radius, initial=0.)\n\n # Record the maximum field angle corresponding to our field radius.\n self.field_angle = angle[-1] * self._angle_unit\n\n # Build dimensionless linear interpolating functions of the\n # radius <-> angle map using the canonical units.\n self._radius_to_angle = scipy.interpolate.interp1d(\n radius, angle, kind='linear', copy=True, bounds_error=True)\n self._angle_to_radius = scipy.interpolate.interp1d(\n angle, radius, kind='linear', copy=True, bounds_error=True)\n\n # Calculate the energy per photon at each wavelength.\n hc = astropy.constants.h * astropy.constants.c\n energy_per_photon = (hc / self._wavelength).to(u.erg)\n\n # Calculate the rate of photons incident on the focal plane per\n # wavelength bin per unit spectral flux density. The fiber acceptance\n # fraction is not included in this calculation.\n wavelength_bin_size = np.gradient(self._wavelength)\n self.photons_per_bin = (\n self.effective_area * wavelength_bin_size / energy_per_photon\n ).to((u.cm**2 * u.Angstrom) / u.erg)\n\n wave_mid = []\n for i, camera in enumerate(self.cameras):\n wave_min, wave_max = camera.wavelength_min, camera.wavelength_max\n wave_mid.append(0.5 * (wave_min + wave_max))\n if i == 0:\n self.wavelength_min = wave_min\n self.wavelength_max = wave_max\n else:\n self.wavelength_min = min(self.wavelength_min, wave_min)\n self.wavelength_max = max(self.wavelength_max, wave_max)\n\n # Sort cameras in order of increasing wavelength.\n self.cameras = [x for (y, x) in sorted(zip(wave_mid, self.cameras))]\n\n\n @property\n def fiberloss_method(self):\n \"\"\"The current method used to calculate fiber acceptance fractions.\n \"\"\"\n return self._fiberloss_method\n\n\n @fiberloss_method.setter\n def fiberloss_method(self, fiberloss_method):\n \"\"\"Set the method used to calculate fiber acceptance fractions.\n\n Must be one of \"table\" or \"galsim\" or \"fastsim\".\n \"\"\"\n if fiberloss_method not in ('table', 'galsim', 'fastsim' ):\n raise ValueError(\n 'fiberloss_method must be \"table\" or \"galsim\" or \"fastsim\".')\n if fiberloss_method == 'table' and self.fiber_acceptance_dict is None:\n raise ValueError('Missing required instrument.fiberloss.table.')\n if fiberloss_method == 'fastsim' and self.fast_fiber_acceptance is None:\n raise ValueError(\n 'Missing required instrument.fiberloss.fast_fiber_acceptance_path.')\n if fiberloss_method == 'galsim':\n try:\n import galsim\n except ImportError:\n raise ValueError('The galsim package is not installed.')\n self._fiberloss_method = fiberloss_method\n\n\n def field_radius_to_angle(self, radius):\n \"\"\"Convert focal plane radius to an angle relative to the boresight.\n\n The mapping is derived from the radial (meridional) plate scale\n function :math:`dr/d\\\\theta(r)` via the integral:\n\n .. math::\n\n \\\\theta(r) = \\\\int_0^{r} \\\\frac{dr}{dr/d\\\\theta(r')}\\\\, dr'\n\n The input values must be within the field of view.\n Use :meth:`field_angle_to_radius` for the inverse transform.\n\n Parameters\n ----------\n radius : astropy.units.Quantity\n One or more radius values where the angle should be calculated.\n Values must be between 0 and ``field radius``.\n\n Returns\n -------\n astropy.units.Quantity\n Opening angle(s) relative to the boresight corresponding to\n the input radius value(s).\n\n Raises\n ------\n ValueError\n One or more input values are outside the allowed range.\n \"\"\"\n return self._radius_to_angle(\n radius.to(self._radius_unit)) * self._angle_unit\n\n\n def field_angle_to_radius(self, angle):\n \"\"\"Convert focal plane radius to an angle relative to the boresight.\n\n The mapping :math:`r(\\\\theta)` is calculated by numerically inverting\n the function :math:`\\\\theta(r)`.\n\n The input values must be within the field of view.\n Use :meth:`field_radius_to_angle` for the inverse transform.\n\n Parameters\n ----------\n angle : astropy.units.Quantity\n One or more angle values where the radius should be calculated.\n Values must be between 0 and ``field_angle``.\n\n Returns\n -------\n astropy.units.Quantity\n Radial coordinate(s) in the focal plane corresponding to the\n input angle value(s).\n\n Raises\n ------\n ValueError\n One or more input values are outside the allowed range.\n \"\"\"\n return self._angle_to_radius(\n angle.to(self._angle_unit)) * self._radius_unit\n\n\n def get_blur_rms(self, wavelength, angle):\n \"\"\"Get the instrument PSF blur at the specified field angle.\n\n Parameters\n ----------\n wavelength : astropy.units.Quantity\n Wavelength where the blur should be calculated.\n angle : astropy.units.Quantity\n Angular separation from the field center.\n\n Returns\n -------\n astropy.units.Quantity\n RMS blur of the instrument at this wavelength and field radius\n in length units.\n \"\"\"\n return self._blur_function(angle, wavelength)\n\n\n def get_centroid_offset(self, angle_x, angle_y, wavelength):\n \"\"\"Get the instrument centroid offset at the specified field angles.\n\n This method does not make any assumptions about how the x and y\n axes are defined, as long as (0, 0) is the field center.\n\n Note that the focal-plane position is input as angles relative to\n the field center, while the offsets are returned as lengths relative\n to the nominal fiber center.\n\n Parameters\n ----------\n angle_x : astropy.units.Quantity\n Angular separation from the field center along x.\n angle_y : astropy.units.Quantity\n Angular separation from the field center along y.\n wavelength : astropy.units.Quantity\n Wavelength where the blur should be calculated.\n\n Returns\n -------\n tuple\n Tuple (dx, dy) of astropy quantities giving the spot centroid\n offset components at this wavelength and position in the focal\n plane. Offsets are given in length units, e.g., microns.\n \"\"\"\n return self._offset_function(angle_x, angle_y, wavelength)\n\n\n def get_focal_plane_optics(self, focal_x, focal_y, wlen_grid):\n \"\"\"Calculate the optical parameters at a set of focal-plane positions.\n\n Uses :meth:`get_centroid_offset`, :meth:`get_blur_rms`, and\n :meth:`field_radius_to_angle` to calculate the optics at each focal\n plane location.\n\n This method does not make any assumptions about how the x and y\n axes are defined, as long as (0, 0) is the field center. However\n radial symmetry is broken by the (dx, dy) offsets calculated by\n :meth:`get_centroid_offset`.\n\n Note that units are required for the input arrays and included with\n the returned arrays.\n\n Parameters\n ----------\n focal_x : :class:`astropy.units.Quantity`\n 1D array of X coordinates in the focal plane relative to the\n boresight, with length units.\n focal_y : :class:`astropy.units.Quantity`\n 1D array of Y coordinates in the focal plane relative to the\n boresight, with length units.\n wlen_grid : :class:`astropy.units.Quantity`\n 1D array of wavelengths where parameters should be tabulated,\n with length units.\n\n Returns\n -------\n tuple\n Tuple of arrays scale, blur, offset with shapes (N,2), (N,M) and\n (N,M,2) where N is the size of the 1D input (x,y) arrays, M is\n the size of the input wavelength grid, and axes of length 2\n correspond to radial and azimuthal axes (not the input x,y!).\n All output arrays have units.\n \"\"\"\n # Check for valid units on the input arrays.\n try:\n focal_x_mm = focal_x.to(u.mm).value\n focal_y_mm = focal_y.to(u.mm).value\n wlen_grid_ang = wlen_grid.to(u.Angstrom).value\n except astropy.units.UnitConversionError:\n raise ValueError('Input arrays have invalid units.')\n except AttributeError:\n raise ValueError('Input arrays are missing required units.')\n\n # Check for expected input array shapes.\n if len(focal_x_mm.shape) != 1 or len(wlen_grid_ang.shape) != 1:\n raise ValueError('Input arrays must be 1D.')\n if focal_x_mm.shape != focal_y_mm.shape:\n raise ValueError('Input (x,y) arrays have different shapes.')\n\n # Allocate output arrays.\n n_xy = len(focal_x_mm)\n n_wlen = len(wlen_grid_ang)\n scale = np.empty((n_xy, 2))\n blur = np.empty((n_xy, n_wlen))\n offset = np.empty((n_xy, n_wlen, 2))\n\n # Convert x, y offsets in length units to field angles.\n focal_r = np.sqrt(focal_x**2+focal_y**2)\n angle_r = self.field_radius_to_angle(focal_r)\n angle_x = np.zeros(focal_x.shape) * angle_r.unit\n angle_y = np.zeros(focal_y.shape) * angle_r.unit\n positive_radius = focal_r>0\n angle_x[positive_radius] = (\n angle_r[positive_radius] / focal_r[positive_radius]\n ) * focal_x[positive_radius]\n angle_y[positive_radius] = (\n angle_r[positive_radius] / focal_r[positive_radius]\n ) * focal_y[positive_radius]\n\n # Calculate the radial and azimuthal plate scales at each location.\n scale[:, 0] = self.radial_scale(focal_r).to(u.um / u.arcsec).value\n scale[:, 1] = self.azimuthal_scale(focal_r).to(u.um / u.arcsec).value\n\n # Calculate the transformations between polar and Cartesian coordinates.\n phi = np.arctan2(focal_y_mm, focal_x_mm)\n cos_phi = np.cos(phi)\n sin_phi = np.sin(phi)\n\n # Lookup the instrument blur and centroid offset at each\n # wavelength for this focal-plane position.\n for i, wlen in enumerate(wlen_grid):\n # Lookup the RMS blurs in focal-plane microns.\n blur[:, i] = self.get_blur_rms(wlen, angle_r).to(u.um).value\n # Lookup the radial centroid offsets in focal-plane microns.\n dx, dy = self.get_centroid_offset(angle_x, angle_y, wlen)\n dx_um = dx.to(u.um).value\n dy_um = dy.to(u.um).value\n # Rotate to polar coordinates.\n offset[:, i, 0] = cos_phi * dx_um + sin_phi * dy_um\n offset[:, i, 1] = -sin_phi * dx_um + cos_phi * dy_um\n\n return scale * (u.um / u.arcsec), blur * u.um, offset * u.um\n\n\n def plot_field_distortion(self):\n \"\"\"Plot focal plane distortions over the field of view.\n\n Requires that the matplotlib package is installed.\n \"\"\"\n import matplotlib.pyplot as plt\n\n # Tabulate the field radius - angle mapping.\n radius = np.linspace(0., self.field_radius.to(u.mm).value, 500) * u.mm\n angle = self.field_radius_to_angle(radius).to(u.deg)\n\n # Calculate the r**2 weighted mean inverse radial scale by minimizing\n # angle - mean_inv_radial_scale * radius with respect to\n # mean_inv_radial_scale.\n mean_inv_radial_scale = (\n np.sum(radius ** 3 * angle) / np.sum(radius ** 4))\n mean_radial_scale = (1. / mean_inv_radial_scale).to(u.um / u.arcsec)\n\n # Calculate the angular distortion relative to the mean radial scale.\n distortion = (angle - radius * mean_inv_radial_scale).to(u.arcsec)\n\n # Eliminate round off error so that the zero distortion case is\n # correctly recovered.\n distortion = np.round(distortion, decimals=5)\n\n # Calculate the fiber area as a function of radius.\n radial_size = (\n 0.5 * self.fiber_diameter / self.radial_scale(radius))\n azimuthal_size = (\n 0.5 * self.fiber_diameter / self.azimuthal_scale(radius))\n fiber_area = (np.pi * radial_size * azimuthal_size).to(u.arcsec ** 2)\n\n # Calculate the r**2 weighted mean fiber area.\n mean_fiber_area = np.sum(radius ** 2 * fiber_area) / np.sum(radius ** 2)\n\n # Calculate the dimensionless fiber area ratio.\n fiber_area_ratio = (fiber_area / mean_fiber_area).si.value\n\n # Calculate the dimensionless ratio of azimuthal / radial plate scales\n # which is the ratio of the on-sky radial / azimuthal extends.\n shape_ratio = (self.azimuthal_scale(radius) /\n self.radial_scale(radius)).si.value\n\n # Make the plots.\n fig, (ax1, ax2) = plt.subplots(2, sharex=True, figsize=(8, 8))\n\n ax1.plot(angle, distortion, 'b-', lw=2)\n ax1.set_ylabel('Field angle distortion [arcsec]', fontsize='large')\n ax1.set_xlim(0., self.field_angle.to(u.deg).value)\n ax1.grid()\n\n ax1.axhline(0., color='r')\n xy = 0.5 * self.field_angle.to(u.deg).value, 0.\n label = '{0:.1f}'.format(mean_radial_scale)\n ax1.annotate(label, xy, xy, color='r', horizontalalignment='center',\n verticalalignment='bottom', fontsize='large')\n\n ax2.plot(angle, fiber_area_ratio, 'b', lw=2, label='Area ratio')\n ax2.plot(angle, shape_ratio, 'k', lw=2, ls='--',\n label='Radial/azimuthal')\n ax2.set_ylabel('Fiber sky area and shape ratios', fontsize='large')\n ax2.grid()\n ax2.legend(loc='upper right')\n\n ax2.axhline(1., color='r')\n xy = 0.5 * self.field_angle.to(u.deg).value, 1.\n label = '{0:.3f}'.format(mean_fiber_area)\n ax2.annotate(label, xy, xy, color='r', horizontalalignment='center',\n verticalalignment='bottom', fontsize='large')\n\n ax2.set_xlabel('Field angle [deg]', fontsize='large')\n plt.subplots_adjust(\n left=0.10, right=0.98, bottom=0.07, top=0.97, hspace=0.05)\n\n\n def plot(self, flux=1e-17 * u.erg / (u.cm**2 * u.s * u.Angstrom),\n exposure_time=1000 * u.s, cmap='nipy_spectral'):\n \"\"\"Plot a summary of this instrument's model.\n\n Requires that the matplotlib package is installed.\n\n Parameters\n ----------\n flux : astropy.units.Quantity\n Constant source flux to use for displaying the instrument response.\n exposure_time : astropy.units.Quantity\n Exposure time to use for displaying the instrument response.\n cmap : str or matplotlib.colors.Colormap\n Matplotlib colormap name or instance to use for displaying the\n instrument response. Colors are selected for each camera\n according to its central wavelength, so a spectral color map\n will give reasonably intuitive results.\n \"\"\"\n import matplotlib.pyplot as plt\n import matplotlib.cm as cm\n\n fig, (ax1, ax2) = plt.subplots(2, sharex=True, figsize=(8, 8))\n ax1_rhs = ax1.twinx()\n ax2_rhs = ax2.twinx()\n cmap = cm.get_cmap(cmap)\n\n wave = self._wavelength.value\n wave_unit = self._wavelength.unit\n dwave = np.gradient(wave)\n\n if self.fiber_acceptance_dict:\n for source_type in self.fiber_acceptance_dict:\n # Plot fiber acceptance fractions without labels.\n ax1.plot(wave, self.fiber_acceptance_dict[source_type], 'k--')\n for camera in self.cameras:\n cwave = camera._wavelength\n\n # Use an approximate spectral color for each band.\n mid_wave = 0.5 * (camera.wavelength_min + camera.wavelength_max)\n color = cmap(\n (mid_wave - self.wavelength_min) /\n (self.wavelength_max - self.wavelength_min))\n\n # Calculate number of photons with perfect fiber acceptance.\n nphot = (flux * self.photons_per_bin * exposure_time *\n camera.throughput / dwave)\n dark_noise = np.sqrt(\n (camera.dark_current_per_bin * exposure_time).value)\n total_noise = np.sqrt(\n dark_noise ** 2 + camera.read_noise_per_bin.value ** 2)\n\n ax1.plot(cwave, camera.throughput, ls='-', color=color)\n\n ax1_rhs.plot(cwave, nphot.value, ls=':', color=color)\n ax1_rhs.fill_between(\n cwave, total_noise / dwave, lw=0, color=color, alpha=0.2)\n ax1_rhs.fill_between(\n cwave, dark_noise / dwave, lw=0, color=color, alpha=0.2)\n ax1_rhs.plot(cwave, total_noise / dwave, ls='-.', color=color)\n\n ax2.plot(\n cwave, camera.rms_resolution.to(wave_unit).value,\n ls='-', color=color)\n ax2.plot(\n cwave, camera.row_size.to(wave_unit / u.pixel).value,\n ls='--', color=color)\n\n ax2_rhs.plot(\n cwave, camera.neff_spatial.to(u.pixel), ls=':', color=color)\n\n ax1.plot([], [], 'k--', label='Fiber Acceptance')\n ax1.plot([], [], 'k-', label='Camera Throughput')\n ax1.plot([], [], 'k:', label='{0}'.format(flux))\n ax1.plot([], [], 'k-.', label='Dark + Readout Noise')\n ax1.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,\n ncol=2, mode=\"expand\", borderaxespad=0.)\n\n ax2.plot([], [], 'k-', label='RMS Resolution')\n ax2.plot([], [], 'k--', label='Row Size')\n ax2.plot([], [], 'k:', label='Column Size')\n ax2.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,\n ncol=3, mode=\"expand\", borderaxespad=0.)\n\n ax1.set_ylim(0., None)\n ax1.set_ylabel('Fiber, Camera Throughput')\n ax1_rhs.set_ylim(0., None)\n ax1_rhs.set_ylabel(\n 'Photons, Electrons / Exposure / {0}'.format(wave_unit))\n ax2.set_ylim(0., None)\n ax2.set_ylabel('RMS Resolution, Row Size [{0}]'.format(wave_unit))\n ax2_rhs.set_ylim(0., None)\n ax2_rhs.set_ylabel('Effective Column Size [pixels]')\n ax2.set_xlabel('Wavelength [{0}]'.format(wave_unit))\n ax2.set_xlim(wave[0], wave[-1])\n\n\ndef initialize(config, camera_output=True):\n \"\"\"Initialize the instrument model from configuration parameters.\n\n This method is responsible for creating a new :class:`Instrument` as\n well as the :class:`Cameras ` it includes.\n\n Parameters\n ----------\n config : :class:`specsim.config.Configuration`\n The configuration parameters to use.\n camera_output : bool\n Initialize support for resolution convolution and downsampling for\n each camera when True.\n\n Returns\n -------\n Instrument\n An initialized instrument model including one or more\n :class:`cameras `.\n \"\"\"\n name = config.instrument.name\n cameras = config.instrument.cameras\n camera_names = cameras.keys()\n initialized_cameras = []\n for camera_name in camera_names:\n camera = getattr(cameras, camera_name)\n ccd = config.load_table(\n camera.ccd, ['row_size', 'fwhm_resolution', 'neff_spatial'])\n throughput = config.load_table(camera.throughput, 'throughput')\n constants = config.get_constants(camera,\n ['read_noise', 'dark_current', 'gain', 'num_sigmas_clip',\n 'output_pixel_size'])\n initialized_cameras.append(specsim.camera.Camera(\n camera_name, config.wavelength, throughput,\n ccd['row_size'], ccd['fwhm_resolution'],\n ccd['neff_spatial'], constants['read_noise'],\n constants['dark_current'], constants['gain'],\n constants['num_sigmas_clip'], constants['output_pixel_size'],\n allow_convolution=camera_output))\n\n constants = config.get_constants(\n config.instrument,\n ['primary_mirror_diameter', 'obscuration_diameter',\n 'support_width', 'fiber_diameter', 'field_radius'])\n\n try:\n # Try to read a tabulated plate scale first.\n plate_scale = config.load_table(\n config.instrument.plate_scale,\n ['radius', 'radial_scale', 'azimuthal_scale'], interpolate=False)\n r_vec = plate_scale['radius']\n sr_vec = plate_scale['radial_scale']\n sa_vec = plate_scale['azimuthal_scale']\n # Build dimensionless linear interpolators for the radial and azimuthal\n # scales using the native units from the tabulated data.\n sr_interpolate = scipy.interpolate.interp1d(\n r_vec.value, sr_vec.value, kind='linear', copy=True)\n sa_interpolate = scipy.interpolate.interp1d(\n r_vec.value, sa_vec.value, kind='linear', copy=True)\n # Wrap interpolators in lambdas that take care of units.\n radial_scale = lambda r: (\n sr_interpolate(r.to(r_vec.unit).value) * sr_vec.unit)\n azimuthal_scale = lambda r: (\n sa_interpolate(r.to(r_vec.unit).value) * sa_vec.unit)\n except AttributeError:\n # Fall back to a constant value.\n plate_scale_constant = config.get_constants(\n config.instrument.plate_scale, ['value'])\n value = plate_scale_constant['value']\n # Create lambdas that return the constant plate scale with units.\n # Use np.ones_like to ensure correct broadcasting.\n radial_scale = lambda r: value * np.ones_like(r.value)\n azimuthal_scale = lambda r: value * np.ones_like(r.value)\n\n # Initialize for both fiberloss methods so that method can be changed\n # at run time.\n fiberloss_method = config.instrument.fiberloss.method\n fiberloss_num_wlen = config.instrument.fiberloss.num_wlen\n fiberloss_num_pixels = config.instrument.fiberloss.num_pixels\n if hasattr(config.instrument.fiberloss, 'table'):\n fiber_acceptance_dict = config.load_table(\n config.instrument.fiberloss, 'fiber_acceptance', as_dict=True)\n else:\n fiber_acceptance_dict = None\n if hasattr(config.instrument.fiberloss, 'fast_fiber_acceptance_path'):\n filename = os.path.join(\n config.abs_base_path,\n config.instrument.fiberloss.fast_fiber_acceptance_path)\n if not os.path.isfile(filename) :\n raise RuntimeError(\n 'Cannot find file {}. May need to update desimodel svn ?'\n .format(filename))\n fast_fiber_acceptance = specsim.fastfiberacceptance.FastFiberAcceptance(\n filename)\n else:\n fast_fiber_acceptance = None\n\n blur_value = getattr(config.instrument.blur, 'value', None)\n if blur_value:\n blur_value = specsim.config.parse_quantity(blur_value, u.micron)\n blur_function = lambda angle, wlen: blur_value\n else:\n blur_function = config.load_table2d(\n config.instrument.blur, 'wavelength', 'r=')\n\n offset_value = getattr(config.instrument.offset, 'value', None)\n if offset_value:\n offset_value = specsim.config.parse_quantity(offset_value, u.micron)\n offset_function = (\n lambda angle_x, angle_y, wlen: (offset_value, 0 * u.um))\n else:\n # Build an interpolator in (r, wlen) of radial chromatic offsets.\n radial_offset_function = config.load_table2d(\n config.instrument.offset, 'wavelength', 'r=')\n # Look for an optional file of achromatic offsets.\n # Static achromatic term, correlated in focal plane\n if hasattr(config.instrument.offset, 'static'):\n # Build an interpolator in (x, y).\n interpolators = config.load_fits2d(\n config.instrument.offset.static, xy_unit=u.deg,\n dx='XOFFSET', dy='YOFFSET')\n static_fx = interpolators['dx']\n static_fy = interpolators['dy']\n else:\n static_fx = None\n static_fy = None\n # Random uncorrelated achromatic term\n if hasattr(config.instrument.offset, 'sigma1d'):\n if hasattr(config.instrument.offset, 'seed'):\n offset_gen = np.random.RandomState(config.instrument.offset.seed)\n else:\n offset_gen = np.random.RandomState()\n sigma1d=specsim.config.parse_quantity(config.instrument.offset.sigma1d)\n random_fx = lambda angle_x, angle_y: offset_gen.normal(size=angle_x.shape) * sigma1d\n random_fy = lambda angle_x, angle_y: offset_gen.normal(size=angle_x.shape) * sigma1d\n else :\n random_fx = None\n random_fy = None\n # Combine the interpolators into a function of (x, y, wlen) that\n # returns (dx, dy). Use default parameter values to capture the\n # necessary state in the inner function's closure.\n def offset_function(angle_x, angle_y, wlen,\n fr=radial_offset_function,\n static_fx=static_fx,\n static_fy=static_fy,\n random_fx=random_fx,\n random_fy=random_fy) :\n angle_r = np.sqrt(angle_x ** 2 + angle_y ** 2)\n dr = fr(angle_r, wlen)\n # Special handling of the origin.\n not_at_origin = (angle_r > 0.)\n ux = np.ones(shape=dr.shape, dtype=float)\n uy = np.ones(shape=dr.shape, dtype=float)\n ux[not_at_origin] = angle_x / angle_r\n uy[not_at_origin] = angle_y / angle_r\n dx = dr * ux\n dy = dr * uy\n # Add interpolated offsets if any.\n if static_fx is not None : dx += static_fx(angle_x, angle_y)\n if static_fy is not None : dy += static_fy(angle_x, angle_y)\n if random_fx is not None : dx += random_fx(angle_x, angle_y)\n if random_fy is not None : dy += random_fy(angle_x, angle_y)\n return dx , dy\n\n instrument = Instrument(\n name, config.wavelength, fiberloss_method, fiber_acceptance_dict,\n fast_fiber_acceptance, fiberloss_num_wlen, fiberloss_num_pixels,\n blur_function, offset_function, initialized_cameras,\n constants['primary_mirror_diameter'], constants['obscuration_diameter'],\n constants['support_width'], constants['fiber_diameter'],\n constants['field_radius'], radial_scale, azimuthal_scale)\n\n if config.verbose:\n # Print some derived quantities.\n print('Telescope effective area: {0:.3f}'\n .format(instrument.effective_area))\n print('Field of view diameter: {0:.1f} = {1:.2f}.'\n .format(2 * instrument.field_radius.to(u.mm),\n 2 * instrument.field_angle.to(u.deg)))\n if fiber_acceptance_dict is not None:\n print('Fiberloss source types: {0}.'\n .format(instrument.fiber_acceptance_dict.keys()))\n\n return instrument\n", "meta": {"hexsha": "7a93e1663a69051e36386b081e1db651e2f3b8cd", "size": 33886, "ext": "py", "lang": "Python", "max_stars_repo_path": "specsim/instrument.py", "max_stars_repo_name": "michaelJwilson/specsim", "max_stars_repo_head_hexsha": "0e3e1b3fa84282b32d61c3c8f189fe98c1a327cf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "specsim/instrument.py", "max_issues_repo_name": "michaelJwilson/specsim", "max_issues_repo_head_hexsha": "0e3e1b3fa84282b32d61c3c8f189fe98c1a327cf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "specsim/instrument.py", "max_forks_repo_name": "michaelJwilson/specsim", "max_forks_repo_head_hexsha": "0e3e1b3fa84282b32d61c3c8f189fe98c1a327cf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.8369987063, "max_line_length": 96, "alphanum_fraction": 0.6386413268, "include": true, "reason": "import numpy,import scipy,import astropy", "num_tokens": 7627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.21733751597763018, "lm_q1q2_score": 0.14001428140505187}} {"text": "# -*- mode: python; coding: utf-8 -*-\n# Copyright 2018 Peter Williams and collaborators.\n# Licensed under the MIT License.\n\n\"\"\"This module provides helpers for doing radiative transfer integrations with\n`grtrans `_, including a simple\nframework for running end-to-end tests.\n\nIn order to use this functionality, the Python module ``radtrans_integrate``\nmust be importable. Sadly `grtrans `_\ndoesn't install itself like a regular Python package, so getting this working\ncan be a pain. Documenting the installation procedure is beyond the scope of\nthis project.\n\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\n\nimport numpy as np\nimport pandas as pd\n\n\n# grtrans' integration methods:\nMETHOD_LSODA_YES_LINEAR_STOKES = 0 # LSODA with IS_LINEAR_STOKES=1\nMETHOD_DELO = 1 # DELO method from Rees+ (1989ApJ...339.1093R)\nMETHOD_FORMAL = 2 # \"formal\" method = \"matricant (O-matrix) method from Landi Degl'Innocenti\"\nMETHOD_LSODA_NO_LINEAR_STOKES = 3 # LSODA with IS_LINEAR_STOKES=0 -- this is \"under development\" spherical stokes\n\n\ndef integrate_ray_formal(x, j, K):\n \"\"\"Use `grtrans `_ to integrate one ray\n using its \"formal\" (matricant / O-matrix) method.\n\n **Call signature**\n\n *x*\n 1D array, shape (n,). Path length along ray, starting from zero, in cm.\n *j*\n Array, shape (n, 4). Emission coefficients: ``j_{IQUV}``, in that order.\n *K*\n Array, shape (n, 7). Absorption coefficients and Faraday mixing coefficients:\n ``alpha_{IQUV}, rho_{QUV}``.\n Return value\n Array of shape (4, m): Stokes intensities ``IQUV`` along parts of the\n ray with non-zero total emissivities; m <= n.\n\n \"\"\"\n # A correct version of the fully-specified absorption matrix is in Leung+\n # 2011 (10.1088/0004-637X/737/1/21). From looking at the function\n # `radtrans_jac_form` of grtrans' `radtrans_integrate.f90` file, one can\n # see that the K vector is indeed packed in the way described above.\n from radtrans_integrate import radtrans_integrate\n\n n = x.size\n\n # The formal method doesn't do the same kind of clipping as LSODA *inside*\n # grtrans, but here we do the same clipping for consistency, and since it\n # is genuinely true that the clipped samples are superfluous.\n\n if np.all(j[:,0] == 0.):\n return np.zeros((4, n))\n\n i0 = 0\n i1 = n - 1\n\n while j[i0,0] == 0.:\n i0 += 1\n while j[i1,0] == 0.:\n i1 -= 1\n\n n = i1 + 1 - i0\n x = x[i0:i1+1]\n j = j[i0:i1+1]\n K = K[i0:i1+1]\n\n # OK we can go.\n\n radtrans_integrate.init_radtrans_integrate_data(\n METHOD_FORMAL, # method selector\n 4, # number of equations\n n, # number of input data points\n n, # number of output data points\n 10., # maximum optical depth; not used by \"formal\"\n 1., # maximum absolute step size; not used by \"formal\"\n 0.1, # absolute tolerance; not used by \"formal\"\n 0.1, # relative tolerance; not used by \"formal\"\n 1e-2, # \"thin\" parameter for DELO method; not used by \"formal\"\n 1, # maximum number of steps; not used by \"formal\"\n )\n\n try:\n tau = x # not used by \"formal\"\n radtrans_integrate.integrate(x[::-1], j[::-1], K[::-1], tau[::-1], 4)\n i = radtrans_integrate.intensity.copy()\n finally:\n # If we exit without calling this, the next init call causes an abort\n radtrans_integrate.del_radtrans_integrate_data()\n return i\n\n\ndef integrate_ray_lsoda(x, j, K, atol=1e-8, rtol=1e-6, max_step_size=None,\n frac_max_step_size=1e-3, max_steps=100000):\n \"\"\"Use `grtrans `_ to integrate one ray\n using its LSODA method.\n\n **Call signature**\n\n *x*\n 1D array, shape (n,). Path length along ray, starting from zero, in cm.\n *j*\n Array, shape (n, 4). Emission coefficients: ``j_{IQUV}``, in that order.\n *K*\n Array, shape (n, 7). Absorption coefficients and Faraday mixing coefficients:\n ``alpha_{IQUV}, rho_{QUV}``.\n *atol*\n Some kind of tolerance parameter.\n *rtol*\n Some kind of tolerance parameter.\n *max_step_size*\n The maximum absolute step size. Overrides *frac_max_step_size*.\n *frac_max_step_size*\n If *max_step_size* is not specified, the maximum step size passed to the\n integrator is ``x.max()`` multiplied by this parameter. Experience shows\n that (for LSODA at least) this parameter must be pretty small to get\n good convergence!\n *max_steps*\n The maximum number of steps to take.\n Return value\n Array of shape (4, m): Stokes intensities IQUV along parts of the ray with\n non-zero total emissivities; m <= n.\n\n \"\"\"\n n = x.size\n\n if max_step_size is None:\n max_step_size = frac_max_step_size * x.max()\n\n # the LSODA method clips its input arrays based on \"tau\" and zero emission\n # coefficients. It's hard for us to find out how it clipped, though, so we\n # reproduce its logic. LSODA doesn't use \"tau\" for anything besides this\n # clipping, so we pass it all zeros.\n\n if np.all(j[:,0] == 0.):\n return np.zeros((4, n))\n\n i0 = 0\n i1 = n - 1\n\n while j[i0,0] == 0.:\n i0 += 1\n while j[i1,0] == 0.:\n i1 -= 1\n\n n = i1 + 1 - i0\n x = x[i0:i1+1]\n j = j[i0:i1+1]\n K = K[i0:i1+1]\n\n # OK we can go.\n\n radtrans_integrate.init_radtrans_integrate_data(\n METHOD_LSODA_YES_LINEAR_STOKES, # method selector\n 4, # number of equations\n n, # number of input data points\n n, # number of output data points\n 10., # maximum optical depth; defused here (see comment above)\n max_step_size, # maximum absolute step size\n atol, # absolute tolerance\n rtol, # relative tolerance\n 1e-2, # \"thin\" parameter for DELO method ... to be researched\n max_steps, # maximum number of steps\n )\n\n try:\n tau = np.zeros(n)\n radtrans_integrate.integrate(x[::-1], j, K, tau, 4)\n i = radtrans_integrate.intensity.copy()\n finally:\n # If we exit without calling this, the next init call causes an abort\n radtrans_integrate.del_radtrans_integrate_data()\n return i\n\n\ndef integrate(d, coeffs, psi):\n \"\"\"Integrate a ray with `grtrans `_,\n using reasonable defaults.\n\n **Call signature**\n\n *d*\n An array giving the location of each sample along the ray, starting from zero, in cm.\n *coeffs*\n An array of shape (N, 8) of RT coefficients in the basis where the\n Stokes U coefficients are always zero. Such arrays are returned by\n :meth:`neurosynchro.impl.PhysicalApproximator.compute_all_nontrivial`.\n *psi*\n An array of angles between the local magnetic field and the observer’s Stokes U\n axis, in radians.\n Return value\n An array of shape (4,), giving the Stokes IQUV at the end of the ray.\n\n This function is mainly intended to test what happens if the passed-in\n coefficients are slightly different due to the neural network\n approximation. So we don't provide many knobs or diagnostics here.\n\n \"\"\"\n from . import detrivialize_stokes_basis\n\n xformed = detrivialize_stokes_basis(coeffs, psi)\n j = np.empty(coeffs.shape[:-1] + (4,))\n j[...,0] = xformed[...,0]\n j[...,1] = xformed[...,2]\n j[...,2] = xformed[...,4]\n j[...,3] = xformed[...,6]\n K = np.empty(coeffs.shape[:-1] + (7,))\n K[...,0] = xformed[...,1]\n K[...,1] = xformed[...,3]\n K[...,2] = xformed[...,5]\n K[...,3:] = xformed[...,7:]\n\n iquv = integrate_ray_formal(d, j, K)\n return iquv[:,-1]\n\n\ndef make_parser(ap=None):\n if ap is None:\n ap = argparse.ArgumentParser()\n\n ap.add_argument('--frequency', '-f', type=float, metavar='',\n default=10.0, help='The observing frequency to simulate')\n ap.add_argument('nndir', type=str, metavar='',\n help='The path to the neural-net directory.')\n ap.add_argument('testdata', type=str, metavar='',\n help='A file containing test data')\n return ap\n\n\ndef grtrans_cli(settings):\n from pwkit import cgs\n from pwkit.cli import die\n from time import time\n from .impl import PhysicalApproximator, hardcoded_nu_ref, hardcoded_ne_ref\n\n # Read and validate the test dataset.\n\n testdata = pd.read_table(settings.testdata)\n\n psi = testdata.get('psi(meta)')\n if psi is None:\n die('the test dataset must contain a column of field-to-Stokes-U angles \\\"psi(meta)\\\"')\n\n d = testdata.get('d(meta)')\n if d is None:\n die('the test dataset must contain a column of integration path lengths \\\"d(meta)\\\"')\n\n n_e = testdata.get('n_e(meta)')\n if n_e is None:\n die('the test dataset must contain a column of particle densities \\\"n_e(meta)\\\"')\n\n time_ms = testdata.get('time_ms(meta)')\n if time_ms is None:\n die('the test dataset must contain a column of computation times \\\"time_ms(meta)\\\"')\n\n s = None\n theta = None\n others = {}\n\n for col in testdata.columns:\n if col.startswith('s('):\n s = testdata[col]\n elif col.startswith('theta('):\n theta = testdata[col]\n elif col.endswith('(lin)') or col.endswith('(log)'):\n others[col.split('(')[0]] = testdata[col]\n\n if s is None:\n die('the test dataset must have an input parameter of the harmonic number \\\"s\\\"')\n\n if theta is None:\n die('the test dataset must have an input parameter of the field-to-LOS angle \\\"theta\\\"')\n\n # Get the coefficients into physical units, packed in our standard format.\n\n nu_hz = settings.frequency * 1e9\n freq_scale = nu_hz / hardcoded_nu_ref\n n_e_scale = n_e / hardcoded_ne_ref\n\n coeffs = np.empty((psi.size, 8))\n coeffs[...,0] = testdata['j_I(res)'] * freq_scale\n coeffs[...,1] = testdata['alpha_I(res)'] / freq_scale\n coeffs[...,2] = testdata['j_Q(res)'] * freq_scale\n coeffs[...,3] = testdata['alpha_Q(res)'] / freq_scale\n coeffs[...,4] = testdata['j_V(res)'] * freq_scale\n coeffs[...,5] = testdata['alpha_V(res)'] / freq_scale\n coeffs[...,6] = testdata['rho_Q(res)'] / freq_scale\n coeffs[...,7] = testdata['rho_V(res)'] / freq_scale\n coeffs *= n_e_scale.values.reshape((-1, 1))\n\n # Ground truth:\n\n iquv_precise = integrate(d, coeffs, psi)\n ctime_precise = time_ms.sum()\n print('Precise computation: I={:.4e} Q={:.4e} U={:.4e} V={:.4e} calc_time={:.0f} ms'.format(\n iquv_precise[0], iquv_precise[1], iquv_precise[2], iquv_precise[3], ctime_precise\n ))\n\n # Now set up the approximator and do the same thing. (Note that often the\n # timing seems backwards, because the time spent doing the precise\n # calculation has already been spent, whereas we have a lot of overhead to\n # set up the neural networks.)\n\n B = 2 * np.pi * cgs.me * cgs.c * nu_hz / (s * cgs.e)\n approx = PhysicalApproximator(settings.nndir)\n t0 = time()\n coeffs, oos = approx.compute_all_nontrivial(nu_hz, B, n_e, theta, **others)\n ctime_approx = 1000 * (time() - t0)\n\n if np.any(oos != 0):\n print('WARNING: some of the approximations were out-of-sample')\n\n iquv_approx = integrate(d, coeffs, psi)\n print('Approx. computation: I={:.4e} Q={:.4e} U={:.4e} V={:.4e} calc_time={:.0f} ms'.format(\n iquv_approx[0], iquv_approx[1], iquv_approx[2], iquv_approx[3], ctime_approx\n ))\n\n acc = np.abs((iquv_approx - iquv_precise) / iquv_precise)\n print('Accuracy: I={:.3f} Q={:.3f} U={:.3f} V={:.3f}'.format(acc[0], acc[1], acc[2], acc[3]))\n\n print('Speedup: {:.1f}'.format(ctime_precise / ctime_approx))\n", "meta": {"hexsha": "9beb0b097fc490d34f9caaf635be7bc49c7344bb", "size": 11785, "ext": "py", "lang": "Python", "max_stars_repo_path": "neurosynchro/grtrans.py", "max_stars_repo_name": "pkgw/neurosynchro", "max_stars_repo_head_hexsha": "f21d198e01146988944728231417ff601b706379", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "neurosynchro/grtrans.py", "max_issues_repo_name": "pkgw/neurosynchro", "max_issues_repo_head_hexsha": "f21d198e01146988944728231417ff601b706379", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-09-26T16:09:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-21T16:34:51.000Z", "max_forks_repo_path": "neurosynchro/grtrans.py", "max_forks_repo_name": "pkgw/neurosynchro", "max_forks_repo_head_hexsha": "f21d198e01146988944728231417ff601b706379", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.820668693, "max_line_length": 113, "alphanum_fraction": 0.6388629614, "include": true, "reason": "import numpy", "num_tokens": 3333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.2538610126142736, "lm_q1q2_score": 0.13977774336765358}} {"text": "\"\"\"Objects representing pure chemical components and pseudo-components.\n\nAttributes\n----------\nCOMP_FAM : list\n Pre-defined component family pick list based on definitions in _[1] and _[2].\n\nNotes\n-----\n\n\nReferences\n----------\n[1] Perry's Chemical Engineers' Handbook; Perry, R. H., Southard, M. Z., Eds.; McGraw-Hill Education: New York, 2019.\n[2] Tihic, A.; Kontogeorgis, G. M.; von Solms, N.;Michelsen, M. L. Applications of the simplified perturbed-chain SAFT\nequation of state using an extended parameter table. Fluid Phase Equilib. 2006, 248, 29-43.\n\"\"\"\n\nCOMP_FAM = ['Alkanes', 'Alkenes', 'Alkynes', 'Cycloalkanes' 'Aromatics', 'Polynuclear Aromatics', 'Aldehydes',\n 'Ketones', 'Heterocyclics', 'Elements', 'Alcohols', 'Phenols', 'Ethers', 'Acids', 'Esters', 'Amines',\n 'Amides', 'Nitriles', 'Nitro Compounds', 'Isocyanates', 'Mercaptans', 'Sulfides',\n 'Halogenated Hydrocarbons', 'Silanes', 'Inorganics', 'Multifunctional']\n\nimport numpy as np\nfrom utilities import *\n\n\nclass Comp(object):\n \"\"\"A pure chemical component.\"\"\"\n def __init__(self, name=None):\n \"\"\"\n Parameters\n ----------\n name : str\n \"\"\"\n # General Attributes\n if name is None:\n raise ValueError(\"Comp object must be initialized with a name and molecular weight.\")\n else:\n # Metadata and constants.\n self.name = name\n self.cas_no = None\n self.formula = None\n self.family = None\n self.mw = None\n self.vdwv = None\n self.vdwa = None\n self.rgyr = None\n self.dipole = None\n self.quadrupole = None\n self.acentric = None\n self.tc = None\n self.pc = None\n self.vc = None\n self.rhoc = None\n self.tt = None\n self.pt = None\n self.bp = None\n self.mp = None\n self.hfus = None\n self.hsub = None\n self.ig_hform = None\n self.ig_gform = None\n self.ig_entr = None\n self.hcomb = None\n\n # Temperature dependent properties.\n self.pvap_l = None\n self.hvap_l = None\n self.den_s = None\n self.den_l = None\n self.beta_s = None\n self.beta_l = None\n self.cp_s = None\n self.cp_l = None\n self.cp_ig = None\n self.visc_l = None\n self.visc_ig = None\n self.tcond_s = None\n self.tcond_l = None\n self.tcond_ig = None\n self.sigma = None\n\n # TODO: Ensure CEOS physical terms are built with getter/setter checks for CEOS objects.\n # Cubic EOS physical parameter dictionaries.\n self.srk_phys = {'a': None, 'b': None, 'm': None}\n self.cpa_phys = {'a0': None, 'b': None, 'c1': None}\n self.pr_phys = {'a': None, 'b': None, 'm': None}\n self.gpr_phys = {'a': None, 'b': None, 'a': None, 'b': None, 'c': None}\n self.tpr_phys = {'a': None, 'b': None, 'l': None, 'm': None, 'n': None}\n\n # SAFT EOS physical parameter dictionaries.\n self.spc_saft_phys = {'m': None, 'sig': None, 'eps': None}\n self.pc_saft_phys = {'m': None, 'sig': None, 'eps': None}\n\n # SAFT EOS association parameter objects.\n self.assoc_sites = None\n self.cpa_assoc = None\n self.spc_saft_assoc = None\n self.pc_saft_assoc = None\n\n @property\n def name(self):\n \"\"\"str : Name of chemical compound.\n\n Value can only be set whe creating a new Comp instance.\n \"\"\"\n return self._name\n\n @name.setter\n def name(self, value):\n try:\n self._name\n except AttributeError:\n if isinstance(value, str):\n self._name = value\n else:\n raise TypeError(\"name must be a string.\")\n\n @property\n def cas_no(self):\n \"\"\"str: Chemical Abstracts Service Registry Number.\"\"\"\n return self._cas_no\n\n @cas_no.setter\n def cas_no(self, value):\n if isinstance(value, str) or value is None:\n self._cas_no = value\n else:\n raise TypeError(\"cas_no must be a string.\")\n\n @property\n def formula(self):\n \"\"\"str : Chemical formula.\"\"\"\n return self._formula\n\n @formula.setter\n def formula(self, value):\n if isinstance(value, str) or value is None:\n self._formula = value\n else:\n raise TypeError(\"formula must be a string.\")\n\n @property\n def family(self):\n \"\"\"str : Chemical family.\"\"\"\n return self._family\n\n @family.setter\n def family(self, value):\n if isinstance(value, str) or value is None:\n if value in COMP_FAM or value is None:\n self._family = value\n else:\n raise ValueError(\"family must be one of the pre-defined values.\")\n else:\n raise TypeError(\"family must be a string.\")\n\n @property\n def mw(self):\n \"\"\"float : Molecular weight, g/mol.\"\"\"\n return self._mw\n\n @mw.setter\n def mw(self, value):\n if (isinstance(value, float) and value >= 0.0) or value is None:\n self._mw = value\n else:\n raise TypeError(\"mw must be a positive float.\")\n\n @property\n def vdwv(self):\n \"\"\"float : Van der Waal's volume, unit TBD.\"\"\"\n return self._vdwv\n\n @vdwv.setter\n def vdwv(self, value):\n if (isinstance(value, float) and value >= 0.0) or value is None:\n self._vdwv = value\n else:\n raise TypeError(\"vdwv must be a positive float.\")\n\n @property\n def vdwa(self):\n \"\"\"float : Van der Waal's surface area, unit TBD.\"\"\"\n return self._vdwa\n\n @vdwa.setter\n def vdwa(self, value):\n if (isinstance(value, float) and value >= 0.0) or value is None:\n self._vdwa = value\n else:\n raise TypeError(\"vdwa must be a positive float.\")\n\n @property\n def rgyr(self):\n \"\"\"float : Radius of gyration, unit TBD.\"\"\"\n return self._rgyr\n\n @rgyr.setter\n def rgyr(self, value):\n if (isinstance(value, float) and value >= 0.0) or value is None:\n self._rgyr = value\n else:\n raise TypeError(\"rgyr must be a positive float.\")\n\n @property\n def dipole(self):\n \"\"\"float : Gas phase dipole moment, unit TBD.\"\"\"\n return self._dipole\n\n @dipole.setter\n def dipole(self, value):\n if (isinstance(value, float) and value >= 0.0) or value is None:\n self._dipole = value\n else:\n raise TypeError(\"dipole must be a positive float.\")\n\n @property\n def quadrupole(self):\n \"\"\"float : Gas phase quadrupole moment, unit TBD.\"\"\"\n return self._quadrupole\n\n @quadrupole.setter\n def quadrupole(self, value):\n if (isinstance(value, float) and value >= 0.0) or value is None:\n self._quadrupole = value\n else:\n raise TypeError(\"quadrupole must be a positive float.\")\n\n @property\n def acentric(self):\n \"\"\"float : Acentric factor, dimensionless.\"\"\"\n return self._acentric\n\n @acentric.setter\n def acentric(self, value):\n if isinstance(value, float) or value is None:\n self._acentric = value\n else:\n raise TypeError(\"acentric must be a float.\")\n\n @property\n def tc(self):\n \"\"\"float : Critical temperature, K.\"\"\"\n return self._tc\n\n @tc.setter\n def tc(self, value):\n if (isinstance(value, float) and value >= 0.0) or value is None:\n self._tc = value\n else:\n raise TypeError(\"tc must be a positive float.\")\n\n @property\n def pc(self):\n \"\"\"float : Critical pressure, Pa.\"\"\"\n return self._pc\n\n @pc.setter\n def pc(self, value):\n if (isinstance(value, float) and value >= 0.0) or value is None:\n self._pc = value\n else:\n raise TypeError(\"pc must be a positive float.\")\n\n @property\n def vc(self):\n \"\"\"float : Critical volume, m**3/mol.\"\"\"\n return self._vc\n\n @vc.setter\n def vc(self, value):\n if (isinstance(value, float) and value >= 0.0) or value is None:\n self._vc = value\n else:\n raise TypeError(\"vc must be a positive float.\")\n\n @property\n def rhoc(self):\n \"\"\"float : Critical density, mol/m**3\"\"\"\n return self._rhoc\n\n @rhoc.setter\n def rhoc(self, value):\n if (isinstance(value, float) and value >= 0.0) or value is None:\n self._rhoc = value\n else:\n raise TypeError(\"rhoc must be a positive float.\")\n\n @property\n def tt(self):\n \"\"\"float : Triple point temperature, K.\"\"\"\n return self._tt\n\n @tt.setter\n def tt(self, value):\n if (isinstance(value, float) and value >= 0.0) or value is None:\n self._tt = value\n else:\n raise TypeError(\"tt must be a positive float.\")\n\n @property\n def pt(self):\n \"\"\"float : Triple point pressure, Pa.\"\"\"\n return self._pt\n\n @pt.setter\n def pt(self, value):\n if (isinstance(value, float) and value >= 0.0) or value is None:\n self._pt = value\n else:\n raise TypeError(\"pt must be a positive float.\")\n\n @property\n def bp(self):\n \"\"\"float : Boiling point, K.\"\"\"\n return self._bp\n\n @bp.setter\n def bp(self, value):\n if (isinstance(value, float) and value >= 0.0) or value is None:\n self._bp = value\n else:\n raise TypeError(\"bp must be a positive float.\")\n\n @property\n def mp(self):\n \"\"\"float : Melting point, K.\"\"\"\n return self._mp\n\n @mp.setter\n def mp(self, value):\n if (isinstance(value, float) and value >= 0.0) or value is None:\n self._mp = value\n else:\n raise TypeError(\"mp must be a positive float.\")\n\n @property\n def hfus(self):\n \"\"\"float : Enthalpy of solid-liquid fusion, J/mol.\"\"\"\n return self._hfus\n\n @hfus.setter\n def hfus(self, value):\n if isinstance(value, float) or value is None:\n self._hfus = value\n else:\n raise TypeError(\"hfus must be a float.\")\n\n @property\n def hsub(self):\n \"\"\"float : Enthalpy of sublimation, J/mol.\"\"\"\n return self._hsub\n\n @hsub.setter\n def hsub(self, value):\n if isinstance(value, float) or value is None:\n self._hsub = value\n else:\n raise TypeError(\"hsub must be a float.\")\n\n @property\n def ig_hform(self):\n \"\"\"float : Ideal gas enthalpy of formation at 298.15, unit TBD.\n\n The compounds are considered to be formed from the elements in their standard states at 298.15K and 1 bar.\n These include C (graphite) and S (rhombic).\n \"\"\"\n return self._ig_hform\n\n @ig_hform.setter\n def ig_hform(self, value):\n if isinstance(value, float) or value is None:\n self._ig_hform = value\n else:\n raise TypeError(\"ig_hform must be a float.\")\n\n @property\n def ig_gform(self):\n \"\"\"float : Ideal gas gibbs energy of formation at 298.15, unit TBD.\"\"\"\n return self._ig_gform\n\n @ig_gform.setter\n def ig_gform(self, value):\n if isinstance(value, float) or value is None:\n self._ig_gform = value\n else:\n raise TypeError(\"ig_gform must be a float.\")\n\n @property\n def ig_entr(self):\n \"\"\"float : Ideal gas gibbs entropy, unit TBD.\"\"\"\n return self._ig_entr\n\n @ig_entr.setter\n def ig_entr(self, value):\n if isinstance(value, float) or value is None:\n self._ig_entr = value\n else:\n raise TypeError(\"ig_entr must be a float.\")\n\n @property\n def hcomb(self):\n \"\"\"float : Standard net enthalpy of combustion, unit TBD.\n\n Enthalpy of combustion is the net value for the compound in its standard state at 298.15K and 1 bar. Products\n of combustion are taken to be CO2 (gas), H2O (gas), F2 (gas), Cl2 (gas), Br2 (gas), I2 (gas), SO2 (gas), N2\n (gas), P4O10 (crystalline), SiO2 (crystobalite), and Al2O3 (crystal, alpha).\n \"\"\"\n return self._hcomb\n\n @hcomb.setter\n def hcomb(self, value):\n if isinstance(value, float) or value is None:\n self._hcomb = value\n else:\n raise TypeError(\"hcomb must be a float.\")\n\n @property\n def pvap_l(self):\n \"\"\"float : Liquid vapor pressure, Pa.\"\"\"\n return self._pvap_l\n\n @pvap_l.setter\n def pvap_l(self, value):\n if isinstance(value, Corel) or value is None:\n self._pvap_l = value\n else:\n raise TypeError(\"pvap_l must be an instance of Corel.\")\n\n @property\n def hvap_l(self):\n \"\"\"float : Enthalpy of saturated liquid vaporization, J/mol.\"\"\"\n return self._hvap_l\n\n @hvap_l.setter\n def hvap_l(self, value):\n if isinstance(value, Corel) or value is None:\n self._hvap_l = value\n else:\n raise TypeError(\"hvap_l must be an instance of Corel.\")\n\n @property\n def den_s(self):\n \"\"\"float : Solid density, kg/m3 or mol/m3.\"\"\"\n return self._den_s\n\n @den_s.setter\n def den_s(self, value):\n if isinstance(value, Corel) or value is None:\n self._den_s = value\n else:\n raise TypeError(\"den_S must be an instance of Corel.\")\n\n @property\n def den_l(self):\n \"\"\"float : Liquid density, kg/m3 or mol/m3.\"\"\"\n return self._den_l\n\n @den_l.setter\n def den_l(self, value):\n if isinstance(value, Corel) or value is None:\n self._den_l = value\n else:\n raise TypeError(\"den_l must be an instance of Corel.\")\n\n @property\n def beta_s(self):\n \"\"\"float : Isothermal solid compressibility, Unit TBD.\n\n beta = -(1/V)*(dV/dP) = (1/rho)*(drho/dP), sign change due to conversion from V to rho with chain rule.\"\"\"\n return self._beta_s\n\n @beta_s.setter\n def beta_s(self, value):\n if isinstance(value, Corel) or value is None:\n self._beta_s = value\n else:\n raise TypeError(\"beta_s must be an instance of Corel.\")\n\n @property\n def beta_l(self):\n \"\"\"float : Isothermal liquid compressibility, Unit TBD.\n\n beta = -(1/V)*(dV/dP) = (1/rho)*(drho/dP), sign change due to conversion from V to rho with chain rule.\"\"\"\n return self._beta_l\n\n @beta_l.setter\n def beta_l(self, value):\n if isinstance(value, Corel) or value is None:\n self._beta_l = value\n else:\n raise TypeError(\"beta_l must be an instance of Corel.\")\n\n @property\n def cp_s(self):\n \"\"\"float : Solid heat capacity, J/mol.K.\"\"\"\n return self._cp_s\n\n @cp_s.setter\n def cp_s(self, value):\n if isinstance(value, Corel) or value is None:\n self._cp_s = value\n else:\n raise TypeError(\"cp_s must be an instance of Corel.\")\n\n @property\n def cp_l(self):\n \"\"\"float : Saturated liquid heat capacity, J/mol.K.\"\"\"\n return self._cp_l\n\n @cp_l.setter\n def cp_l(self, value):\n if isinstance(value, Corel) or value is None:\n self._cp_l = value\n else:\n raise TypeError(\"cp_l must be an instance of Corel.\")\n\n @property\n def cp_ig(self):\n \"\"\"float : Ideal gas heat capacity, J/mol.K.\"\"\"\n return self._cp_ig\n\n @cp_ig.setter\n def cp_ig(self, value):\n if isinstance(value, Corel) or value is None:\n self._cp_ig = value\n else:\n raise TypeError(\"cp_ig must be an instance of Corel.\")\n\n @property\n def visc_l(self):\n \"\"\"float : Saturated liquid viscosity, unit TBD.\"\"\"\n return self._visc_l\n\n @visc_l.setter\n def visc_l(self, value):\n if isinstance(value, Corel) or value is None:\n self._visc_l = value\n else:\n raise TypeError(\"visc_l must be an instance of Corel.\")\n\n @property\n def visc_ig(self):\n \"\"\"float : Ideal gas viscosity, unit TBD.\"\"\"\n return self._visc_ig\n\n @visc_ig.setter\n def visc_ig(self, value):\n if isinstance(value, Corel) or value is None:\n self._visc_ig = value\n else:\n raise TypeError(\"visc_ig must be an instance of Corel.\")\n\n @property\n def tcond_s(self):\n \"\"\"float : Solid thermal conductivity, unit TBD.\"\"\"\n\n @tcond_s.setter\n def tcond_s(self, value):\n if isinstance(value, Corel) or value is None:\n self._tcond_s = value\n else:\n raise TypeError(\"tcond_s must be an instance of Corel.\")\n\n @property\n def tcond_l(self):\n \"\"\"float : Saturated liquid thermal conductivity, unit TBD.\"\"\"\n return self._tcond_l\n\n @tcond_l.setter\n def tcond_l(self, value):\n if isinstance(value, Corel) or value is None:\n self._tcond_l = value\n else:\n raise TypeError(\"tcond_l must be an instance of Corel.\")\n\n @property\n def tcond_ig(self):\n \"\"\"float : Ideal gas thermal conductivity, unit TBD.\"\"\"\n return self._tcond_ig\n\n @tcond_ig.setter\n def tcond_ig(self, value):\n if isinstance(value, Corel) or value is None:\n self._tcond_ig = value\n else:\n raise TypeError(\"tcond_ig must be an instance of Corel.\")\n\n @property\n def sigma(self):\n \"\"\"float : Surface tension, unit TBD.\"\"\"\n return self._sigma\n\n @sigma.setter\n def sigma(self, value):\n if isinstance(value, Corel) or value is None:\n self._sigma = value\n else:\n raise TypeError(\"sigma must be an instance of Corel.\")\n\n def k_wilson(self, p=None, t=None):\n \"\"\"Wilson's equilibrium ratio (Ki = yi / xi).\n\n Parameters\n ----------\n p : float\n Pressure, Pa.\n t : float\n Temperature, K.\n\n Returns\n -------\n float\n Wilson's K-factor.\n \"\"\"\n if isinstance(p, float) and isinstance(t, float) and p > 0.0 and t > 0.0:\n return (self._pc / p) * np.exp(5.37 * (1.0 + self._acentric) * (1.0 - self._tc / t))\n else:\n raise RuntimeError(\"p and t must both be positive floats.\")\n\n def melting_curve(self, t=None):\n \"\"\"Melting curve for a pure solid.\n\n Melting pressure can be estimated with the Clausius-Clapeyron equation. A very simple approach assumes that\n changes in the enthalpy of fusion, liquid molar volume, and solid molar volume are negligible over the\n temperature range of interest. With these assumptions, the equation of the melting curve is as follows:\n\n dp/dt = delta_h / (t * delta_v)\n\n p - p0 = (delta_h / delta_v) * ln(t / t0)\n\n Variation of the enthalpy of fusion with temperature is related to differences in heat capacity between phases.\n\n ddelta_h/dt = dh_l/dt - dh_s/dt = cp_l - cp_s = detla_cp\n\n delta_h = integral_from_t0_to_t(delta_cp * dt) + delta_h0\n\n Temperature dependence of the heat capacity difference is usually weak and can be neglected.\n\n delta_h = delta_cp * (t - t0) + delta_h0\n\n Liquid and solid heat capacities can be evaluated at the melting temperature. These values are be derived from\n cp_l(t) and cp_s(t) correlations OR it can be entered as a constant (a useful adjustable parameter for\n correlating melting curves, sublimation curves, and solubility. The equation of the melting curve is as follows:\n\n p - p0 = (delta_cp / delta_v) * (t - t0) + ((delta_h - t0 * delta_cp) / delta_v) * ln(t / t0)\n\n Parameters\n ----------\n t : float\n Temperature specification, K.\n\n Returns\n -------\n float\n Melting pressure, Pa.\n\n References\n ----------\n [1] Tosun, I. The thermodynamics of phase and reaction equilibria, 1st ed., Elsevier: Amsterdam, 2013.\n [2] Poling, B. E.; Praunitz, J. M.; O'Connell, J. P. The properties of gases and liquids, 5th ed.,\n McGraw-Hill, 2000.\n [3] Pappa, G. D.; Voutsas, E. C.; Magoulas, K.; Tassios, D. P. Estimation of the differential molar heat\n capacities of organic compounds at their melting point. Ind. Eng. Chem. Res. 2005, 44, 3799–3806.\n \"\"\"\n if isinstance(t, float) and t > 0.0:\n if self._hfus and self._mp and self._den_l and self._den_s:\n p0 = 101325.0\n t0 = self._mp\n tavg = (t + t0) / 2.0\n v_l = 1.0 / self._den_l(tavg)\n v_s = 1.0 / self._den_s(tavg)\n delta_v = v_l - v_s\n if self._cp_l and self._cp_s:\n delta_cp = self._cp_l(tavg) - self._cp_s(tavg)\n return p0 + (delta_cp/delta_v) * (t - t0) + ((self._hfus - t0 * delta_cp)/delta_v) * np.log(t/t0)\n else:\n return p0 + (self._hfus/delta_v) * np.log(t/t0)\n else:\n raise RuntimeError(\"Enthalpy of fusion at melting point, liquid density, and solid density required.\")\n else:\n raise RuntimeError(\"t must be a positive float.\")\n\n def sublimation_curve(self):\n \"\"\"Sublimation curve for a pure solid.\n\n Sublimation pressure can be estimated with the Clausius-Clapeyron equation. A very simple approach assumes that\n changes in the enthalpy of sublimation and solid molar volume are negligible over the temperature range of\n interest. With these assumptions, the equation of the melting curve is as follows:\n\n dp/dt = delta_h / (t * delta_v)\n\n delta_h_sub = delta_h_vap + delta_h_fusion\n\n delta_v = v_v - v_s ~ v_v = R*t/p_sub\n\n p - p0 = (delta_h / delta_v) * ln(t / t0)\n\n Parameters\n ----------\n t : float\n Temperature specification, K.\n\n Returns\n -------\n float\n Sublimation pressure, Pa.\n\n References\n ----------\n [1] Tosun, I. The thermodynamics of phase and reaction equilibria, 1st ed., Elsevier: Amsterdam, 2013.\n [2] Poling, B. E.; Praunitz, J. M.; O'Connell, J. P. The properties of gases and liquids, 5th ed.,\n McGraw-Hill, 2000.\n [3] Pappa, G. D.; Voutsas, E. C.; Magoulas, K.; Tassios, D. P. Estimation of the differential molar heat\n capacities of organic compounds at their melting point. Ind. Eng. Chem. Res. 2005, 44, 3799–3806.\n \"\"\"\n return\n\n def density(self, t=None, p=None, phase='l', spec='molar'):\n \"\"\"Pure component liquid and/or solid density estimation.\n\n This function evaluates liquid or solid densities at pressures deviating from the vapor pressure curve or\n melting curve. The first step is calculating an initial density along the vapor pressure curve or melting curve.\n The next step is to correct for pressure with the isothermal compressibility:\n\n rho = rho_0 * exp(beta * (p - p_0))\n\n In this expression, rho_0 and p_0 are the saturation or melting density. If pressure is not specified, then the\n saturated liquid or melting point solid density is returned. IF\n\n Parameters\n ----------\n p : float\n Pressure, Pa.\n t : float\n Temperature, K.\n spec : str\n Phase specification (either 'mass' or 'molar').\n\n Returns\n -------\n float or None\n Density of saturated liquid or melting point solid. None returned if 't' is outside correlation temp limits.\n float or None\n Density of solid phase at temperature 't' (None if no solid density correlation available).\n str\n Unit ('kg/m3' or 'mol/m3').\n \"\"\"\n if not isinstance(p, (float, None)):\n raise TypeError(\"p must be None or a positive float.\")\n elif not isinstance(t, float) and p > 0.0:\n raise TypeError(\"t must be a positive float.\")\n elif phase not in ['l', 's']:\n raise ValueError(\"phase must be either 'l' or 's'.\")\n elif spec not in ['mass', 'molar']:\n raise ValueError(\"spec must be either 'molar' or 'mass'.\")\n else:\n if self._beta_l and p:\n p_corr_l = np.exp(self._beta_l(t) * ())\n else:\n beta_l = 0.0\n\n if self._beta_s:\n beta_s = self._beta_s(t)\n else:\n beta_s = 0.0\n\n if self._den_l and not self._den_s:\n # Liquid density correlation exists, solid density correlation does not.\n if spec == 'molar':\n if self._den_l.unit == 'kg/m3':\n return self._den_l(t) * 1000.0 / self._mw\n elif self._den_l.unit == 'mol/m3':\n return self._den_l(t)\n else:\n raise RuntimeError(\"liquid density correlation does not have a valid unit.\")\n elif spec == 'mass':\n return\n else:\n raise ValueError(\"spec is not valid.\")\n elif not self._den_l and self._den_s:\n # Liquid density correlation does not exist, solid density correlation exists.\n if spec == 'molar':\n return\n elif spec == 'mass':\n return\n else:\n raise ValueError(\"spec is not valid.\")\n elif self._den_l and self._den_s:\n # Liquid density and solid density correlations exist.\n if spec == 'molar':\n return\n elif spec == 'mass':\n return\n else:\n raise ValueError(\"spec is not valid.\")\n else:\n raise RuntimeError(\"liquid and solid density correlations not loaded for Comp.\")\n\n # TODO: Improve interface by making these checks part of getter/setter methods?\n def _check_assoc_sites(self):\n # Check to ensure there are no duplicate association sites.\n if self.assoc_sites is not None:\n if not isinstance(self.assoc_sites, (list, tuple)):\n raise TypeError(\"Comp objects must be a list of unique assoc_site objects.\")\n elif len(self.assoc_sites) != len(set(self.assoc_sites)):\n raise ValueError(\"Comp objects must be a list of unique assoc_site objects.\")\n else:\n pass\n\n def _check_assoc_parameters(self):\n # Check to ensure association parameter are lists of AssocSiteInter objects.\n if self.assoc_sites is not None:\n if self.cpa_assoc is not None:\n for asi in self.cpa_assoc:\n if not isinstance(asi, AssocSiteInter):\n raise TypeError(\"Association parameter lists must contain AssocSiteInter objects.\")\n\n def __eq__(self, other):\n if isinstance(other, Comp):\n name_eq = self.name == other.name\n return name_eq\n return False\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __hash__(self):\n return hash(self.name)\n\n def __str__(self):\n return \"Name: {}, CAS No.: {}\".format(self.name, self.cas_no)\n\n\nclass PseudoComp(object):\n \"\"\"A pseudo-component (polymer, distillation cut, asphaltene, etc.).\n\n Notes\n -----\n # TODO: Improve agreement bewteeen Comp and PseudoComp classes. Currently a skeleton implementation.\n # TODO: Add Riazi correlations to estimate Tc, Pc, Vc, Rhoc from mw, sg, NBP.\n \"\"\"\n\n def __init__(self, name):\n \"\"\"\n Parameters\n ----------\n name : str\n \"\"\"\n # General Attributes\n self.name = name\n self.mw = None\n self.sg = None\n self.nbp = None\n self.acentric = None\n self.tc = None\n self.pc = None\n self.vc = None\n self.rhoc = None\n\n # EOS Physical Attributes\n self.srk_phys = None\n self.pr_phys = None\n self.gpr_phys = None\n self.cpa_phys = None\n self.spc_saft_phys = None\n\n # EOS Association Attributes\n self.assoc_sites = None\n self.cpa_assoc = None\n self.spc_saft_assoc = None\n\n @property\n def name(self):\n \"\"\"str : Name of pseudo-component.\n\n Value can only be set whe creating a new Comp instance.\n \"\"\"\n return self._name\n\n @name.setter\n def name(self, value):\n try:\n self._name\n except AttributeError:\n self._name = value\n\n def __eq__(self, other):\n if isinstance(other, PseudoComp):\n name_eq = self.name == other.name\n return name_eq\n return False\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __hash__(self):\n return hash(self.name)\n\n def __str__(self):\n return \"Name: {}, MW: {}, SG: {}, NBP: {}\".format(self.name, self.mw, self.sg, self.nbp)\n\n\nclass CompSet(object):\n \"\"\"Set of components or pseudo-components.\n\n Notes\n -----\n \"\"\"\n def __init__(self, comps=None):\n \"\"\"\n Parameters\n ----------\n comps : list or tuple of Comp objects\n \"\"\"\n if comps is None:\n raise ValueError(\"comps must be provided to create an instance of CompSet.\")\n else:\n self.comps = comps\n\n @property\n def comps(self):\n \"\"\"list or tuple of Comp objects : A collection of Comp objects.\n\n Values can only be set whe creating a new CompSet instance.\n \"\"\"\n return self._comps\n\n @comps.setter\n def comps(self, value):\n try:\n self._comps\n except AttributeError:\n if isinstance(value, (list, tuple)):\n if len(value) == 0:\n raise ValueError(\"comps must contain at least one Comp object.\")\n elif len(value) != len(set(value)):\n raise ValueError(\"comps cannot contain duplicate Comp objects.\")\n elif all(isinstance(item, (Comp, PseudoComp)) for item in value):\n self._comps = value\n else:\n raise TypeError(\"comps must contain only Comp or PseudoComp objects.\")\n else:\n raise TypeError(\"comps must be a list or tuple.\")\n\n @property\n def size(self):\n \"\"\"int : The number of Comp or PseudoComp objects in 'comps'.\"\"\"\n return len(self._comps)\n\n @property\n def can_associate(self):\n \"\"\"list of bool : Boolean indicating if Comp or PseudoComp objects in 'comps' can associate.\"\"\"\n result = []\n for comp in self._comps:\n if comp.assoc_sites is not None:\n result.append(True)\n else:\n result.append(False)\n return result\n\n @property\n def mw(self):\n \"\"\"list of float or None : Molecular weight for each Comp or PseudoComp objects in 'comps'.\n\n Returns None if any Comp or PseudoComp object is missing molecular weight.\"\"\"\n result = []\n for comp in self._comps:\n if comp.mw is None:\n return None\n else:\n result.append(comp.mw)\n return np.array(result)\n\n def __eq__(self, other):\n if isinstance(other, CompSet):\n return self.comps == other.comps\n return False\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __hash__(self):\n return hash(self._comps)\n\n def __str__(self):\n result = []\n for comp in self._comps:\n result.append(comp.name)\n return \",\".join(tuple(result))\n", "meta": {"hexsha": "74c6585d8159ae16d96d53fbdac3fb854bccde83", "size": 31903, "ext": "py", "lang": "Python", "max_stars_repo_path": "phaseprop/comps.py", "max_stars_repo_name": "theleftcoast/phaseprop", "max_stars_repo_head_hexsha": "05effbbb9700ba32ca1bbf5c61120531df6f98dd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "phaseprop/comps.py", "max_issues_repo_name": "theleftcoast/phaseprop", "max_issues_repo_head_hexsha": "05effbbb9700ba32ca1bbf5c61120531df6f98dd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phaseprop/comps.py", "max_forks_repo_name": "theleftcoast/phaseprop", "max_forks_repo_head_hexsha": "05effbbb9700ba32ca1bbf5c61120531df6f98dd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1278952669, "max_line_length": 120, "alphanum_fraction": 0.567689559, "include": true, "reason": "import numpy", "num_tokens": 7802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2751297357103299, "lm_q1q2_score": 0.13971414400970744}} {"text": "##############################################################################\n#\n# File format versions:\n#\n# 1: initial version\n#\n# 2: now contains reciprocal planck opacity and rosseland opacity\n# previous rosseland opacity was actually reciprocal planck opacity\n#\n##############################################################################\n\nfrom __future__ import print_function, division\n\nimport os\nimport hashlib\n\nimport h5py\nimport numpy as np\nfrom astropy import log as logger\nimport six\n\nfrom ..version import __version__\n\nfrom ..util.constants import c\nfrom ..util.functions import FreezableClass\nfrom ..util.interpolate import interp1d_fast_loglog\nfrom ..util.integrate import integrate_loglog\nfrom ..util.nans import check_for_nans\n\nfrom .optical_properties import OpticalProperties\nfrom .emissivities import Emissivities\nfrom .mean_opacities import MeanOpacities\n\n\ndef henyey_greenstein(mu, g, p_lin_max):\n P1 = (1. - g * g) / (1. + g * g - 2. * g * mu) ** 1.5\n P2 = - p_lin_max * P1 * (1. - mu * mu) / (1. + mu * mu)\n P3 = P1 * 2. * mu / (1. + mu * mu)\n P4 = 0.\n return P1, P2, P3, P4\n\n\nclass SphericalDust(FreezableClass):\n r\"\"\"\n This class should be used in cases where fully arbitrary dust properties\n need to be specified, within the framework of randomly oriented grains,\n which means that the scattering phase function has the general form:\n\n .. math:: R(\\theta) = \\left[\\begin{array}{cccc}P_1 & P_2 & 0 & 0 \\\\P_2 & P_1 & 0 & 0 \\\\0 & 0 & P_3 & -P_4 \\\\0 & 0 & P_4 & P_3\\end{array}\\right]\n\n This class is initialized with::\n\n d = SphericalDust()\n\n and the properties should then be set manually. See\n `here `_\n for a description of the available properties and how to set them.\n \"\"\"\n\n def __init__(self, *args):\n\n self._file = None\n self.md5 = None\n\n self.optical_properties = OpticalProperties()\n self.mean_opacities = MeanOpacities()\n self.emissivities = Emissivities()\n\n self.set_sublimation_specific_energy('no', 0.)\n\n self._freeze()\n\n if len(args) == 0:\n pass\n elif len(args) == 1:\n self.read(args[0])\n else:\n raise Exception(\"SphericalDust cannot take more than one argument\")\n\n def hash(self):\n\n h = hashlib.md5()\n\n if self.optical_properties is None or not self.optical_properties.all_set():\n h.update('none'.encode('utf-8'))\n else:\n h.update(self.optical_properties.hash().encode('utf-8'))\n\n if self.emissivities is None or not self.emissivities.all_set():\n h.update('none'.encode('utf-8'))\n else:\n h.update(self.emissivities.hash().encode('utf-8'))\n\n if self.mean_opacities is None or not self.mean_opacities.all_set():\n h.update('none'.encode('utf-8'))\n else:\n h.update(self.mean_opacities.hash().encode('utf-8'))\n\n import struct\n h.update(self.sublimation_mode.encode('utf-8'))\n h.update(struct.pack('>d', self.sublimation_energy))\n\n return h.hexdigest()\n\n def set_lte_emissivities(self, n_temp=1200, temp_min=0.1, temp_max=100000.):\n '''\n Calculate the emissivities assuming LTE\n\n Parameters\n ----------\n n_temp : int, optional\n The number of temperatures to calculate the emissivities for\n temp_min : float, optional\n The minimum temperature to calculate the emissivities for\n temp_max : float, optional\n The maximum temperature to calculate the emissivities for\n '''\n self.mean_opacities.compute(self.optical_properties, n_temp=n_temp,\n temp_min=temp_min, temp_max=temp_max)\n self.emissivities.set_lte(self.optical_properties, self.mean_opacities)\n\n def plot(self, filename):\n\n # Check that the optical properties have been set\n self.optical_properties.ensure_all_set()\n\n import matplotlib.pyplot as plt\n\n # Save original rc parameters\n rc_orig = plt.rcParams\n\n # Reset to defaults\n plt.rcdefaults()\n plt.rc('legend', fontsize=7)\n plt.rc('axes', titlesize='x-small')\n plt.rc('axes', labelsize='x-small')\n plt.rc('xtick', labelsize='xx-small')\n plt.rc('ytick', labelsize='xx-small')\n plt.rc('axes', linewidth=0.5)\n plt.rc('patch', linewidth=0.5)\n\n # Compute mean opacities if not already existent\n self._compute_mean_opacities()\n\n # Check that emissivities are set (before computing mean opacities)\n if not self.emissivities.all_set():\n logger.info(\"Computing emissivities assuming LTE\")\n self.emissivities.set_lte(self.optical_properties, self.mean_opacities)\n\n # Initialize figure\n fig = plt.figure(figsize=(10, 12))\n\n # Plot optical properties\n fig = self.optical_properties.plot(fig, [421, 423, 424, 425, 426])\n\n # Plot mean opacities\n fig = self.mean_opacities.plot(fig, 428)\n\n # Plot emissivities\n fig = self.emissivities.plot(fig, 427)\n\n # Adjust spacing between subplots\n fig.subplots_adjust(left=0.08, right=0.92, wspace=0.22, hspace=0.30)\n\n # Save figure\n fig.savefig(filename, bbox_inches='tight')\n\n # Close figure to save RAM\n plt.close(fig)\n\n # Restore rc parameters\n plt.rc(rc_orig)\n\n def set_sublimation_temperature(self, mode, temperature=0.):\n '''\n Set the dust sublimation mode and temperature.\n\n Parameters\n ----------\n mode : str\n The dust sublimation mode, which can be:\n * 'no' - no sublimation\n * 'fast' - remove all dust in cells exceeding the\n sublimation temperature\n * 'slow' - reduce the dust in cells exceeding the\n sublimation temperature\n * 'cap' - any temperature exceeding the sublimation\n temperature is reset to the sublimation\n temperature.\n\n temperature : float, optional\n The dust sublimation temperature, in K\n '''\n\n if mode not in ['no', 'fast', 'slow', 'cap']:\n raise Exception(\"mode should be one of no/fast/slow/cap\")\n\n if mode != 'no' and temperature is None:\n raise Exception(\"Need to specify a sublimation temperature\")\n\n self.sublimation_mode = mode\n self.sublimation_energy = self.temperature2specific_energy(temperature)\n\n def set_sublimation_specific_energy(self, mode, specific_energy=0.):\n '''\n Set the dust sublimation mode and specific energy.\n\n Parameters\n ----------\n mode : str\n The dust sublimation mode, which can be:\n * 'no' - no sublimation\n * 'fast' - remove all dust in cells exceeding the\n sublimation specific energy\n * 'slow' - reduce the dust in cells exceeding the\n sublimation specific energy\n * 'cap' - any specific energy exceeding the sublimation\n specific energy is reset to the sublimation\n specific energy.\n\n specific_energy : float, optional\n The dust sublimation specific energy, in cgs\n '''\n\n if mode not in ['no', 'fast', 'slow', 'cap']:\n raise Exception(\"mode should be one of no/fast/slow/cap\")\n\n if mode != 'no' and specific_energy is None:\n raise Exception(\"Need to specify a sublimation specific_energy\")\n\n self.sublimation_mode = mode\n self.sublimation_energy = specific_energy\n\n def _write_dust_sublimation(self, group):\n group.attrs['sublimation_mode'] = np.string_(self.sublimation_mode)\n if self.sublimation_mode in ['slow', 'fast', 'cap']:\n group.attrs['sublimation_specific_energy'] = self.sublimation_energy\n\n def _read_dust_sublimation(self, group):\n if 'sublimation_mode' in group.attrs:\n self.sublimation_mode = group.attrs['sublimation_mode'].decode('ascii')\n if self.sublimation_mode in ['slow', 'fast', 'cap']:\n self.sublimation_energy = group.attrs['sublimation_specific_energy']\n\n def _compute_mean_opacities(self):\n if not self.mean_opacities.all_set():\n self.mean_opacities.compute(self.optical_properties)\n\n def write(self, filename, compression=True):\n '''\n Write out to a standard dust file, including calculations of the mean\n opacities and optionally thermal emissivities.\n '''\n\n # Check that the optical properties have been set\n self.optical_properties.ensure_all_set()\n\n # Compute mean opacities if not already existent\n self._compute_mean_opacities()\n\n # Check that emissivities are set (before computing mean opacities)\n if not self.emissivities.all_set():\n logger.info(\"Computing emissivities assuming LTE\")\n self.emissivities.set_lte(self.optical_properties, self.mean_opacities)\n\n # Create dust table set\n if isinstance(filename, six.string_types):\n dt = h5py.File(filename, 'w')\n else:\n dt = filename\n\n # Add standard keywords to header\n dt.attrs['version'] = 2\n dt.attrs['type'] = 1\n dt.attrs['python_version'] = np.string_(__version__)\n if self.md5:\n dt.attrs['asciimd5'] = np.string_(self.md5)\n\n # Add optical properties and scattering angle tables\n self.optical_properties.to_hdf5_group(dt)\n\n # Add mean opacities table\n self.mean_opacities.to_hdf5_group(dt)\n\n # Add emissivities and emissivity variable tables\n self.emissivities.to_hdf5_group(dt)\n\n # Dust sublimation parameters\n self._write_dust_sublimation(dt)\n\n # Check that there are no NaN values in the file - if there are, a\n # warning is emitted.\n check_for_nans(dt)\n\n # Close dust file\n if isinstance(dt, h5py.File):\n dt.close()\n\n self._file = (filename, self.hash())\n\n def read(self, filename):\n '''\n Read in from a standard dust file\n '''\n\n from ..util.functions import asstr\n\n if isinstance(filename, six.string_types):\n\n # Check file exists\n if not os.path.exists(filename):\n raise Exception(\"File not found: %s\" % filename)\n\n # Read in dust table set\n dt = h5py.File(filename, 'r')\n close = True\n\n else:\n\n # Read in dust table set\n dt = filename\n close = False\n\n # Check version and type\n if dt.attrs['version'] not in [1, 2]:\n raise Exception(\"Version should be 1 or 2\")\n if dt.attrs['type'] != 1:\n raise Exception(\"Type should be 1\")\n if 'asciimd5' in dt.attrs:\n self.md5 = asstr(dt.attrs['asciimd5'])\n else:\n self.md5 = None\n\n # Read in the optical properties\n self.optical_properties.from_hdf5_group(dt)\n\n # Read in the planck and rosseland mean opacities\n if dt.attrs['version'] == 1:\n logger.warning(\"Version 1 dust file detected - discarding mean opacities and recomputing them\")\n self.mean_opacities.compute(self.optical_properties)\n else:\n self.mean_opacities.from_hdf5_group(dt)\n\n # Read in emissivities\n self.emissivities.from_hdf5_group(dt)\n\n # Dust sublimation parameters\n self._read_dust_sublimation(dt)\n\n # Close file object if needed\n if close:\n dt.close()\n self._file = (filename, self.hash())\n\n def chi_nu_temperature(self, temperature):\n \"\"\"\n Compute the mean opacity to extinction for a blackbody at a given temperature.\n\n Parameters\n ----------\n temperature : float\n The temperature of the blackbody to use\n\n Returns\n -------\n chi_nu_mean : float\n The mean opacity to extinction\n \"\"\"\n self._compute_mean_opacities()\n return interp1d_fast_loglog(self.mean_opacities.temperature,\n self.mean_opacities.chi_planck,\n temperature,\n bounds_error=True)\n\n def kappa_nu_temperature(self, temperature):\n \"\"\"\n Compute the mean opacity to absorption for a blackbody at a given temperature.\n\n Parameters\n ----------\n temperature : float\n The temperature of the blackbody to use\n\n Returns\n -------\n kappa_nu_mean : float\n The mean opacity to absorption\n \"\"\"\n self._compute_mean_opacities()\n return interp1d_fast_loglog(self.mean_opacities.temperature,\n self.mean_opacities.kappa_planck,\n temperature,\n bounds_error=True)\n\n def chi_nu_spectrum(self, nu, fnu):\n \"\"\"\n Compute the mean opacity to extinction for a given spectrum.\n\n Parameters\n ----------\n nu : array_like\n The frequencies, in Hz\n fnu : array_like\n The monochromatic fluxes per unit frequency. Units are unimportant\n since proportionality constants are cancelled out in the\n computation.\n\n Returns\n -------\n chi_nu_mean : float\n The mean opacity to extinction\n \"\"\"\n if nu.max() > self.optical_properties.nu.max() or nu.min() < self.optical_properties.nu.min():\n raise Exception(\"Opacity to extinction is not defined at all \"\n \"spectrum frequencies\")\n chi_nu = self.optical_properties.interp_chi_nu(nu)\n return (integrate_loglog(nu, fnu * chi_nu) /\n integrate_loglog(nu, fnu))\n\n def kappa_nu_spectrum(self, nu, fnu):\n \"\"\"\n Compute the mean opacity to absorption for a given spectrum.\n\n Parameters\n ----------\n nu : array_like\n The frequencies, in Hz\n fnu : array_like\n The monochromatic fluxes per unit frequency. Units are unimportant\n since proportionality constants are cancelled out in the\n computation.\n\n Returns\n -------\n kappa_nu_mean : float\n The mean opacity to absorption\n \"\"\"\n if nu.max() > self.optical_properties.nu.max() or nu.min() < self.optical_properties.nu.min():\n raise Exception(\"Opacity to absorption is not defined at all \"\n \"spectrum frequencies\")\n kappa_nu = self.optical_properties.interp_kappa_nu(nu)\n return (integrate_loglog(nu, fnu * kappa_nu) /\n integrate_loglog(nu, fnu))\n\n def temperature2specific_energy(self, temperature):\n \"\"\"\n Convert a temperature to its corresponding specific energy value.\n\n Parameters\n ----------\n temperature : float or array_like\n The temperature to convert\n\n Returns\n -------\n specific_energy : float or array_like\n The specific energy corresponding to the input temperature\n \"\"\"\n\n self._compute_mean_opacities()\n\n specific_energy = interp1d_fast_loglog(self.mean_opacities.temperature,\n self.mean_opacities.specific_energy,\n temperature,\n bounds_error=False,\n fill_value=np.nan)\n\n if np.isscalar(temperature):\n if temperature < self.mean_opacities.temperature[0]:\n specific_energy = self.mean_opacities.specific_energy[0]\n elif temperature > self.mean_opacities.temperature[-1]:\n specific_energy = self.mean_opacities.specific_energy[-1]\n else:\n specific_energy[temperature < self.mean_opacities.temperature[0]] = self.mean_opacities.specific_energy[0]\n specific_energy[temperature > self.mean_opacities.temperature[-1]] = self.mean_opacities.specific_energy[-1]\n\n return specific_energy\n\n def specific_energy2temperature(self, specific_energy):\n \"\"\"\n Convert a specific energy value to its corresponding temperature.\n\n Parameters\n ----------\n specific_energy : float or array_like\n The specific energy to convert\n\n Returns\n -------\n temperature : float or array_like\n The temperature corresponding to the input specific energy\n \"\"\"\n\n self._compute_mean_opacities()\n\n temperature = interp1d_fast_loglog(self.mean_opacities.specific_energy,\n self.mean_opacities.temperature,\n specific_energy,\n bounds_error=False,\n fill_value=np.nan)\n\n if np.isscalar(specific_energy):\n if specific_energy < self.mean_opacities.specific_energy[0]:\n temperature = self.mean_opacities.temperature[0]\n elif specific_energy > self.mean_opacities.specific_energy[-1]:\n temperature = self.mean_opacities.temperature[-1]\n else:\n temperature[specific_energy < self.mean_opacities.specific_energy[0]] = self.mean_opacities.temperature[0]\n temperature[specific_energy > self.mean_opacities.specific_energy[-1]] = self.mean_opacities.temperature[-1]\n\n return temperature\n\n\nclass IsotropicDust(SphericalDust):\n \"\"\"\n This class should be used for dust properties that include isotropic\n scattering. The dust properties should be instatiated as::\n\n d = IsotropicDust(nu, albedo, chi)\n\n where ``nu``, ``albedo``, and ``chi`` are 1-D Numpy arrays containing the\n frequencies, albedo, and opacity to extinction respectively.\n \"\"\"\n\n def __init__(self, nu, albedo, chi):\n\n SphericalDust.__init__(self)\n\n # Set cos(theta) grid for computing the scattering matrix elements\n self.optical_properties.mu = np.linspace(-1., 1., 2)\n\n # Set optical properties\n self.optical_properties.nu = nu\n self.optical_properties.albedo = albedo\n self.optical_properties.chi = chi\n\n # Compute scattering matrix elements\n self.optical_properties.initialize_scattering_matrix()\n\n # Set scattering matrix to isotropic values\n self.optical_properties.P1[:, :] = 1.\n self.optical_properties.P2[:, :] = 0.\n self.optical_properties.P3[:, :] = 1.\n self.optical_properties.P4[:, :] = 0.\n\n # Sort optical properties\n self.optical_properties._sort()\n\n\nclass HenyeyGreensteinDust(SphericalDust):\n \"\"\"\n This class should be used for dust properties that include\n scattering parameterized by the `Henyey-Greenstein, 1941\n `_ function. The dust properties should\n be instatiated as::\n\n d = HenyeyGreensteinDust(nu, albedo, chi, g, p_lin_max)\n\n where ``nu``, ``albedo``, and ``chi`` are 1-D Numpy arrays containing the\n frequencies, albedo, and opacity to extinction respectively, and ``g`` and\n ``p_lin_max`` are also 1-D Numpy arrays containing the asymmetry parameter\n and the maximum linear polarization.\n \"\"\"\n\n def __init__(self, nu, albedo, chi, g, p_lin_max):\n\n SphericalDust.__init__(self)\n\n # Set cos(theta) grid for computing the scattering matrix elements\n n_mu = 100\n self.optical_properties.mu = np.linspace(-1., 1., n_mu)\n\n # Set optical properties\n self.optical_properties.nu = nu\n self.optical_properties.albedo = albedo\n self.optical_properties.chi = chi\n\n # Compute scattering matrix elements\n self.optical_properties.initialize_scattering_matrix()\n\n for i in range(n_mu):\n self.optical_properties.P1[:, i], \\\n self.optical_properties.P2[:, i], \\\n self.optical_properties.P3[:, i], \\\n self.optical_properties.P4[:, i] = henyey_greenstein(self.optical_properties.mu[i], g, p_lin_max)\n\n\nclass HOCHUNKDust(HenyeyGreensteinDust):\n \"\"\"\n This class should be used for dust properties that include\n scattering parameterized by the `Henyey-Greenstein, 1941\n `_ function, which are formatted for the\n `HOCHUNK code `_. The dust\n properties should be instatiated as::\n\n d = HOCHUNKDust(filename)\n\n where ``filename`` is the name of the file containing the dust properties\n in the HOCHUNK format.\n \"\"\"\n\n def __init__(self, filename):\n\n # Read in dust file\n dustfile = np.loadtxt(filename, dtype=[('wav', float), ('c_ext', float),\n ('c_sca', float), ('chi', float), ('g', float),\n ('p_lin_max', float)], usecols=[0, 1, 2, 3, 4, 5])\n\n # Ensure file is ordered in increasing frequency\n if dustfile['wav'][-1] > dustfile['wav'][0]:\n dustfile = dustfile[::-1]\n\n # Compute frequency and albedo\n nu = c / dustfile['wav'] * 1.e4\n albedo = dustfile['c_sca'] / dustfile['c_ext']\n\n self.md5 = hashlib.md5(open(filename, 'rb').read()).hexdigest()\n\n HenyeyGreensteinDust.__init__(self, nu, albedo, dustfile['chi'], dustfile['g'], dustfile['p_lin_max'])\n\nTTsreDust = HOCHUNKDust\n\n\nclass CoatsphSingle(SphericalDust):\n\n def __init__(self, directory, size, density):\n '''\n Initialize single-component dust.\n\n Parameters\n ----------\n directory : str\n Directory containing all the files describing the dust\n size : float\n Grain size, in cm\n density : float\n Dust grain density, in g/cm^3\n '''\n\n SphericalDust.__init__(self)\n\n f = open('%s/coatsph_forw.dat' % directory, 'rb')\n version = f.readline()\n n_components = int(f.readline().strip().split()[5])\n\n # Read in main dust file\n\n dustfile = np.loadtxt(f, skiprows=3,\n dtype=[('x', float), ('radius', float), ('wav', float),\n ('q_ext', float), ('q_sca', float), ('q_back', float),\n ('g', float)])\n\n n_wav = len(dustfile)\n\n self.optical_properties.nu = c / dustfile['wav'] * 1.e4\n self.optical_properties.albedo = dustfile['q_sca'] / dustfile['q_ext']\n self.optical_properties.chi = 0.75 * dustfile['q_ext'] / size / density\n\n # Read in scattering matrix elements\n\n for i in range(n_wav):\n\n filename = '%s/coatsph_scat_%04i_0001.dat' % (directory, i + 1)\n\n phasefile = np.loadtxt(filename, skiprows=9,\n dtype=[('theta', float), ('s11', float), ('polariz',\n float), ('s12', float), ('s33', float), ('s34',\n float)])\n\n if i == 0:\n self.optical_properties.mu = np.cos(np.radians(phasefile['theta']))\n self.optical_properties.initialize_scattering_matrix()\n\n self.optical_properties.P1[i, :] = phasefile['s11']\n self.optical_properties.P2[i, :] = phasefile['s12']\n self.optical_properties.P3[i, :] = phasefile['s33']\n self.optical_properties.P4[i, :] = phasefile['s34']\n\n\nclass CoatsphMultiple(SphericalDust):\n\n def __init__(self, directory):\n '''\n Initialize multi-component dust.\n\n Parameters\n ----------\n directory : str\n Directory containing all the files describing the dust\n '''\n\n SphericalDust.__init__(self)\n\n f = open('%s/coatsph_forw.dat' % directory, 'rb')\n version = f.readline()\n n_components = int(f.readline().strip().split()[5])\n\n # Read in main dust file\n\n dustfile = np.loadtxt(f, skiprows=7,\n dtype=[('wav', float), ('c_ext', float), ('c_sca', float),\n ('chi', float), ('g', float), ('pmax', float),\n ('thetmax', float)])\n\n n_wav = len(dustfile)\n self.optical_properties.nu = c / dustfile['wav'] * 1.e4\n self.optical_properties.albedo = dustfile['c_sca'] / dustfile['c_ext']\n self.optical_properties.chi = dustfile['chi']\n\n # Read in scattering matrix elements\n\n for i in range(n_wav):\n\n filename = '%s/coatsph_scat.%04i.dat' % (directory, i + 1)\n\n phasefile = np.loadtxt(filename, skiprows=7,\n dtype=[('theta', float), ('s11', float), ('polariz',\n float), ('s12', float), ('s33', float), ('s34',\n float)])\n\n if i == 0:\n self.optical_properties.mu = np.cos(np.radians(phasefile['theta']))\n self.optical_properties.initialize_scattering_matrix()\n\n self.optical_properties.P1[i, :] = phasefile['s11']\n self.optical_properties.P2[i, :] = phasefile['s12']\n self.optical_properties.P3[i, :] = phasefile['s33']\n self.optical_properties.P4[i, :] = phasefile['s34']\n\n\nclass MieXDust(SphericalDust):\n\n def __init__(self, model):\n\n SphericalDust.__init__(self)\n\n wav = np.loadtxt('%s.alb' % model, usecols=[0])\n self.optical_properties.albedo = np.loadtxt('%s.alb' % model, usecols=[1])\n kappa = np.loadtxt('%s.k_abs' % model, usecols=[1])\n self.optical_properties.chi = kappa / (1 - self.optical_properties.albedo)\n\n # Check for NaN values\n for quantity in ['chi', 'albedo']:\n\n values = self.optical_properties.__dict__[quantity]\n\n if np.any(np.isnan(values)):\n logger.warning(\"NaN values found inside MieX %s file - interpolating\" % quantity)\n invalid = np.isnan(values)\n values[invalid] = interp1d_fast_loglog(wav[~invalid], values[~invalid], wav[invalid])\n if np.any(np.isnan(values)):\n raise Exception(\"Did not manage to fix NaN values in MieX %s\" % quantity)\n\n self.optical_properties.nu = c / wav * 1.e4\n\n n_wav = len(wav)\n n_mu = (len(open('%s.f11' % model).readlines()) // n_wav) - 1\n\n mu = np.zeros(n_mu)\n\n # Read mu\n f11 = open('%s.f11' % model)\n f11.readline()\n f11.readline()\n for i in range(n_mu):\n mu[i] = np.cos(np.radians(float(f11.readline().split()[0])))\n f11.close()\n self.optical_properties.mu = mu[::-1]\n\n # Read in matrix elements\n\n self.optical_properties.initialize_scattering_matrix()\n\n f11 = open('%s.f11' % model)\n f12 = open('%s.f12' % model)\n f33 = open('%s.f33' % model)\n f34 = open('%s.f34' % model)\n\n f11.readline()\n f12.readline()\n f33.readline()\n f34.readline()\n\n for j in range(n_wav):\n\n if float(f11.readline()) != wav[j]:\n raise Exception(\"Incorrect wavelength in f11\")\n if float(f12.readline()) != wav[j]:\n raise Exception(\"Incorrect wavelength in f12\")\n if float(f33.readline()) != wav[j]:\n raise Exception(\"Incorrect wavelength in f33\")\n if float(f34.readline()) != wav[j]:\n raise Exception(\"Incorrect wavelength in f34\")\n\n for i in range(n_mu):\n\n self.optical_properties.P1[j, n_mu - i - 1] = float(f11.readline().split()[1])\n self.optical_properties.P2[j, n_mu - i - 1] = float(f12.readline().split()[1])\n self.optical_properties.P3[j, n_mu - i - 1] = float(f33.readline().split()[1])\n self.optical_properties.P4[j, n_mu - i - 1] = float(f34.readline().split()[1])\n\n for i in range(n_mu):\n\n for quantity in ['P1', 'P2', 'P3', 'P4']:\n\n values = self.optical_properties.__dict__[quantity]\n\n if np.any(np.isnan(values[:, i])):\n logger.warning(\"NaN values found inside MieX %s file - interpolating\" % quantity)\n invalid = np.isnan(values[:, i])\n values[:, i][invalid] = interp1d_fast_loglog(wav[~invalid], values[:, i][~invalid], wav[invalid])\n if np.any(np.isnan(values[:, i])):\n raise Exception(\"Did not manage to fix NaN values in MieX %s\" % quantity)\n\n\nclass BHDust(SphericalDust):\n \"\"\"\n This class should be used for dust properties that were computed using\n `this dust calculation code `_ which\n is a wrapper to the ``bhmie`` routine originally written by C.F. Bohren and\n D. Huffman and improved by B. Draine.\n\n When using the ``bhmie`` code, you should set the output format to ``2``,\n which will create a number of files ending in ``.wav``, ``.mu``, ``.alb``,\n etc. Then, instantiate this class with the name of the directory containing\n these output files along with the prefix used. For example, if you use\n ``directory/mydust`` as a prefix in ``bhmie``, you can import this dust\n with::\n\n >>> from hyperion.dust import BHDust\n >>> d = BHDust('directory/mydust')\n\n \"\"\"\n\n def __init__(self, model):\n\n SphericalDust.__init__(self)\n\n mu = np.loadtxt('%s.mu' % model)\n\n nu = c / np.loadtxt('%s.wav' % model) * 1.e4\n albedo = np.loadtxt('%s.alb' % model)\n chi = np.loadtxt('%s.chi' % model)\n\n P1 = np.loadtxt('%s.f11' % model)\n P2 = np.loadtxt('%s.f12' % model)\n P3 = np.loadtxt('%s.f33' % model)\n P4 = np.loadtxt('%s.f34' % model)\n\n if nu[-1] < nu[0]:\n nu = nu[::-1]\n albedo = albedo[::-1]\n chi = chi[::-1]\n P1 = P1[::-1, :]\n P2 = P2[::-1, :]\n P3 = P3[::-1, :]\n P4 = P4[::-1, :]\n\n if mu[-1] < mu[0]:\n mu = mu[::-1]\n P1 = P1[:, ::-1]\n P2 = P2[:, ::-1]\n P3 = P3[:, ::-1]\n P4 = P4[:, ::-1]\n\n self.optical_properties.mu = mu\n\n self.optical_properties.nu = nu\n self.optical_properties.albedo = albedo\n self.optical_properties.chi = chi\n\n self.optical_properties.P1 = P1\n self.optical_properties.P2 = P2\n self.optical_properties.P3 = P3\n self.optical_properties.P4 = P4\n", "meta": {"hexsha": "4286ac46a4607854cf9d80230831f041f134e192", "size": 31342, "ext": "py", "lang": "Python", "max_stars_repo_path": "hyperion/dust/dust_type.py", "max_stars_repo_name": "christopherlovell/hyperion", "max_stars_repo_head_hexsha": "f65c253abf0bdf174a9302666bc2fec57f7ae7da", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2015-01-29T20:58:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T23:36:39.000Z", "max_issues_repo_path": "hyperion/dust/dust_type.py", "max_issues_repo_name": "christopherlovell/hyperion", "max_issues_repo_head_hexsha": "f65c253abf0bdf174a9302666bc2fec57f7ae7da", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 83, "max_issues_repo_issues_event_min_datetime": "2015-01-07T11:04:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T16:26:33.000Z", "max_forks_repo_path": "hyperion/dust/dust_type.py", "max_forks_repo_name": "christopherlovell/hyperion", "max_forks_repo_head_hexsha": "f65c253abf0bdf174a9302666bc2fec57f7ae7da", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2015-04-21T13:17:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T02:42:20.000Z", "avg_line_length": 35.7785388128, "max_line_length": 147, "alphanum_fraction": 0.5762874099, "include": true, "reason": "import numpy,from astropy", "num_tokens": 7158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2751297238231752, "lm_q1q2_score": 0.13971413797326923}} {"text": "#!/usr/bin/python\n\n# Comments and/or additions are welcome (send e-mail to:\n# robert.paton@chem.ox.ac.uk\n\n#####################################\n# vib_scale_factors.py #\n#####################################\n### Written by: Rob Paton #########\n### Last modified: Mar 27, 2017 ###\n#####################################\n\nimport numpy as np\n\nimport sys\nif sys.version_info > (2, ):\n # Py3\n Str_char = \"U%d\"\nelse:\n # Py2\n Str_char = \"S%d\"\n\n'''\nFrequency scaling factors, taken from the beta 2 version of version 3 of The Trhular group database (https://t1.chem.umn.edu/freqscale/index.html\nI. M. Alecu, J. Zheng, Y. Zhao, and D. G. Truhlar, J. Chem. Theory Comput. 6, 2872-2887 (2010).\n\nThe array is ordered as:\n[level/basis set, zpe_fac, zpe_ref, zpe_meth, harm_fac, harm_ref, harm_meth, fund_fac, fund_ref, fund_meth]\nwhere zpe_fac, harm_fac and fund_fac are the scaling factors for ZPEs, harmonic frequencies, and fundamentals, respectively.\n\nThe ref and meth elements refer to original references and method of determinantion by the Truhlar group. All information taken from\nhttps://comp.chem.umn.edu/freqscale/version3b2.htm\n\nMethods\nD: The scale factor was directly obtained from the ZPVE15/10 or F38/10 databases given in Ref. 1.\nC: The scale factor was obtained by applying a small systematic correction of -0.0025 to preexisting scale factor. The references for the preexisting (uncorrected) scale factors are given in Supporting Information of Ref. 1 and in Version 1 of this database\nR: The scale factor was obtained via the Reduced Scale Factor Optimization Model described in Ref. 1. Briefly, this entails using the ZPE6 database for determining ZPE scale factors, and/or using the universal scale factor ratios of aF/ZPE = 0.974 and aH/ZPE = 1.014 to obtain the respective values for the scale factors for fundamental and harmonic frequencies.\n'''\nscaling_refs = np.array([(\"none\"), (\"I. M. Alecu, J. Zheng, Y. Zhao, and D. G. Truhlar, J. Chem. Theory Comput. 6, 2872-2887 (2010).\"),(\"Y. Zhao and D. G. Truhlar, unpublished (2003), modified by systematic correction of -0.0025 by I. M. Alecu (2010).\"), (\"I. M. Alecu, unpublished (2011).\"), (\"J. Zheng, R. J. Rocha, M. Pelegrini, L. F. A. Ferrao, E. F. V. Carvalho, O. Roberto-Neto, F. B. C. Machado, and D. G. Truhlar, J. Chem. Phys. 136, 184310/1-10 (2012).\"), (\"J. Zheng and D. G. Truhlar, unpublished (2014).\"), (\"J. Bao and D. G. Truhlar, unpublished (2014).\"), (\"H. Yu, J. Zheng, and D. G. Truhlar, unpublished (2015)\")])\n\nscaling_data = np.array([(\"AM1\" , 0.948 , 1 , \"R\" , 0.961 , 1 , \"R\" , 0.923 , 1 , \"R\" ),(\"B1B95/6-31+G(d,p)\" , 0.971 , 1 , \"C\" , 0.985 , 1 , \"R\" , 0.946 , 1 , \"R\" ),(\"B1B95/MG3S\" , 0.973 , 1 , \"C\" , 0.987 , 1 , \"R\" , 0.948 , 1 , \"R\" ),(\"B1LYP/MG3S\" , 0.978 , 1 , \"D\" , 0.994 , 1 , \"D\" , 0.955 , 1 , \"D\" ),(\"B3LYP/6-31G(2df,2p)\" , 0.981 , 1 , \"C\" , 0.995 , 1 , \"R\" , 0.955 , 1 , \"R\" ),(\"B3LYP/6-31G(d)\" , 0.977 , 1 , \"R\" , 0.991 , 1 , \"R\" , 0.952 , 1 , \"R\" ),(\"B3LYP/aug-cc-pVTZ\" , 0.985 , 3 , \"R\" , 0.999 , 3 , \"R\" , 0.959 , 3 , \"R\" ),(\"B3LYP/def2-TZVP\" , 0.985 , 3 , \"R\" , 0.999 , 3 , \"R\" , 0.959 , 3 , \"R\" ),(\"B3LYP/ma-TZVP\" , 0.986 , 1 , \"R\" , 1.000 , 1 , \"R\" , 0.960 , 1 , \"R\" ),(\"B3LYP/MG3S\" , 0.983 , 1 , \"D\" , 0.998 , 1 , \"D\" , 0.960 , 1 , \"D\" ),(\"B3P86/6-31G(d)\" , 0.971 , 1 , \"R\" , 0.985 , 1 , \"R\" , 0.946 , 1 , \"R\" ),(\"B3PW91/6-31G(d)\" , 0.972 , 1 , \"R\" , 0.986 , 1 , \"R\" , 0.947 , 1 , \"R\" ),(\"B97-3/ma-TZVP\" , 0.975 , 1 , \"R\" , 0.989 , 1 , \"R\" , 0.950 , 1 , \"R\" ),(\"B97-3/MG3S\" , 0.972 , 1 , \"D\" , 0.986 , 1 , \"D\" , 0.947 , 1 , \"D\" ),(\"B98/def2-TZVP\" , 0.984 , 1 , \"R\" , 0.998 , 1 , \"R\" , 0.958 , 1 , \"R\" ),(\"B98/ma-TZVP\" , 0.985 , 1 , \"R\" , 0.999 , 1 , \"R\" , 0.959 , 1 , \"R\" ),(\"B98/MG3S\" , 0.982 , 1 , \"D\" , 0.995 , 1 , \"D\" , 0.956 , 1 , \"D\" ),(\"BB1K/6-31+G(d,p)\" , 0.954 , 1 , \"C\" , 0.967 , 1 , \"R\" , 0.929 , 1 , \"R\" ),(\"BB1K/MG3S\" , 0.957 , 1 , \"C\" , 0.970 , 1 , \"R\" , 0.932 , 1 , \"R\" ),(\"BB95/6-31+G(d,p)\" , 1.011 , 1 , \"C\" , 1.025 , 1 , \"R\" , 0.985 , 1 , \"R\" ),(\"BB95/MG3S\" , 1.012 , 1 , \"C\" , 1.026 , 1 , \"R\" , 0.986 , 1 , \"R\" ),(\"BLYP/6-311G(df,p)\" , 1.013 , 1 , \"R\" , 1.027 , 1 , \"R\" , 0.987 , 1 , \"R\" ),(\"BLYP/6-31G(d)\" , 1.009 , 1 , \"R\" , 1.023 , 1 , \"R\" , 0.983 , 1 , \"R\" ),(\"BLYP/MG3S\" , 1.013 , 1 , \"D\" , 1.031 , 1 , \"D\" , 0.991 , 1 , \"D\" ),(\"BMC-CCSD\" , 0.985 , 1 , \"D\" , 1.001 , 1 , \"D\" , 0.962 , 1 , \"D\" ),(\"BMK/ma-TZVP\" , 0.972 , 1 , \"R\" , 0.986 , 1 , \"R\" , 0.947 , 1 , \"R\" ),(\"BMK/MG3S\" , 0.971 , 1 , \"D\" , 0.984 , 1 , \"D\" , 0.945 , 1 , \"D\" ),(\"BP86/6-31G(d)\" , 1.007 , 1 , \"R\" , 1.021 , 1 , \"R\" , 0.981 , 1 , \"R\" ),(\"BP86/ma-TZVP\" , 1.014 , 1 , \"R\" , 1.028 , 1 , \"R\" , 0.988 , 1 , \"R\" ),(\"BPW60/6-311+G(d,p)\" , 0.934 , 2 , \"C\" , 0.910 , 2 , \"R\" , 0.947 , 2 , \"R\" ),(\"BPW63/MG3S\" , 0.923 , 2 , \"C\" , 0.899 , 2 , \"R\" , 0.936 , 2 , \"R\" ),(\"CAM-B3LYP/ma-TZVP\" , 0.976 , 1 , \"R\" , 0.990 , 1 , \"R\" , 0.951 , 1 , \"R\" ),(\"CCSD(T)/jul-cc-pVTZ\" , 0.984 , 1 , \"R\" , 0.998 , 1 , \"R\" , 0.958 , 1 , \"R\" ),(\"CCSD(T)/aug-cc-pVTZ\" , 0.987 , 1 , \"R\" , 1.001 , 1 , \"R\" , 0.961 , 1 , \"R\" ),(\"CCSD(T)-F12/jul-cc-pVTZ\" , 0.981 , 1 , \"R\" , 0.995 , 1 , \"R\" , 0.955 , 1 , \"R\" ),(\"CCSD(T)-F12a/cc-pVTZ-F12\" , 0.984 , 1 , \"R\" , 0.998 , 1 , \"R\" , 0.958 , 1 , \"R\" ),(\"CCSD/jul-cc-pVTZ\" , 0.973 , 1 , \"R\" , 0.987 , 1 , \"R\" , 0.948 , 1 , \"R\" ),(\"CCSD-F12/jul-cc-pVTZ\" , 0.971 , 1 , \"R\" , 0.985 , 1 , \"R\" , 0.946 , 1 , \"R\" ),(\"G96LYP80/6-311+G(d,p)\" , 0.911 , 2 , \"C\" , 0.887 , 2 , \"R\" , 0.924 , 2 , \"R\" ),(\"G96LYP82/MG3S\" , 0.907 , 2 , \"C\" , 0.883 , 2 , \"R\" , 0.920 , 2 , \"R\" ),(\"GAM/def2-TZVP\" , 0.980 , 7 , \"D\" , 0.994 , 7 , \"D\" , 0.955 , 7 , \"D\" ),(\"GAM/ma-TZVP\" , 0.981 , 7 , \"D\" , 0.995 , 7 , \"D\" , 0.956 , 7 , \"D\" ),(\"HF/3-21G\" , 0.919 , 1 , \"R\" , 0.932 , 1 , \"R\" , 0.895 , 1 , \"R\" ),(\"HF/6-31+G(d)\" , 0.911 , 1 , \"R\" , 0.924 , 1 , \"R\" , 0.887 , 1 , \"R\" ),(\"HF/6-31+G(d,p)\" , 0.915 , 1 , \"C\" , 0.928 , 1 , \"R\" , 0.891 , 1 , \"R\" ),(\"HF/6-311G(d,p)\" , 0.920 , 1 , \"R\" , 0.933 , 1 , \"R\" , 0.896 , 1 , \"R\" ),(\"HF/6-311G(df,p)\" , 0.920 , 1 , \"R\" , 0.933 , 1 , \"R\" , 0.896 , 1 , \"R\" ),(\"HF/6-31G(d)\" , 0.909 , 1 , \"R\" , 0.922 , 1 , \"R\" , 0.885 , 1 , \"R\" ),(\"HF/6-31G(d,p)\" , 0.913 , 1 , \"R\" , 0.926 , 1 , \"R\" , 0.889 , 1 , \"R\" ),(\"HF/MG3S\" , 0.919 , 1 , \"D\" , 0.932 , 1 , \"D\" , 0.895 , 1 , \"D\" ),(\"HFLYP/MG3S\" , 0.899 , 1 , \"D\" , 0.912 , 1 , \"D\" , 0.876 , 1 , \"D\" ),(\"HSEh1PBE/ma-TZVP\" , 0.979 , 1 , \"R\" , 0.993 , 1 , \"R\" , 0.954 , 1 , \"R\" ),(\"M05/aug-cc-pVTZ\" , 0.978 , 1 , \"R\" , 0.992 , 1 , \"R\" , 0.953 , 1 , \"R\" ),(\"M05/def2-TZVP\" , 0.978 , 3 , \"R\" , 0.991 , 3 , \"R\" , 0.952 , 3 , \"R\" ),(\"M05/ma-TZVP\" , 0.979 , 1 , \"R\" , 0.993 , 1 , \"R\" , 0.954 , 1 , \"R\" ),(\"M05/maug-cc-pVTZ\" , 0.978 , 1 , \"R\" , 0.992 , 1 , \"R\" , 0.953 , 1 , \"R\" ),(\"M05/MG3S\" , 0.977 , 1 , \"D\" , 0.989 , 1 , \"D\" , 0.951 , 1 , \"D\" ),(\"M05-2X/6-31+G(d,p)\" , 0.961 , 1 , \"D\" , 0.974 , 1 , \"D\" , 0.936 , 1 , \"D\" ),(\"M05-2X/aug-cc-pVTZ\" , 0.964 , 1 , \"R\" , 0.977 , 1 , \"R\" , 0.939 , 1 , \"R\" ),(\"M05-2X/def2-TZVPP\" , 0.962 , 1 , \"D\" , 0.976 , 1 , \"D\" , 0.938 , 1 , \"D\" ),(\"M05-2X/ma-TZVP\" , 0.965 , 1 , \"R\" , 0.979 , 1 , \"R\" , 0.940 , 1 , \"R\" ),(\"M05-2X/maug-cc-pVTZ\" , 0.964 , 1 , \"R\" , 0.977 , 1 , \"R\" , 0.939 , 1 , \"R\" ),(\"M05-2X/MG3S\" , 0.962 , 1 , \"D\" , 0.975 , 1 , \"D\" , 0.937 , 1 , \"D\" ),(\"M06/6-31+G(d,p)\" , 0.980 , 1 , \"D\" , 0.989 , 1 , \"D\" , 0.950 , 1 , \"D\" ),(\"M06/aug-cc-pVTZ\" , 0.984 , 1 , \"R\" , 0.998 , 1 , \"R\" , 0.958 , 1 , \"R\" ),(\"M06/def2-TZVP\" , 0.982 , 3 , \"R\" , 0.996 , 3 , \"R\" , 0.956 , 3 , \"R\" ),(\"M06/def2-TZVPP\" , 0.979 , 1 , \"D\" , 0.992 , 1 , \"D\" , 0.953 , 1 , \"D\" ),(\"M06/ma-TZVP\" , 0.982 , 1 , \"R\" , 0.996 , 1 , \"R\" , 0.956 , 1 , \"R\" ),(\"M06/maug-cc-pVTZ\" , 0.982 , 1 , \"R\" , 0.996 , 1 , \"R\" , 0.956 , 1 , \"R\" ),(\"M06/MG3S\" , 0.981 , 1 , \"D\" , 0.994 , 1 , \"D\" , 0.955 , 1 , \"D\" ),(\"M06-2X/6-31+G(d,p)\" , 0.967 , 1 , \"D\" , 0.979 , 1 , \"D\" , 0.940 , 1 , \"D\" ),(\"M06-2X/6-311+G(d,p)\" , 0.970 , 5 , \"D\" , 0.983 , 5 , \"R\" , 0.944 , 5 , \"R\" ),(\"M06-2X/6-311++G(d,p)\" , 0.970 , 5 , \"D\" , 0.983 , 5 , \"R\" , 0.944 , 5 , \"R\" ),(\"M06-2X/aug-cc-pVTZ\" , 0.971 , 1 , \"D\" , 0.985 , 1 , \"D\" , 0.946 , 1 , \"D\" ),(\"M06-2X/def2-TZVP\" , 0.971 , 7 , \"D\" , 0.984 , 7 , \"D\" , 0.946 , 7 , \"D\" ),(\"M06-2X/def2-QZVP\" , 0.970 , 7 , \"D\" , 0.983 , 7 , \"D\" , 0.945 , 7 , \"D\" ),(\"M06-2X/def2-TZVPP\" , 0.970 , 1 , \"D\" , 0.983 , 1 , \"D\" , 0.945 , 1 , \"D\" ),(\"M06-2X/ma-TZVP\" , 0.972 , 1 , \"R\" , 0.986 , 1 , \"R\" , 0.947 , 1 , \"R\" ),(\"M06/maug-cc-pVTZ\" , 0.971 , 1 , \"D\" , 0.984 , 1 , \"D\" , 0.945 , 1 , \"D\" ),(\"M06-2X/MG3S\" , 0.970 , 1 , \"D\" , 0.982 , 1 , \"D\" , 0.944 , 1 , \"D\" ),(\"M06-HF/6-31+G(d,p)\" , 0.954 , 1 , \"D\" , 0.969 , 1 , \"D\" , 0.931 , 1 , \"D\" ),(\"M06-HF/aug-cc-pVTZ\" , 0.961 , 1 , \"R\" , 0.974 , 1 , \"R\" , 0.936 , 1 , \"R\" ),(\"M06-HF/def2-TZVPP\" , 0.958 , 1 , \"D\" , 0.970 , 1 , \"D\" , 0.932 , 1 , \"D\" ),(\"M06-HF/ma-TZVP\" , 0.957 , 1 , \"R\" , 0.970 , 1 , \"R\" , 0.932 , 1 , \"R\" ),(\"M06-HF/maug-cc-pVTZ\" , 0.959 , 1 , \"R\" , 0.972 , 1 , \"R\" , 0.934 , 1 , \"R\" ),(\"M06-HF/MG3S\" , 0.955 , 1 , \"D\" , 0.967 , 1 , \"D\" , 0.930 , 1 , \"D\" ),(\"M06-L/6-31+G(d,p)\" , 0.978 , 1 , \"D\" , 0.992 , 1 , \"D\" , 0.953 , 1 , \"D\" ),(\"M06-L/aug-cc-pVTZ\" , 0.980 , 1 , \"R\" , 0.994 , 1 , \"R\" , 0.955 , 1 , \"R\" ),(\"M06-L(DKH2)/aug-cc-pwcVTZ-DK\" , 0.985 , 1 , \"D\" , 0.999 , 1 , \"R\" , 0.959 , 1 , \"R\" ),(\"M06-L/def2-TZVP\" , 0.976 , 3 , \"R\" , 0.990 , 3 , \"R\" , 0.951 , 3 , \"R\" ),(\"M06-L/def2-TZVPP\" , 0.976 , 1 , \"D\" , 0.995 , 1 , \"D\" , 0.956 , 1 , \"D\" ),(\"M06-L/ma-TZVP\" , 0.977 , 1 , \"R\" , 0.991 , 1 , \"R\" , 0.952 , 1 , \"R\" ),(\"M06-L/maug-cc-pVTZ\" , 0.977 , 1 , \"R\" , 0.991 , 1 , \"R\" , 0.952 , 1 , \"R\" ),(\"M06-L/MG3S\" , 0.978 , 1 , \"D\" , 0.996 , 1 , \"D\" , 0.958 , 1 , \"D\" ),(\"M08-HX/6-31+G(d,p)\" , 0.972 , 1 , \"D\" , 0.983 , 1 , \"D\" , 0.944 , 1 , \"D\" ),(\"M08-HX/aug-cc-pVTZ\" , 0.975 , 1 , \"R\" , 0.989 , 1 , \"R\" , 0.950 , 1 , \"R\" ),(\"M08-HX/cc-pVTZ+\" , 0.974 , 1 , \"D\" , 0.985 , 1 , \"D\" , 0.946 , 1 , \"D\" ),(\"M08-HX/def2-TZVPP\" , 0.973 , 1 , \"D\" , 0.984 , 1 , \"D\" , 0.945 , 1 , \"D\" ),(\"M08-HX/jun-cc-pVTZ\" , 0.974 , 6 , \"D\" , 0.986 , 6 , \"D\" , 0.947 , 6 , \"D\" ),(\"M08-HX/ma-TZVP\" , 0.976 , 1 , \"R\" , 0.990 , 1 , \"R\" , 0.951 , 1 , \"R\" ),(\"M08-HX/maug-cc-pVTZ\" , 0.976 , 1 , \"R\" , 0.990 , 1 , \"R\" , 0.951 , 1 , \"R\" ),(\"M08-HX/MG3S\" , 0.973 , 1 , \"D\" , 0.984 , 1 , \"D\" , 0.946 , 1 , \"D\" ),(\"M08-SO/6-31+G(d,p)\" , 0.979 , 1 , \"D\" , 0.989 , 1 , \"D\" , 0.951 , 1 , \"D\" ),(\"M08-SO/aug-cc-pVTZ\" , 0.985 , 1 , \"R\" , 0.999 , 1 , \"R\" , 0.959 , 1 , \"R\" ),(\"M08-SO/cc-pVTZ+\" , 0.982 , 1 , \"D\" , 0.995 , 1 , \"D\" , 0.956 , 1 , \"D\" ),(\"M08-SO/def2-TZVPP\" , 0.980 , 1 , \"D\" , 0.993 , 1 , \"D\" , 0.954 , 1 , \"D\" ),(\"M08-SO/ma-TZVP\" , 0.984 , 1 , \"R\" , 0.998 , 1 , \"R\" , 0.958 , 1 , \"R\" ),(\"M08-SO/maug-cc-pVTZ\" , 0.983 , 1 , \"R\" , 0.997 , 1 , \"R\" , 0.957 , 1 , \"R\" ),(\"M08-SO/MG3\" , 0.984 , 4 , \"D\" , 0.998 , 4 , \"R\" , 0.959 , 4 , \"R\" ),(\"M08-SO/MG3S\" , 0.983 , 1 , \"D\" , 0.995 , 1 , \"D\" , 0.956 , 1 , \"D\" ),(\"M08-SO/MG3SXP\" , 0.984 , 1 , \"D\" , 0.996 , 1 , \"D\" , 0.957 , 1 , \"D\" ),(\"MN12-L/MG3S\" , 0.968 , 6 , \"D\" , 0.981 , 6 , \"D\" , 0.943 , 6 , \"D\" ),(\"MN12-SX/6-311++G(d,p)\" , 0.976 , 6 , \"D\" , 0.986 , 6 , \"D\" , 0.947 , 6 , \"D\" ),(\"MN15-L/MG3S\" , 0.977 , 1 , \"D\" , 0.991 , 1 , \"R\" , 0.952 , 1 , \"R\" ),(\"MN15-L/maug-cc-pVTZ\" , 0.979 , 1 , \"D\" , 0.993 , 1 , \"R\" , 0.954 , 1 , \"R\" ),(\"MC3BB\" , 0.965 , 1 , \"C\" , 0.979 , 1 , \"R\" , 0.940 , 1 , \"R\" ),(\"MC3MPW\" , 0.964 , 1 , \"C\" , 0.977 , 1 , \"R\" , 0.939 , 1 , \"R\" ),(\"MC-QCISD/3\" , 0.992 , 1 , \"C\" , 1.006 , 1 , \"R\" , 0.966 , 1 , \"R\" ),(\"MOHLYP/ma-TZVP\" , 1.027 , 1 , \"R\" , 1.041 , 1 , \"R\" , 1.000 , 1 , \"R\" ),(\"MOHLYP/MG3S\" , 1.022 , 1 , \"R\" , 1.036 , 1 , \"R\" , 0.995 , 1 , \"R\" ),(\"MP2(FC)/6-31+G(d,p)\" , 0.968 , 1 , \"C\" , 0.982 , 1 , \"R\" , 0.943 , 1 , \"R\" ),(\"MP2(FC)/6-311G(d,p)\" , 0.970 , 1 , \"R\" , 0.984 , 1 , \"R\" , 0.945 , 1 , \"R\" ),(\"MP2(FC)/6-31G(d)\" , 0.964 , 1 , \"R\" , 0.977 , 1 , \"R\" , 0.939 , 1 , \"R\" ),(\"MP2(FC)/6-31G(d,p)\" , 0.958 , 1 , \"R\" , 0.971 , 1 , \"R\" , 0.933 , 1 , \"R\" ),(\"MP2(FC)/cc-pVDZ\" , 0.977 , 1 , \"C\" , 0.991 , 1 , \"R\" , 0.952 , 1 , \"R\" ),(\"MP2(FULL)/6-31G(d)\" , 0.963 , 1 , \"R\" , 0.976 , 1 , \"R\" , 0.938 , 1 , \"R\" ),(\"MP4(SDQ)/jul-cc-pVTZ\", 0.973 , 1 , \"R\" , 0.987 , 1 , \"R\" , 0.948 , 1 , \"R\" ),(\"MPW1B95/6-31+G(d,p)\" , 0.970 , 1 , \"C\" , 0.984 , 1 , \"R\" , 0.945 , 1 , \"R\" ),(\"MPW1B95/MG3\" , 0.970 , 1 , \"C\" , 0.984 , 1 , \"R\" , 0.945 , 1 , \"R\" ),(\"MPW1B95/MG3S\" , 0.972 , 1 , \"C\" , 0.986 , 1 , \"R\" , 0.947 , 1 , \"R\" ),(\"MPW1K/6-31+G(d,p)\" , 0.949 , 1 , \"C\" , 0.962 , 1 , \"R\" , 0.924 , 1 , \"R\" ),(\"MPW1K/ma-TZVP\" , 0.956 , 1 , \"R\" , 0.969 , 1 , \"R\" , 0.931 , 1 , \"R\" ),(\"MPW1K/MG3\" , 0.953 , 1 , \"C\" , 0.966 , 1 , \"R\" , 0.928 , 1 , \"R\" ),(\"MPW1K/MG3S\" , 0.956 , 1 , \"C\" , 0.969 , 1 , \"R\" , 0.931 , 1 , \"R\" ),(\"MPW1K/MIDI!\" , 0.953 , 1 , \"R\" , 0.966 , 1 , \"R\" , 0.928 , 1 , \"R\" ),(\"MPW1K/MIDIY\" , 0.947 , 1 , \"R\" , 0.960 , 1 , \"R\" , 0.922 , 1 , \"R\" ),(\"MPW3LYP/6-31+G(d,p)\" , 0.980 , 1 , \"C\" , 0.994 , 1 , \"R\" , 0.955 , 1 , \"R\" ),(\"MPW3LYP/6-311+G(2d,p)\" , 0.986 , 1 , \"R\" , 1.000 , 1 , \"R\" , 0.960 , 1 , \"R\" ),(\"MPW3LYP/6-31G(d)\" , 0.976 , 1 , \"R\" , 0.990 , 1 , \"R\" , 0.951 , 1 , \"R\" ),(\"MPW3LYP/ma-TZVP\" , 0.986 , 1 , \"R\" , 1.000 , 1 , \"R\" , 0.960 , 1 , \"R\" ),(\"MPW3LYP/MG3S\" , 0.982 , 1 , \"C\" , 0.996 , 1 , \"R\" , 0.956 , 1 , \"R\" ),(\"MPW74/6-311+G(d,p)\" , 0.912 , 2 , \"C\" , 0.888 , 2 , \"R\" , 0.925 , 2 , \"R\" ),(\"MPW76/MG3S\" , 0.909 , 2 , \"C\" , 0.885 , 2 , \"R\" , 0.922 , 2 , \"R\" ),(\"MPWB1K/6-31+G(d,p)\" , 0.951 , 1 , \"C\" , 0.964 , 1 , \"R\" , 0.926 , 1 , \"R\" ),(\"MPWB1K/MG3S\" , 0.954 , 1 , \"C\" , 0.967 , 1 , \"R\" , 0.929 , 1 , \"R\" ),(\"MPWLYP1M/ma-TZVP\" , 1.009 , 1 , \"R\" , 1.023 , 1 , \"R\" , 0.983 , 1 , \"R\" ),(\"OreLYP/ma-TZVP\" , 1.010 , 7 , \"D\" , 1.024 , 7 , \"D\" , 0.984 , 7 , \"D\" ),(\"OreLYP/def2-TZVP\" , 1.008 , 7 , \"D\" , 1.023 , 7 , \"D\" , 0.982 , 7 , \"D\" ),(\"PBE/def2-TZVP\" , 1.011 , 3 , \"R\" , 1.026 , 3 , \"R\" , 0.985 , 3 , \"R\" ),(\"PBE/MG3S\" , 1.010 , 1 , \"D\" , 1.025 , 1 , \"D\" , 0.985 , 1 , \"D\" ),(\"PBE/ma-TZVP\" , 1.014 , 1 , \"D\" , 1.028 , 1 , \"D\" , 0.987 , 1 , \"D\" ),(\"PBE0/MG3S\" , 0.975 , 1 , \"D\" , 0.989 , 1 , \"D\" , 0.950 , 1 , \"D\" ),(\"PBE1KCIS/MG3\" , 0.981 , 1 , \"C\" , 0.995 , 1 , \"R\" , 0.955 , 1 , \"R\" ),(\"PBE1KCIS/MG3S\" , 0.981 , 1 , \"C\" , 0.995 , 1 , \"R\" , 0.955 , 1 , \"R\" ),(\"PM3\" , 0.940 , 1 , \"R\" , 0.953 , 1 , \"R\" , 0.916 , 1 , \"R\" ),(\"PM6\" , 1.078 , 1 , \"R\" , 1.093 , 1 , \"R\" , 1.050 , 1 , \"R\" ),(\"PW6B95/6-31+G(d,p)\" , 0.970 , 1 , \"C\" , 0.984 , 1 , \"R\" , 0.945 , 1 , \"R\" ),(\"QCISD(FC)/6-31G(d)\" , 0.973 , 1 , \"R\" , 0.987 , 1 , \"R\" , 0.948 , 1 , \"R\" ),(\"revTPSS/def2-TZVP\" , 0.998 , 7 , \"D\" , 1.012 , 7 , \"D\" , 0.972 , 7 , \"D\" ),(\"revTPSS/ma-TZVP\" , 0.999 , 7 , \"D\" , 1.013 , 7 , \"D\" , 0.973 , 7 , \"D\" ),(\"SOGGA/ma-TZVP\" , 1.017 , 1 , \"R\" , 1.031 , 1 , \"R\" , 0.991 , 1 , \"R\" ),(\"tHCTHhyb/ma-TZVP\" , 0.989 , 1 , \"R\" , 1.003 , 1 , \"R\" , 0.963 , 1 , \"R\" ),(\"TPSS1KCIS/def2-TZVP\" , 0.982 , 1 , \"R\" , 0.996 , 1 , \"R\" , 0.956 , 1 , \"R\" ),(\"TPSS1KCIS/ma-TZVP\" , 0.983 , 1 , \"R\" , 0.997 , 1 , \"R\" , 0.957 , 1 , \"R\" ),(\"TPSSh/MG3S\" , 0.984 , 1 , \"D\" , 1.002 , 1 , \"D\" , 0.963 , 1 , \"D\" ),(\"VSXC/MG3S\" , 0.986 , 1 , \"D\" , 1.001 , 1 , \"D\" , 0.962 , 1 , \"D\" ),(\"wB97/def2-TZVP\", 0.969 , 1 , \"R\" , 0.983 , 1 , \"R\" , 0.944 , 1 , \"R\" ),(\"wB97/ma-TZVP\", 0.970 , 1 , \"R\" , 0.984 , 1 , \"R\" , 0.945 , 1 , \"R\" ),(\"wB97X/def2-TZVP\", 0.970 , 1 , \"R\" , 0.984 , 1 , \"R\" , 0.945 , 1 , \"R\" ),(\"wB97X/ma-TZVP\" , 0.971 , 1 , \"R\" , 0.985 , 1 , \"R\" , 0.946 , 1 , \"R\" ),(\"wB97X-D/def2-TZVP\", 0.975 , 1 , \"R\" , 0.989 , 1 , \"R\" , 0.950 , 1 , \"R\" ),(\"wB97X-D/ma-TZVP\", 0.975 , 1 , \"R\" , 0.989 , 1 , \"R\" , 0.950 , 1 , \"R\" ),(\"wB97X-D/maug-cc-pVTZ\", 0.974 , 1 , \"R\" , 0.988 , 1 , \"R\" , 0.949 , 1 , \"R\" ),(\"X1B95/6-31+G(d,p)\" , 0.968 , 1 , \"C\" , 0.982 , 1 , \"R\" , 0.943 , 1 , \"R\" ),(\"X1B95/MG3S\" , 0.971 , 1 , \"C\" , 0.985 , 1 , \"R\" , 0.946 , 1 , \"R\" ),(\"XB1K/6-31+G(d,p)\" , 0.952 , 1 , \"C\" , 0.965 , 1 , \"R\" , 0.927 , 1 , \"R\" ),(\"XB1K/MG3S\" , 0.955 , 1 , \"C\" , 0.968 , 1 , \"R\" , 0.930 , 1 , \"R\" )],dtype=[('level', Str_char%30),('zpe_fac', 'f4'), ('zpe_ref', 'i4'), ('zpe_meth', Str_char%1), ('harm_fac', 'f4'), ('harm_ref', 'i4'), ('harm_meth', Str_char%1), ('fund_fac', 'f4'), ('fund_ref', 'i4'), ('fund_meth', Str_char%1)])\n", "meta": {"hexsha": "e1957122b2a192f34f39e33957a03f31ba6cfa7d", "size": 17486, "ext": "py", "lang": "Python", "max_stars_repo_path": "goodvibes/vib_scale_factors.py", "max_stars_repo_name": "jaimergp/GoodVibes", "max_stars_repo_head_hexsha": "94125fb0aac9127ec5fe790be3634228738efa1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "goodvibes/vib_scale_factors.py", "max_issues_repo_name": "jaimergp/GoodVibes", "max_issues_repo_head_hexsha": "94125fb0aac9127ec5fe790be3634228738efa1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "goodvibes/vib_scale_factors.py", "max_forks_repo_name": "jaimergp/GoodVibes", "max_forks_repo_head_hexsha": "94125fb0aac9127ec5fe790be3634228738efa1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 416.3333333333, "max_line_length": 14968, "alphanum_fraction": 0.4008349537, "include": true, "reason": "import numpy", "num_tokens": 10960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.2628418489200747, "lm_q1q2_score": 0.1396240538612324}} {"text": "from itertools import product as product\r\nfrom math import ceil\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport torch\r\n\r\nfrom utils.config import cfg_mnet\r\n\r\n\r\n#-----------------------------#\r\n# 中心解码,宽高解码\r\n#-----------------------------#\r\ndef decode(loc, priors, variances):\r\n boxes = torch.cat((priors[:, :2] + loc[:, :2] * variances[0] * priors[:, 2:],\r\n priors[:, 2:] * torch.exp(loc[:, 2:] * variances[1])), 1)\r\n boxes[:, :2] -= boxes[:, 2:] / 2\r\n boxes[:, 2:] += boxes[:, :2]\r\n return boxes\r\n\r\n#-----------------------------#\r\n# 关键点解码\r\n#-----------------------------#\r\ndef decode_landm(pre, priors, variances):\r\n landms = torch.cat((priors[:, :2] + pre[:, :2] * variances[0] * priors[:, 2:],\r\n priors[:, :2] + pre[:, 2:4] * variances[0] * priors[:, 2:],\r\n priors[:, :2] + pre[:, 4:6] * variances[0] * priors[:, 2:],\r\n priors[:, :2] + pre[:, 6:8] * variances[0] * priors[:, 2:],\r\n priors[:, :2] + pre[:, 8:10] * variances[0] * priors[:, 2:],\r\n ), dim=1)\r\n return landms\r\n\r\nclass Anchors(object):\r\n def __init__(self, cfg, image_size=None):\r\n super(Anchors, self).__init__()\r\n self.min_sizes = cfg['min_sizes']\r\n self.steps = cfg['steps']\r\n self.clip = cfg['clip']\r\n #---------------------------#\r\n # 图片的尺寸\r\n #---------------------------#\r\n self.image_size = image_size\r\n #---------------------------#\r\n # 三个有效特征层高和宽\r\n #---------------------------#\r\n self.feature_maps = [[ceil(self.image_size[0]/step), ceil(self.image_size[1]/step)] for step in self.steps]\r\n\r\n def get_anchors(self):\r\n anchors = []\r\n for k, f in enumerate(self.feature_maps):\r\n min_sizes = self.min_sizes[k]\r\n #-----------------------------------------#\r\n # 对特征层的高和宽进行循环迭代\r\n #-----------------------------------------#\r\n for i, j in product(range(f[0]), range(f[1])):\r\n for min_size in min_sizes:\r\n s_kx = min_size / self.image_size[1]\r\n s_ky = min_size / self.image_size[0]\r\n dense_cx = [x * self.steps[k] / self.image_size[1] for x in [j + 0.5]]\r\n dense_cy = [y * self.steps[k] / self.image_size[0] for y in [i + 0.5]]\r\n for cy, cx in product(dense_cy, dense_cx):\r\n anchors += [cx, cy, s_kx, s_ky]\r\n\r\n output = torch.Tensor(anchors).view(-1, 4)\r\n output = np.zeros_like(anchors[:, :4])\r\n output[:,0] = anchors[:,0] - anchors[:,2] / 2\r\n output[:,1] = anchors[:,1] - anchors[:,3] / 2\r\n output[:,2] = anchors[:,0] + anchors[:,2] / 2\r\n output[:,3] = anchors[:,1] + anchors[:,3] / 2\r\n\r\n if self.clip:\r\n output = np.clip(output, 0, 1)\r\n return output\r\n\r\nif __name__ == \"__main__\":\r\n cfg_mnet['image_size'] = 640\r\n #--------------------------------#\r\n # 先验框的生成\r\n #--------------------------------#\r\n cfg = cfg_mnet\r\n anchors = Anchors(cfg, image_size = (cfg_mnet['image_size'], cfg_mnet['image_size'])).get_anchors()\r\n anchors = anchors[-800:] * cfg_mnet['image_size']\r\n\r\n #--------------------------------#\r\n # 先验框中心绘制\r\n #--------------------------------#\r\n center_x = (anchors[:, 0] + anchors[:, 2]) / 2\r\n center_y = (anchors[:, 1] + anchors[:, 3]) / 2\r\n\r\n fig = plt.figure()\r\n ax = fig.add_subplot(121)\r\n plt.ylim(-300,900)\r\n plt.xlim(-300,900)\r\n ax.invert_yaxis()\r\n plt.scatter(center_x,center_y)\r\n\r\n #--------------------------------#\r\n # 先验框宽高绘制\r\n #--------------------------------#\r\n box_widths = anchors[0:2,2] - anchors[0:2,0]\r\n box_heights = anchors[0:2,3] - anchors[0:2,1]\r\n for i in [0,1]:\r\n rect = plt.Rectangle([anchors[i, 0], anchors[i, 1]], box_widths[i], box_heights[i], color=\"r\", fill=False)\r\n ax.add_patch(rect)\r\n\r\n #--------------------------------#\r\n # 先验框中心绘制\r\n #--------------------------------#\r\n ax = fig.add_subplot(122)\r\n plt.ylim(-300,900)\r\n plt.xlim(-300,900)\r\n ax.invert_yaxis() #y轴反向\r\n plt.scatter(center_x,center_y)\r\n\r\n #--------------------------------#\r\n # 对先验框调整获得预测框\r\n #--------------------------------#\r\n mbox_loc = np.random.randn(800, 4)\r\n mbox_ldm = np.random.randn(800, 10)\r\n\r\n anchors[:, :2] = (anchors[:, :2] + anchors[:, 2:]) / 2\r\n anchors[:, 2:] = (anchors[:, 2:] - anchors[:, :2]) * 2\r\n\r\n mbox_loc = torch.Tensor(mbox_loc)\r\n anchors = torch.Tensor(anchors)\r\n cfg_mnet['variance'] = torch.Tensor(cfg_mnet['variance'])\r\n decode_bbox = decode(mbox_loc, anchors, cfg_mnet['variance'])\r\n\r\n box_widths = decode_bbox[0: 2, 2] - decode_bbox[0: 2, 0]\r\n box_heights = decode_bbox[0: 2, 3] - decode_bbox[0: 2, 1]\r\n\r\n for i in [0,1]:\r\n rect = plt.Rectangle([decode_bbox[i, 0], decode_bbox[i, 1]], box_widths[i], box_heights[i], color=\"r\", fill=False)\r\n plt.scatter((decode_bbox[i, 2] + decode_bbox[i, 0]) / 2, (decode_bbox[i,3] + decode_bbox[i,1]) / 2, color=\"b\")\r\n ax.add_patch(rect)\r\n\r\n plt.show()\r\n", "meta": {"hexsha": "98e57bee50ee6f8d46cc58a9db674e9a96c669d7", "size": 5292, "ext": "py", "lang": "Python", "max_stars_repo_path": "vision_for_anchors.py", "max_stars_repo_name": "KinghooWei/retinaface-pytorch", "max_stars_repo_head_hexsha": "307d978947cc90132c45aee5b556affedcf8db8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vision_for_anchors.py", "max_issues_repo_name": "KinghooWei/retinaface-pytorch", "max_issues_repo_head_hexsha": "307d978947cc90132c45aee5b556affedcf8db8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vision_for_anchors.py", "max_forks_repo_name": "KinghooWei/retinaface-pytorch", "max_forks_repo_head_hexsha": "307d978947cc90132c45aee5b556affedcf8db8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.347826087, "max_line_length": 123, "alphanum_fraction": 0.4457671958, "include": true, "reason": "import numpy", "num_tokens": 1530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.26284183737131667, "lm_q1q2_score": 0.1396240477264239}} {"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\nimport numpy as np\nimport astropy.units as u\nfrom gammapy.maps import Map, MapCoord, WcsGeom, MapAxes\nfrom gammapy.modeling.models import PowerLawSpectralModel\nfrom gammapy.utils.random import InverseCDFSampler, get_random_state\nfrom gammapy.utils.gauss import Gauss2DPDF\nfrom .kernel import PSFKernel\nfrom .table import EnergyDependentTablePSF\nfrom ..core import IRFMap\n\n__all__ = [\"PSFMap\"]\n\n\nclass PSFMap(IRFMap):\n \"\"\"Class containing the Map of PSFs and allowing to interact with it.\n\n Parameters\n ----------\n psf_map : `~gammapy.maps.Map`\n the input PSF Map. Should be a Map with 2 non spatial axes.\n rad and true energy axes should be given in this specific order.\n exposure_map : `~gammapy.maps.Map`\n Associated exposure map. Needs to have a consistent map geometry.\n\n Examples\n --------\n ::\n\n import numpy as np\n from astropy import units as u\n from astropy.coordinates import SkyCoord\n from gammapy.maps import Map, WcsGeom, MapAxis\n from gammapy.irf import EnergyDependentMultiGaussPSF, EffectiveAreaTable2D\n from gammapy.makers.utils import make_psf_map, PSFMap, make_map_exposure_true_energy\n\n # Define energy axis. Note that the name is fixed.\n energy_axis = MapAxis.from_edges(np.logspace(-1., 1., 4), unit='TeV', name='energy')\n # Define rad axis. Again note the axis name\n rads = np.linspace(0., 0.5, 100) * u.deg\n rad_axis = MapAxis.from_edges(rads, unit='deg', name='theta')\n\n # Define parameters\n pointing = SkyCoord(0., 0., unit='deg')\n max_offset = 4 * u.deg\n\n # Create WcsGeom\n geom = WcsGeom.create(binsz=0.25*u.deg, width=10*u.deg, skydir=pointing, axes=[rad_axis, energy_axis])\n\n # Extract EnergyDependentTablePSF from CTA 1DC IRF\n filename = '$GAMMAPY_DATA/cta-1dc/caldb/data/cta/1dc/bcf/South_z20_50h/irf_file.fits'\n psf = EnergyDependentMultiGaussPSF.read(filename, hdu='POINT SPREAD FUNCTION')\n psf3d = psf.to_psf3d(rads)\n aeff2d = EffectiveAreaTable2D.read(filename, hdu='EFFECTIVE AREA')\n\n # Create the exposure map\n exposure_geom = geom.to_image().to_cube([energy_axis])\n exposure_map = make_map_exposure_true_energy(pointing, \"1 h\", aeff2d, exposure_geom)\n\n # create the PSFMap for the specified pointing\n psf_map = make_psf_map(psf3d, pointing, geom, max_offset, exposure_map)\n\n # Get an EnergyDependentTablePSF at any position in the image\n psf_table = psf_map.get_energy_dependent_table_psf(SkyCoord(2., 2.5, unit='deg'))\n\n # Write map to disk\n psf_map.write('psf_map.fits')\n \"\"\"\n tag = \"psf_map\"\n required_axes = [\"rad\", \"energy_true\"]\n\n def __init__(self, psf_map, exposure_map=None):\n super().__init__(irf_map=psf_map, exposure_map=exposure_map)\n\n @property\n def psf_map(self):\n return self._irf_map\n\n @psf_map.setter\n def psf_map(self, value):\n self._irf_map = value\n\n def get_energy_dependent_table_psf(self, position=None):\n \"\"\"Get energy-dependent PSF at a given position.\n\n By default the PSF at the center of the map is returned.\n\n Parameters\n ----------\n position : `~astropy.coordinates.SkyCoord`\n the target position. Should be a single coordinates\n\n Returns\n -------\n psf_table : `~gammapy.irf.EnergyDependentTablePSF`\n the table PSF\n \"\"\"\n if position is None:\n position = self.psf_map.geom.center_skydir\n\n if position.size != 1:\n raise ValueError(\n \"EnergyDependentTablePSF can be extracted at one single position only.\"\n )\n\n energy = self.psf_map.geom.axes[\"energy_true\"].center\n rad = self.psf_map.geom.axes[\"rad\"].center\n\n coords = {\n \"skycoord\": position,\n \"energy_true\": energy.reshape((-1, 1, 1, 1)),\n \"rad\": rad.reshape((1, -1, 1, 1)),\n }\n\n data = self.psf_map.interp_by_coord(coords)\n psf_values = u.Quantity(data[:, :, 0, 0], unit=self.psf_map.unit, copy=False)\n\n if self.exposure_map is not None:\n coords = {\n \"skycoord\": position,\n \"energy_true\": energy.reshape((-1, 1, 1)),\n \"rad\": 0 * u.deg,\n }\n data = self.exposure_map.interp_by_coord(coords).squeeze()\n exposure = data * self.exposure_map.unit\n else:\n exposure = None\n\n # Beware. Need to revert rad and energies to follow the TablePSF scheme.\n return EnergyDependentTablePSF(\n axes=self.psf_map.geom.axes[[\"energy_true\", \"rad\"]],\n data=psf_values.value,\n unit=psf_values.unit,\n exposure=exposure,\n )\n\n def get_psf_kernel(self, position, geom, max_radius=None, factor=4):\n \"\"\"Returns a PSF kernel at the given position.\n\n The PSF is returned in the form a WcsNDMap defined by the input Geom.\n\n Parameters\n ----------\n position : `~astropy.coordinates.SkyCoord`\n the target position. Should be a single coordinate\n geom : `~gammapy.maps.Geom`\n the target geometry to use\n max_radius : `~astropy.coordinates.Angle`\n maximum angular size of the kernel map\n factor : int\n oversampling factor to compute the PSF\n\n Returns\n -------\n kernel : `~gammapy.irf.PSFKernel`\n the resulting kernel\n \"\"\"\n if position is None:\n position = self.psf_map.geom.center_skydir\n\n table_psf = self.get_energy_dependent_table_psf(position)\n\n if max_radius is None:\n max_radius = np.max(table_psf.axes[\"rad\"].center)\n min_radius_geom = np.min(geom.width) / 2.0\n max_radius = min(max_radius, min_radius_geom)\n\n return PSFKernel.from_table_psf(table_psf, geom, max_radius, factor)\n\n def containment_radius_map(self, energy, fraction=0.68):\n \"\"\"Containment radius map.\n\n Parameters\n ----------\n energy : `~astropy.units.Quantity`\n Scalar energy at which to compute the containment radius\n fraction : float\n the containment fraction (range: 0 to 1)\n\n Returns\n -------\n containment_radius_map : `~gammapy.maps.Map`\n Containment radius map\n \"\"\"\n coords = self.psf_map.geom.to_image().get_coord().skycoord.flatten()\n m = Map.from_geom(self.psf_map.geom.to_image(), unit=\"deg\")\n\n for coord in coords:\n psf_table = self.get_energy_dependent_table_psf(coord)\n containment_radius = psf_table.containment_radius(\n energy_true=energy, fraction=fraction\n )\n m.fill_by_coord(coord, np.atleast_1d(containment_radius))\n\n return m\n\n @classmethod\n def from_geom(cls, geom):\n \"\"\"Create psf map from geom.\n\n Parameters\n ----------\n geom : `Geom`\n PSF map geometry.\n\n Returns\n -------\n psf_map : `PSFMap`\n Point spread function map.\n \"\"\"\n geom_exposure_psf = geom.squash(axis_name=\"rad\")\n exposure_psf = Map.from_geom(geom_exposure_psf, unit=\"m2 s\")\n psf_map = Map.from_geom(geom, unit=\"sr-1\")\n return cls(psf_map, exposure_psf)\n\n def sample_coord(self, map_coord, random_state=0):\n \"\"\"Apply PSF corrections on the coordinates of a set of simulated events.\n\n Parameters\n ----------\n map_coord : `~gammapy.maps.MapCoord` object.\n Sequence of coordinates and energies of sampled events.\n random_state : {int, 'random-seed', 'global-rng', `~numpy.random.RandomState`}\n Defines random number generator initialisation.\n Passed to `~gammapy.utils.random.get_random_state`.\n\n Returns\n -------\n corr_coord : `~gammapy.maps.MapCoord` object.\n Sequence of PSF-corrected coordinates of the input map_coord map.\n \"\"\"\n\n random_state = get_random_state(random_state)\n rad_axis = self.psf_map.geom.axes[\"rad\"]\n\n coord = {\n \"skycoord\": map_coord.skycoord.reshape(-1, 1),\n \"energy_true\": map_coord[\"energy_true\"].reshape(-1, 1),\n \"rad\": rad_axis.center,\n }\n\n pdf = (\n self.psf_map.interp_by_coord(coord)\n * rad_axis.center.value\n * rad_axis.bin_width.value\n )\n\n sample_pdf = InverseCDFSampler(pdf, axis=1, random_state=random_state)\n pix_coord = sample_pdf.sample_axis()\n separation = rad_axis.pix_to_coord(pix_coord)\n\n position_angle = random_state.uniform(360, size=len(map_coord.lon)) * u.deg\n\n event_positions = map_coord.skycoord.directional_offset_by(\n position_angle=position_angle, separation=separation\n )\n return MapCoord.create(\n {\"skycoord\": event_positions, \"energy_true\": map_coord[\"energy_true\"]}\n )\n\n @classmethod\n def from_energy_dependent_table_psf(cls, table_psf, geom=None):\n \"\"\"Create PSF map from table PSF object.\n\n Helper function to create an allsky PSF map from\n table PSF, which does not depend on position.\n\n Parameters\n ----------\n table_psf : `EnergyDependentTablePSF`\n Table PSF\n\n Returns\n -------\n psf_map : `PSFMap`\n Point spread function map.\n \"\"\"\n if geom is None:\n geom = WcsGeom.create(\n npix=(2, 1),\n proj=\"CAR\",\n binsz=180,\n axes=table_psf.axes.reverse,\n )\n coords = geom.get_coord()\n\n data = table_psf.evaluate(\n energy_true=coords[\"energy_true\"], rad=coords[\"rad\"]\n )\n psf_map = Map.from_geom(geom, data=data.to_value(\"sr-1\"), unit=\"sr-1\")\n\n geom_exposure = geom.squash(axis_name=\"rad\")\n\n exposure_map = Map.from_geom(geom_exposure, unit=\"cm2 s\", data=1)\n data = table_psf.exposure\n exposure_map.quantity = exposure_map.data * data.reshape((-1, 1, 1, 1))\n return cls(psf_map=psf_map, exposure_map=exposure_map)\n\n @classmethod\n def from_gauss(cls, energy_axis_true, rad_axis=None, sigma=0.1 * u.deg):\n \"\"\"Create all -sky PSF map from Gaussian width.\n\n This is used for testing and examples.\n\n The width can be the same for all energies\n or be an array with one value per energy node.\n It does not depend on position.\n\n Parameters\n ----------\n energy_axis_true : `~gammapy.maps.MapAxis`\n True energy axis.\n rad_axis : `~gammapy.maps.MapAxis`\n Offset angle wrt source position axis.\n sigma : `~astropy.coordinates.Angle`\n Gaussian width.\n\n Returns\n -------\n psf_map : `PSFMap`\n Point spread function map.\n \"\"\"\n from gammapy.datasets.map import RAD_AXIS_DEFAULT\n\n if rad_axis is None:\n rad_axis = RAD_AXIS_DEFAULT.copy()\n\n axes = MapAxes([energy_axis_true, rad_axis])\n coords = axes.get_coord()\n\n sigma = np.broadcast_to(u.Quantity(sigma), energy_axis_true.nbin, subok=True)\n gauss = Gauss2DPDF(sigma=sigma.reshape((-1, 1)))\n data = gauss(coords[\"rad\"])\n\n table_psf = EnergyDependentTablePSF(\n axes=axes, unit=data.unit, data=data.value\n )\n return cls.from_energy_dependent_table_psf(table_psf)\n\n def to_image(self, spectrum=None, keepdims=True):\n \"\"\"Reduce to a 2-D map after weighing\n with the associated exposure and a spectrum\n\n Parameters\n ----------\n spectrum : `~gammapy.modeling.models.SpectralModel`, optional\n Spectral model to compute the weights.\n Default is power-law with spectral index of 2.\n keepdims : bool, optional\n If True, the energy axis is kept with one bin.\n If False, the axis is removed\n\n\n Returns\n -------\n psf_out : `PSFMap`\n `PSFMap` with the energy axis summed over\n \"\"\"\n from gammapy.makers.utils import _map_spectrum_weight\n\n if spectrum is None:\n spectrum = PowerLawSpectralModel(index=2.0)\n\n exp_weighed = _map_spectrum_weight(self.exposure_map, spectrum)\n exposure = exp_weighed.sum_over_axes(\n axes_names=[\"energy_true\"], keepdims=keepdims\n )\n\n psf_data = exp_weighed.data * self.psf_map.data / exposure.data\n psf_map = Map.from_geom(geom=self.psf_map.geom, data=psf_data, unit=\"sr-1\")\n\n psf = psf_map.sum_over_axes(axes_names=[\"energy_true\"], keepdims=keepdims)\n return self.__class__(psf_map=psf, exposure_map=exposure)\n", "meta": {"hexsha": "bc92ad9293c90c559575ea00eba89bdedbe67572", "size": 12934, "ext": "py", "lang": "Python", "max_stars_repo_path": "gammapy/irf/psf/psf_map.py", "max_stars_repo_name": "kabartay/gammapy", "max_stars_repo_head_hexsha": "015206d2418b1d254f1c9d3ea819ab0c5ece99e9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-02T21:35:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T21:35:27.000Z", "max_issues_repo_path": "gammapy/irf/psf/psf_map.py", "max_issues_repo_name": "kabartay/gammapy", "max_issues_repo_head_hexsha": "015206d2418b1d254f1c9d3ea819ab0c5ece99e9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gammapy/irf/psf/psf_map.py", "max_forks_repo_name": "kabartay/gammapy", "max_forks_repo_head_hexsha": "015206d2418b1d254f1c9d3ea819ab0c5ece99e9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5828877005, "max_line_length": 110, "alphanum_fraction": 0.614504407, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 3114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117165898111866, "lm_q2_score": 0.2720245569956929, "lm_q1q2_score": 0.13919947865073473}} {"text": "from collections import OrderedDict\nfrom collections.abc import Iterable\nfrom copy import deepcopy\nfrom math import cos, sin, pi\nfrom numbers import Real\nfrom xml.etree import ElementTree as ET\nimport sys\nimport warnings\n\nimport numpy as np\n\nimport openmc\nimport openmc.checkvalue as cv\nfrom openmc.surface import Halfspace\nfrom openmc.region import Region, Intersection, Complement\nfrom openmc._xml import get_text\nfrom .mixin import IDManagerMixin\n\n\nclass Cell(IDManagerMixin):\n r\"\"\"A region of space defined as the intersection of half-space created by\n quadric surfaces.\n\n Parameters\n ----------\n cell_id : int, optional\n Unique identifier for the cell. If not specified, an identifier will\n automatically be assigned.\n name : str, optional\n Name of the cell. If not specified, the name is the empty string.\n fill : openmc.Material or openmc.Universe or openmc.Lattice or None or iterable of openmc.Material, optional\n Indicates what the region of space is filled with\n region : openmc.Region, optional\n Region of space that is assigned to the cell.\n\n Attributes\n ----------\n id : int\n Unique identifier for the cell\n name : str\n Name of the cell\n fill : openmc.Material or openmc.Universe or openmc.Lattice or None or iterable of openmc.Material\n Indicates what the region of space is filled with. If None, the cell is\n treated as a void. An iterable of materials is used to fill repeated\n instances of a cell with different materials.\n fill_type : {'material', 'universe', 'lattice', 'distribmat', 'void'}\n Indicates what the cell is filled with.\n region : openmc.Region or None\n Region of space that is assigned to the cell.\n rotation : Iterable of float\n If the cell is filled with a universe, this array specifies the angles\n in degrees about the x, y, and z axes that the filled universe should be\n rotated. The rotation applied is an intrinsic rotation with specified\n Tait-Bryan angles. That is to say, if the angles are :math:`(\\phi,\n \\theta, \\psi)`, then the rotation matrix applied is :math:`R_z(\\psi)\n R_y(\\theta) R_x(\\phi)` or\n\n .. math::\n\n \\left [ \\begin{array}{ccc} \\cos\\theta \\cos\\psi & -\\cos\\phi \\sin\\psi\n + \\sin\\phi \\sin\\theta \\cos\\psi & \\sin\\phi \\sin\\psi + \\cos\\phi\n \\sin\\theta \\cos\\psi \\\\ \\cos\\theta \\sin\\psi & \\cos\\phi \\cos\\psi +\n \\sin\\phi \\sin\\theta \\sin\\psi & -\\sin\\phi \\cos\\psi + \\cos\\phi\n \\sin\\theta \\sin\\psi \\\\ -\\sin\\theta & \\sin\\phi \\cos\\theta & \\cos\\phi\n \\cos\\theta \\end{array} \\right ]\n\n A rotation matrix can also be specified directly by setting this\n attribute to a nested list (or 2D numpy array) that specifies each\n element of the matrix.\n rotation_matrix : numpy.ndarray\n The rotation matrix defined by the angles specified in the\n :attr:`Cell.rotation` property.\n temperature : float or iterable of float\n Temperature of the cell in Kelvin. Multiple temperatures can be given\n to give each distributed cell instance a unique temperature.\n translation : Iterable of float\n If the cell is filled with a universe, this array specifies a vector\n that is used to translate (shift) the universe.\n paths : list of str\n The paths traversed through the CSG tree to reach each cell\n instance. This property is initialized by calling the\n :meth:`Geometry.determine_paths` method.\n num_instances : int\n The number of instances of this cell throughout the geometry.\n volume : float\n Volume of the cell in cm^3. This can either be set manually or\n calculated in a stochastic volume calculation and added via the\n :meth:`Cell.add_volume_information` method.\n\n \"\"\"\n\n next_id = 1\n used_ids = set()\n\n def __init__(self, cell_id=None, name='', fill=None, region=None):\n # Initialize Cell class attributes\n self.id = cell_id\n self.name = name\n self.fill = fill\n self.region = region\n self._rotation = None\n self._rotation_matrix = None\n self._temperature = None\n self._translation = None\n self._paths = None\n self._num_instances = None\n self._volume = None\n self._atoms = None\n\n def __contains__(self, point):\n if self.region is None:\n return True\n else:\n return point in self.region\n\n def __repr__(self):\n string = 'Cell\\n'\n string += '{: <16}=\\t{}\\n'.format('\\tID', self.id)\n string += '{: <16}=\\t{}\\n'.format('\\tName', self.name)\n\n if self.fill_type == 'material':\n string += '{: <16}=\\tMaterial {}\\n'.format('\\tFill', self.fill.id)\n elif self.fill_type == 'void':\n string += '{: <16}=\\tNone\\n'.format('\\tFill')\n elif self.fill_type == 'distribmat':\n string += '{: <16}=\\t{}\\n'.format('\\tFill', list(map(\n lambda m: m if m is None else m.id, self.fill)))\n else:\n string += '{: <16}=\\t{}\\n'.format('\\tFill', self.fill.id)\n\n string += '{: <16}=\\t{}\\n'.format('\\tRegion', self.region)\n string += '{: <16}=\\t{}\\n'.format('\\tRotation', self.rotation)\n if self.fill_type == 'material':\n string += '\\t{0: <15}=\\t{1}\\n'.format('Temperature',\n self.temperature)\n string += '{: <16}=\\t{}\\n'.format('\\tTranslation', self.translation)\n\n return string\n\n @property\n def name(self):\n return self._name\n\n @property\n def fill(self):\n return self._fill\n\n @property\n def fill_type(self):\n if isinstance(self.fill, openmc.Material):\n return 'material'\n elif isinstance(self.fill, openmc.Universe):\n return 'universe'\n elif isinstance(self.fill, openmc.Lattice):\n return 'lattice'\n elif isinstance(self.fill, Iterable):\n return 'distribmat'\n else:\n return 'void'\n\n @property\n def region(self):\n return self._region\n\n @property\n def rotation(self):\n return self._rotation\n\n @property\n def rotation_matrix(self):\n return self._rotation_matrix\n\n @property\n def temperature(self):\n return self._temperature\n\n @property\n def translation(self):\n return self._translation\n\n @property\n def volume(self):\n return self._volume\n\n @property\n def paths(self):\n if self._paths is None:\n raise ValueError('Cell instance paths have not been determined. '\n 'Call the Geometry.determine_paths() method.')\n return self._paths\n\n @property\n def bounding_box(self):\n if self.region is not None:\n return self.region.bounding_box\n else:\n return (np.array([-np.inf, -np.inf, -np.inf]),\n np.array([np.inf, np.inf, np.inf]))\n\n @property\n def num_instances(self):\n if self._num_instances is None:\n raise ValueError(\n 'Number of cell instances have not been determined. Call the '\n 'Geometry.determine_paths() method.')\n return self._num_instances\n\n @name.setter\n def name(self, name):\n if name is not None:\n cv.check_type('cell name', name, str)\n self._name = name\n else:\n self._name = ''\n\n @fill.setter\n def fill(self, fill):\n if fill is not None:\n if isinstance(fill, Iterable):\n for i, f in enumerate(fill):\n if f is not None:\n cv.check_type('cell.fill[i]', f, openmc.Material)\n\n elif not isinstance(fill, (openmc.Material, openmc.Lattice,\n openmc.Universe)):\n msg = 'Unable to set Cell ID=\"{0}\" to use a non-Material or ' \\\n 'Universe fill \"{1}\"'.format(self._id, fill)\n raise ValueError(msg)\n\n self._fill = fill\n\n @rotation.setter\n def rotation(self, rotation):\n cv.check_length('cell rotation', rotation, 3)\n self._rotation = np.asarray(rotation)\n\n # Save rotation matrix -- the reason we do this instead of having it be\n # automatically calculated when the rotation_matrix property is accessed\n # is so that plotting on a rotated geometry can be done faster.\n if self._rotation.ndim == 2:\n # User specified rotation matrix directly\n self._rotation_matrix = self._rotation\n else:\n phi, theta, psi = self.rotation*(-pi/180.)\n c3, s3 = cos(phi), sin(phi)\n c2, s2 = cos(theta), sin(theta)\n c1, s1 = cos(psi), sin(psi)\n self._rotation_matrix = np.array([\n [c1*c2, c1*s2*s3 - c3*s1, s1*s3 + c1*c3*s2],\n [c2*s1, c1*c3 + s1*s2*s3, c3*s1*s2 - c1*s3],\n [-s2, c2*s3, c2*c3]])\n\n @translation.setter\n def translation(self, translation):\n cv.check_type('cell translation', translation, Iterable, Real)\n cv.check_length('cell translation', translation, 3)\n self._translation = np.asarray(translation)\n\n @temperature.setter\n def temperature(self, temperature):\n # Make sure temperatures are positive\n cv.check_type('cell temperature', temperature, (Iterable, Real))\n if isinstance(temperature, Iterable):\n cv.check_type('cell temperature', temperature, Iterable, Real)\n for T in temperature:\n cv.check_greater_than('cell temperature', T, 0.0, True)\n else:\n cv.check_greater_than('cell temperature', temperature, 0.0, True)\n\n # If this cell is filled with a universe or lattice, propagate\n # temperatures to all cells contained. Otherwise, simply assign it.\n if self.fill_type in ('universe', 'lattice'):\n for c in self.get_all_cells().values():\n if c.fill_type == 'material':\n c._temperature = temperature\n else:\n self._temperature = temperature\n\n @region.setter\n def region(self, region):\n if region is not None:\n cv.check_type('cell region', region, Region)\n self._region = region\n\n @volume.setter\n def volume(self, volume):\n if volume is not None:\n cv.check_type('cell volume', volume, Real)\n self._volume = volume\n\n def add_volume_information(self, volume_calc):\n \"\"\"Add volume information to a cell.\n\n Parameters\n ----------\n volume_calc : openmc.VolumeCalculation\n Results from a stochastic volume calculation\n\n \"\"\"\n if volume_calc.domain_type == 'cell':\n if self.id in volume_calc.volumes:\n self._volume = volume_calc.volumes[self.id].n\n self._atoms = volume_calc.atoms[self.id]\n else:\n raise ValueError('No volume information found for this cell.')\n else:\n raise ValueError('No volume information found for this cell.')\n\n def get_nuclides(self):\n \"\"\"Returns all nuclides in the cell\n\n Returns\n -------\n nuclides : list of str\n List of nuclide names\n\n \"\"\"\n return self.fill.get_nuclides() if self.fill_type != 'void' else []\n\n def get_nuclide_densities(self):\n \"\"\"Return all nuclides contained in the cell and their densities\n\n Returns\n -------\n nuclides : collections.OrderedDict\n Dictionary whose keys are nuclide names and values are 2-tuples of\n (nuclide, density)\n\n \"\"\"\n\n nuclides = OrderedDict()\n\n if self.fill_type == 'material':\n nuclides.update(self.fill.get_nuclide_densities())\n elif self.fill_type == 'void':\n pass\n else:\n if self._atoms is not None:\n volume = self.volume\n for name, atoms in self._atoms.items():\n nuclide = openmc.Nuclide(name)\n density = 1.0e-24 * atoms.n/volume # density in atoms/b-cm\n nuclides[name] = (nuclide, density)\n else:\n raise RuntimeError(\n 'Volume information is needed to calculate microscopic cross '\n 'sections for cell {}. This can be done by running a '\n 'stochastic volume calculation via the '\n 'openmc.VolumeCalculation object'.format(self.id))\n\n return nuclides\n\n def get_all_cells(self, memo=None):\n \"\"\"Return all cells that are contained within this one if it is filled with a\n universe or lattice\n\n Returns\n -------\n cells : collections.orderedDict\n Dictionary whose keys are cell IDs and values are :class:`Cell`\n instances\n\n \"\"\"\n\n cells = OrderedDict()\n\n if memo and self in memo:\n return cells\n\n if memo is not None:\n memo.add(self)\n\n if self.fill_type in ('universe', 'lattice'):\n cells.update(self.fill.get_all_cells(memo))\n\n return cells\n\n def get_all_materials(self, memo=None):\n \"\"\"Return all materials that are contained within the cell\n\n Returns\n -------\n materials : collections.OrderedDict\n Dictionary whose keys are material IDs and values are\n :class:`Material` instances\n\n \"\"\"\n materials = OrderedDict()\n if self.fill_type == 'material':\n materials[self.fill.id] = self.fill\n elif self.fill_type == 'distribmat':\n for m in self.fill:\n if m is not None:\n materials[m.id] = m\n else:\n # Append all Cells in each Cell in the Universe to the dictionary\n cells = self.get_all_cells(memo)\n for cell in cells.values():\n materials.update(cell.get_all_materials(memo))\n\n return materials\n\n def get_all_universes(self):\n \"\"\"Return all universes that are contained within this one if any of\n its cells are filled with a universe or lattice.\n\n Returns\n -------\n universes : collections.OrderedDict\n Dictionary whose keys are universe IDs and values are\n :class:`Universe` instances\n\n \"\"\"\n\n universes = OrderedDict()\n\n if self.fill_type == 'universe':\n universes[self.fill.id] = self.fill\n universes.update(self.fill.get_all_universes())\n elif self.fill_type == 'lattice':\n universes.update(self.fill.get_all_universes())\n\n return universes\n\n def clone(self, clone_materials=True, clone_regions=True, memo=None):\n \"\"\"Create a copy of this cell with a new unique ID, and clones\n the cell's region and fill.\n\n Parameters\n ----------\n clone_materials : bool\n Whether to create separate copies of the materials filling cells\n contained in this cell, or the material filling this cell.\n clone_regions : bool\n Whether to create separate copies of the regions bounding cells\n contained in this cell, and the region bounding this cell.\n memo : dict or None\n A nested dictionary of previously cloned objects. This parameter\n is used internally and should not be specified by the user.\n\n Returns\n -------\n clone : openmc.Cell\n The clone of this cell\n\n \"\"\"\n\n if memo is None:\n memo = {}\n\n # If no memoize'd clone exists, instantiate one\n if self not in memo:\n # Temporarily remove paths\n paths = self._paths\n self._paths = None\n\n clone = deepcopy(self)\n clone.id = None\n clone._num_instances = None\n\n # Restore paths on original instance\n self._paths = paths\n\n if self.region is not None:\n if clone_regions:\n clone.region = self.region.clone(memo)\n else:\n clone.region = self.region\n if self.fill is not None:\n if self.fill_type == 'distribmat':\n if not clone_materials:\n clone.fill = self.fill\n else:\n clone.fill = [fill.clone(memo) if fill is not None else\n None for fill in self.fill]\n elif self.fill_type == 'material':\n if not clone_materials:\n clone.fill = self.fill\n else:\n clone.fill = self.fill.clone(memo)\n else:\n clone.fill = self.fill.clone(clone_materials,\n clone_regions, memo)\n\n # Memoize the clone\n memo[self] = clone\n\n return memo[self]\n\n def create_xml_subelement(self, xml_element, memo=None):\n \"\"\"Add the cell's xml representation to an incoming xml element\n\n Parameters\n ----------\n xml_element : xml.etree.ElementTree.Element\n XML element to be added to\n\n memo : set or None\n A set of object IDs representing geometry entities already\n written to ``xml_element``. This parameter is used internally\n and should not be specified by users.\n\n Returns\n -------\n None\n\n \"\"\"\n element = ET.Element(\"cell\")\n element.set(\"id\", str(self.id))\n\n if len(self._name) > 0:\n element.set(\"name\", str(self.name))\n\n if self.fill_type == 'void':\n element.set(\"material\", \"void\")\n\n elif self.fill_type == 'material':\n element.set(\"material\", str(self.fill.id))\n\n elif self.fill_type == 'distribmat':\n element.set(\"material\", ' '.join(['void' if m is None else str(m.id)\n for m in self.fill]))\n\n elif self.fill_type in ('universe', 'lattice'):\n element.set(\"fill\", str(self.fill.id))\n self.fill.create_xml_subelement(xml_element, memo)\n\n if self.region is not None:\n # Set the region attribute with the region specification\n region = str(self.region)\n if region.startswith('('):\n region = region[1:-1]\n if len(region) > 0:\n element.set(\"region\", region)\n\n # Only surfaces that appear in a region are added to the geometry\n # file, so the appropriate check is performed here. First we create\n # a function which is called recursively to navigate through the CSG\n # tree. When it reaches a leaf (a Halfspace), it creates a \n # element for the corresponding surface if none has been created\n # thus far.\n def create_surface_elements(node, element, memo=None):\n if isinstance(node, Halfspace):\n if memo and node.surface in memo:\n return\n if memo is not None:\n memo.add(node.surface)\n xml_element.append(node.surface.to_xml_element())\n\n elif isinstance(node, Complement):\n create_surface_elements(node.node, element, memo)\n else:\n for subnode in node:\n create_surface_elements(subnode, element, memo)\n\n # Call the recursive function from the top node\n create_surface_elements(self.region, xml_element, memo)\n\n if self.temperature is not None:\n if isinstance(self.temperature, Iterable):\n element.set(\"temperature\", ' '.join(\n str(t) for t in self.temperature))\n else:\n element.set(\"temperature\", str(self.temperature))\n\n if self.translation is not None:\n element.set(\"translation\", ' '.join(map(str, self.translation)))\n\n if self.rotation is not None:\n element.set(\"rotation\", ' '.join(map(str, self.rotation.ravel())))\n\n return element\n\n @classmethod\n def from_xml_element(cls, elem, surfaces, materials, get_universe):\n \"\"\"Generate cell from XML element\n\n Parameters\n ----------\n elem : xml.etree.ElementTree.Element\n `` element\n surfaces : dict\n Dictionary mapping surface IDs to :class:`openmc.Surface` instances\n materials : dict\n Dictionary mapping material IDs to :class:`openmc.Material`\n instances (defined in :math:`openmc.Geometry.from_xml`)\n get_universe : function\n Function returning universe (defined in\n :meth:`openmc.Geometry.from_xml`)\n\n Returns\n -------\n Cell\n Cell instance\n\n \"\"\"\n cell_id = int(get_text(elem, 'id'))\n name = get_text(elem, 'name')\n c = cls(cell_id, name)\n\n # Assign material/distributed materials or fill\n mat_text = get_text(elem, 'material')\n if mat_text is not None:\n mat_ids = mat_text.split()\n if len(mat_ids) > 1:\n c.fill = [materials[i] for i in mat_ids]\n else:\n c.fill = materials[mat_ids[0]]\n else:\n fill_id = int(get_text(elem, 'fill'))\n c.fill = get_universe(fill_id)\n\n # Assign region\n region = get_text(elem, 'region')\n if region is not None:\n c.region = Region.from_expression(region, surfaces)\n\n # Check for other attributes\n t = get_text(elem, 'temperature')\n if t is not None:\n if ' ' in t:\n c.temperature = [float(t_i) for t_i in t.split()]\n else:\n c.temperature = float(t)\n for key in ('temperature', 'rotation', 'translation'):\n value = get_text(elem, key)\n if value is not None:\n setattr(c, key, [float(x) for x in value.split()])\n\n # Add this cell to appropriate universe\n univ_id = int(get_text(elem, 'universe', 0))\n get_universe(univ_id).add_cell(c)\n return c\n", "meta": {"hexsha": "e01cb8613752d8717572788a2d40372e102c27de", "size": 22442, "ext": "py", "lang": "Python", "max_stars_repo_path": "openmc/cell.py", "max_stars_repo_name": "SamPUG/openmc", "max_stars_repo_head_hexsha": "70c19dfef4991c5f89161a87868f109c47efc76d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-19T14:46:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-19T14:46:10.000Z", "max_issues_repo_path": "openmc/cell.py", "max_issues_repo_name": "SamPUG/openmc", "max_issues_repo_head_hexsha": "70c19dfef4991c5f89161a87868f109c47efc76d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-02-24T15:13:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-17T18:59:22.000Z", "max_forks_repo_path": "openmc/cell.py", "max_forks_repo_name": "SamPUG/openmc", "max_forks_repo_head_hexsha": "70c19dfef4991c5f89161a87868f109c47efc76d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3974763407, "max_line_length": 112, "alphanum_fraction": 0.5747259603, "include": true, "reason": "import numpy", "num_tokens": 4795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.23934935817440722, "lm_q1q2_score": 0.13913452165051565}} {"text": "\"\"\"\npython implementation of shadow3 OE object\n\"\"\"\nimport numpy\nfrom shadow4.compatibility.gfile import GFile\n\n\nclass OE(object):\n\n def __init__(self):\n\n self.FMIRR = 5\n self.F_TORUS = 0\n self.FCYL = 0\n self.F_EXT = 0\n self.FSTAT = 0\n self.F_SCREEN = 0\n self.F_PLATE = 0\n self.FSLIT = 0\n self.FWRITE = 0\n self.F_RIPPLE = 0\n self.F_MOVE = 0\n self.F_THICK = 0\n self.F_BRAGG_A = 0\n self.F_G_S = 0\n self.F_R_RAN = 0\n self.F_GRATING = 0\n self.F_MOSAIC = 0\n self.F_JOHANSSON = 0\n self.F_SIDE = 0\n self.F_CENTRAL = 0\n self.F_CONVEX = 0\n self.F_REFLEC = 0\n self.F_RUL_ABS = 0\n self.F_RULING = 0\n self.F_PW = 0\n self.F_PW_C = 0\n self.F_VIRTUAL = 0\n self.FSHAPE = 1\n self.FHIT_C = 0\n self.F_MONO = 0\n self.F_REFRAC = 0\n self.F_DEFAULT = 1\n self.F_REFL = 0\n self.F_HUNT = 1\n self.F_CRYSTAL = 0\n self.F_PHOT_CENT = 0\n self.F_ROUGHNESS = 0\n self.F_ANGLE = 0\n self.NPOINT = 5000\n self.NCOL = 18\n self.N_SCREEN = 0\n self.ISTAR1 = 0\n self.CIL_ANG = 0.00000000000000\n self.ELL_THE = 0.00000000000000\n self.N_PLATES = 0\n self.IG_SEED = 0\n self.MOSAIC_SEED = 1626261131\n self.ALPHA = 0.00000000000000\n self.SSOUR = 0.00000000000000\n self.THETA = 0.00000000000000\n self.SIMAG = 0.00000000000000\n self.RDSOUR = 0.00000000000000\n self.RTHETA = 0.00000000000000\n self.OFF_SOUX = 0.00000000000000\n self.OFF_SOUY = 0.00000000000000\n self.OFF_SOUZ = 0.00000000000000\n self.ALPHA_S = 0.00000000000000\n self.RLEN1 = 0.00000000000000\n self.RLEN2 = 0.00000000000000\n self.RMIRR = 0.00000000000000\n self.AXMAJ = 0.00000000000000\n self.AXMIN = 0.00000000000000\n self.CONE_A = 0.00000000000000\n self.R_MAJ = 0.00000000000000\n self.R_MIN = 0.00000000000000\n self.RWIDX1 = 0.00000000000000\n self.RWIDX2 = 0.00000000000000\n self.PARAM = 0.00000000000000\n self.HUNT_H = 0.00000000000000\n self.HUNT_L = 0.00000000000000\n self.BLAZE = 0.00000000000000\n self.RULING = 12000.0000000000\n self.ORDER = -1.00000000000000\n self.PHOT_CENT = 5.00000000000000\n self.X_ROT = 0.00000000000000\n self.D_SPACING = 0.00000000000000\n self.A_BRAGG = 0.00000000000000\n self.SPREAD_MOS = 0.00000000000000\n self.THICKNESS = 0.00000000000000\n self.R_JOHANSSON = 0.00000000000000\n self.Y_ROT = 0.00000000000000\n self.Z_ROT = 0.00000000000000\n self.OFFX = 0.00000000000000\n self.OFFY = 0.00000000000000\n self.OFFZ = 0.00000000000000\n self.SLLEN = 0.00000000000000\n self.SLWID = 0.00000000000000\n self.SLTILT = 0.00000000000000\n self.COD_LEN = 0.00000000000000\n self.COD_WID = 0.00000000000000\n self.X_SOUR = 0.00000000000000\n self.Y_SOUR = 0.00000000000000\n self.Z_SOUR = 0.00000000000000\n self.X_SOUR_ROT = 0.00000000000000\n self.Y_SOUR_ROT = 0.00000000000000\n self.Z_SOUR_ROT = 0.00000000000000\n self.R_LAMBDA = 5.00000000000000\n self.THETA_I = 0.00000000000000\n self.ALPHA_I = 0.00000000000000\n self.T_INCIDENCE = 88.0000000000000\n self.T_SOURCE = 10.0000000000000\n self.T_IMAGE = 20.0000000000000\n self.T_REFLECTION = 88.0000000000000\n self.FILE_SOURCE = \"begin.dat\"\n self.FILE_RIP = \"\"\n self.FILE_REFL = \"\"\n self.FILE_MIR = \"\"\n self.FILE_ROUGH = \"\"\n self.FZP = 0\n self.HOLO_R1 = 300.000000000000\n self.HOLO_R2 = 300.000000000000\n self.HOLO_DEL = -20.0000000000000\n self.HOLO_GAM = -20.0000000000000\n self.HOLO_W = 4879.86000000000\n self.HOLO_RT1 = 0.00000000000000\n self.HOLO_RT2 = 0.00000000000000\n self.AZIM_FAN = 0.00000000000000\n self.DIST_FAN = 0.00000000000000\n self.COMA_FAC = 0.00000000000000\n self.ALFA = 0.00000000000000\n self.GAMMA = 0.00000000000000\n self.R_IND_OBJ = 1.00000000000000\n self.R_IND_IMA = 1.00000000000000\n self.R_ATTENUATION_OBJ = 0.00000000000000\n self.R_ATTENUATION_IMA = 0.00000000000000\n self.F_R_IND = 0\n self.FILE_R_IND_OBJ = \"\"\n self.FILE_R_IND_IMA = \"\"\n self.RUL_A1 = 0.00000000000000\n self.RUL_A2 = 0.00000000000000\n self.RUL_A3 = 0.00000000000000\n self.RUL_A4 = 0.00000000000000\n self.F_POLSEL = 4\n self.F_FACET = 0\n self.F_FAC_ORIENT = 0\n self.F_FAC_LATT = 0\n self.RFAC_LENX = 10.0000000000000\n self.RFAC_LENY = 10.0000000000000\n self.RFAC_PHAX = 0.00000000000000\n self.RFAC_PHAY = 0.00000000000000\n self.RFAC_DELX1 = 0.00000000000000\n self.RFAC_DELX2 = 0.00000000000000\n self.RFAC_DELY1 = 0.00000000000000\n self.RFAC_DELY2 = 0.00000000000000\n self.FILE_FAC = \"\"\n self.F_SEGMENT = 0\n self.ISEG_XNUM = 1\n self.ISEG_YNUM = 1\n self.FILE_SEGMENT = \"\"\n self.FILE_SEGP = \"\"\n self.SEG_LENX = 0.00000000000000\n self.SEG_LENY = 0.00000000000000\n self.F_KOMA = 0\n self.FILE_KOMA = \"\"\n self.F_EXIT_SHAPE = 0\n self.F_INC_MNOR_ANG = 0\n self.ZKO_LENGTH = 0.00000000000000\n self.RKOMA_CX = 0.00000000000000\n self.RKOMA_CY = 0.00000000000000\n self.F_KOMA_CA = 0\n self.FILE_KOMA_CA = \"\"\n self.F_KOMA_BOUNCE = 0\n self.X_RIP_AMP = 0.00000000000000\n self.X_RIP_WAV = 0.00000000000000\n self.X_PHASE = 0.00000000000000\n self.Y_RIP_AMP = 0.00000000000000\n self.Y_RIP_WAV = 0.00000000000000\n self.Y_PHASE = 0.00000000000000\n self.N_RIP = 0\n self.ROUGH_X = 0.00000000000000\n self.ROUGH_Y = 0.00000000000000\n self.OE_NUMBER = 0\n self.IDUMMY = 0\n self.DUMMY = 0.00000000000000\n\n self.CX_SLIT = numpy.zeros(11)\n self.CX_SLIT[1] = 0.00000000000000\n self.CX_SLIT[2] = 0.00000000000000\n self.CX_SLIT[3] = 0.00000000000000\n self.CX_SLIT[4] = 0.00000000000000\n self.CX_SLIT[5] = 0.00000000000000\n self.CX_SLIT[6] = 0.00000000000000\n self.CX_SLIT[7] = 0.00000000000000\n self.CX_SLIT[8] = 0.00000000000000\n self.CX_SLIT[9] = 0.00000000000000\n self.CX_SLIT[10] = 0.00000000000000\n\n self.CZ_SLIT = numpy.zeros(11)\n self.CZ_SLIT[1] = 0.00000000000000\n self.CZ_SLIT[2] = 0.00000000000000\n self.CZ_SLIT[3] = 0.00000000000000\n self.CZ_SLIT[4] = 0.00000000000000\n self.CZ_SLIT[5] = 0.00000000000000\n self.CZ_SLIT[6] = 0.00000000000000\n self.CZ_SLIT[7] = 0.00000000000000\n self.CZ_SLIT[8] = 0.00000000000000\n self.CZ_SLIT[9] = 0.00000000000000\n self.CZ_SLIT[10] = 0.00000000000000\n\n self.D_PLATE = numpy.zeros(11)\n self.D_PLATE[1] = 0.00000000000000\n self.D_PLATE[2] = 0.00000000000000\n self.D_PLATE[3] = 0.00000000000000\n self.D_PLATE[4] = 0.00000000000000\n self.D_PLATE[5] = 0.00000000000000\n self.D_PLATE[6] = 0.00000000000000\n self.D_PLATE[7] = 0.00000000000000\n self.D_PLATE[8] = 0.00000000000000\n self.D_PLATE[9] = 0.00000000000000\n self.D_PLATE[10] = 0.00000000000000\n\n self.FILE_ABS = numpy.chararray(11)\n self.FILE_ABS[1] = \"\"\n self.FILE_ABS[2] = \"\"\n self.FILE_ABS[3] = \"\"\n self.FILE_ABS[4] = \"\"\n self.FILE_ABS[5] = \"\"\n self.FILE_ABS[6] = \"\"\n self.FILE_ABS[7] = \"\"\n self.FILE_ABS[8] = \"\"\n self.FILE_ABS[9] = \"\"\n self.FILE_ABS[10] = \"\"\n\n self.FILE_SCR_EXT = numpy.chararray(11)\n self.FILE_SCR_EXT[1] = \"\"\n self.FILE_SCR_EXT[2] = \"\"\n self.FILE_SCR_EXT[3] = \"\"\n self.FILE_SCR_EXT[4] = \"\"\n self.FILE_SCR_EXT[5] = \"\"\n self.FILE_SCR_EXT[6] = \"\"\n self.FILE_SCR_EXT[7] = \"\"\n self.FILE_SCR_EXT[8] = \"\"\n self.FILE_SCR_EXT[9] = \"\"\n self.FILE_SCR_EXT[10] = \"\"\n\n self.I_ABS = numpy.zeros(11)\n self.I_ABS[1] = 0\n self.I_ABS[2] = 0\n self.I_ABS[3] = 0\n self.I_ABS[4] = 0\n self.I_ABS[5] = 0\n self.I_ABS[6] = 0\n self.I_ABS[7] = 0\n self.I_ABS[8] = 0\n self.I_ABS[9] = 0\n self.I_ABS[10] = 0\n\n self.I_SCREEN = numpy.zeros(11)\n self.I_SCREEN[1] = 0\n self.I_SCREEN[2] = 0\n self.I_SCREEN[3] = 0\n self.I_SCREEN[4] = 0\n self.I_SCREEN[5] = 0\n self.I_SCREEN[6] = 0\n self.I_SCREEN[7] = 0\n self.I_SCREEN[8] = 0\n self.I_SCREEN[9] = 0\n self.I_SCREEN[10] = 0\n\n self.I_SLIT = numpy.zeros(11)\n self.I_SLIT[1] = 0\n self.I_SLIT[2] = 0\n self.I_SLIT[3] = 0\n self.I_SLIT[4] = 0\n self.I_SLIT[5] = 0\n self.I_SLIT[6] = 0\n self.I_SLIT[7] = 0\n self.I_SLIT[8] = 0\n self.I_SLIT[9] = 0\n self.I_SLIT[10] = 0\n\n self.I_STOP = numpy.zeros(11)\n self.I_STOP[1] = 0\n self.I_STOP[2] = 0\n self.I_STOP[3] = 0\n self.I_STOP[4] = 0\n self.I_STOP[5] = 0\n self.I_STOP[6] = 0\n self.I_STOP[7] = 0\n self.I_STOP[8] = 0\n self.I_STOP[9] = 0\n self.I_STOP[10] = 0\n\n self.K_SLIT = numpy.zeros(11)\n self.K_SLIT[1] = 0\n self.K_SLIT[2] = 0\n self.K_SLIT[3] = 0\n self.K_SLIT[4] = 0\n self.K_SLIT[5] = 0\n self.K_SLIT[6] = 0\n self.K_SLIT[7] = 0\n self.K_SLIT[8] = 0\n self.K_SLIT[9] = 0\n self.K_SLIT[10] = 0\n\n self.RX_SLIT = numpy.zeros(11)\n self.RX_SLIT[1] = 0.00000000000000\n self.RX_SLIT[2] = 0.00000000000000\n self.RX_SLIT[3] = 0.00000000000000\n self.RX_SLIT[4] = 0.00000000000000\n self.RX_SLIT[5] = 0.00000000000000\n self.RX_SLIT[6] = 0.00000000000000\n self.RX_SLIT[7] = 0.00000000000000\n self.RX_SLIT[8] = 0.00000000000000\n self.RX_SLIT[9] = 0.00000000000000\n self.RX_SLIT[10] = 0.00000000000000\n\n self.RZ_SLIT = numpy.zeros(11)\n self.RZ_SLIT[1] = 0.00000000000000\n self.RZ_SLIT[2] = 0.00000000000000\n self.RZ_SLIT[3] = 0.00000000000000\n self.RZ_SLIT[4] = 0.00000000000000\n self.RZ_SLIT[5] = 0.00000000000000\n self.RZ_SLIT[6] = 0.00000000000000\n self.RZ_SLIT[7] = 0.00000000000000\n self.RZ_SLIT[8] = 0.00000000000000\n self.RZ_SLIT[9] = 0.00000000000000\n self.RZ_SLIT[10] = 0.00000000000000\n\n self.SCR_NUMBER = numpy.zeros(11)\n self.SCR_NUMBER[1] = 0\n self.SCR_NUMBER[2] = 0\n self.SCR_NUMBER[3] = 0\n self.SCR_NUMBER[4] = 0\n self.SCR_NUMBER[5] = 0\n self.SCR_NUMBER[6] = 0\n self.SCR_NUMBER[7] = 0\n self.SCR_NUMBER[8] = 0\n self.SCR_NUMBER[9] = 0\n self.SCR_NUMBER[10] = 0\n\n self.SL_DIS = numpy.zeros(11)\n self.SL_DIS[1] = 0.00000000000000\n self.SL_DIS[2] = 0.00000000000000\n self.SL_DIS[3] = 0.00000000000000\n self.SL_DIS[4] = 0.00000000000000\n self.SL_DIS[5] = 0.00000000000000\n self.SL_DIS[6] = 0.00000000000000\n self.SL_DIS[7] = 0.00000000000000\n self.SL_DIS[8] = 0.00000000000000\n self.SL_DIS[9] = 0.00000000000000\n self.SL_DIS[10] = 0.00000000000000\n\n self.THICK = numpy.zeros(11)\n self.THICK[1] = 0.00000000000000\n self.THICK[2] = 0.00000000000000\n self.THICK[3] = 0.00000000000000\n self.THICK[4] = 0.00000000000000\n self.THICK[5] = 0.00000000000000\n self.THICK[6] = 0.00000000000000\n self.THICK[7] = 0.00000000000000\n self.THICK[8] = 0.00000000000000\n self.THICK[9] = 0.00000000000000\n self.THICK[10] = 0.00000000000000\n\n self.CCC = numpy.zeros(11)\n self.CCC[1] = 0.00000000000000\n self.CCC[2] = 0.00000000000000\n self.CCC[3] = 0.00000000000000\n self.CCC[4] = 0.00000000000000\n self.CCC[5] = 0.00000000000000\n self.CCC[6] = 0.00000000000000\n self.CCC[7] = 0.00000000000000\n self.CCC[8] = 0.00000000000000\n self.CCC[9] = 0.00000000000000\n self.CCC[10] = 0.00000000000000\n\n def load(self,filename=\"start.01\"):\n self.load_start01(filename=filename)\n\n def load_start01(self,filename=\"start.01\"):\n a = GFile()\n a.load_gfile((filename))\n dict1 = a.get_as_dictionary()\n\n for key in dict1.keys():\n if hasattr(self,key):\n # print(\"assigning: \",key,dict1[key])\n setattr(self, key, dict1[key])\n else: # this is for arrays...\n try:\n command = \"self.%s = %s\"%(key,repr(dict1[key]))\n # print(\"command: \",command)\n exec(command)\n except:\n print(\" error executing: \",command)\n # self.THICK[6] = 110.0\n\nif __name__ == \"__main__\":\n # write start.01 file with shadow4\n import Shadow\n oe_shadow3 = Shadow.OE()\n oe_shadow3.write(\"start.01\")\n\n # read it with compatibility tools\n oe1 = OE()\n oe1.load(filename=\"start.01\")\n\n print(dir(oe1))\n\n print(\">>>>>oe1.RX_SLIT\",oe1.RX_SLIT)\n print(\">>>>>Y_ROT\",oe1.Y_ROT )\n print(\">>>>>ISTAR1\",oe1.ISTAR1 )\n print(\">>>>>THICK\",oe1.THICK )\n\n assert(oe1.THICK[6] == oe_shadow3.THICK[6])\n\n\n\n", "meta": {"hexsha": "b2280bdb35e4cda382ac9cb6577f984b46206014", "size": 13676, "ext": "py", "lang": "Python", "max_stars_repo_path": "shadow4tests/compatibility/oe.py", "max_stars_repo_name": "srio/shadow4tests", "max_stars_repo_head_hexsha": "7123475d830fa619a866dbde9afe28a9ff405dfd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "shadow4tests/compatibility/oe.py", "max_issues_repo_name": "srio/shadow4tests", "max_issues_repo_head_hexsha": "7123475d830fa619a866dbde9afe28a9ff405dfd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "shadow4tests/compatibility/oe.py", "max_forks_repo_name": "srio/shadow4tests", "max_forks_repo_head_hexsha": "7123475d830fa619a866dbde9afe28a9ff405dfd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4845605701, "max_line_length": 67, "alphanum_fraction": 0.5771424393, "include": true, "reason": "import numpy", "num_tokens": 5112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.24220562872535945, "lm_q1q2_score": 0.13894814289397406}} {"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Functions to deal with HSC filters.\"\"\"\n\nimport os\nimport json\n\nimport numpy as np\n\nfrom astropy.io import fits\nfrom astropy.table import Table\nfrom astropy import constants as const\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\nfrom matplotlib import rcParams\n\nimport unagi\n\n__all__ = ['filters_to_kcorrect', 'hsc_filters', 'HscFilter', 'SolarSpectrum']\n\nplt.rc('text', usetex=True)\nrcParams.update({'xtick.major.pad': '7.0'})\nrcParams.update({'xtick.major.size': '7.5'})\nrcParams.update({'xtick.major.width': '1.5'})\nrcParams.update({'xtick.minor.pad': '7.0'})\nrcParams.update({'xtick.minor.size': '3.5'})\nrcParams.update({'xtick.minor.width': '1.0'})\nrcParams.update({'ytick.major.pad': '7.0'})\nrcParams.update({'ytick.major.size': '7.5'})\nrcParams.update({'ytick.major.width': '1.5'})\nrcParams.update({'ytick.minor.pad': '7.0'})\nrcParams.update({'ytick.minor.size': '3.5'})\nrcParams.update({'ytick.minor.width': '1.0'})\nrcParams.update({'axes.titlepad': '15.0'})\nrcParams.update({'font.size': 26})\n\n# Directory that save the transmission curves of the filter\nFILTER_DIR = os.path.join(os.path.dirname(unagi.__file__), 'data', 'filters')\n# Directory that keeps the solar spectra\nSOLAR_DIR = os.path.join(os.path.dirname(unagi.__file__), 'data', 'solar')\n\n# Formal names and nick names of the filters\nFILTER_LIST = ['HSC-G', 'HSC-R', 'HSC-R2', 'HSC-I', 'HSC-I2', 'HSC-Z', 'HSC-Y',\n 'HSC-NB387', 'HSC-NB816', 'HSC-NB921']\nFILTER_SHORT = ['g', 'r', 'r2', 'i', 'i2', 'z', 'y', 'nb387', 'nb816', 'nb921']\n\n# Colors to show the filter\nFILTER_COLORS = ['#2ca02c', '#ff7f0e', '#ff7f0e', '#d62728', '#d62728',\n '#8c564b', '#7f7f7f', 'c', 'm', 'purple']\n\n# AB reference flux in unit of erg/s/cm^2/Hz\nAB_FLUX = 3.631e-20\n# Speed of light in unit of AA/s\nC_AA_PER_SEC = const.c.to('AA/s').value\n\n\nclass Filter(object):\n \"\"\"Class for organizing HSC filters.\n\n Please see the following page for more details about HSC filters:\n https://www.subarutelescope.org/Observing/Instruments/HSC/sensitivity.html\n\n This class is based on the Filter() class from Ben Johnson's sedpy\n https://github.com/bd-j/sedpy/blob/master/sedpy/observate.py\n \"\"\"\n def __init__(self, band, origin=False, center=False):\n \"\"\"Read in the HSC filter transmission curves.\n \"\"\"\n if band.strip().upper() in FILTER_LIST:\n self.index = FILTER_LIST.index(band.strip().upper())\n elif band.strip().lower() in FILTER_SHORT:\n self.index = FILTER_SHORT.index(band.strip().lower())\n else:\n raise NameError(\"# Wrong filter name!\")\n\n # Name of the filter\n self.filter = FILTER_LIST[self.index]\n self.short = FILTER_SHORT[self.index]\n\n # Color to show the filter\n self.color = FILTER_COLORS[self.index]\n\n # Old or new version of r- and i-band filters\n if self.short == 'r' or self.short == 'i':\n self.version = 'old'\n else:\n self.version = 'new'\n\n # Whether the transmission curve is the total one or the just-filter one\n if origin:\n # This is the \"origin\" filter response curve from the HSC webpage:\n # https://www.subarutelescope.org/Observing/Instruments/HSC/sensitivity.html\n # Type of the transmission curve: area weighted one or for center\n filter_dir = os.path.join(FILTER_DIR, 'origin')\n self.type = 'just_filter'\n self.center = False\n if center:\n # This is for the center of the camera\n self.center = True\n self.name = '{}.txt'.format(self.filter)\n else:\n # This is the area-weighted mean one\n self.center = False\n self.name = 'w{}.txt'.format(self.filter)\n else:\n # This is the total transmission curves from Kawanomoto et al. 2018\n # Downloaded from here:\n # https://hsc-release.mtk.nao.ac.jp/doc/wp-content/uploads/2019/04/hsc_responses_all_rev3.tar.gz\n # Assume airmass=1.2 and PWV=1.5\n filter_dir = os.path.join(FILTER_DIR, 'total')\n self.type = 'total'\n self.name = 'hsc_{}_v2018.dat'.format(self.short)\n\n # Find the file and read in the transmission curve\n self.filename = os.path.join(filter_dir, self.name)\n self.wave, self.trans = self._load_filter()\n self.npts = len(self.wave)\n\n # Basic properties of the filter\n self.wave_effective = None\n self.wave_pivot = None\n self.wave_mean = None\n self.wave_average = None\n self.rectangular_width = None\n self.gauss_width = None\n self.effective_width = None\n self._basic_properties()\n\n # AB Zeropoint in counts\n self.ab_zero_counts = self._counts(\n self.wave, AB_FLUX * C_AA_PER_SEC / (self.wave ** 2))\n\n # AB absolute magnitude of Sun in this band\n self.solar_ab_mag = self._solar_ab_mag(kind='Willmer2018')\n\n # Convert to Kcorrect filter format\n self.to_kfilter()\n\n # Save it as a JSON file\n self.to_json()\n\n def _load_filter(self):\n \"\"\"Load and process the transimission curve.\"\"\"\n if not os.path.isfile(self.filename):\n raise IOError(\"# Cannot find the response curve file {}\".format(self.filename))\n\n # Read in the .txt response curve\n wave, trans = np.genfromtxt(self.filename, usecols=(0, 1), unpack=True)\n\n use = np.isfinite(trans) & (trans >= 0)\n order = wave[use].argsort()\n wave = wave[use][order]\n trans = trans[use][order]\n\n return wave, trans\n\n def print(self):\n \"\"\"Print out basic properties of the filter.\"\"\"\n print(\"# Filter: {}\".format(self.filename))\n print(\"# Filter type: {}\".format(self.type))\n print(\"# Version: {}\".format(self.version))\n print(\"# Effective wavelength : {:8.3f} Angstrom\".format(self.wave_effective))\n print(\"# Pivot wavelength : {:8.3f} Angstrom\".format(self.wave_pivot))\n print(\"# Mean wavelength : {:8.3f} Angstrom\".format(self.wave_mean))\n print(\"# Effective width : {:8.3f} Angstrom\".format(self.effective_width))\n print(\"# Rectangular width : {:8.3f} Angstrom\".format(self.rectangular_width))\n print(\"# AB absolute magnitude of the sun : {:6.3f} mag\".format(self.solar_ab_mag))\n\n def plot(self):\n \"\"\"Plot the transmission curves of the filter.\"\"\"\n fig = plt.figure(figsize=(8, 5))\n ax1 = fig.add_subplot(111)\n ax1.grid(linestyle='--', linewidth=2, alpha=0.8)\n ax1.axhline(0.0, linewidth=2, color='k', alpha=0.8)\n # Filled the transmission curve\n ax1.fill_between(self.wave, 0.0, self.trans, edgecolor='k', alpha=0.4,\n linewidth=2.5, facecolor=FILTER_COLORS[self.index])\n ax1.text(0.9, 0.85, r'$\\rm {}$'.format(self.short), transform=ax1.transAxes)\n # Highlight the effective and pivot wavelength\n ax1.axvline(self.wave_effective, linewidth=2.0, linestyle='--',\n label=r'$\\lambda_{\\rm eff}$')\n ax1.axvline(self.wave_pivot, linewidth=2.0, linestyle='-.',\n label=r'$\\lambda_{\\rm piv}$')\n _ = ax1.set_xlabel(r'$\\mathrm{Wavelength}\\ [\\AA]$')\n _ = ax1.set_ylabel(r'$\\mathrm{Transmission}$')\n ax1.legend(loc='lower right', fontsize=18)\n\n return fig\n\n def _basic_properties(self):\n \"\"\"Get the basic properties of the filter.\n\n These properties include several 'effective' wavelength definitions and\n several width definitions.\n\n See Fukugita et al. (1996) AJ 111, 1748 for discussion and definition\n of many of these quantities.\n \"\"\"\n # Calculate some useful integrals\n i0 = np.trapz(self.trans * np.log(self.wave), np.log(self.wave))\n i1 = np.trapz(self.trans, np.log(self.wave))\n i2 = np.trapz(self.trans * self.wave, self.wave)\n i3 = np.trapz(self.trans, self.wave)\n\n # Effective wavelength\n self.wave_effective = np.exp(i0 / i1)\n # Pivot wavelength\n self.wave_pivot = np.sqrt(i2 / i1)\n # Mean wavelength\n self.wave_mean = self.wave_effective\n self.wave_average = i2 / i3\n # Rectangular width of the filter\n self.rectangular_width = i3 / self.trans.max()\n\n i4 = np.trapz(self.trans * (np.log(self.wave / self.wave_effective)) ** 2.0,\n np.log(self.wave))\n\n # Gaussian width of the filter\n self.gauss_width = (i4 / i1) ** (0.5)\n # Effectove width of the filter\n self.effective_width = (2.0 * np.sqrt(2. * np.log(2.)) *\n self.gauss_width * self.wave_effective)\n\n def _counts(self, obj_wave, obj_flux):\n \"\"\"Project source spectrum onto filter and return the detector signal.\n \"\"\"\n # Interpolate filter transmission to source spectrum\n newtrans = np.interp(obj_wave, self.wave, self.trans, left=0., right=0.)\n\n # Integrate lambda * f_lambda * R\n if True in (newtrans > 0.):\n positive = np.where(newtrans > 0.)[0]\n ind = slice(max(positive.min() - 1, 0),\n min(positive.max() + 2, len(obj_wave)))\n counts = np.trapz(obj_wave[ind] * newtrans[ind] *\n obj_flux[..., ind], obj_wave[ind], axis=-1)\n return np.squeeze(counts)\n\n return float('NaN')\n\n def _solar_ab_mag(self, kind='Willmer2018'):\n \"\"\"Get the absolute magnitude of Sun in this band.\n \"\"\"\n # Get the solar spectrum\n solar_spectrum = SolarSpectrum(kind=kind)\n counts = self._counts(solar_spectrum.wave, solar_spectrum.flux)\n return -2.5 * np.log10(counts / self.ab_zero_counts)\n\n def to_kfilter(self):\n \"\"\"Convert the filter transmission curve into Kcorrect format.\n \"\"\"\n _ = filters_to_kcorrect(self.filename)\n\n def as_dict(self):\n \"\"\"Convert it into a dict.\"\"\"\n filter_dict = self.__dict__\n filter_dict['wave'] = list(filter_dict['wave'])\n filter_dict['trans'] = list(filter_dict['trans'])\n return filter_dict\n\n def to_json(self):\n \"\"\"Save as a JSON file.\"\"\"\n pre, _ = os.path.splitext(self.filename)\n json_out = pre + '.json'\n with open(json_out, 'w') as jf:\n json.dump(self.as_dict(), jf)\n\n\ndef hsc_filters(origin=False, center=False, use_saved=True):\n \"\"\"Get the tabel that summarizes information about HSC filters.\"\"\"\n if origin:\n if center:\n tab_id = 'origin_center'\n xml_table = os.path.join(FILTER_DIR, 'hsc_filters_origin_center.xml')\n else:\n tab_id = 'origin_weighted'\n xml_table = os.path.join(FILTER_DIR, 'hsc_filters_origin_weighted.xml')\n else:\n tab_id = 'total'\n xml_table = os.path.join(FILTER_DIR, 'hsc_filters_total.xml')\n\n # If already created, just read it in\n if os.path.isfile(xml_table) and use_saved:\n return Table.read(xml_table, format='votable', table_id=tab_id)\n else:\n # Summarize the filters\n # Total transmission curves\n f_table = Table(\n [Filter(f, origin=origin, center=center).as_dict() for f in FILTER_LIST])\n f_table.write(xml_table, format='votable', table_id=tab_id, overwrite=True)\n return f_table\n\n\ndef filters_to_kcorrect(curve_file, verbose=False):\n \"\"\"\n Convert a filter response curve to the Kcorrect format.\n\n This is used by Kcorrect and iSEDFit.\n \"\"\"\n if not os.path.isfile(curve_file):\n raise IOError(\"# Cannot find the response curve file {}\".format(curve_file))\n\n # Read in the .txt response curve\n wave, response = np.genfromtxt(curve_file, usecols=(0, 1), unpack=True)\n\n # Output file name\n prefix, _ = os.path.splitext(curve_file)\n output_par = prefix + '.par'\n\n if os.path.isfile(output_par):\n if verbose:\n print(\"# Curve {0} is already available\".format(output_par))\n else:\n assert len(wave) == len(response), '''\n Wavelength and response curve should have the same size'''\n\n par = open(output_par, 'w')\n par.write(\n \"# %s\\n typedef struct {\\n double lambda;\\n double pass;\\n } KFILTER;\\n\\n\")\n for w, r in zip(wave, response):\n par.write(\"KFILTER %10.4f %11.7f\\n\" % (w, r))\n par.close()\n\n return wave, response\n\n\nclass SolarSpectrum(object):\n \"\"\"Class to hold solar spectrum.\n\n On deriving Solar absolute magnitude:\n ------------------------------------\n To derive the Sun's absolute magnitudes, the IAU 2012 definitions of the astronomical unit\n (au) (Prša et al. 2016) and parsec were used, giving a distance modulus for the\n Sun of −31.5721 mag.\n\n To rationalize the use of solar constants, the IAU in 2015 adopted a nominal value for the Sun's\n luminosity L⊙ = 3.828 × 10^8 W (Prša et al. 2016), which corresponds to an average\n TSI of 1361 W m−2 at 1 au and an absolute bolometric magnitude of MBol = 4.74.\n \"\"\"\n def __init__(self, kind='Willmer2018'):\n \"\"\"Read in the solar spectrum and process it.\"\"\"\n # Conversion to d=10 pc from 1 AU\n au_to_10pc = (1.0 / (3600 * 180 / np.pi * 10)) ** 2.0\n\n if kind.strip() == 'Willmer2018':\n # This is based on the work by Willmer 2018:\n # https://iopscience.iop.org/article/10.3847/1538-4365/aabfdf\n # More information can be found on this webpage:\n # http://mips.as.arizona.edu/~cnaw/sun.html\n # About the spectrum:\n # The solar SED used here also combines observations with model spectra.\n # The observed spectrum is a composite calculated by Haberreiter et al. (2017)\n # using data from over 20 space-based instruments for an arbitrary date\n # (2008 December 19, JDN = 2454820) during the solar minimum.\n # The absolute calibration is set using the ${ATLAS}\\,3$ composite spectrum\n # of Thuillier et al. (2004), and constraining the Total Solar Irradiance (TSI)\n # to the value measured for each day by Dudok de Wit et al. (2017).\n # The observed composite ends at ~2.0 μm, and to extend the SED into the infrared;\n # the model spectra of Fontenla et al. (2011) and Kurucz (2011) are used.\n self.file = os.path.join(SOLAR_DIR, 'sun_composite.fits')\n if os.path.isfile(self.file):\n solar_fits = fits.open(self.file)[1].data\n # Wavelength\n self.wave = solar_fits['WAVE']\n self.wave_unit = 'Angstrom'\n self.flux = solar_fits['FLUX'] * au_to_10pc\n self.flux_unit = 'erg/s/cm^2/AA'\n else:\n raise IOError(\"# Cannot find the solar spectrum {}\".format(self.file))\n elif kind.strip() == 'Kurucz1993':\n # This is the theoretical spectrum of the Sun from Kurucz\n # from: ftp://ftp.stsci.edu/cdbs/grid/k93models/standards/sun_kurucz93.fits\n # The theoretical spectrum is scaled to match the observed spectrum\n # from 1.5 - 2.5 microns, and then it is used where the observed spectrum ends.\n # The theoretical model of the Sun from Kurucz93 atlas using the following\n # parameters when the Sun is at 1 au.\n # log_Z T_eff log_g V_{Johnson} +0.0 5777 +4.44 -26.75\n self.file = os.path.join(SOLAR_DIR, 'sun_kurucz93.fits')\n\n # This file should be in AA and erg/s/cm^2/AA at 1AU\n if os.path.isfile(self.file):\n solar_fits = fits.open(self.file)[1].data\n # Wavelength\n self.wave = solar_fits['WAVELENGTH']\n self.wave_unit = 'Angstrom'\n self.flux = solar_fits['FLUX'] * au_to_10pc\n self.flux_unit = 'erg/s/cm^2/AA'\n else:\n raise IOError(\"# Cannot find the solar spectrum {}\".format(self.file))\n else:\n raise NameError(\"# Wrong type of Solar spectrum: [Willmer2018|Kurucz1993]\")\n\n self.wave_min, self.wave_max = self.wave.min(), self.wave.max()\n self.solar = np.column_stack((self.wave, self.flux))\n", "meta": {"hexsha": "7db16226e1942d71e6d1840a7b5bf32b2f3588ce", "size": 16463, "ext": "py", "lang": "Python", "max_stars_repo_path": "unagi/filters.py", "max_stars_repo_name": "Christopher-Bradshaw/unagi", "max_stars_repo_head_hexsha": "29bb2df0c8674438f24c3932e0b1b65a83dec4ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2019-06-04T02:21:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T01:59:18.000Z", "max_issues_repo_path": "unagi/filters.py", "max_issues_repo_name": "minaskar/unagi", "max_issues_repo_head_hexsha": "821858aa3912bd5bc7bc347a54e3b70afceeb101", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2018-08-19T07:09:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-08T08:45:28.000Z", "max_forks_repo_path": "unagi/filters.py", "max_forks_repo_name": "minaskar/unagi", "max_forks_repo_head_hexsha": "821858aa3912bd5bc7bc347a54e3b70afceeb101", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-08-04T22:30:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-08T09:10:10.000Z", "avg_line_length": 41.5732323232, "max_line_length": 108, "alphanum_fraction": 0.6077871591, "include": true, "reason": "import numpy,from astropy", "num_tokens": 4225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.24508500761839527, "lm_q1q2_score": 0.13872266059907157}} {"text": "# -*- coding: utf-8 -*-\n\"\"\"\nDJI D-Gamut Colourspace\n=======================\n\nDefines the *DJI D-Gamut* colourspace:\n\n- :attr:`colour.models.DJI_D_GAMUT_COLOURSPACE`.\n\nReferences\n----------\n- :cite:`DJI2017` : Dji. (2017). White Paper on D-Log and D-Gamut of DJI\n Cinema Color System. Retrieved from https://dl.djicdn.com/downloads/\\\nzenmuse+x7/20171010/D-Log_D-Gamut_Whitepaper.pdf\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport numpy as np\n\nfrom colour.colorimetry import ILLUMINANTS\nfrom colour.models.rgb import (RGB_Colourspace, log_encoding_DJIDLog,\n log_decoding_DJIDLog)\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013-2020 - Colour Developers'\n__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-developers@colour-science.org'\n__status__ = 'Production'\n\n__all__ = [\n 'DJI_D_GAMUT_PRIMARIES', 'DJI_D_GAMUT_WHITEPOINT_NAME',\n 'DJI_D_GAMUT_WHITEPOINT', 'DJI_D_GAMUT_TO_XYZ_MATRIX',\n 'XYZ_TO_DJI_D_GAMUT_MATRIX', 'DJI_D_GAMUT_COLOURSPACE'\n]\n\nDJI_D_GAMUT_PRIMARIES = np.array([\n [0.71, 0.31],\n [0.21, 0.88],\n [0.09, -0.08],\n])\n\"\"\"\n*DJI D-Gamut* colourspace primaries.\n\nDJI_D_GAMUT_PRIMARIES : ndarray, (3, 2)\n\"\"\"\n\nDJI_D_GAMUT_WHITEPOINT_NAME = 'D65'\n\"\"\"\n*DJI D-Gamut* colourspace whitepoint name.\n\nDJI_D_GAMUT_WHITEPOINT : unicode\n\"\"\"\n\nDJI_D_GAMUT_WHITEPOINT = (ILLUMINANTS['CIE 1931 2 Degree Standard Observer'][\n DJI_D_GAMUT_WHITEPOINT_NAME])\n\"\"\"\n*DJI D-Gamut* colourspace whitepoint.\n\nDJI_D_GAMUT_WHITEPOINT : ndarray\n\"\"\"\n\nDJI_D_GAMUT_TO_XYZ_MATRIX = np.array([[0.6482, 0.1940,\n 0.1082], [0.2830, 0.8132, -0.0962],\n [-0.0183, -0.0832, 1.1903]])\n\"\"\"\n*DJI D-Gamut* colourspace to *CIE XYZ* tristimulus values matrix.\n\nDJI_D_GAMUT_TO_XYZ_MATRIX : array_like, (3, 3)\n\"\"\"\n\nXYZ_TO_DJI_D_GAMUT_MATRIX = np.array([[1.7257, -0.4314,\n -0.1917], [-0.6025, 1.3906, 0.1671],\n [-0.0156, 0.0905, 0.8489]])\n\"\"\"\n*CIE XYZ* tristimulus values to *DJI D-Gamut* colourspace matrix.\n\nXYZ_TO_DJI_D_GAMUT_MATRIX : array_like, (3, 3)\n\"\"\"\n\nDJI_D_GAMUT_COLOURSPACE = RGB_Colourspace(\n 'DJI D-Gamut',\n DJI_D_GAMUT_PRIMARIES,\n DJI_D_GAMUT_WHITEPOINT,\n DJI_D_GAMUT_WHITEPOINT_NAME,\n DJI_D_GAMUT_TO_XYZ_MATRIX,\n XYZ_TO_DJI_D_GAMUT_MATRIX,\n log_encoding_DJIDLog,\n log_decoding_DJIDLog,\n)\nDJI_D_GAMUT_COLOURSPACE.__doc__ = \"\"\"\n*DJI_D-Gamut* colourspace.\n\n References\n ----------\n :cite:`DJI2017`\n\nDJI_D_GAMUT_COLOURSPACE : RGB_Colourspace\n\"\"\"\n", "meta": {"hexsha": "7274dae2875ba34eafca8078e1c0a89152264a18", "size": 2679, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/models/rgb/datasets/dji_dgamut.py", "max_stars_repo_name": "jchwei/colour", "max_stars_repo_head_hexsha": "2b2ad0a0f2052a1a0b4b076b489687235e804fdf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "colour/models/rgb/datasets/dji_dgamut.py", "max_issues_repo_name": "jchwei/colour", "max_issues_repo_head_hexsha": "2b2ad0a0f2052a1a0b4b076b489687235e804fdf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colour/models/rgb/datasets/dji_dgamut.py", "max_forks_repo_name": "jchwei/colour", "max_forks_repo_head_hexsha": "2b2ad0a0f2052a1a0b4b076b489687235e804fdf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5247524752, "max_line_length": 78, "alphanum_fraction": 0.6715192236, "include": true, "reason": "import numpy", "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.22815649691270323, "lm_q1q2_score": 0.13864229688977786}} {"text": "from dataclasses import dataclass, field, asdict\nfrom copy import copy\nfrom enum import Enum, auto\nfrom typing import Sequence, TYPE_CHECKING, Optional, Union, TypeVar, Type\nimport numpy as np\nfrom .witt import witt\nimport lightweaver.constants as Const\nfrom numpy.polynomial.legendre import leggauss\nfrom .utils import ConvergenceError, view_flatten, get_data_path\nfrom .atomic_table import PeriodicTable, AtomicAbundance, DefaultAtomicAbundance\nimport astropy.units as u\nimport pickle\n\nif TYPE_CHECKING:\n from .LwCompiled import LwSpectrum\n\nclass ScaleType(Enum):\n '''\n Atmospheric scales used in the definition of 1D atmospheres to allow the\n correct conversion to a height based system.\n Options:\n\n - `Geometric`\n\n - `ColumnMass`\n\n - `Tau500`\n\n '''\n Geometric = 0\n ColumnMass = auto()\n Tau500 = auto()\n\nclass BoundaryCondition:\n '''\n Base class for boundary conditions.\n\n Defines the interface; do not use directly.\n\n Attributes\n ----------\n These attributes are only available after set_required_angles has been called.\n\n mux : np.ndarray\n The mu_x to return from compute_bc (in order).\n muy : np.ndarray\n The mu_y to return from compute_bc (in order).\n muz : np.ndarray\n The mu_z to return from compute_bc (in order).\n indexVector : np.ndarray\n A 2D array of integer shape (mu, toObs) - where mu is the mu index on\n the associated atmosphere - relating each index of the second (Nrays)\n axis of a pair of (mu, toObs). Used to construct and destructure this\n array.\n\n '''\n def compute_bc(self, atmos: 'Atmosphere', spect: 'LwSpectrum') -> np.ndarray:\n '''\n Called when the radiation boundary condition is needed by the backend.\n\n Parameters\n ----------\n atmos : Atmosphere\n The atmospheric object in which to compute the radiation.\n spect : LwSpectrum\n The computational spectrum object provided by the Context.\n\n Returns\n -------\n result : np.ndarray\n This function needs to return a contiguous array of shape [Nwave,\n Nrays, Nbc], where Nwave is the number of wavelengths in the\n wavelength grid, Nrays is the number of rays in the angular\n quadrature (also including up/down directions) ordered as\n specified by the mux/y/z and indexVector variables on this\n object, Nbc is the number of spatial positions the boundary\n condition needs to be defined at ordered in a flattened [Nz, Ny,\n Nx] fashion. (dtype: 'Stratifications':\n '''\n Makes an instance of `Stratifications` reshaped to the provided\n shape for multi-dimensional atmospheres.\n For internal use.\n\n Parameters\n ----------\n shape : tuple\n Shape to reform the stratifications, provided by\n `Layout.dimensioned_shape`.\n\n Returns\n -------\n stratifications : Stratifications\n Reshaped stratifications.\n '''\n strat = copy(self)\n strat.cmass = self.cmass.reshape(shape)\n strat.tauRef = self.tauRef.reshape(shape)\n return strat\n\n def unit_view(self) -> 'Stratifications':\n '''\n Makes an instance of `Stratifications` with the correct `astropy.units`\n For internal use.\n\n Returns\n -------\n stratifications : Stratifications\n The same data with units applied.\n '''\n strat = copy(self)\n strat.cmass = self.cmass << u.kg / u.m**2\n strat.tauRef = self.tauRef << u.dimensionless_unscaled\n return strat\n\n def dimensioned_unit_view(self, shape) -> 'Stratifications':\n '''\n Makes an instance of `Stratifications` reshaped to the provided shape\n with the correct `astropy.units` for multi-dimensional atmospheres.\n For internal use.\n\n Parameters\n ----------\n shape : tuple\n Shape to reform the stratifications, provided by\n `Layout.dimensioned_shape`.\n\n Returns\n -------\n stratifications : Stratifications\n Reshaped stratifications with units.\n '''\n strat = self.dimensioned_view(shape)\n return strat.unit_view()\n\n@dataclass\nclass Layout:\n '''\n Storage for basic atmospheric parameters whose presence is determined by problem dimensionality, boundary conditions and optional stratifications.\n\n Attributes\n ----------\n Ndim : int\n Number of dimensions in model.\n\n x : np.ndarray\n Ordinates of grid points along the x-axis (present for Ndim >= 2) [m].\n y : np.ndarray\n Ordinates of grid points along the y-axis (present for Ndim == 3) [m].\n z : np.ndarray\n Ordinates of grid points along the z-axis (present for all Ndim) [m].\n vx : np.ndarray\n x component of plasma velocity (present for Ndim >= 2) [m/s].\n vy : np.ndarray\n y component of plasma velocity (present for Ndim == 3) [m/s].\n vz : np.ndarray\n z component of plasma velocity (present for all Ndim) [m/s]. Aliased to `vlos` when `Ndim==1`\n xLowerBc : BoundaryCondition\n Boundary condition for the plane of minimal x-coordinate.\n xUpperBc : BoundaryCondition\n Boundary condition for the plane of maximal x-coordinate.\n yLowerBc : BoundaryCondition\n Boundary condition for the plane of minimal y-coordinate.\n yUpperBc : BoundaryCondition\n Boundary condition for the plane of maximal y-coordinate.\n zLowerBc : BoundaryCondition\n Boundary condition for the plane of minimal z-coordinate.\n zUpperBc : BoundaryCondition\n Boundary condition for the plane of maximal z-coordinate.\n '''\n\n Ndim: int\n x: np.ndarray\n y: np.ndarray\n z: np.ndarray\n vx: np.ndarray\n vy: np.ndarray\n vz: np.ndarray\n xLowerBc: BoundaryCondition\n xUpperBc: BoundaryCondition\n yLowerBc: BoundaryCondition\n yUpperBc: BoundaryCondition\n zLowerBc: BoundaryCondition\n zUpperBc: BoundaryCondition\n stratifications: Optional[Stratifications] = None\n\n @classmethod\n def make_1d(cls, z: np.ndarray, vz: np.ndarray,\n lowerBc: BoundaryCondition, upperBc: BoundaryCondition,\n stratifications: Optional[Stratifications]=None) -> 'Layout':\n '''\n Construct 1D Layout.\n '''\n\n return cls(Ndim=1, x=np.array(()), y=np.array(()),\n z=z, vx=np.array(()), vy=np.array(()),\n vz=vz, xLowerBc=NoBc(), xUpperBc=NoBc(),\n yLowerBc=NoBc(), yUpperBc=NoBc(),\n zLowerBc=lowerBc, zUpperBc=upperBc,\n stratifications=stratifications)\n\n @classmethod\n def make_2d(cls, x: np.ndarray, z: np.ndarray,\n vx: np.ndarray, vz: np.ndarray,\n xLowerBc: BoundaryCondition, xUpperBc: BoundaryCondition,\n zLowerBc: BoundaryCondition, zUpperBc: BoundaryCondition,\n stratifications: Optional[Stratifications]=None) -> 'Layout':\n '''\n Construct 2D Layout.\n '''\n\n Bc = BoundaryCondition\n return cls(Ndim=2, x=x, y=np.array(()), z=z,\n vx=vx, vy=np.array(()), vz=vz,\n xLowerBc=xLowerBc, xUpperBc=xUpperBc,\n yLowerBc=NoBc(), yUpperBc=NoBc(),\n zLowerBc=zLowerBc, zUpperBc=zUpperBc,\n stratifications=stratifications)\n\n @classmethod\n def make_3d(cls, x: np.ndarray, y: np.ndarray, z: np.ndarray,\n vx: np.ndarray, vy: np.ndarray, vz: np.ndarray,\n xLowerBc: BoundaryCondition, xUpperBc: BoundaryCondition,\n yLowerBc: BoundaryCondition, yUpperBc: BoundaryCondition,\n zLowerBc: BoundaryCondition, zUpperBc: BoundaryCondition,\n stratifications: Optional[Stratifications]=None) -> 'Layout':\n '''\n Construct 3D Layout.\n '''\n\n return cls(Ndim=3, x=x, y=y, z=z,\n vx=vx, vy=vy, vz=vz,\n xLowerBc=xLowerBc, xUpperBc=xUpperBc,\n yLowerBc=yLowerBc, yUpperBc=yUpperBc,\n zLowerBc=zLowerBc, zUpperBc=zUpperBc,\n stratifications=stratifications)\n\n @property\n def Nx(self) -> int:\n '''\n Number of grid points along the x-axis.\n '''\n return self.x.shape[0]\n\n @property\n def Ny(self) -> int:\n '''\n Number of grid points along the y-axis.\n '''\n return self.y.shape[0]\n\n @property\n def Nz(self) -> int:\n '''\n Number of grid points along the z-axis.\n '''\n return self.z.shape[0]\n\n @property\n def Noutgoing(self) -> int:\n '''\n Number of grid points at which the outgoing radiation is computed.\n '''\n return max(1, self.Nx, self.Nx * self.Ny)\n\n @property\n def vlos(self) -> np.ndarray:\n if self.Ndim > 1:\n raise ValueError('vlos is ambiguous when Ndim > 1, use vx, vy, or vz instead.')\n return self.vz\n\n @property\n def Nspace(self) -> int:\n '''\n Number of spatial points present in the grid.\n '''\n if self.Ndim == 1:\n return self.Nz\n elif self.Ndim == 2:\n return self.Nx * self.Nz\n elif self.Ndim == 3:\n return self.Nx * self.Ny * self.Nz\n else:\n raise ValueError('Invalid Ndim: %d, check geometry initialisation' % self.Ndim)\n\n @property\n def tauRef(self):\n '''\n Alias to `self.stratifications.tauRef`, if computed.\n '''\n if self.stratifications is not None:\n return self.stratifications.tauRef\n else:\n raise ValueError('tauRef not computed for this Atmosphere')\n\n @property\n def cmass(self):\n '''\n Alias to `self.stratifications.cmass`, if computed.\n '''\n if self.stratifications is not None:\n return self.stratifications.cmass\n else:\n raise ValueError('tauRef not computed for this Atmosphere')\n\n @property\n def dimensioned_shape(self):\n '''\n Tuple defining the shape to which the arrays of atmospheric paramters\n can be reshaped to be indexed in a 1/2/3D fashion.\n '''\n if self.Ndim == 1:\n shape = (self.Nz,)\n elif self.Ndim == 2:\n shape = (self.Nz, self.Nx)\n elif self.Ndim == 3:\n shape = (self.Nz, self.Ny, self.Nx)\n else:\n raise ValueError('Unreasonable Ndim (%d)' % self.Ndim)\n return shape\n\n def dimensioned_view(self) -> 'Layout':\n '''\n Returns a view over the contents of Layout reshaped so all data has\n the correct (1/2/3D) dimensionality for the atmospheric model, as\n these are all stored under a flat scheme.\n '''\n layout = copy(self)\n shape = self.dimensioned_shape\n if self.stratifications is not None:\n layout.stratifications = self.stratifications.dimensioned_view(shape)\n if self.vx.size > 0:\n layout.vx = self.vx.reshape(shape)\n if self.vy.size > 0:\n layout.vy = self.vy.reshape(shape)\n if self.vz.size > 0:\n layout.vz = self.vz.reshape(shape)\n return layout\n\n def unit_view(self) -> 'Layout':\n '''\n Returns a view over the contents of the Layout with the correct\n `astropy.units`.\n '''\n layout = copy(self)\n layout.x = self.x << u.m\n layout.y = self.y << u.m\n layout.z = self.z << u.m\n layout.vx = self.vx << u.m / u.s\n layout.vy = self.vy << u.m / u.s\n layout.vz = self.vz << u.m / u.s\n if self.stratifications is not None:\n layout.stratifications = self.stratifications.unit_view()\n return layout\n\n def dimensioned_unit_view(self) -> 'Layout':\n '''\n Returns a view over the contents of Layout reshaped so all data has\n the correct (1/2/3D) dimensionality for the atmospheric model, and\n the correct `astropy.units`.\n '''\n layout = self.dimensioned_view()\n return layout.unit_view()\n\n@dataclass\nclass Atmosphere:\n '''\n Storage for all atmospheric data. These arrays will be shared directly\n with the backend, so a modification here also modifies the data seen by\n the backend. Be careful to modify these arrays *in place*, as their data\n is shared by direct memory reference. Use the class methods to construct\n atmospheres of different dimensionality.\n\n Attributes\n ----------\n structure : Layout\n A layout structure holding the atmospheric stratification, and\n velocity description.\n temperature : np.ndarray\n The atmospheric temperature structure.\n vturb : np.ndarray\n The atmospheric microturbulent velocity structure.\n ne : np.ndarray\n The electron density structure in the atmosphere.\n nHTot : np.ndarray\n The total hydrogen number density distribution throughout the\n atmosphere.\n B : np.ndarray, optional\n The magnitude of the stratified magnetic field throughout the\n atmosphere (Tesla).\n gammaB : np.ndarray, optional\n Co-altitude of magnetic field vector (radians) throughout the\n atmosphere from the local vertical.\n chiB : np.ndarray, optional\n Azimuth of magnetic field vector (radians) in the x-y plane, measured\n from the x-axis.\n '''\n\n structure: Layout\n temperature: np.ndarray\n vturb: np.ndarray\n ne: np.ndarray\n nHTot: np.ndarray\n B: Optional[np.ndarray] = None\n gammaB: Optional[np.ndarray] = None\n chiB: Optional[np.ndarray] = None\n\n @property\n def Ndim(self) -> int:\n '''\n Ndim : int\n The dimensionality (1, 2, or 3) of the atmospheric model.\n '''\n return self.structure.Ndim\n\n @property\n def Nx(self) -> int:\n '''\n Nx : int\n The number of points in the x-direction discretisation.\n '''\n return self.structure.Nx\n\n @property\n def Ny(self) -> int:\n '''\n Ny : int\n The number of points in the y-direction discretisation.\n '''\n return self.structure.Ny\n\n @property\n def Nz(self) -> int:\n '''\n Nz : int\n The number of points in the y-direction discretisation.\n '''\n return self.structure.Nz\n\n @property\n def Noutgoing(self) -> int:\n '''\n Noutgoing : int\n The number of cells at the top of the atmosphere (that each produce a\n spectrum).\n '''\n return self.structure.Noutgoing\n\n @property\n def vx(self) -> np.ndarray:\n '''\n vx : np.ndarray\n x component of plasma velocity (present for Ndim >= 2) [m/s].\n '''\n return self.structure.vx\n\n @property\n def vy(self) -> np.ndarray:\n '''\n vy : np.ndarray\n y component of plasma velocity (present for Ndim == 3) [m/s].\n '''\n return self.structure.vy\n\n @property\n def vz(self) -> np.ndarray:\n '''\n vz : np.ndarray\n z component of plasma velocity (present for all Ndim) [m/s]. Aliased\n to `vlos` when `Ndim==1`\n '''\n return self.structure.vz\n\n @property\n def vlos(self) -> np.ndarray:\n '''\n vz : np.ndarray\n z component of plasma velocity (present for all Ndim) [m/s]. Only\n available when Ndim==1`.\n '''\n return self.structure.vlos\n\n @property\n def cmass(self) -> np.ndarray:\n '''\n cmass : np.ndarray\n Column mass [kg m-2].\n '''\n return self.structure.cmass\n\n @property\n def tauRef(self) -> np.ndarray:\n '''\n tauRef : np.ndarray\n Reference optical depth at 500 nm.\n '''\n return self.structure.tauRef\n\n @property\n def height(self) -> np.ndarray:\n return self.structure.z\n\n @property\n def x(self) -> np.ndarray:\n '''\n x : np.ndarray\n Ordinates of grid points along the x-axis (present for Ndim >= 2) [m].\n '''\n return self.structure.x\n\n @property\n def y(self) -> np.ndarray:\n '''\n y : np.ndarray\n Ordinates of grid points along the y-axis (present for Ndim == 3) [m].\n '''\n return self.structure.y\n\n @property\n def z(self) -> np.ndarray:\n '''\n z : np.ndarray\n Ordinates of grid points along the z-axis (present for all Ndim) [m].\n '''\n return self.structure.z\n\n @property\n def zLowerBc(self) -> BoundaryCondition:\n '''\n zLowerBc : BoundaryCondition\n Boundary condition for the plane of minimal z-coordinate.\n '''\n return self.structure.zLowerBc\n\n @property\n def zUpperBc(self) -> BoundaryCondition:\n '''\n zUpperBc : BoundaryCondition\n Boundary condition for the plane of maximal z-coordinate.\n '''\n return self.structure.zUpperBc\n\n @property\n def yLowerBc(self) -> BoundaryCondition:\n '''\n yLowerBc : BoundaryCondition\n Boundary condition for the plane of minimal y-coordinate.\n '''\n return self.structure.yLowerBc\n\n @property\n def yUpperBc(self) -> BoundaryCondition:\n '''\n yUpperBc : BoundaryCondition\n Boundary condition for the plane of maximal y-coordinate.\n '''\n return self.structure.yUpperBc\n\n @property\n def xLowerBc(self) -> BoundaryCondition:\n '''\n xLowerBc : BoundaryCondition\n Boundary condition for the plane of minimal x-coordinate.\n '''\n return self.structure.xLowerBc\n\n @property\n def xUpperBc(self) -> BoundaryCondition:\n '''\n xUpperBc : BoundaryCondition\n Boundary condition for the plane of maximal x-coordinate.\n '''\n return self.structure.xUpperBc\n\n @property\n def Nspace(self):\n '''\n Nspace : int\n Total number of points in the atmospheric spatial discretistaion.\n '''\n return self.structure.Nspace\n\n @property\n def Nrays(self):\n '''\n Nrays : int\n Number of rays in angular discretisation used.\n '''\n if self.muz is None:\n raise AttributeError('Nrays not set, call atmos.rays or .quadrature first')\n\n return self.muz.shape[0]\n\n def dimensioned_view(self):\n '''\n Returns a view over the contents of Layout reshaped so all data has\n the correct (1/2/3D) dimensionality for the atmospheric model, as\n these are all stored under a flat scheme.\n '''\n shape = self.structure.dimensioned_shape\n atmos = copy(self)\n atmos.structure = self.structure.dimensioned_view()\n atmos.temperature = self.temperature.reshape(shape)\n atmos.vturb = self.vturb.reshape(shape)\n atmos.ne = self.ne.reshape(shape)\n atmos.nHTot = self.nHTot.reshape(shape)\n if self.B is not None:\n atmos.B = self.B.reshape(shape)\n atmos.chiB = self.chiB.reshape(shape)\n atmos.gammaB = self.gammaB.reshape(shape)\n return atmos\n\n def unit_view(self):\n '''\n Returns a view over the contents of the Layout with the correct\n `astropy.units`.\n '''\n atmos = copy(self)\n atmos.structure = self.structure.unit_view()\n atmos.temperature = self.temperature << u.K\n atmos.vturb = self.vturb << u.m / u.s\n atmos.ne = self.ne << u.m**(-3)\n atmos.nHTot = self.nHTot << u.m**(-3)\n if self.B is not None:\n atmos.B = self.B << u.T\n atmos.chiB = self.chiB << u.rad\n atmos.gammaB = self.gammaB << u.rad\n return atmos\n\n def dimensioned_unit_view(self):\n '''\n Returns a view over the contents of Layout reshaped so all data has\n the correct (1/2/3D) dimensionality for the atmospheric model, and\n the correct `astropy.units`.\n '''\n atmos = self.dimensioned_view()\n return atmos.unit_view()\n\n @classmethod\n def make_1d(cls, scale: ScaleType, depthScale: np.ndarray,\n temperature: np.ndarray, vlos: np.ndarray,\n vturb: np.ndarray, ne: Optional[np.ndarray]=None,\n hydrogenPops: Optional[np.ndarray]=None,\n nHTot: Optional[np.ndarray]=None,\n B: Optional[np.ndarray]=None,\n gammaB: Optional[np.ndarray]=None,\n chiB: Optional[np.ndarray]=None,\n lowerBc: Optional[BoundaryCondition]=None,\n upperBc: Optional[BoundaryCondition]=None,\n convertScales: bool=True,\n abundance: Optional[AtomicAbundance]=None,\n logG: float=2.44,\n Pgas: Optional[np.ndarray]=None,\n Pe: Optional[np.ndarray]=None,\n Ptop: Optional[float]=None,\n PeTop: Optional[float]=None,\n verbose: bool=False):\n '''\n Constructor for 1D Atmosphere objects. Optionally will use an\n equation of state (EOS) to estimate missing parameters.\n\n If sufficient information is provided (i.e. all required parameters\n and ne and (hydrogenPops or nHTot)) then the EOS is not invoked to\n estimate any thermodynamic properties. If both of nHTot and\n hydrogenPops are omitted, then the electron pressure will be used\n with the Wittmann equation of state to estimate the mass density, and\n the hydrogen number density will be inferred from this and the\n abundances. If, instead, ne is omitted, then the mass density will be\n used with the Wittmann EOS to estimate the electron pressure.\n If both of these are omitted then the EOS will be used to estimate\n both. If:\n\n - Pgas is provided, then this gas pressure will define the\n atmospheric stratification and will be used with the EOS.\n\n - Pe is provided, then this electron pressure will define the\n atmospheric stratification and will be used with the EOS.\n\n - Ptop is provided, then this gas pressure at the top of the\n atmosphere will be used with the log gravitational acceleration\n logG, and the EOS to estimate the missing parameters assuming\n hydrostatic equilibrium.\n\n - PeTop is provided, then this electron pressure at the top of\n the atmosphere will be used with the log gravitational\n acceleration logG, and the EOS to estimate the missing parameters\n assuming hydrostatic equilibrium.\n\n - If all of Pgas, Pe, Ptop, PeTop are omitted then Ptop will be\n estimated from the gas pressure in the FALC model at the\n temperature at the top boundary. The hydrostatic reconstruction\n will then continue as usual.\n\n convertScales will substantially slow down this function due to the\n slow calculation of background opacities used to compute tauRef. If\n an atmosphere is constructed with a Geometric stratification, and an\n estimate of tauRef is not required before running the main RT module,\n then this can be set to False.\n All of these parameters can be provided as astropy Quantities, and\n will be converted in the constructor.\n\n Parameters\n ----------\n scale : ScaleType\n The type of stratification used along the z-axis.\n depthScale : np.ndarray\n The z-coordinates used along the chosen stratification. The\n stratification is expected to start at the top of the atmosphere\n (closest to the observer), and descend along the observer's line\n of sight.\n temperature : np.ndarray\n Temperature structure of the atmosphere [K].\n vlos : np.ndarray\n Velocity structure of the atmosphere along z [m/s].\n vturb : np.ndarray\n Microturbulent velocity structure of the atmosphere [m/s].\n ne : np.ndarray\n Electron density structure of the atmosphere [m-3].\n hydrogenPops : np.ndarray, optional\n Detailed (per level) hydrogen number density structure of the\n atmosphere [m-3], 2D array [Nlevel, Nspace].\n nHTot : np.ndarray, optional\n Total hydrogen number density structure of the atmosphere [m-3]\n B : np.ndarray, optional.\n Magnetic field strength [T].\n gammaB : np.ndarray, optional\n Co-altitude of magnetic field vector [radians].\n chiB : np.ndarray, optional\n Azimuth of magnetic field vector (in x-y plane, from x) [radians].\n lowerBc : BoundaryCondition, optional\n Boundary condition for incoming radiation at the minimal z\n coordinate (default: ThermalisedRadiation).\n upperBc : BoundaryCondition, optional\n Boundary condition for incoming radiation at the maximal z\n coordinate (default: ZeroRadiation).\n convertScales : bool, optional\n Whether to automatically compute tauRef and cmass for an\n atmosphere given in a stratification of m (default: True).\n abundance: AtomicAbundance, optional\n An instance of AtomicAbundance giving the abundances of each\n atomic species in the given atmosphere, only used if the EOS is\n invoked. (default: DefaultAtomicAbundance)\n logG: float, optional\n The log10 of the magnitude of gravitational acceleration [m/s2]\n (default: 2.44).\n Pgas: np.ndarray, optional\n The gas pressure stratification of the atmosphere [Pa],\n optionally used by the EOS.\n Pe: np.ndarray, optional\n The electron pressure stratification of the atmosphere [Pa],\n optionally used by the EOS.\n Ptop: np.ndarray, optional\n The gas pressure at the top of the atmosphere [Pa], optionally\n used by the EOS for a hydrostatic reconstruction.\n Petop: np.ndarray, optional\n The electron pressure at the top of the atmosphere [Pa],\n optionally used by the EOS for a hydrostatic reconstruction.\n verbose: bool, optional\n Explain decisions made with the EOS to estimate missing\n parameters (if invoked) through print calls (default: False).\n\n Raises\n ------\n ValueError\n if incorrect arguments or unable to construct estimate missing\n parameters.\n '''\n if scale == ScaleType.Geometric:\n depthScale = (depthScale << u.m).value\n elif scale == ScaleType.ColumnMass:\n depthScale = (depthScale << u.kg / u.m**2).value\n temperature = (temperature << u.K).value\n vlos = (vlos << u.m / u.s).value\n vturb = (vturb << u.m / u.s).value\n if ne is not None:\n ne = (ne << u.m**(-3)).value\n if hydrogenPops is not None:\n hydrogenPops = (hydrogenPops << u.m**(-3)).value\n if nHTot is not None:\n nHTot = (nHTot << u.m**(-3)).value\n if B is not None:\n B = (B << u.T).value\n if gammaB is not None:\n gammaB = (gammaB << u.rad).value\n if chiB is not None:\n chiB = (chiB << u.rad).value\n\n if lowerBc is None:\n lowerBc = ThermalisedRadiation()\n elif isinstance(lowerBc, PeriodicRadiation):\n raise ValueError('Cannot set periodic boundary conditions for 1D atmosphere')\n if upperBc is None:\n upperBc = ZeroRadiation()\n elif isinstance(upperBc, PeriodicRadiation):\n raise ValueError('Cannot set periodic boundary conditions for 1D atmosphere')\n\n if scale != ScaleType.Geometric and not convertScales:\n raise ValueError('Height scale must be provided if scale conversion is not applied')\n\n if nHTot is None and hydrogenPops is not None:\n nHTot = np.sum(hydrogenPops, axis=0)\n\n if np.any(temperature < 2000):\n # NOTE(cmo): Minimum value was decreased in NICOLE so should be safe\n raise ValueError('Minimum temperature too low for EOS (< 2000 K)')\n\n if abundance is None:\n abundance = DefaultAtomicAbundance\n\n wittAbundances = np.array([abundance[e] for e in PeriodicTable.elements])\n eos = witt(abund_init=wittAbundances)\n\n Nspace = depthScale.shape[0]\n if nHTot is None and ne is not None:\n if verbose:\n print('Setting nHTot from electron pressure.')\n pe = ne * Const.CM_TO_M**3 * eos.BK * temperature\n rho = np.zeros(Nspace)\n for k in range(Nspace):\n rho[k] = eos.rho_from_pe(temperature[k], pe[k])\n nHTot = np.copy(rho / (Const.CM_TO_M**3 / Const.G_TO_KG) / (Const.Amu * abundance.massPerH))\n elif ne is None and nHTot is not None:\n if verbose:\n print('Setting ne from mass density.')\n rho = Const.Amu * abundance.massPerH * nHTot * Const.CM_TO_M**3 / Const.G_TO_KG\n pe = np.zeros(Nspace)\n for k in range(Nspace):\n pe[k] = eos.pe_from_rho(temperature[k], rho[k])\n ne = np.copy(pe / (eos.BK * temperature) / Const.CM_TO_M**3)\n elif ne is None and nHTot is None:\n if Pgas is not None and Pgas.shape[0] != Nspace:\n raise ValueError('Dimensions of Pgas do not match atmospheric depth')\n if Pe is not None and Pe.shape[0] != Nspace:\n raise ValueError('Dimensions of Pe do not match atmospheric depth')\n\n if Pgas is not None and Pe is None:\n if verbose:\n print('Setting ne, nHTot from provided gas pressure.')\n # Convert to cgs for eos\n pgas = Pgas * (Const.CM_TO_M**2 / Const.G_TO_KG)\n pe = np.zeros(Nspace)\n for k in range(Nspace):\n pe[k] = eos.pe_from_pg(temperature[k], pgas[k])\n elif Pe is not None and Pgas is None:\n if verbose:\n print('Setting ne, nHTot from provided electron pressure.')\n # Convert to cgs for eos\n pe = Pe * (Const.CM_TO_M**2 / Const.G_TO_KG)\n pgas = np.zeros(Nspace)\n for k in range(Nspace):\n pgas[k] = eos.pg_from_pe(temperature[k], pe[k])\n elif Pgas is None and Pe is None:\n # Doing Hydrostatic Eq. based here on NICOLE implementation\n gravAcc = 10**logG / Const.CM_TO_M\n Avog = 6.022045e23 # Avogadro's Number\n if Ptop is None and PeTop is not None:\n if verbose:\n print('Setting ne, nHTot to hydrostatic equilibrium (logG=%f) from provided top electron pressure.' % logG)\n PeTop *= (Const.CM_TO_M**2 / Const.G_TO_KG)\n Ptop = eos.pg_from_pe(temperature[0], PeTop)\n elif Ptop is not None and PeTop is None:\n if verbose:\n print('Setting ne, nHTot to hydrostatic equilibrium (logG=%f) from provided top gas pressure.' % logG)\n Ptop *= (Const.CM_TO_M**2 / Const.G_TO_KG)\n PeTop = eos.pe_from_pg(temperature[0], Ptop)\n elif Ptop is None and PeTop is None:\n if verbose:\n print('Setting ne, nHTot to hydrostatic equilibrium (logG=%f) from FALC gas pressure at upper boundary temperature.' % logG)\n Ptop = get_top_pressure(eos, temperature[0])\n PeTop = eos.pe_from_pg(temperature[0], Ptop)\n else:\n raise ValueError(\"Cannot set both Ptop and PeTop\")\n\n if scale == ScaleType.Tau500:\n tau = depthScale\n elif scale == ScaleType.Geometric:\n height = depthScale / Const.CM_TO_M\n else:\n cmass = depthScale / Const.G_TO_KG * Const.CM_TO_M**2\n\n # NOTE(cmo): Compute HSE following the NICOLE method.\n rho = np.zeros(Nspace)\n chi_c = np.zeros(Nspace)\n pgas = np.zeros(Nspace)\n pe = np.zeros(Nspace)\n pgas[0] = Ptop\n pe[0] = PeTop\n chi_c[0] = eos.contOpacity(temperature[0], pgas[0], pe[0], np.array([5000.0]))\n avg_mol_weight = lambda k: abundance.massPerH / (abundance.totalAbundance + pe[k] / pgas[k])\n rho[0] = Ptop * avg_mol_weight(0) / Avog / eos.BK / temperature[0]\n chi_c[0] /= rho[0]\n\n for k in range(1, Nspace):\n chi_c[k] = chi_c[k-1]\n rho[k] = rho[k-1]\n for it in range(200):\n if scale == ScaleType.Tau500:\n dtau = tau[k] - tau[k-1]\n pgas[k] = pgas[k-1] + gravAcc * dtau / (0.5 * (chi_c[k-1] + chi_c[k]))\n elif scale == ScaleType.Geometric:\n pgas[k] = pgas[k-1] * np.exp(-gravAcc / Avog / eos.BK * avg_mol_weight(k-1) * 0.5 * (1.0 / temperature[k-1] + 1.0 / temperature[k]) * (height[k] - height[k-1]))\n else:\n pgas[k] = gravAcc * cmass[k]\n\n pe[k] = eos.pe_from_pg(temperature[k], pgas[k])\n prevChi = chi_c[k]\n chi_c[k] = eos.contOpacity(temperature[k], pgas[k], pe[k], np.array([5000.0]))\n rho[k] = pgas[k] * avg_mol_weight(k) / Avog / eos.BK / temperature[k]\n chi_c[k] /= rho[k]\n\n change = np.abs(prevChi - chi_c[k]) / (prevChi + chi_c[k])\n if change < 1e-5:\n break\n else:\n raise ConvergenceError('No convergence in HSE at depth point %d, last change %2.4e' % (k, change))\n nHTot = np.copy(rho / (Const.CM_TO_M**3 / Const.G_TO_KG) / (Const.Amu * abundance.massPerH))\n ne = np.copy(pe / (eos.BK * temperature) / Const.CM_TO_M**3)\n\n # NOTE(cmo): Compute final pgas, pe from EOS that will be used for\n # background opacity.\n rhoSI = Const.Amu * abundance.massPerH * nHTot\n rho = Const.Amu * abundance.massPerH * nHTot * Const.CM_TO_M**3 / Const.G_TO_KG\n pgas = np.zeros_like(depthScale)\n pe = np.zeros_like(depthScale)\n for k in range(Nspace):\n pgas[k] = eos.pg_from_rho(temperature[k], rho[k])\n pe[k] = eos.pe_from_rho(temperature[k], rho[k])\n\n chi_c = np.zeros_like(depthScale)\n for k in range(depthScale.shape[0]):\n chi_c[k] = eos.contOpacity(temperature[k], pgas[k], pe[k], np.array([5000.0])) / Const.CM_TO_M\n\n # NOTE(cmo): We should now have a uniform minimum set of data (other\n # than the scale type), allowing us to simply convert between the\n # scales we do have!\n if convertScales:\n if scale == ScaleType.ColumnMass:\n height = np.zeros_like(depthScale)\n tau_ref = np.zeros_like(depthScale)\n cmass = depthScale\n\n height[0] = 0.0\n tau_ref[0] = chi_c[0] / rhoSI[0] * cmass[0]\n for k in range(1, cmass.shape[0]):\n height[k] = height[k-1] - 2.0 * (cmass[k] - cmass[k-1]) / (rhoSI[k-1] + rhoSI[k])\n tau_ref[k] = tau_ref[k-1] + 0.5 * (chi_c[k-1] + chi_c[k]) * (height[k-1] - height[k])\n\n hTau1 = np.interp(1.0, tau_ref, height)\n height -= hTau1\n elif scale == ScaleType.Geometric:\n cmass = np.zeros(Nspace)\n tau_ref = np.zeros(Nspace)\n height = depthScale\n\n cmass[0] = (nHTot[0] * abundance.massPerH + ne[0]) * (Const.KBoltzmann * temperature[0] / 10**logG)\n tau_ref[0] = 0.5 * chi_c[0] * (height[0] - height[1])\n if tau_ref[0] > 1.0:\n tau_ref[0] = 0.0\n\n for k in range(1, Nspace):\n cmass[k] = cmass[k-1] + 0.5 * (rhoSI[k-1] + rhoSI[k]) * (height[k-1] - height[k])\n tau_ref[k] = tau_ref[k-1] + 0.5 * (chi_c[k-1] + chi_c[k]) * (height[k-1] - height[k])\n elif scale == ScaleType.Tau500:\n cmass = np.zeros(Nspace)\n height = np.zeros(Nspace)\n tau_ref = depthScale\n\n cmass[0] = (tau_ref[0] / chi_c[0]) * rhoSI[0]\n for k in range(1, Nspace):\n height[k] = height[k-1] - 2.0 * (tau_ref[k] - tau_ref[k-1]) / (chi_c[k-1] + chi_c[k])\n cmass[k] = cmass[k-1] + 0.5 * (chi_c[k-1] + chi_c[k]) * (height[k-1] - height[k])\n\n hTau1 = np.interp(1.0, tau_ref, height)\n height -= hTau1\n else:\n raise ValueError(\"Other scales not handled yet\")\n\n stratifications: Optional[Stratifications] = Stratifications(cmass=cmass, tauRef=tau_ref)\n\n else:\n stratifications = None\n\n layout = Layout.make_1d(z=height, vz=vlos,\n lowerBc=lowerBc, upperBc=upperBc,\n stratifications=stratifications)\n atmos = cls(structure=layout, temperature=temperature, vturb=vturb,\n ne=ne, nHTot=nHTot, B=B, gammaB=gammaB, chiB=chiB)\n\n return atmos\n\n @classmethod\n def make_2d(cls, height: np.ndarray, x: np.ndarray,\n temperature: np.ndarray, vx: np.ndarray,\n vz: np.ndarray, vturb: np.ndarray,\n ne: Optional[np.ndarray]=None,\n nHTot: Optional[np.ndarray]=None,\n B: Optional[np.ndarray]=None,\n gammaB: Optional[np.ndarray]=None,\n chiB: Optional[np.ndarray]=None,\n xUpperBc: Optional[BoundaryCondition]=None,\n xLowerBc: Optional[BoundaryCondition]=None,\n zUpperBc: Optional[BoundaryCondition]=None,\n zLowerBc: Optional[BoundaryCondition]=None,\n abundance: Optional[AtomicAbundance]=None,\n verbose=False):\n '''\n Constructor for 2D Atmosphere objects.\n\n No provision for estimating parameters using hydrostatic equilibrium\n is provided, but one of ne, or nHTot can be omitted and inferred by\n use of the Wittmann equation of state.\n The atmosphere must be defined on a geometric stratification.\n All atmospheric parameters are expected in a 2D [z, x] array.\n\n Parameters\n ----------\n height : np.ndarray\n The z-coordinates of the atmospheric grid. The stratification is\n expected to start at the top of the atmosphere (closest to the\n observer), and descend along the observer's line of sight.\n x : np.ndarray\n The (horizontal) x-coordinates of the atmospheric grid.\n temperature : np.ndarray\n Temperature structure of the atmosphere [K].\n vx : np.ndarray\n x-component of the atmospheric velocity [m/s].\n vz : np.ndarray\n z-component of the atmospheric velocity [m/s].\n vturb : np.ndarray\n Microturbulent velocity structure [m/s].\n ne : np.ndarray\n Electron density structure of the atmosphere [m-3].\n nHTot : np.ndarray, optional\n Total hydrogen number density structure of the atmosphere [m-3].\n B : np.ndarray, optional.\n Magnetic field strength [T].\n gammaB : np.ndarray, optional\n Co-altitude of magnetic field vector [radians].\n chiB : np.ndarray, optional\n Azimuth of magnetic field vector (in x-y plane, from x) [radians].\n xLowerBc : BoundaryCondition, optional\n Boundary condition for incoming radiation at the minimal x\n coordinate (default: PeriodicRadiation).\n xUpperBc : BoundaryCondition, optional\n Boundary condition for incoming radiation at the maximal x\n coordinate (default: PeriodicRadiation).\n zLowerBc : BoundaryCondition, optional\n Boundary condition for incoming radiation at the minimal z\n coordinate (default: ThermalisedRadiation).\n zUpperBc : BoundaryCondition, optional\n Boundary condition for incoming radiation at the maximal z\n coordinate (default: ZeroRadiation).\n convertScales : bool, optional\n Whether to automatically compute tauRef and cmass for an\n atmosphere given in a stratification of m (default: True).\n abundance: AtomicAbundance, optional\n An instance of AtomicAbundance giving the abundances of each\n atomic species in the given atmosphere, only used if the EOS is\n invoked. (default: DefaultAtomicAbundance)\n verbose: bool, optional\n Explain decisions made with the EOS to estimate missing\n parameters (if invoked) through print calls (default: False).\n\n Raises\n ------\n ValueError\n if incorrect arguments or unable to construct estimate missing\n parameters.\n '''\n\n x = (x << u.m).value\n height = (height << u.m).value\n temperature = (temperature << u.K).value\n vx = (vx << u.m / u.s).value\n vz = (vz << u.m / u.s).value\n vturb = (vturb << u.m / u.s).value\n if ne is not None:\n ne = (ne << u.m**(-3)).value\n if nHTot is not None:\n nHTot = (nHTot << u.m**(-3)).value\n if B is not None:\n B = (B << u.T).value\n flatB = view_flatten(B)\n else:\n flatB = None\n\n if gammaB is not None:\n gammaB = (gammaB << u.rad).value\n flatGammaB = view_flatten(gammaB)\n else:\n flatGammaB = None\n\n if chiB is not None:\n chiB = (chiB << u.rad).value\n flatChiB = view_flatten(chiB)\n else:\n flatChiB = None\n\n if zLowerBc is None:\n zLowerBc = ThermalisedRadiation()\n elif isinstance(zLowerBc, PeriodicRadiation):\n raise ValueError('Cannot set periodic boundary conditions for z-axis.')\n if zUpperBc is None:\n zUpperBc = ZeroRadiation()\n elif isinstance(zUpperBc, PeriodicRadiation):\n raise ValueError('Cannot set periodic boundary conditions for z-axis.')\n if xUpperBc is None:\n xUpperBc = PeriodicRadiation()\n if xLowerBc is None:\n xLowerBc = PeriodicRadiation()\n if abundance is None:\n\n abundance = DefaultAtomicAbundance\n\n wittAbundances = np.array([abundance[e] for e in PeriodicTable.elements])\n eos = witt(abund_init=wittAbundances)\n\n flatHeight = view_flatten(height)\n flatTemperature = view_flatten(temperature)\n Nspace = flatHeight.shape[0]\n if nHTot is None and ne is not None:\n if verbose:\n print('Setting nHTot from electron pressure.')\n flatNe = view_flatten(ne)\n pe = flatNe * Const.CM_TO_M**3 * eos.BK * flatTemperature\n rho = np.zeros(Nspace)\n for k in range(Nspace):\n rho[k] = eos.rho_from_pe(flatTemperature[k], pe[k])\n nHTot = np.copy(rho / (Const.CM_TO_M**3 / Const.G_TO_KG) / (Const.Amu * abundance.massPerH))\n elif ne is None and nHTot is not None:\n if verbose:\n print('Setting ne from mass density.')\n flatNHTot = view_flatten(nHTot)\n rho = Const.Amu * abundance.massPerH * flatNHTot * Const.CM_TO_M**3 / Const.G_TO_KG\n pe = np.zeros(Nspace)\n for k in range(Nspace):\n pe[k] = eos.pe_from_rho(flatTemperature[k], rho[k])\n ne = np.copy(pe / (eos.BK * flatTemperature) / Const.CM_TO_M**3)\n elif ne is None and nHTot is None:\n raise ValueError('Cannot omit both ne and nHTot (currently).')\n flatX = view_flatten(x)\n flatNHTot = view_flatten(nHTot)\n flatNe = view_flatten(ne)\n flatVx = view_flatten(vx)\n flatVz = view_flatten(vz)\n flatVturb = view_flatten(vturb)\n\n layout = Layout.make_2d(x=flatX, z=flatHeight, vx=flatVx, vz=flatVz,\n xLowerBc=xLowerBc, xUpperBc=xUpperBc,\n zLowerBc=zLowerBc, zUpperBc=zUpperBc,\n stratifications=None)\n\n atmos = cls(structure=layout, temperature=flatTemperature,\n vturb=flatVturb, ne=flatNe, nHTot=flatNHTot, B=flatB,\n gammaB=flatGammaB, chiB=flatChiB)\n return atmos\n\n\n def quadrature(self, Nrays: Optional[int]=None,\n mu: Optional[Sequence[float]]=None,\n wmu: Optional[Sequence[float]]=None):\n '''\n Compute the angular quadrature for solving the RTE and Kinetic\n Equilibrium in a given atmosphere.\n\n Procedure varies with dimensionality.\n\n By convention muz is always positive, as the direction on this axis\n is determined by the toObs term that is used internally to the formal\n solver.\n\n 1D:\n If a number of rays is given (typically 3 or 5), then the\n Gauss-Legendre quadrature for this set is used.\n If mu and wmu are instead given then these will be validated and\n used.\n\n 2+D:\n If the number of rays selected is in the list of near optimal\n quadratures for unpolarised radiation provided by Stepan et al\n 2020 (A&A, 646 A24), then this is used. Otherwise an exception is\n raised.\n\n The available quadratures are:\n\n +--------+-------+\n | Points | Order |\n +========+=======+\n | 1 | 3 |\n +--------+-------+\n | 3 | 7 |\n +--------+-------+\n | 6 | 9 |\n +--------+-------+\n | 7 | 11 |\n +--------+-------+\n | 10 | 13 |\n +--------+-------+\n | 11 | 15 |\n +--------+-------+\n\n Parameters\n ----------\n Nrays : int, optional\n The number of rays to use in the quadrature. See notes above.\n mu : sequence of float, optional\n The cosine of the angle made between the between each of the set\n of rays and the z axis, only used in 1D.\n wmu : sequence of float, optional\n The integration weights for each mu, must be provided if mu is provided.\n\n Raises\n ------\n ValueError\n on incorrect input.\n '''\n\n if self.Ndim == 1:\n if Nrays is not None and mu is None:\n if Nrays >= 1:\n x, w = leggauss(Nrays)\n mid, halfWidth = 0.5, 0.5\n x = mid + halfWidth * x\n w *= halfWidth\n\n self.muz = x\n self.wmu = w\n else:\n raise ValueError('Unsupported Nrays=%d' % Nrays)\n elif Nrays is not None and mu is not None:\n if wmu is None:\n raise ValueError('Must provide wmu when providing mu')\n if Nrays != len(mu):\n raise ValueError('mu must be Nrays long if Nrays is provided')\n if len(mu) != len(wmu):\n raise ValueError('mu and wmu must be the same shape')\n\n self.muz = np.array(mu)\n self.wmu = np.array(wmu)\n\n self.muy = np.zeros_like(self.muz)\n self.mux = np.sqrt(1.0 - self.muz**2)\n else:\n with open(get_data_path() + 'Quadratures.pickle', 'rb') as pkl:\n quads = pickle.load(pkl)\n\n rays = {int(q.split('n')[1]): q for q in quads}\n if Nrays not in rays:\n raise ValueError('For multidimensional cases Nrays must be in %s' % repr(rays))\n\n quad = quads[rays[Nrays]]\n\n if self.Ndim == 2:\n Nrays *= 2\n theta = np.deg2rad(quad[:, 1])\n chi = np.deg2rad(quad[:, 2])\n # polar coords:\n # x = sin theta cos chi\n # y = sin theta sin chi\n # z = cos theta\n self.mux = np.zeros(Nrays)\n self.mux[:Nrays // 2] = np.sin(theta) * np.cos(chi)\n self.mux[Nrays // 2:] = -np.sin(theta) * np.cos(chi)\n self.muz = np.zeros(Nrays)\n self.muz[:Nrays // 2] = np.cos(theta)\n self.muz[Nrays // 2:] = np.cos(theta)\n self.wmu = np.zeros(Nrays)\n self.wmu[:Nrays // 2] = quad[:, 0]\n self.wmu[Nrays // 2:] = quad[:, 0]\n self.wmu /= np.sum(self.wmu)\n self.muy = np.sqrt(1.0 - (self.mux**2 + self.muz**2))\n\n else:\n raise NotImplementedError()\n\n self.configure_bcs()\n\n\n def rays(self, muz: Union[float, Sequence[float]],\n mux: Optional[Union[float, Sequence[float]]]=None,\n muy: Optional[Union[float, Sequence[float]]]=None,\n wmu: Optional[Union[float, Sequence[float]]]=None):\n '''\n Set up the rays on the Atmosphere for computing the intensity in a\n particular direction (or set of directions).\n\n If only the z angle is set then the ray is assumed in the x-z plane.\n If either muz or muy is omitted then this angle is inferred by\n normalisation of the projection.\n\n By convention muz is always positive, as the direction on this axis\n is determined by the toObs term that is used internally to the formal\n solver.\n\n Parameters\n ----------\n muz : float or sequence of float, optional\n The angular projections along the z axis.\n mux : float or sequence of float, optional\n The angular projections along the x axis.\n muy : float or sequence of float, optional\n The angular projections along the y axis.\n wmu : float or sequence of float, optional\n The integration weights for the given ray if J is to be\n integrated for angle set.\n\n Raises\n ------\n ValueError\n if the angular projections or integration weights are incorrectly\n normalised.\n '''\n\n if isinstance(muz, float):\n muz = [muz]\n if isinstance(mux, float):\n mux = [mux]\n if isinstance(muy, float):\n muy = [muy]\n\n if mux is None and muy is None:\n self.muz = np.array(muz)\n self.wmu = np.zeros_like(self.muz)\n self.muy = np.zeros_like(self.muz)\n self.mux = np.sqrt(1.0 - self.muz**2)\n elif muy is None:\n self.muz = np.array(muz)\n self.wmu = np.zeros_like(self.muz)\n self.mux = np.array(mux)\n self.muy = np.sqrt(1.0 - (self.muz**2 + self.mux**2))\n elif mux is None:\n self.muz = np.array(muz)\n self.wmu = np.zeros_like(self.muz)\n self.muy = np.array(muy)\n self.mux = np.sqrt(1.0 - (self.muz**2 + self.muy**2))\n else:\n self.muz = np.array(muz)\n self.mux = np.array(mux)\n self.muy = np.array(muy)\n self.wmu = np.zeros_like(muz)\n\n if not np.allclose(self.muz**2 + self.mux**2 + self.muy**2, 1):\n raise ValueError('mux**2 + muy**2 + muz**2 != 1.0')\n\n if not np.all(self.muz > 0):\n raise ValueError('muz must be > 0')\n\n if wmu is not None:\n self.wmu = np.array(wmu)\n\n if not np.isclose(self.wmu.sum(), 1.0):\n raise ValueError('sum of wmus is not 1.0')\n\n self.configure_bcs()\n\n def configure_bcs(self):\n '''\n Configure the required angular information for all boundary\n conditions on the model.\n '''\n\n # NOTE(cmo): We always have z-bcs\n # For zLowerBc, muz is positive, and we have all mux, muz\n mux, muy, muz = self.mux, self.muy, self.muz\n # NOTE(cmo): indexVector is of shape (mu, toObs) to allow the core to\n # easily destructure the blob that will be handed to it from\n # compute_bc.\n indexVector = np.ones((self.mux.shape[0], 2), dtype=np.int32) * -1\n indexVector[:, 1] = np.arange(mux.shape[0])\n self.zLowerBc.set_required_angles(mux, muy, muz, indexVector)\n\n indexVector = np.ones((mux.shape[0], 2), dtype=np.int32) * -1\n indexVector[:, 0] = np.arange(mux.shape[0])\n self.zUpperBc.set_required_angles(-mux, -muy, -muz, indexVector)\n\n # NOTE(cmo): If 2+D we have x-bcs too\n # xLowerBc has all muz and all mux > 0\n mux, muy, muz = [], [], []\n indexVector = np.ones((self.mux.shape[0], 2), dtype=np.int32) * -1\n count = 0\n musDone = np.zeros(self.muz.shape[0], dtype=np.bool)\n for mu in range(self.muz.shape[0]):\n for equalMu in np.argwhere(np.abs(self.muz) == self.muz[mu]).reshape(-1)[::-1]:\n if musDone[equalMu]:\n continue\n musDone[equalMu] = True\n\n for toObsI in range(2):\n sign = [-1, 1][toObsI]\n sMux = sign * self.mux[equalMu]\n if sMux > 0:\n mux.append(sMux)\n muy.append(sign * self.muy[equalMu])\n muz.append(sign * self.muz[equalMu])\n indexVector[equalMu, toObsI] = count\n count += 1\n if np.all(musDone):\n break\n\n mux = np.array(mux)\n muy = np.array(muy)\n muz = np.array(muz)\n self.xLowerBc.set_required_angles(mux, muy, muz, indexVector)\n\n mux, muy, muz = [], [], []\n indexVector = np.ones((self.mux.shape[0], 2), dtype=np.int32) * -1\n count = 0\n musDone = np.zeros(self.muz.shape[0], dtype=np.bool)\n for mu in range(self.muz.shape[0]):\n for equalMu in np.argwhere(np.abs(self.muz) == self.muz[mu]).reshape(-1):\n if musDone[equalMu]:\n continue\n musDone[equalMu] = True\n\n for toObsI in range(2):\n sign = [-1, 1][toObsI]\n sMux = sign * self.mux[equalMu]\n if sMux < 0:\n mux.append(sMux)\n muy.append(sign * self.muy[equalMu])\n muz.append(sign * self.muz[equalMu])\n indexVector[equalMu, toObsI] = count\n count += 1\n if np.all(musDone):\n break\n\n mux = np.array(mux)\n muy = np.array(muy)\n muz = np.array(muz)\n self.xUpperBc.set_required_angles(mux, muy, muz, indexVector)\n\n self.yLowerBc.set_required_angles(np.zeros((0)), np.zeros((0)), np.zeros((0)),\n np.ones((self.mux.shape[0], 2), dtype=np.int32) * -1)\n self.yUpperBc.set_required_angles(np.zeros((0)), np.zeros((0)), np.zeros((0)),\n np.ones((self.mux.shape[0], 2), dtype=np.int32) * -1)\n\n if self.Ndim > 2:\n raise ValueError('Only <= 2D atmospheres supported currently.')\n", "meta": {"hexsha": "46d9d0a05506f4622b68c99a655e3b800e3cd53d", "size": 59111, "ext": "py", "lang": "Python", "max_stars_repo_path": "lightweaver/atmosphere.py", "max_stars_repo_name": "aasensio/Lightweaver", "max_stars_repo_head_hexsha": "9a261e72235f05df548148da140012f40dbd1e4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lightweaver/atmosphere.py", "max_issues_repo_name": "aasensio/Lightweaver", "max_issues_repo_head_hexsha": "9a261e72235f05df548148da140012f40dbd1e4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lightweaver/atmosphere.py", "max_forks_repo_name": "aasensio/Lightweaver", "max_forks_repo_head_hexsha": "9a261e72235f05df548148da140012f40dbd1e4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4586857515, "max_line_length": 188, "alphanum_fraction": 0.5666965539, "include": true, "reason": "import numpy,from numpy,import astropy", "num_tokens": 14274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.23370636225126956, "lm_q1q2_score": 0.13850995174021605}} {"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\nfrom warnings import warn\nimport collections\nimport socket\nimport json\nimport urllib.request\nimport urllib.error\nimport urllib.parse\n\nimport numpy as np\nimport erfa\n\nfrom astropy import units as u\nfrom astropy import constants as consts\nfrom astropy.units.quantity import QuantityInfoBase\nfrom astropy.utils.exceptions import AstropyUserWarning\nfrom .angles import Angle, Longitude, Latitude\nfrom .representation import CartesianRepresentation, CartesianDifferential\nfrom .errors import UnknownSiteException\nfrom astropy.utils import data\n\n\n__all__ = ['EarthLocation']\n\nGeodeticLocation = collections.namedtuple('GeodeticLocation', ['lon', 'lat', 'height'])\n\n# Available ellipsoids (defined in erfam.h, with numbers exposed in erfa).\nELLIPSOIDS = ('WGS84', 'GRS80', 'WGS72')\n\nOMEGA_EARTH = u.Quantity(7.292115855306589e-5, 1./u.s)\n\"\"\"\nRotational velocity of Earth. In UT1 seconds, this would be 2 pi / (24 * 3600),\nbut we need the value in SI seconds.\nSee Explanatory Supplement to the Astronomical Almanac, ed. P. Kenneth Seidelmann (1992),\nUniversity Science Books.\n\"\"\"\n\n\ndef _check_ellipsoid(ellipsoid=None, default='WGS84'):\n if ellipsoid is None:\n ellipsoid = default\n if ellipsoid not in ELLIPSOIDS:\n raise ValueError(f'Ellipsoid {ellipsoid} not among known ones ({ELLIPSOIDS})')\n return ellipsoid\n\n\ndef _get_json_result(url, err_str, use_google):\n\n # need to do this here to prevent a series of complicated circular imports\n from .name_resolve import NameResolveError\n try:\n # Retrieve JSON response from Google maps API\n resp = urllib.request.urlopen(url, timeout=data.conf.remote_timeout)\n resp_data = json.loads(resp.read().decode('utf8'))\n\n except urllib.error.URLError as e:\n # This catches a timeout error, see:\n # http://stackoverflow.com/questions/2712524/handling-urllib2s-timeout-python\n if isinstance(e.reason, socket.timeout):\n raise NameResolveError(err_str.format(msg=\"connection timed out\"))\n else:\n raise NameResolveError(err_str.format(msg=e.reason))\n\n except socket.timeout:\n # There are some cases where urllib2 does not catch socket.timeout\n # especially while receiving response data on an already previously\n # working request\n raise NameResolveError(err_str.format(msg=\"connection timed out\"))\n\n if use_google:\n results = resp_data.get('results', [])\n\n if resp_data.get('status', None) != 'OK':\n raise NameResolveError(err_str.format(msg=\"unknown failure with \"\n \"Google API\"))\n\n else: # OpenStreetMap returns a list\n results = resp_data\n\n if not results:\n raise NameResolveError(err_str.format(msg=\"no results returned\"))\n\n return results\n\n\nclass EarthLocationInfo(QuantityInfoBase):\n \"\"\"\n Container for meta information like name, description, format. This is\n required when the object is used as a mixin column within a table, but can\n be used as a general way to store meta information.\n \"\"\"\n _represent_as_dict_attrs = ('x', 'y', 'z', 'ellipsoid')\n\n def _construct_from_dict(self, map):\n # Need to pop ellipsoid off and update post-instantiation. This is\n # on the to-fix list in #4261.\n ellipsoid = map.pop('ellipsoid')\n out = self._parent_cls(**map)\n out.ellipsoid = ellipsoid\n return out\n\n def new_like(self, cols, length, metadata_conflicts='warn', name=None):\n \"\"\"\n Return a new EarthLocation instance which is consistent with the\n input ``cols`` and has ``length`` rows.\n\n This is intended for creating an empty column object whose elements can\n be set in-place for table operations like join or vstack.\n\n Parameters\n ----------\n cols : list\n List of input columns\n length : int\n Length of the output column object\n metadata_conflicts : str ('warn'|'error'|'silent')\n How to handle metadata conflicts\n name : str\n Output column name\n\n Returns\n -------\n col : EarthLocation (or subclass)\n Empty instance of this class consistent with ``cols``\n \"\"\"\n # Very similar to QuantityInfo.new_like, but the creation of the\n # map is different enough that this needs its own rouinte.\n # Get merged info attributes shape, dtype, format, description.\n attrs = self.merge_cols_attributes(cols, metadata_conflicts, name,\n ('meta', 'format', 'description'))\n # The above raises an error if the dtypes do not match, but returns\n # just the string representation, which is not useful, so remove.\n attrs.pop('dtype')\n # Make empty EarthLocation using the dtype and unit of the last column.\n # Use zeros so we do not get problems for possible conversion to\n # geodetic coordinates.\n shape = (length,) + attrs.pop('shape')\n data = u.Quantity(np.zeros(shape=shape, dtype=cols[0].dtype),\n unit=cols[0].unit, copy=False)\n # Get arguments needed to reconstruct class\n map = {key: (data[key] if key in 'xyz' else getattr(cols[-1], key))\n for key in self._represent_as_dict_attrs}\n out = self._construct_from_dict(map)\n # Set remaining info attributes\n for attr, value in attrs.items():\n setattr(out.info, attr, value)\n\n return out\n\n\nclass EarthLocation(u.Quantity):\n \"\"\"\n Location on the Earth.\n\n Initialization is first attempted assuming geocentric (x, y, z) coordinates\n are given; if that fails, another attempt is made assuming geodetic\n coordinates (longitude, latitude, height above a reference ellipsoid).\n When using the geodetic forms, Longitudes are measured increasing to the\n east, so west longitudes are negative. Internally, the coordinates are\n stored as geocentric.\n\n To ensure a specific type of coordinates is used, use the corresponding\n class methods (`from_geocentric` and `from_geodetic`) or initialize the\n arguments with names (``x``, ``y``, ``z`` for geocentric; ``lon``, ``lat``,\n ``height`` for geodetic). See the class methods for details.\n\n\n Notes\n -----\n This class fits into the coordinates transformation framework in that it\n encodes a position on the `~astropy.coordinates.ITRS` frame. To get a\n proper `~astropy.coordinates.ITRS` object from this object, use the ``itrs``\n property.\n \"\"\"\n\n _ellipsoid = 'WGS84'\n _location_dtype = np.dtype({'names': ['x', 'y', 'z'],\n 'formats': [np.float64]*3})\n _array_dtype = np.dtype((np.float64, (3,)))\n\n info = EarthLocationInfo()\n\n def __new__(cls, *args, **kwargs):\n # TODO: needs copy argument and better dealing with inputs.\n if (len(args) == 1 and len(kwargs) == 0 and\n isinstance(args[0], EarthLocation)):\n return args[0].copy()\n try:\n self = cls.from_geocentric(*args, **kwargs)\n except (u.UnitsError, TypeError) as exc_geocentric:\n try:\n self = cls.from_geodetic(*args, **kwargs)\n except Exception as exc_geodetic:\n raise TypeError('Coordinates could not be parsed as either '\n 'geocentric or geodetic, with respective '\n 'exceptions \"{}\" and \"{}\"'\n .format(exc_geocentric, exc_geodetic))\n return self\n\n @classmethod\n def from_geocentric(cls, x, y, z, unit=None):\n \"\"\"\n Location on Earth, initialized from geocentric coordinates.\n\n Parameters\n ----------\n x, y, z : `~astropy.units.Quantity` or array_like\n Cartesian coordinates. If not quantities, ``unit`` should be given.\n unit : `~astropy.units.UnitBase` object or None\n Physical unit of the coordinate values. If ``x``, ``y``, and/or\n ``z`` are quantities, they will be converted to this unit.\n\n Raises\n ------\n astropy.units.UnitsError\n If the units on ``x``, ``y``, and ``z`` do not match or an invalid\n unit is given.\n ValueError\n If the shapes of ``x``, ``y``, and ``z`` do not match.\n TypeError\n If ``x`` is not a `~astropy.units.Quantity` and no unit is given.\n \"\"\"\n if unit is None:\n try:\n unit = x.unit\n except AttributeError:\n raise TypeError(\"Geocentric coordinates should be Quantities \"\n \"unless an explicit unit is given.\")\n else:\n unit = u.Unit(unit)\n\n if unit.physical_type != 'length':\n raise u.UnitsError(\"Geocentric coordinates should be in \"\n \"units of length.\")\n\n try:\n x = u.Quantity(x, unit, copy=False)\n y = u.Quantity(y, unit, copy=False)\n z = u.Quantity(z, unit, copy=False)\n except u.UnitsError:\n raise u.UnitsError(\"Geocentric coordinate units should all be \"\n \"consistent.\")\n\n x, y, z = np.broadcast_arrays(x, y, z)\n struc = np.empty(x.shape, cls._location_dtype)\n struc['x'], struc['y'], struc['z'] = x, y, z\n return super().__new__(cls, struc, unit, copy=False)\n\n @classmethod\n def from_geodetic(cls, lon, lat, height=0., ellipsoid=None):\n \"\"\"\n Location on Earth, initialized from geodetic coordinates.\n\n Parameters\n ----------\n lon : `~astropy.coordinates.Longitude` or float\n Earth East longitude. Can be anything that initialises an\n `~astropy.coordinates.Angle` object (if float, in degrees).\n lat : `~astropy.coordinates.Latitude` or float\n Earth latitude. Can be anything that initialises an\n `~astropy.coordinates.Latitude` object (if float, in degrees).\n height : `~astropy.units.Quantity` or float, optional\n Height above reference ellipsoid (if float, in meters; default: 0).\n ellipsoid : str, optional\n Name of the reference ellipsoid to use (default: 'WGS84').\n Available ellipsoids are: 'WGS84', 'GRS80', 'WGS72'.\n\n Raises\n ------\n astropy.units.UnitsError\n If the units on ``lon`` and ``lat`` are inconsistent with angular\n ones, or that on ``height`` with a length.\n ValueError\n If ``lon``, ``lat``, and ``height`` do not have the same shape, or\n if ``ellipsoid`` is not recognized as among the ones implemented.\n\n Notes\n -----\n For the conversion to geocentric coordinates, the ERFA routine\n ``gd2gc`` is used. See https://github.com/liberfa/erfa\n \"\"\"\n ellipsoid = _check_ellipsoid(ellipsoid, default=cls._ellipsoid)\n # We use Angle here since there is no need to wrap the longitude -\n # gd2gc will just take cos/sin anyway. And wrapping might fail\n # on readonly input.\n lon = Angle(lon, u.degree, copy=False)\n lat = Latitude(lat, u.degree, copy=False)\n # don't convert to m by default, so we can use the height unit below.\n if not isinstance(height, u.Quantity):\n height = u.Quantity(height, u.m, copy=False)\n # get geocentric coordinates. Have to give one-dimensional array.\n xyz = erfa.gd2gc(getattr(erfa, ellipsoid),\n lon.to_value(u.radian),\n lat.to_value(u.radian),\n height.to_value(u.m))\n self = xyz.ravel().view(cls._location_dtype,\n cls).reshape(xyz.shape[:-1])\n self._unit = u.meter\n self._ellipsoid = ellipsoid\n return self.to(height.unit)\n\n @classmethod\n def of_site(cls, site_name):\n \"\"\"\n Return an object of this class for a known observatory/site by name.\n\n This is intended as a quick convenience function to get basic site\n information, not a fully-featured exhaustive registry of observatories\n and all their properties.\n\n Additional information about the site is stored in the ``.info.meta``\n dictionary of sites obtained using this method (see the examples below).\n\n .. note::\n When this function is called, it will attempt to download site\n information from the astropy data server. If you would like a site\n to be added, issue a pull request to the\n `astropy-data repository `_ .\n If a site cannot be found in the registry (i.e., an internet\n connection is not available), it will fall back on a built-in list,\n In the future, this bundled list might include a version-controlled\n list of canonical observatories extracted from the online version,\n but it currently only contains the Greenwich Royal Observatory as an\n example case.\n\n\n Parameters\n ----------\n site_name : str\n Name of the observatory (case-insensitive).\n\n Returns\n -------\n site : This class (a `~astropy.coordinates.EarthLocation` or subclass)\n The location of the observatory.\n\n Examples\n --------\n\n >>> from astropy.coordinates import EarthLocation\n >>> keck = EarthLocation.of_site('Keck Observatory') # doctest: +REMOTE_DATA\n >>> keck.geodetic # doctest: +REMOTE_DATA +FLOAT_CMP\n GeodeticLocation(lon=, lat=, height=)\n >>> keck.info # doctest: +REMOTE_DATA\n name = W. M. Keck Observatory\n dtype = void192\n unit = m\n class = EarthLocation\n n_bad = 0\n >>> keck.info.meta # doctest: +REMOTE_DATA\n {'source': 'IRAF Observatory Database', 'timezone': 'US/Aleutian'}\n\n See Also\n --------\n get_site_names : the list of sites that this function can access\n \"\"\" # noqa\n registry = cls._get_site_registry()\n try:\n el = registry[site_name]\n except UnknownSiteException as e:\n raise UnknownSiteException(e.site, 'EarthLocation.get_site_names',\n close_names=e.close_names)\n\n if cls is el.__class__:\n return el\n else:\n newel = cls.from_geodetic(*el.to_geodetic())\n newel.info.name = el.info.name\n return newel\n\n @classmethod\n def of_address(cls, address, get_height=False, google_api_key=None):\n \"\"\"\n Return an object of this class for a given address by querying either\n the OpenStreetMap Nominatim tool [1]_ (default) or the Google geocoding\n API [2]_, which requires a specified API key.\n\n This is intended as a quick convenience function to get easy access to\n locations. If you need to specify a precise location, you should use the\n initializer directly and pass in a longitude, latitude, and elevation.\n\n In the background, this just issues a web query to either of\n the APIs noted above. This is not meant to be abused! Both\n OpenStreetMap and Google use IP-based query limiting and will ban your\n IP if you send more than a few thousand queries per hour [2]_.\n\n .. warning::\n If the query returns more than one location (e.g., searching on\n ``address='springfield'``), this function will use the **first**\n returned location.\n\n Parameters\n ----------\n address : str\n The address to get the location for. As per the Google maps API,\n this can be a fully specified street address (e.g., 123 Main St.,\n New York, NY) or a city name (e.g., Danbury, CT), or etc.\n get_height : bool, optional\n This only works when using the Google API! See the ``google_api_key``\n block below. Use the retrieved location to perform a second query to\n the Google maps elevation API to retrieve the height of the input\n address [3]_.\n google_api_key : str, optional\n A Google API key with the Geocoding API and (optionally) the\n elevation API enabled. See [4]_ for more information.\n\n\n Returns\n -------\n location : This class (a `~astropy.coordinates.EarthLocation` or subclass)\n The location of the input address.\n\n References\n ----------\n .. [1] https://nominatim.openstreetmap.org/\n .. [2] https://developers.google.com/maps/documentation/geocoding/start\n .. [3] https://developers.google.com/maps/documentation/elevation/start\n .. [4] https://developers.google.com/maps/documentation/geocoding/get-api-key\n\n \"\"\"\n\n use_google = google_api_key is not None\n\n # Fail fast if invalid options are passed:\n if not use_google and get_height:\n raise ValueError(\n 'Currently, `get_height` only works when using '\n 'the Google geocoding API, which requires passing '\n 'a Google API key with `google_api_key`. See: '\n 'https://developers.google.com/maps/documentation/geocoding/get-api-key '\n 'for information on obtaining an API key.')\n\n if use_google: # Google\n pars = urllib.parse.urlencode({'address': address,\n 'key': google_api_key})\n geo_url = f\"https://maps.googleapis.com/maps/api/geocode/json?{pars}\"\n\n else: # OpenStreetMap\n pars = urllib.parse.urlencode({'q': address,\n 'format': 'json'})\n geo_url = f\"https://nominatim.openstreetmap.org/search?{pars}\"\n\n # get longitude and latitude location\n err_str = f\"Unable to retrieve coordinates for address '{address}'; {{msg}}\"\n geo_result = _get_json_result(geo_url, err_str=err_str,\n use_google=use_google)\n\n if use_google:\n loc = geo_result[0]['geometry']['location']\n lat = loc['lat']\n lon = loc['lng']\n\n else:\n loc = geo_result[0]\n lat = float(loc['lat']) # strings are returned by OpenStreetMap\n lon = float(loc['lon'])\n\n if get_height:\n pars = {'locations': f'{lat:.8f},{lon:.8f}',\n 'key': google_api_key}\n pars = urllib.parse.urlencode(pars)\n ele_url = f\"https://maps.googleapis.com/maps/api/elevation/json?{pars}\"\n\n err_str = f\"Unable to retrieve elevation for address '{address}'; {{msg}}\"\n ele_result = _get_json_result(ele_url, err_str=err_str,\n use_google=use_google)\n height = ele_result[0]['elevation']*u.meter\n\n else:\n height = 0.\n\n return cls.from_geodetic(lon=lon*u.deg, lat=lat*u.deg, height=height)\n\n @classmethod\n def get_site_names(cls):\n \"\"\"\n Get list of names of observatories for use with\n `~astropy.coordinates.EarthLocation.of_site`.\n\n .. note::\n When this function is called, it will first attempt to\n download site information from the astropy data server. If it\n cannot (i.e., an internet connection is not available), it will fall\n back on the list included with astropy (which is a limited and dated\n set of sites). If you think a site should be added, issue a pull\n request to the\n `astropy-data repository `_ .\n\n\n Returns\n -------\n names : list of str\n List of valid observatory names\n\n See Also\n --------\n of_site : Gets the actual location object for one of the sites names\n this returns.\n \"\"\"\n return cls._get_site_registry().names\n\n @classmethod\n def _get_site_registry(cls, force_download=False, force_builtin=False):\n \"\"\"\n Gets the site registry. The first time this either downloads or loads\n from the data file packaged with astropy. Subsequent calls will use the\n cached version unless explicitly overridden.\n\n Parameters\n ----------\n force_download : bool or str\n If not False, force replacement of the cached registry with a\n downloaded version. If a str, that will be used as the URL to\n download from (if just True, the default URL will be used).\n force_builtin : bool\n If True, load from the data file bundled with astropy and set the\n cache to that.\n\n returns\n -------\n reg : astropy.coordinates.sites.SiteRegistry\n \"\"\"\n # need to do this here at the bottom to avoid circular dependencies\n from .sites import get_builtin_sites, get_downloaded_sites\n\n if force_builtin and force_download:\n raise ValueError('Cannot have both force_builtin and force_download True')\n\n if force_builtin:\n reg = cls._site_registry = get_builtin_sites()\n else:\n reg = getattr(cls, '_site_registry', None)\n if force_download or not reg:\n try:\n if isinstance(force_download, str):\n reg = get_downloaded_sites(force_download)\n else:\n reg = get_downloaded_sites()\n except OSError:\n if force_download:\n raise\n msg = ('Could not access the online site list. Falling '\n 'back on the built-in version, which is rather '\n 'limited. If you want to retry the download, do '\n '{0}._get_site_registry(force_download=True)')\n warn(AstropyUserWarning(msg.format(cls.__name__)))\n reg = get_builtin_sites()\n cls._site_registry = reg\n\n return reg\n\n @property\n def ellipsoid(self):\n \"\"\"The default ellipsoid used to convert to geodetic coordinates.\"\"\"\n return self._ellipsoid\n\n @ellipsoid.setter\n def ellipsoid(self, ellipsoid):\n self._ellipsoid = _check_ellipsoid(ellipsoid)\n\n @property\n def geodetic(self):\n \"\"\"Convert to geodetic coordinates for the default ellipsoid.\"\"\"\n return self.to_geodetic()\n\n def to_geodetic(self, ellipsoid=None):\n \"\"\"Convert to geodetic coordinates.\n\n Parameters\n ----------\n ellipsoid : str, optional\n Reference ellipsoid to use. Default is the one the coordinates\n were initialized with. Available are: 'WGS84', 'GRS80', 'WGS72'\n\n Returns\n -------\n (lon, lat, height) : tuple\n The tuple contains instances of `~astropy.coordinates.Longitude`,\n `~astropy.coordinates.Latitude`, and `~astropy.units.Quantity`\n\n Raises\n ------\n ValueError\n if ``ellipsoid`` is not recognized as among the ones implemented.\n\n Notes\n -----\n For the conversion to geodetic coordinates, the ERFA routine\n ``gc2gd`` is used. See https://github.com/liberfa/erfa\n \"\"\"\n ellipsoid = _check_ellipsoid(ellipsoid, default=self.ellipsoid)\n self_array = self.to(u.meter).view(self._array_dtype, np.ndarray)\n lon, lat, height = erfa.gc2gd(getattr(erfa, ellipsoid), self_array)\n return GeodeticLocation(\n Longitude(lon * u.radian, u.degree,\n wrap_angle=180.*u.degree, copy=False),\n Latitude(lat * u.radian, u.degree, copy=False),\n u.Quantity(height * u.meter, self.unit, copy=False))\n\n @property\n def lon(self):\n \"\"\"Longitude of the location, for the default ellipsoid.\"\"\"\n return self.geodetic[0]\n\n @property\n def lat(self):\n \"\"\"Longitude of the location, for the default ellipsoid.\"\"\"\n return self.geodetic[1]\n\n @property\n def height(self):\n \"\"\"Height of the location, for the default ellipsoid.\"\"\"\n return self.geodetic[2]\n\n # mostly for symmetry with geodetic and to_geodetic.\n @property\n def geocentric(self):\n \"\"\"Convert to a tuple with X, Y, and Z as quantities\"\"\"\n return self.to_geocentric()\n\n def to_geocentric(self):\n \"\"\"Convert to a tuple with X, Y, and Z as quantities\"\"\"\n return (self.x, self.y, self.z)\n\n def get_itrs(self, obstime=None):\n \"\"\"\n Generates an `~astropy.coordinates.ITRS` object with the location of\n this object at the requested ``obstime``.\n\n Parameters\n ----------\n obstime : `~astropy.time.Time` or None\n The ``obstime`` to apply to the new `~astropy.coordinates.ITRS`, or\n if None, the default ``obstime`` will be used.\n\n Returns\n -------\n itrs : `~astropy.coordinates.ITRS`\n The new object in the ITRS frame\n \"\"\"\n # Broadcast for a single position at multiple times, but don't attempt\n # to be more general here.\n if obstime and self.size == 1 and obstime.shape:\n self = np.broadcast_to(self, obstime.shape, subok=True)\n\n # do this here to prevent a series of complicated circular imports\n from .builtin_frames import ITRS\n return ITRS(x=self.x, y=self.y, z=self.z, obstime=obstime)\n\n itrs = property(get_itrs, doc=\"\"\"An `~astropy.coordinates.ITRS` object with\n for the location of this object at the\n default ``obstime``.\"\"\")\n\n def get_gcrs(self, obstime):\n \"\"\"GCRS position with velocity at ``obstime`` as a GCRS coordinate.\n\n Parameters\n ----------\n obstime : `~astropy.time.Time`\n The ``obstime`` to calculate the GCRS position/velocity at.\n\n Returns\n --------\n gcrs : `~astropy.coordinates.GCRS` instance\n With velocity included.\n \"\"\"\n # do this here to prevent a series of complicated circular imports\n from .builtin_frames import GCRS\n\n itrs = self.get_itrs(obstime)\n # Assume the observatory itself is fixed on the ground.\n # We do a direct assignment rather than an update to avoid validation\n # and creation of a new object.\n zeros = np.broadcast_to(0. * u.km / u.s, (3,) + itrs.shape, subok=True)\n itrs.data.differentials['s'] = CartesianDifferential(zeros)\n return itrs.transform_to(GCRS(obstime=obstime))\n\n def get_gcrs_posvel(self, obstime):\n \"\"\"\n Calculate the GCRS position and velocity of this object at the\n requested ``obstime``.\n\n Parameters\n ----------\n obstime : `~astropy.time.Time`\n The ``obstime`` to calculate the GCRS position/velocity at.\n\n Returns\n --------\n obsgeoloc : `~astropy.coordinates.CartesianRepresentation`\n The GCRS position of the object\n obsgeovel : `~astropy.coordinates.CartesianRepresentation`\n The GCRS velocity of the object\n \"\"\"\n # GCRS position\n gcrs_data = self.get_gcrs(obstime).data\n obsgeopos = gcrs_data.without_differentials()\n obsgeovel = gcrs_data.differentials['s'].to_cartesian()\n return obsgeopos, obsgeovel\n\n def gravitational_redshift(self, obstime,\n bodies=['sun', 'jupiter', 'moon'],\n masses={}):\n \"\"\"Return the gravitational redshift at this EarthLocation.\n\n Calculates the gravitational redshift, of order 3 m/s, due to the\n requested solar system bodies.\n\n Parameters\n ----------\n obstime : `~astropy.time.Time`\n The ``obstime`` to calculate the redshift at.\n\n bodies : iterable, optional\n The bodies (other than the Earth) to include in the redshift\n calculation. List elements should be any body name\n `get_body_barycentric` accepts. Defaults to Jupiter, the Sun, and\n the Moon. Earth is always included (because the class represents\n an *Earth* location).\n\n masses : dict of str to Quantity, optional\n The mass or gravitational parameters (G * mass) to assume for the\n bodies requested in ``bodies``. Can be used to override the\n defaults for the Sun, Jupiter, the Moon, and the Earth, or to\n pass in masses for other bodies.\n\n Returns\n --------\n redshift : `~astropy.units.Quantity`\n Gravitational redshift in velocity units at given obstime.\n \"\"\"\n # needs to be here to avoid circular imports\n from .solar_system import get_body_barycentric\n\n bodies = list(bodies)\n # Ensure earth is included and last in the list.\n if 'earth' in bodies:\n bodies.remove('earth')\n bodies.append('earth')\n _masses = {'sun': consts.GM_sun,\n 'jupiter': consts.GM_jup,\n 'moon': consts.G * 7.34767309e22*u.kg,\n 'earth': consts.GM_earth}\n _masses.update(masses)\n GMs = []\n M_GM_equivalency = (u.kg, u.Unit(consts.G * u.kg))\n for body in bodies:\n try:\n GMs.append(_masses[body].to(u.m**3/u.s**2, [M_GM_equivalency]))\n except KeyError:\n raise KeyError(f'body \"{body}\" does not have a mass!')\n except u.UnitsError as exc:\n exc.args += ('\"masses\" argument values must be masses or '\n 'gravitational parameters',)\n raise\n\n positions = [get_body_barycentric(name, obstime) for name in bodies]\n # Calculate distances to objects other than earth.\n distances = [(pos - positions[-1]).norm() for pos in positions[:-1]]\n # Append distance from Earth's center for Earth's contribution.\n distances.append(CartesianRepresentation(self.geocentric).norm())\n # Get redshifts due to all objects.\n redshifts = [-GM / consts.c / distance for (GM, distance) in\n zip(GMs, distances)]\n # Reverse order of summing, to go from small to big, and to get\n # \"earth\" first, which gives m/s as unit.\n return sum(redshifts[::-1])\n\n @property\n def x(self):\n \"\"\"The X component of the geocentric coordinates.\"\"\"\n return self['x']\n\n @property\n def y(self):\n \"\"\"The Y component of the geocentric coordinates.\"\"\"\n return self['y']\n\n @property\n def z(self):\n \"\"\"The Z component of the geocentric coordinates.\"\"\"\n return self['z']\n\n def __getitem__(self, item):\n result = super().__getitem__(item)\n if result.dtype is self.dtype:\n return result.view(self.__class__)\n else:\n return result.view(u.Quantity)\n\n def __array_finalize__(self, obj):\n super().__array_finalize__(obj)\n if hasattr(obj, '_ellipsoid'):\n self._ellipsoid = obj._ellipsoid\n\n def __len__(self):\n if self.shape == ():\n raise IndexError('0-d EarthLocation arrays cannot be indexed')\n else:\n return super().__len__()\n\n def _to_value(self, unit, equivalencies=[]):\n \"\"\"Helper method for to and to_value.\"\"\"\n # Conversion to another unit in both ``to`` and ``to_value`` goes\n # via this routine. To make the regular quantity routines work, we\n # temporarily turn the structured array into a regular one.\n array_view = self.view(self._array_dtype, np.ndarray)\n if equivalencies == []:\n equivalencies = self._equivalencies\n new_array = self.unit.to(unit, array_view, equivalencies=equivalencies)\n return new_array.view(self.dtype).reshape(self.shape)\n", "meta": {"hexsha": "167b6ec09474ed2cd4cbd40241766f6760b19b11", "size": 32327, "ext": "py", "lang": "Python", "max_stars_repo_path": "astropy/coordinates/earth.py", "max_stars_repo_name": "Apoorve73/astropy", "max_stars_repo_head_hexsha": "a995665c06b8d145ba811e3cbc59b0dfb8d20bd6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "astropy/coordinates/earth.py", "max_issues_repo_name": "Apoorve73/astropy", "max_issues_repo_head_hexsha": "a995665c06b8d145ba811e3cbc59b0dfb8d20bd6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "astropy/coordinates/earth.py", "max_forks_repo_name": "Apoorve73/astropy", "max_forks_repo_head_hexsha": "a995665c06b8d145ba811e3cbc59b0dfb8d20bd6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7626076261, "max_line_length": 118, "alphanum_fraction": 0.6016333096, "include": true, "reason": "import numpy,from astropy", "num_tokens": 7145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.25683198569916993, "lm_q1q2_score": 0.13842813082775185}} {"text": "\nfrom __future__ import (absolute_import, print_function, division)\n\nfrom astropy.table import Table\nimport numpy as np\nfrom astropy.io import fits\n\n# fix needed till astropy.io get's updated - need to check this\nfits.column.ASCII2NUMPY['E'] = fits.column.ASCII2NUMPY['F'] = 'f8'\n\nimport matplotlib.pyplot as plt\nimport string as st\nimport subprocess\nfrom scipy import interpolate\nfrom scipy.integrate import simps\nfrom pydirtygrid.PhotDG import PhotDG\nimport h5py\n\n__all__ = ['SpecDG']\n\nclass SpecDG:\n def __init__(self):\n \"\"\"\n Read in the mapping file for all spectra\n \n Returns\n -------\n (self.)plan: Table\n table containing the identification of each spectrum, \n as well as its parameters\n \n (self.)seds: list\n empty list to save the spectra if you want to\n \"\"\"\n mapfile = '/astro/dust_kg3/klaw/cloudy2/dirtygrid_db/django/param_table6_combined.tsvx'\n self.plan = Table.read(mapfile, format='ascii')\n self.seds = []\n #self.waves = []\n \n def findFile(self,file_id):\n \"\"\"\n Returns the full filename for a given GID from the spectrum mapping.\n \n Parameter\n ---------\n file_id: string\n identification number of the spectrum to be read; \n 'gid' column of the self.plan Table\n \n Returns\n -------\n filepath+filename: string\n the absolute path and name of the .fits file\n \"\"\"\n\n alphab = []\n for i in range(26): alphab.append(st.uppercase[i])\n alphab = np.array(alphab)\n ind_id = []\n for i in range(len(file_id)):\n tmp_i = np.where(file_id[i] == alphab)\n if len(tmp_i[0] == 1):\n ind_id.append(tmp_i[0][0])\n else:\n break\n prefix = ''.join(alphab[ind_id])\n filepath = '/astro/dust_kg3/klaw/cloudy2/nasa_fits/'+prefix \\\n +'/'+str(file_id[-4:-2])+'/'\n files = []\n proc = subprocess.Popen(['ls', filepath], stdout=subprocess.PIPE)\n for line in proc.stdout.readlines(): files.append(line.rstrip())\n filename = [s for s in files if file_id in s]\n if len(filename) == 0: \n return 'Void'\n else:\n filename = filename[0]\n return filepath+filename\n\n def findGidFromParam(self, grain, geom, sf_type, metal, age, sfr, tau):\n \"\"\"\n Returns the GID given a set of parameters \n (If you want to plot or something)\n \n Parameters\n ----------\n grain: string\n type of grain\n \n geom: string\n geometry\n \n sf_type: string\n star formation type \n \n metal: float\n metallicity\n \n age: float\n age of the stellar population\n \n sfr: float\n star formation rate\n \n tau: float\n optical depth\n \n Returns\n -------\n file_gid: string\n identification number of the spectrum with the given set \n of parameters\n \"\"\"\n # ToDo: A better way to do this?\n ind = np.where( (self.plan['grain'] == grain) \n & (self.plan['geom'] == geom) \n & (self.plan['sf_type'] == sf_type) \n & (self.plan['metal'] == metal) \n & (self.plan['age'] == age) \n & (self.plan['sfr'] == sfr) \n & (self.plan['tau'] == tau) )\n # Not all spectra available \n # -- Exit if non existant - Until interpolation?\n if len(ind[0]) == 0: \n return\n # If valid, then go on\n file_gid = self.plan['gid'][ind[0][0]]\n return file_gid\n \n def findParamsFromGid(self, thisgid):\n \"\"\"\n Returns the parameter values for a given GID \n (Used later to update the cube)\n \n Parameters\n ----------\n thisgid: string\n identification number of the spectrum\n \n Returns\n -------\n thisgt, thisgm, thissf, thismt, thissa, thissr, thista: integers\n indices of the parameter values for the given spectrum, \n in the multidimensional photometry cube\n \"\"\"\n ind_gid = np.where(self.plan['gid'] == thisgid)\n thisgt = self.plan['grain'][ind_gid[0][0]] # Grain type\n thisgm = self.plan['geom'][ind_gid[0][0]] # Geometry\n thissf = self.plan['sf_type'][ind_gid[0][0]] # Star formation type\n thismt = self.plan['metal'][ind_gid[0][0]] # Metal\n thissa = self.plan['age'][ind_gid[0][0]] # Stellar age\n thissr = self.plan['sfr'][ind_gid[0][0]] # Star formation rate\n thista = self.plan['tau'][ind_gid[0][0]] # Optical depth\n return thisgt, thisgm, thissf, thismt, thissa, thissr, thista\n \n def specGet(self, filename):\n \"\"\"\n Save a spectrum from the filename\n \n Parameters\n ----------\n filename: string\n absolute path to the spectrum you want to read\n \n Returns\n -------\n (self.)seds: list\n update the list to add the SED\n (self.)waves: array\n the wavelengths to the SED\n \"\"\"\n # Read the fits file\n hdulist = fits.open(filename)\n scidata = hdulist[1].data \n self.seds.append(scidata['Flux'])\n self.waves = scidata['Wavelength']\n \n def specPlot(self, ind=-1):\n \"\"\"\n Plot SEDs, either giving a specific index of which if more that \n one saved, or all of them\n \n Parameters\n ----------\n ind: integer(s) (Optional)\n indices of the SED you wish to plot\n \"\"\"\n plt.xscale('log')\n plt.yscale('log')\n plt.ylabel('Luminosity [$erg$ $s^{-1}$ $\\mu m^{-1}$]', fontsize=15)\n plt.xlabel('Wavelength [$\\mu m$]', fontsize=15)\n if ind == -1:\n print('Plotting all SEDs in object')\n for i in range(len(self.seds)): \n plt.plot(self.waves, self.seds[i])\n else:\n for i in ind: plt.plot(self.waves, np.array(self.seds[ind]))\n # ToDo: need a legend\n # ToDo: specify an figure/subplot if desired?\n plt.show()\n \n def spec2Phot(self, trans_curve, trans_waves, wave0, energy=1):\n \"\"\"\n Compute the new photometry\n \n Parameters\n ----------\n trans_curve: array\n transmission curve of the new filter /!\\ Alread read, as an array\n \n trans_waves: array\n wavelengths of the new filter\n \n wave0: float\n center/effective wavelength of the new filter\n \n energy: integer (Optional)\n specification for integration with energy(=1, default) or photons\n \n Returns\n -------\n newcube: array(3, 6, 2, 5, 50, 29, 25) (float)\n new photometry cube\n \"\"\"\n # Create an instance of the PhotDG class to call functions\n phtemp = PhotDG(silent=1) \n light_speed = 2.998e14 # microns/s\n n_files = len(self.plan['gid'])\n # Create the array to fill\n newcube = np.empty((3,6,2,5,50,29,25))\n # Read in each spectrum\n for i in range(n_files):\n if (i % 1000) == 0: \n print(i)\n filename = self.findFile(self.plan['gid'][i])\n if filename == 'Void': \n continue\n hdu = fits.open(filename)\n scidata = hdu[1].data\n spec = scidata['Flux'] # SED\n # Wavelength (same for all files)\n if i == 0: \n dgwave = scidata['Wavelength'] \n # Interpolate the spectral response on DG wavelength grid\n # Do it in log space\n func = interpolate.interp1d(trans_waves, np.log10(trans_curve), \n kind='slinear')\n tr_ind = np.where( (dgwave > np.min(trans_waves)) \n & (dgwave < np.max(trans_waves)))\n newtran = func(dgwave[tr_ind])\n newtran = 10**newtran\n # Frequencies\n nu0 = light_speed/wave0#[indf]\n nu = light_speed/dgwave[tr_ind]\n # Total response curve, for integration (Used simps) \n if energy == 1:\n tot_resp_curve = simps(newtran*nu0/nu, dgwave[tr_ind])\n tmp_phot = simps(spec[tr_ind]*newtran, dgwave[tr_ind]) \n newphot = tmp_phot / tot_resp_curve\n else: # In photons. Do the Blackbody too?\n tot_resp_curve = simps(newtran*nu0/nu**2, dgwave[tr_ind])\n tmp_phot = simps(spec[tr_ind]*newtran/nu, dgwave[tr_ind]) \n newphot = tmp_phot / tot_resp_curve\n # Fill the array \n curgt, curgm, cursf, curmt, cursa, cursr, curta = \\\n self.findParamsFromGid(self.plan['gid'][i])\n indgt, indgm, indsf, indmt, indsa, indsr, indta = \\\n phtemp.findIndexFromParams(curgt, curgm, cursf, curmt, \n cursa, cursr, curta)\n newcube[indgt, indgm, indsf, indmt, indsa, indsr, indta] = newphot\n\n return newcube\n #ToDo: maybe save sometimes to avoid all recompute if fails somewhere?\n\n##########\n \n \n \n \n\n\n", "meta": {"hexsha": "4bd61294b613440f96098f8216527c5649dfde27", "size": 9522, "ext": "py", "lang": "Python", "max_stars_repo_path": "pydirtygrid/SpecDG.py", "max_stars_repo_name": "Stargrazer82301/dirtygrid", "max_stars_repo_head_hexsha": "da9f074d5ede33236f2f6ec6e11db1a3591a2a85", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pydirtygrid/SpecDG.py", "max_issues_repo_name": "Stargrazer82301/dirtygrid", "max_issues_repo_head_hexsha": "da9f074d5ede33236f2f6ec6e11db1a3591a2a85", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2016-08-21T18:06:21.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-15T20:07:04.000Z", "max_forks_repo_path": "pydirtygrid/SpecDG.py", "max_forks_repo_name": "Stargrazer82301/dirtygrid", "max_forks_repo_head_hexsha": "da9f074d5ede33236f2f6ec6e11db1a3591a2a85", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-08-23T13:58:42.000Z", "max_forks_repo_forks_event_max_datetime": "2017-10-23T16:42:17.000Z", "avg_line_length": 33.8861209964, "max_line_length": 95, "alphanum_fraction": 0.5247847091, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 2319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.2568319856991699, "lm_q1q2_score": 0.1384281308277518}} {"text": "# -*- coding: utf-8 -*-\nfrom ..._core import bolton_q_sat, ensure_contiguous_state\nfrom sympl import (\n ImplicitTendencyComponent, get_constant, initialize_numpy_arrays_with_properties)\nimport numpy as np\nimport logging\ntry:\n from . import _emanuel_convection\nexcept ImportError as error:\n logging.warning(\n 'Import failed. Emanuel Convection is likely not compiled and will not '\n 'be available.'\n )\n print(error)\n\n\nclass EmanuelConvection(ImplicitTendencyComponent):\n \"\"\"\n The Emanuel convection scheme from `[Emanuel and Zivkovic-Rothman]`_\n\n .. _[Emanuel and Zivkovic-Rothman]:\n http://journals.ametsoc.org/doi/abs/10.1175/1520-0469(1999)056%3C1766%3ADAEOAC%3E2.0.CO%3B2\n\n \"\"\"\n\n input_properties = {\n 'air_temperature': {\n 'dims': ['*', 'mid_levels'],\n 'units': 'degK',\n },\n 'specific_humidity': {\n 'dims': ['*', 'mid_levels'],\n 'units': 'kg/kg',\n },\n 'eastward_wind': {\n 'dims': ['*', 'mid_levels'],\n 'units': 'm s^-1',\n },\n 'northward_wind': {\n 'dims': ['*', 'mid_levels'],\n 'units': 'm s^-1',\n },\n 'air_pressure': {\n 'dims': ['*', 'mid_levels'],\n 'units': 'mbar',\n },\n 'air_pressure_on_interface_levels': {\n 'dims': ['*', 'interface_levels'],\n 'units': 'mbar',\n },\n 'cloud_base_mass_flux': {\n 'dims': ['*'],\n 'units': 'kg m^-2 s^-1',\n },\n }\n\n diagnostic_properties = {\n 'convective_state': {\n 'dims': ['*'],\n 'units': 'dimensionless',\n 'dtype': np.int32,\n },\n 'convective_precipitation_rate': {\n 'dims': ['*'],\n 'units': 'mm day^-1',\n },\n 'convective_downdraft_velocity_scale': {\n 'dims': ['*'],\n 'units': 'm s^-1',\n },\n 'convective_downdraft_temperature_scale': {\n 'dims': ['*'],\n 'units': 'degK',\n },\n 'convective_downdraft_specific_humidity_scale': {\n 'dims': ['*'],\n 'units': 'kg/kg',\n },\n 'cloud_base_mass_flux': {\n 'dims': ['*'],\n 'units': 'kg m^-2 s^-1',\n },\n 'atmosphere_convective_available_potential_energy': {\n 'dims': ['*'],\n 'units': 'J kg^-1',\n },\n 'air_temperature_tendency_from_convection': {\n 'dims': ['*', 'mid_levels'],\n 'units': 'degK day^-1',\n }\n }\n\n tendency_properties = {\n 'air_temperature': {'units': 'degK s^-1'},\n 'specific_humidity': {'units': 'kg/kg s^-1'},\n 'eastward_wind': {'units': 'm s^-2'},\n 'northward_wind': {'units': 'm s^-2'},\n }\n\n def __init__(self,\n minimum_convecting_layer=1,\n autoconversion_water_content_threshold=0.0011,\n autoconversion_temperature_threshold=-55,\n entrainment_mixing_coefficient=1.5,\n downdraft_area_fraction=0.05,\n precipitation_fraction_outside_cloud=0.12,\n speed_water_droplets=50.0,\n speed_snow=5.5,\n rain_evaporation_coefficient=1.0,\n snow_evaporation_coefficient=0.8,\n convective_momentum_transfer_coefficient=0.7,\n downdraft_surface_velocity_coefficient=10.0,\n convection_bouyancy_threshold=0.9,\n mass_flux_relaxation_rate=0.1,\n mass_flux_damping_rate=0.1,\n reference_mass_flux_timescale=300.,\n **kwargs):\n \"\"\"\n\n Args:\n\n minimum_convecting_layer (int, optional):\n The least model level from which convection can be initiated. Normally set\n to :code:`1` if using bulk PBL schemes. Else, it should be set to the first\n model level at which the temperature is defined.\n\n autoconversion_water_content_threshold (float, optional):\n The amount of water vapour in :math:`kg/kg`\n above which condensation occurs in warm (above freezing point of water)\n clouds. This value linearly reduces to zero between the freezing point and\n the :code:`autoconversion_temperature_threshold`.\n\n autoconversion_temperature_threshold (float, optional):\n The temperature in :math:`^\\circ C` below which\n all water vapour is converted to rain/snow.\n\n entrainment_mixing_coefficient (float, optional):\n The coefficient of mixing for entrainment of environmental air into\n the cloud.\n\n downdraft_area_fraction (float, optional):\n The fractional area covered by unsaturated downdrafts.\n\n precipitation_fraction_outside_cloud (float, optional):\n The fraction of precipitation falling outside the cloud.\n\n speed_water_droplets (float, optional):\n The speed of descent of water droplets in :math:`Pa/s`.\n\n speed_snow (float, optional):\n The speed of descent of snow in :math:`Pa/s`.\n\n rain_evaporation_coefficient (float, optional):\n Coefficient governing the rate of evaporation of rain.\n\n snow_evaporation_coefficient (float, optional):\n Coefficient governing the rate of evaporation of snow.\n\n convective_momentum_transfer_coefficient (float, optional):\n Coefficient **between 0 and 1** governing momentum transport\n by clouds. A value of 1 **shuts off** momentum transport.\n\n downdraft_surface_velocity_coefficient (float, optional):\n Coefficient mulitplying the downdraft mass flux to calculate\n the downdraft velocity scale.\n\n convection_bouyancy_threshold (float, optional):\n The maximum negative temperature perturbation in :math:`degK` a parcel can\n have below the temperature at its level of free convection.\n If difference is greater, and previous cloud base mass flux\n is zero, there is no convection.\n\n mass_flux_relaxation_rate (float, optional):\n Coefficient governing the rate of relaxation to subcloud-layer\n quasi-equilibrium.\n\n mass_flux_damping_rate (float, optional):\n Coefficient which damps the currently calculated mass flux towards\n the value from the previous time step.\n\n reference_mass_flux_timescale (float, optional):\n Timescale used to calculate the actual damping coefficient along with\n :code:`mass_flux_damping_rate` and the current time step.\n\n \"\"\"\n\n if (convective_momentum_transfer_coefficient < 0 or\n convective_momentum_transfer_coefficient > 1):\n raise ValueError(\"Momentum transfer coefficient must be between 0 and 1.\")\n\n if (downdraft_area_fraction < 0 or\n downdraft_area_fraction > 1):\n raise ValueError(\"Downdraft fraction must be between 0 and 1.\")\n\n if (precipitation_fraction_outside_cloud < 0 or\n precipitation_fraction_outside_cloud > 1):\n raise ValueError(\"Outside cloud precipitation fraction must be between 0 and 1.\")\n\n self._con_mom_txfr = convective_momentum_transfer_coefficient\n self._downdraft_area_frac = downdraft_area_fraction\n self._precip_frac_outside_cloud = precipitation_fraction_outside_cloud\n self._min_conv_layer = minimum_convecting_layer\n self._crit_humidity = autoconversion_water_content_threshold\n self._crit_temp = autoconversion_temperature_threshold\n self._entrain_coeff = entrainment_mixing_coefficient\n self._droplet_speed = speed_water_droplets\n self._snow_speed = speed_snow\n self._rain_evap = rain_evaporation_coefficient\n self._snow_evap = snow_evaporation_coefficient\n self._beta = downdraft_surface_velocity_coefficient\n self._dtmax = convection_bouyancy_threshold\n self._mf_damp = mass_flux_damping_rate\n self._alpha = mass_flux_relaxation_rate\n self._mf_timescale = reference_mass_flux_timescale\n self._ntracers = 0\n self._set_fortran_constants()\n super(EmanuelConvection, self).__init__(**kwargs)\n\n def _set_fortran_constants(self):\n self._g = get_constant('gravitational_acceleration', 'm/s^2')\n self._Cpd = get_constant('heat_capacity_of_dry_air_at_constant_pressure', 'J/kg/degK')\n self._Cpv = get_constant('heat_capacity_of_vapor_phase', 'J/kg/degK')\n self._Rdair = get_constant('gas_constant_of_dry_air', 'J/kg/degK')\n self._Rcond = get_constant('gas_constant_of_vapor_phase', 'J/kg/degK')\n self._Lv = get_constant('latent_heat_of_condensation', 'J/kg')\n self._rho_condensible = get_constant('density_of_liquid_phase', 'kg/m^3')\n self._Cl = get_constant('specific_enthalpy_of_vapor_phase', 'J/kg')\n _emanuel_convection.init_emanuel_convection(\n self._min_conv_layer,\n self._crit_humidity,\n self._crit_temp, self._entrain_coeff,\n self._downdraft_area_frac,\n self._precip_frac_outside_cloud,\n self._droplet_speed, self._snow_speed,\n self._rain_evap, self._snow_evap,\n self._con_mom_txfr, self._dtmax,\n self._beta, self._alpha, self._mf_damp,\n self._Cpd, self._Cpv, self._Cl,\n self._Rcond, self._Rdair,\n self._Lv, self._g,\n self._rho_condensible, self._mf_timescale)\n\n @ensure_contiguous_state\n def array_call(self, raw_state, timestep):\n \"\"\"\n Get convective heating and moistening.\n\n Args:\n\n raw_state (dict):\n The state dictionary of numpy arrays satisfying this\n component's input properties.\n\n Returns:\n\n tendencies (dict), diagnostics (dict):\n * The heating and moistening tendencies\n * Any diagnostics associated.\n\n \"\"\"\n self._set_fortran_constants()\n\n num_cols, num_levs = raw_state['air_temperature'].shape\n\n max_conv_level = num_levs - 3\n\n tendencies = initialize_numpy_arrays_with_properties(\n self.tendency_properties, raw_state, self.input_properties\n )\n diagnostics = initialize_numpy_arrays_with_properties(\n self.diagnostic_properties, raw_state, self.input_properties\n )\n\n q_sat = bolton_q_sat(\n raw_state['air_temperature'],\n raw_state['air_pressure'] * 100,\n self._Cpd, self._Cpv\n )\n\n _emanuel_convection.convect(\n num_levs,\n num_cols,\n max_conv_level,\n self._ntracers,\n timestep.total_seconds(),\n raw_state['air_temperature'],\n raw_state['specific_humidity'],\n q_sat,\n raw_state['eastward_wind'],\n raw_state['northward_wind'],\n raw_state['air_pressure'],\n raw_state['air_pressure_on_interface_levels'],\n diagnostics['convective_state'],\n diagnostics['convective_precipitation_rate'],\n diagnostics['convective_downdraft_velocity_scale'],\n diagnostics['convective_downdraft_temperature_scale'],\n diagnostics['convective_downdraft_specific_humidity_scale'],\n raw_state['cloud_base_mass_flux'],\n diagnostics['atmosphere_convective_available_potential_energy'],\n tendencies['air_temperature'],\n tendencies['specific_humidity'],\n tendencies['eastward_wind'],\n tendencies['northward_wind'])\n\n diagnostics['air_temperature_tendency_from_convection'][:] = (\n tendencies['air_temperature'] * 86400.)\n diagnostics['cloud_base_mass_flux'][:] = raw_state['cloud_base_mass_flux']\n return tendencies, diagnostics\n", "meta": {"hexsha": "0c3e3f5d8f7d1d59cc15bbe4e19f3a5b206933a6", "size": 12213, "ext": "py", "lang": "Python", "max_stars_repo_path": "climt/_components/emanuel/component.py", "max_stars_repo_name": "Ai33L/climt", "max_stars_repo_head_hexsha": "17fcdc43ec8ed9903dfb566bae99154f282ce85f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 116, "max_stars_repo_stars_event_min_datetime": "2017-02-12T01:45:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T20:19:03.000Z", "max_issues_repo_path": "climt/_components/emanuel/component.py", "max_issues_repo_name": "Ai33L/climt", "max_issues_repo_head_hexsha": "17fcdc43ec8ed9903dfb566bae99154f282ce85f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 115, "max_issues_repo_issues_event_min_datetime": "2017-07-23T21:19:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T16:49:21.000Z", "max_forks_repo_path": "climt/_components/emanuel/component.py", "max_forks_repo_name": "Ai33L/climt", "max_forks_repo_head_hexsha": "17fcdc43ec8ed9903dfb566bae99154f282ce85f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 30, "max_forks_repo_forks_event_min_datetime": "2017-05-24T11:52:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T16:45:19.000Z", "avg_line_length": 39.5242718447, "max_line_length": 103, "alphanum_fraction": 0.6087775321, "include": true, "reason": "import numpy", "num_tokens": 2680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.25091278688527247, "lm_q1q2_score": 0.138154424865416}} {"text": "# -*- coding: utf-8 -*-\n# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n#\n# LICENSE\n#\n# Copyright (C) 2015-2019 GEM Foundation, G. Weatherill, M. Pagani\n#\n# The Hazard Modeller's Toolkit is free software: you can redistribute\n# it and/or modify it under the terms of the GNU Affero General Public\n# License as published by the Free Software Foundation, either version\n# 3 of the License, or (at your option) any later version.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with OpenQuake. If not, see \n#\n# DISCLAIMER\n#\n# The software Hazard Modeller's Toolkit (openquake.hmtk) provided herein\n# is released as a prototype implementation on behalf of\n# scientists and engineers working within the GEM Foundation (Global\n# Earthquake Model).\n#\n# It is distributed for the purpose of open collaboration and in the\n# hope that it will be useful to the scientific, engineering, disaster\n# risk and software design communities.\n#\n# The software is NOT distributed as part of GEM's OpenQuake suite\n# (https://www.globalquakemodel.org/tools-products) and must be considered as a\n# separate entity. The software provided herein is designed and implemented\n# by scientific staff. It is not developed to the design standards, nor\n# subject to same level of critical review by professional software\n# developers, as GEM's OpenQuake software suite.\n#\n# Feedback and contribution to the software is welcome, and can be\n# directed to the hazard scientific staff of the GEM Model Facility\n# (hazard@globalquakemodel.org).\n#\n# The Hazard Modeller's Toolkit (openquake.hmtk) is therefore distributed WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n# for more details.\n#\n# The GEM Foundation, and the authors of the software, assume no\n# liability for use of the software.\n\n\"\"\"\nPython tools for calculating activity rates on a grid from a source model\n\"\"\"\nimport numpy as np\nfrom openquake.hazardlib.sourceconverter import SourceConverter\nfrom openquake.hazardlib import nrml\nfrom openquake.hazardlib.source.complex_fault import ComplexFaultSource\nfrom openquake.hazardlib.source.characteristic import CharacteristicFaultSource\nfrom openquake.hazardlib.source.simple_fault import SimpleFaultSource\nfrom openquake.hazardlib.source.area import AreaSource\nfrom openquake.hazardlib.source.point import PointSource\nfrom openquake.hazardlib.geo.mesh import Mesh\nfrom openquake.hazardlib.geo.polygon import Polygon\n\n\nclass RateGrid(object):\n \"\"\"\n Class for calculation of activity rate grids\n\n :param float xspc:\n Longitude spacing of grid\n :param float yspc:\n Latitude spacing of grid\n :param float zspc:\n Depth spacing (km) of grid\n :param np.ndarray xlim:\n Longitude cell bounds\n :param np.ndarray ylim:\n Latitude cell bounds\n :param np.ndarray zlim:\n Depth cell bounds\n :param int nx:\n Number of longitude cells\n :param int ny:\n Number of latitude cells\n :param int nz:\n Number of depth cells\n :param list source_model:\n Seismic source mode\n :param np.ndarray rates:\n Activity rates\n :param float area_discretisation:\n Discretisation step (km) of area sources\n \"\"\"\n\n def __init__(self, limits, sources, area_discretisation=10.):\n \"\"\"\n Instantiate class with grid configurations\n :param list limits:\n Grid configuration [west, east, xspc, south, north, yspc,\n upper, lower, zspc]\n \"\"\"\n self.xspc = limits[2]\n self.yspc = limits[5]\n self.zspc = limits[8]\n self.xlim = np.arange(limits[0], limits[1] + self.xspc, self.xspc)\n self.ylim = np.arange(limits[3], limits[4] + self.yspc, self.yspc)\n self.zlim = np.arange(limits[6], limits[7] + self.zspc, self.zspc)\n self.nx = len(self.xlim)\n self.ny = len(self.ylim)\n self.nz = len(self.zlim)\n self.source_model = sources\n self.rates = np.zeros([self.nx - 1, self.ny - 1, self.nz - 1],\n dtype=float)\n self.area_discretisation = area_discretisation\n\n @classmethod\n def from_model_files(cls, limits, input_model, investigation_time=1.0,\n simple_mesh_spacing=1.0, complex_mesh_spacing=5.0,\n mfd_width=0.1, area_discretisation=10.0):\n \"\"\"\n Reads the hazard model from a file\n\n :param list limits:\n Grid configuration [west, east, xspc, south, north, yspc,\n upper, lower, zspc]\n :param str input_model:\n Path to input source model\n :param float investigation_time:\n Investigation time of Poisson model\n :param float simple_mesh_spacing:\n Rupture mesh spacing of simple fault (km)\n :param float complex_mesh_spacing:\n Rupture mesh spacing of complex fault (km)\n :param float mfd_width:\n Spacing (in magnitude units) of MFD\n :param float area_discretisation:\n Spacing of discretisation of area source (km)\n \"\"\"\n converter = SourceConverter(investigation_time,\n simple_mesh_spacing,\n complex_mesh_spacing,\n mfd_width,\n area_discretisation)\n sources = []\n for grp in nrml.to_python(input_model, converter):\n sources.extend(grp.sources)\n return cls(limits, sources, area_discretisation)\n\n def number_sources(self):\n \"\"\"\n Returns the number of sources\n \"\"\"\n return len(self.source_model)\n\n def get_rates(self, mmin, mmax=np.inf):\n \"\"\"\n Returns the cumulative rates greater than Mmin\n\n :param float mmin:\n Minimum magnitude\n \"\"\"\n nsrcs = self.number_sources()\n for iloc, source in enumerate(self.source_model):\n print(\"Source Number %s of %s, Name = %s, Typology = %s\" % (\n iloc + 1,\n nsrcs,\n source.name,\n source.__class__.__name__))\n if isinstance(source, CharacteristicFaultSource):\n self._get_fault_rates(source, mmin, mmax)\n elif isinstance(source, ComplexFaultSource):\n self._get_fault_rates(source, mmin, mmax)\n elif isinstance(source, SimpleFaultSource):\n self._get_fault_rates(source, mmin, mmax)\n elif isinstance(source, AreaSource):\n self._get_area_rates(source, mmin, mmax)\n elif isinstance(source, PointSource):\n self._get_point_rates(source, mmin, mmax)\n else:\n print(\"Source type %s not recognised - skipping!\" % source)\n continue\n\n def _get_point_location(self, location):\n \"\"\"\n Returns the location in the output grid corresponding to the cell in\n which the epicentre lays\n\n :param location:\n Source hypocentre as instance of :class:\n openquake.hazardlib.geo.point.Point\n :returns:\n xloc - Location of longitude cell\n yloc - Location of latitude cell\n \"\"\"\n if (location.longitude < self.xlim[0]) or\\\n (location.longitude > self.xlim[-1]):\n return None, None\n xloc = int(((location.longitude - self.xlim[0]) / self.xspc) + 1E-7)\n if (location.latitude < self.ylim[0]) or\\\n (location.latitude > self.ylim[-1]):\n return None, None\n yloc = int(((location.latitude - self.ylim[0]) / self.yspc) + 1E-7)\n return xloc, yloc\n\n def _get_point_rates(self, source, mmin, mmax=np.inf):\n \"\"\"\n Adds the rates for a point source\n\n :param source:\n Point source as instance of :class:\n openquake.hazardlib.source.point.PointSource\n :param float mmin:\n Minimum Magnitude\n :param float mmax:\n Maximum Magnitude\n \"\"\"\n xloc, yloc = self._get_point_location(source.location)\n if (xloc is None) or (yloc is None):\n return\n # Get annual rates\n annual_rate = source.get_annual_occurrence_rates()\n mags = np.array([val[0] for val in annual_rate])\n annual_rate = np.array([val[1] for val in annual_rate])\n idx = np.logical_and(mags >= mmin, mags < mmax)\n annual_rate = np.sum(annual_rate[idx])\n for hypo_depth in source.hypocenter_distribution.data:\n zloc = int((hypo_depth[1] - self.zlim[0]) / self.zspc)\n if (zloc < 0) or (zloc >= (self.nz - 1)):\n continue\n else:\n self.rates[xloc, yloc, zloc] += float(hypo_depth[0]) * \\\n annual_rate\n\n def _get_area_rates(self, source, mmin, mmax=np.inf):\n \"\"\"\n Adds the rates from the area source by discretising the source\n to a set of point sources\n\n :param source:\n Area source as instance of :class:\n openquake.hazardlib.source.area.AreaSource\n \"\"\"\n points = list(source)\n for point in points:\n self._get_point_rates(point, mmin, mmax)\n\n def _get_fault_rates(self, source, mmin, mmax=np.inf):\n \"\"\"\n Adds the rates for a simple or complex fault source\n\n :param source:\n Fault source as instance of :class:\n openquake.hazardlib.source.simple_fault.SimpleFaultSource or\n openquake.hazardlib.source.complex_fault.ComplexFaultSource\n \"\"\"\n for rupt in list(source.iter_ruptures()):\n valid_rupt = (rupt.mag >= mmin) and (rupt.mag < mmax)\n if not valid_rupt:\n continue\n grd = np.column_stack([rupt.surface.mesh.lons.flatten(),\n rupt.surface.mesh.lats.flatten(),\n rupt.surface.mesh.depths.flatten()])\n npts = np.shape(grd)[0]\n counter = np.histogramdd(grd,\n bins=[self.xlim, self.ylim, self.zlim]\n )[0]\n point_rate = rupt.occurrence_rate / float(npts)\n self.rates += (point_rate * counter)\n\n\nclass RatePolygon(RateGrid):\n \"\"\"\n Calculates the rate of events within a polygon\n\n :param limits:\n Polygon as instance of :class: openquake.hazardlib.geo.polygon.Polygon\n :param float upper_depth:\n Upper seismic depth of the polygon (km)\n :param float lower_depth:\n Lower seismic depth of the polygon (km)\n :param list source_model:\n List of seismic sources\n :param float rates:\n Activity rate of polygon\n :param float area_discretisation:\n Discretisation spacing (km) of the area source\n \"\"\"\n\n def __init__(self, limits, sources, area_discretisation=10.):\n \"\"\"\n Instantiate class with grid configurations\n :param dict limits:\n Configuration as dictionary containing:\n * polygon - OpenQuake Polygon\n * uppper_depth - upper seismogenic depth (km)\n * lower_depth - lower seismogenic depth (km)\n \"\"\"\n assert isinstance(limits[\"polygon\"], Polygon)\n self.limits = limits[\"polygon\"]\n self.upper_depth = limits[\"upper_depth\"]\n self.lower_depth = limits[\"lower_depth\"]\n self.source_model = sources\n self.rates = 0.0\n self.area_discretisation = area_discretisation\n\n def _get_point_rates(self, source, mmin, mmax=np.inf):\n \"\"\"\n Adds the rates for a point source\n\n :param source:\n Point source as instance of :class:\n openquake.hazardlib.source.point.PointSource\n :param float mmin:\n Minimum Magnitude\n :param float mmax:\n Maximum Magnitude\n \"\"\"\n src_mesh = Mesh.from_points_list([source.location])\n in_poly = self.limits.intersects(src_mesh)[0]\n if not in_poly:\n return\n else:\n for (mag, rate) in source.get_annual_occurrence_rates():\n if (mag < mmin) or (mag > mmax):\n return\n else:\n for (prob, depth) in source.hypocenter_distribution.data:\n if (depth < self.upper_depth) or\\\n (depth > self.lower_depth):\n continue\n else:\n self.rates += (prob * rate)\n\n def _get_fault_rates(self, source, mmin, mmax=np.inf):\n \"\"\"\n Adds the rates for a simple or complex fault source\n\n :param source:\n Fault source as instance of :class:\n openquake.hazardlib.source.simple_fault.SimpleFaultSource or\n openquake.hazardlib.source.complex_fault.ComplexFaultSource\n \"\"\"\n for rup in list(source.iter_ruptures()):\n if (rup.mag < mmin) or (rup.mag > mmax):\n # Magnitude outside search range\n continue\n depths = rup.surface.mesh.depths.flatten()\n # Generate simple mesh from surface\n rupt_mesh = Mesh(rup.surface.mesh.lons.flatten(),\n rup.surface.mesh.lats.flatten(),\n depths)\n # Mesh points in polygon\n in_poly = self.limits.intersects(rupt_mesh)\n in_depth = np.logical_and(depths >= self.upper_depth,\n depths <= self.lower_depth)\n idx = np.logical_and(in_poly, in_depth)\n if np.any(idx):\n node_rate = rup.occurrence_rate / float(len(depths))\n self.rates += (node_rate * np.sum(idx))\n", "meta": {"hexsha": "3f9a21e59a00220f380e4db456400e171117b57b", "size": 13970, "ext": "py", "lang": "Python", "max_stars_repo_path": "A_SHERIFS_CAD/lib/hmtk/comparison/rate_grids.py", "max_stars_repo_name": "fault2shaESCWG/CentralApenninesLabFAULT2RISK", "max_stars_repo_head_hexsha": "362cbc8b8dda0c2b5ba1e0ef5c9144fb6acb2ed3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A_SHERIFS_CAD/lib/hmtk/comparison/rate_grids.py", "max_issues_repo_name": "fault2shaESCWG/CentralApenninesLabFAULT2RISK", "max_issues_repo_head_hexsha": "362cbc8b8dda0c2b5ba1e0ef5c9144fb6acb2ed3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A_SHERIFS_CAD/lib/hmtk/comparison/rate_grids.py", "max_forks_repo_name": "fault2shaESCWG/CentralApenninesLabFAULT2RISK", "max_forks_repo_head_hexsha": "362cbc8b8dda0c2b5ba1e0ef5c9144fb6acb2ed3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-10-30T16:39:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-27T17:12:43.000Z", "avg_line_length": 39.1316526611, "max_line_length": 81, "alphanum_fraction": 0.6066571224, "include": true, "reason": "import numpy", "num_tokens": 3085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.27202456289736326, "lm_q1q2_score": 0.13813730041464575}} {"text": "#! /usr/bin/env python\n\n\"\"\"\nModule with the MCMC (``emcee``) sampling for model spectra parameter \nestimation.\n\"\"\"\n\n__author__ = 'V. Christiaens, O. Wertz, Carlos Alberto Gomez Gonzalez'\n__all__ = ['mcmc_spec_sampling',\n 'spec_lnprob',\n 'spec_chain_zero_truncated',\n 'spec_show_corner_plot',\n 'spec_show_walk_plot',\n 'spec_confidence']\n\nfrom astropy import constants as con\nimport numpy as np\nimport os\nfrom os.path import isdir, isfile\nimport emcee\nimport inspect\nimport datetime\nimport corner\nfrom matplotlib import pyplot as plt\nfrom matplotlib.ticker import MaxNLocator\nimport pickle\nfrom scipy.stats import norm\nfrom ..conf import time_ini, timing\nfrom ..conf.utils_conf import sep\nfrom ..fits import open_fits, write_fits\nfrom ..negfc.utils_mcmc import gelman_rubin, autocorr_test\nfrom .chi import goodness_of_fit\nfrom .model_resampling import make_model_from_params, make_resampled_models\nfrom .utils_spec import mj_from_rj_and_logg\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n\n\ndef spec_lnprior(params, labels, bounds, priors=None):\n \"\"\" Define the prior log-function.\n \n Parameters\n ----------\n params: tuple\n The model parameters.\n labels: Tuple of strings\n Tuple of labels in the same order as initial_state, that is:\n - first all parameters related to loaded models (e.g. 'Teff', 'logg')\n - then the planet photometric radius 'R', in Jupiter radius\n - (optionally) the flux of emission lines (labels should match those in\n the em_lines dictionary), in units of the model spectrum (times mu)\n - (optionally) the optical extinction 'Av', in mag\n - (optionally) the ratio of total to selective optical extinction 'Rv'\n - (optionally) 'Tbb1', 'Rbb1', 'Tbb2', 'Rbb2', etc. for each extra bb\n contribution.\n bounds: dictionary\n Each entry should be associated with a tuple corresponding to lower and \n upper bounds respectively. Bounds should be provided for ALL model\n parameters, including 'R' (planet photometric radius). 'Av' (optical \n extinction) is optional. If provided here, Av will also be fitted.\n All keywords that are neither 'R', 'Av' nor 'M' will \n be considered model grid parameters.\n Example for BT-SETTL: bounds = {'Teff':(1000,2000), 'logg':(3.0,4.5),\n 'R':(0.1,5), 'Av':(0.,2.5)}\n 'M' can be used for a prior on the mass of the planet. In that case the\n corresponding prior log probability is computed from the values for \n parameters 'logg' and 'R'.\n priors: dictionary, opt\n If not None, sets prior estimates for each parameter of the model. Each \n entry should be set to either None (no prior) or a tuple of 2 elements \n containing prior estimate and uncertainty on the estimate.\n Missing entries (i.e. provided in bounds dictionary but not here) will\n be associated no prior.\n e.g. priors = {'Teff':(1600,100), 'logg':(3.5,0.5),\n 'R':(1.6,0.1), 'Av':(1.8,0.2), 'M':(10,3)}\n Important: dictionary entry names should match exactly those of bounds.\n \n Returns\n -------\n out: float.\n If all parameters are within bounds:\n * 0 if no prior,\n * the sum of gaussian log proba for each prior otherwise.\n If at least one model parameters is out of bounds:\n returns -np.inf \n \"\"\"\n n_params = len(params)\n n_labs = len(labels)\n n_dico = len(bounds) \n if n_dico!=n_params or n_dico != n_labs:\n raise TypeError('params, labels and bounds should have same length')\n\n cond = True\n for pp in range(n_params):\n if not bounds[labels[pp]][0] <= params[pp] <= bounds[labels[pp]][1]:\n cond=False\n\n if cond:\n lnprior = 0.\n if priors is not None:\n for key, prior in priors.items():\n if key == 'M' and 'logg' in labels:\n idx_logg =labels.index(\"logg\")\n idx_rp = labels.index(\"R\")\n rp = params[idx_rp]\n logg = params[idx_logg]\n mp = mj_from_rj_and_logg(rp, logg)\n lnprior += -0.5 * (mp - prior[0])**2 / prior[1]**2\n else:\n idx_prior = labels.index(key)\n lnprior += -0.5*(params[idx_prior]-prior[0])**2/prior[1]**2\n return lnprior\n else:\n return -np.inf\n\n\ndef spec_lnlike(params, labels, grid_param_list, lbda_obs, spec_obs, err_obs, \n dist, model_grid=None, model_reader=None, em_lines={}, \n em_grid={}, dlbda_obs=None, instru_corr=None, \n instru_fwhm=None, instru_idx=None, filter_reader=None, \n AV_bef_bb=False, units_obs='si', units_mod='si', interp_order=1):\n \"\"\" Define the likelihood log-function.\n \n Parameters\n ----------\n params : tuple\n Set of models parameters for which the model grid has to be \n interpolated.\n labels: Tuple of strings\n Tuple of labels in the same order as initial_state, that is:\n - first all parameters related to loaded models (e.g. 'Teff', 'logg')\n - then the planet photometric radius 'R', in Jupiter radius\n - (optionally) the flux of emission lines (labels should match those in\n the em_lines dictionary), in units of the model spectrum (times mu)\n - (optionally) the optical extinction 'Av', in mag\n - (optionally) the ratio of total to selective optical extinction 'Rv'\n - (optionally) 'Tbb1', 'Rbb1', 'Tbb2', 'Rbb2', etc. for each extra bb\n contribution.\n grid_param_list : list of 1d numpy arrays/lists OR None\n - If list, should contain list/numpy 1d arrays with available grid of \n model parameters. \n - Set to None for a pure n-blackbody fit, n=1,2,...\n - Note1: model grids should not contain grids on radius and Av, but \n these should still be passed in initial_state (Av optional).\n - Note2: for a combined grid model + black body, just provide\n the grid parameter list here, and provide values for 'Tbbn' and 'Rbbn'\n in initial_state, labels and bounds.\n lbda_obs : numpy 1d ndarray or list\n Wavelength of observed spectrum. If several instruments, should be \n ordered per instrument, not necessarily as monotonically increasing \n wavelength. Hereafter, n_ch = len(lbda_obs).\n spec_obs : numpy 1d ndarray or list\n Observed spectrum for each value of lbda_obs.\n err_obs : numpy 1d/2d ndarray or list\n Uncertainties on the observed spectrum. If 2d array, should be [2,n_ch]\n where the first (resp. second) column corresponds to lower (upper) \n uncertainty, and n_ch is the length of lbda_obs and spec_obs.\n dist : float\n Distance in parsec, used for flux scaling of the models.\n model_grid : numpy N-d array, optional\n If provided, should contain the grid of model spectra for each\n free parameter of the given grid. I.e. for a grid of n_T values of Teff \n and n_g values of Logg, the numpy array should be n_T x n_g x n_ch x 2, \n where n_ch is the number of wavelengths for the observed spectrum,\n and the last 2 dims are for wavelength and fluxes respectively.\n If provided, takes precedence over model_name/model_reader.\n model_reader : python routine, opt\n External routine that reads a model file and returns a 2D numpy array, \n where the first column corresponds to wavelengths, and the second \n contains model values. See example routine in model_interpolation() \n description.\n em_lines: dictionary, opt\n Dictionary of emission lines to be added on top of the model spectrum.\n Each dict entry should be the name of the line, assigned to a tuple of\n 4 values: \n 1) the wavelength (in mu); \n 2) a string indicating whether line intensity is expressed in flux \n ('F'), luminosity ('L') or log(L/LSun) (\"LogL\");\n 3) the FWHM of the gaussian (or None if to be set automatically); \n 4) whether the FWHM is expressed in 'nm', 'mu' or 'km/s'. \n The third and fourth can also be set to None. In that case, the FWHM of \n the gaussian will automatically be set to the equivalent width of the\n line, calculated from the flux to be injected and the continuum \n level (measured in the grid model to which the line is injected). \n Examples: em_lines = {'BrG':(2.1667,'F',None, None)};\n em_lines = {'BrG':(2.1667,'LogL', 100, 'km/s')}\n em_grid: dictionary pointing to lists, opt\n Dictionary where each entry corresponds to an emission line and points\n to a list of values to inject for emission line fluxes. For computation \n efficiency, interpolation will be performed between the points of this \n grid during the MCMC sampling. Dict entries should match labels and \n em_lines.\n dlbda_obs: numpy 1d ndarray or list, optional\n Spectral channel width for the observed spectrum. It should be provided \n IF one wants to weigh each point based on the spectral \n resolution of the respective instruments (as in Olofsson et al. 2016).\n instru_corr : numpy 2d ndarray or list, optional\n Spectral correlation throughout post-processed images in which the \n spectrum is measured. It is specific to the combination of instrument, \n algorithm and radial separation of the companion from the central star.\n Can be computed using distances.spectral_correlation(). In case of\n a spectrum obtained with different instruments, build it with\n distances.combine_corrs(). If not provided, it will consider the \n uncertainties in each spectral channels are independent. See Greco & \n Brandt (2017) for details.\n instru_fwhm : float or list, optional\n The instrumental spectral fwhm provided in nm. This is used to convolve\n the model spectrum. If several instruments are used, provide a list of \n instru_fwhm values, one for each instrument whose spectral resolution\n is coarser than the model - including broad band\n filter FWHM if relevant.\n instru_idx: numpy 1d array, optional\n 1d array containing an index representing each instrument used \n to obtain the spectrum, label them from 0 to n_instru. Zero for points \n that don't correspond to any instru_fwhm provided above, and i in \n [1,n_instru] for points associated to instru_fwhm[i-1]. This parameter \n must be provided if the spectrum consists of points obtained with \n different instruments.\n filter_reader: python routine, optional\n External routine that reads a filter file and returns a 2D numpy array, \n where the first column corresponds to wavelengths, and the second \n contains transmission values. Important: if not provided, but strings \n are detected in instru_fwhm, the default format assumed for the files:\n - first row containing header\n - starting from 2nd row: 1st column: WL in mu, 2nd column: transmission\n Note: files should all have the same format and wavelength units.\n AV_bef_bb: bool, optional\n If both extinction and an extra bb component are free parameters, \n whether to apply extinction before adding the BB component (e.g. \n extinction mostly from circumplanetary dust) or after the BB component\n (e.g. mostly insterstellar extinction).\n units_obs : str, opt {'si','cgs','jy'}\n Units of observed spectrum. 'si' for W/m^2/mu; 'cgs' for ergs/s/cm^2/mu \n or 'jy' for janskys.\n units_mod: str, opt {'si','cgs','jy'}\n Units of the model. 'si' for W/m^2/mu; 'cgs' for ergs/s/cm^2/mu or 'jy'\n for janskys. If different to units_obs, the spectrum units will be \n converted.\n interp_order: int, opt, {-1,0,1} \n Interpolation mode for model interpolation.\n -1: log interpolation (i.e. linear interpolatlion on log(Flux))\n 0: nearest neighbour model.\n 1: Order 1 spline interpolation.\n \n Returns\n -------\n out: float\n The log of the likelihood.\n \n \"\"\"\n\n if grid_param_list is not None:\n if model_grid is None and model_reader is None:\n msg = \"model_name and model_reader must be provided\"\n raise TypeError(msg)\n \n lbda_mod, spec_mod = make_model_from_params(params, labels, grid_param_list, \n dist, lbda_obs, model_grid, \n model_reader, em_lines, em_grid, \n dlbda_obs, instru_fwhm, \n instru_idx, filter_reader, \n AV_bef_bb, units_obs, units_mod, \n interp_order)\n \n # evaluate the goodness of fit indicator\n chi = goodness_of_fit(lbda_obs, spec_obs, err_obs, lbda_mod, spec_mod, \n dlbda_obs=dlbda_obs, instru_corr=instru_corr, \n instru_fwhm=instru_fwhm, instru_idx=instru_idx, \n filter_reader=filter_reader, plot=False, outfile=None)\n \n # log likelihood\n lnlikelihood = -0.5 * chi\n \n return lnlikelihood\n\n\ndef spec_lnprob(params, labels, bounds, grid_param_list, lbda_obs, spec_obs, \n err_obs, dist, model_grid=None, model_reader=None, em_lines={},\n em_grid={}, dlbda_obs=None, instru_corr=None, instru_fwhm=None, \n instru_idx=None, filter_reader=None, AV_bef_bb=False, \n units_obs='si', units_mod='si', interp_order=1, priors=None, \n physical=True):\n \"\"\" Define the probability log-function as the sum between the prior and\n likelihood log-functions.\n \n Parameters\n ----------\n params: tuple\n The model parameters.\n labels: Tuple of strings\n Tuple of labels in the same order as initial_state, that is:\n - first all parameters related to loaded models (e.g. 'Teff', 'logg')\n - then the planet photometric radius 'R', in Jupiter radius\n - (optionally) the flux of emission lines (labels should match those \\\n in the em_lines dictionary), in units of the model spectrum (times mu)\n - (optionally) the optical extinction 'Av', in mag\n - (optionally) the ratio of total to selective optical extinction 'Rv'\n - (optionally) 'Tbb1', 'Rbb1', 'Tbb2', 'Rbb2', etc. for each extra bb \\\n contribution.\n bounds: dictionary\n Each entry should be associated with a tuple corresponding to lower and \n upper bounds respectively. Bounds should be provided for ALL model\n parameters, including 'R' (planet photometric radius). 'Av' (optical \n extinction) is optional. If provided here, Av will also be fitted.\n All keywords that are neither 'R', 'Av' nor 'M' will \n be considered model grid parameters.\n Example for BT-SETTL: bounds = {'Teff':(1000,2000), 'logg':(3.0,4.5),\n 'R':(0.1,5), 'Av':(0.,2.5)}\n 'M' can be used for a prior on the mass of the planet. In that case the\n corresponding prior log probability is computed from the values for \n parameters 'logg' and 'R'.\n grid_param_list : list of 1d numpy arrays/lists OR None\n - If list, should contain list/numpy 1d arrays with available grid of \\\n model parameters. \n - Set to None for a pure n-blackbody fit, n=1,2,...\n - Note1: model grids should not contain grids on radius and Av, but \\\n these should still be passed in initial_state (Av optional).\n - Note2: for a combined grid model + black body, just provide \\\n the grid parameter list here, and provide values for 'Tbbn' and 'Rbbn' \\\n in initial_state, labels and bounds.\n lbda_obs : numpy 1d ndarray or list\n Wavelength of observed spectrum. If several instruments, should be \n ordered per instrument, not necessarily as monotonically increasing \n wavelength. Hereafter, n_ch = len(lbda_obs).\n spec_obs : numpy 1d ndarray or list\n Observed spectrum for each value of lbda_obs.\n err_obs : numpy 1d/2d ndarray or list\n Uncertainties on the observed spectrum. If 2d array, should be [2,n_ch]\n where the first (resp. second) column corresponds to lower (upper) \n uncertainty, and n_ch is the length of lbda_obs and spec_obs.\n dist : float\n Distance in parsec, used for flux scaling of the models.\n model_grid : numpy N-d array, optional\n If provided, should contain the grid of model spectra for each\n free parameter of the given grid. I.e. for a grid of n_T values of Teff \n and n_g values of Logg, the numpy array should be n_T x n_g x n_ch x 2, \n where n_ch is the number of wavelengths for the observed spectrum,\n and the last 2 dims are for wavelength and fluxes respectively.\n If provided, takes precedence over model_name/model_reader.\n model_reader : python routine\n External routine that reads a model file and returns a 2D numpy array, \n where the first column corresponds to wavelengths, and the second \n contains model values. See example routine in model_interpolation() \n description.\n em_lines: dictionary, opt\n Dictionary of emission lines to be added on top of the model spectrum.\n Each dict entry should be the name of the line, assigned to a tuple of\n 4 values: \n 1) the wavelength (in mu); \n 2) a string indicating whether line intensity is expressed in flux \n ('F'), luminosity ('L') or log(L/LSun) (\"LogL\");\n 3) the FWHM of the gaussian (or None if to be set automatically); \n 4) whether the FWHM is expressed in 'nm', 'mu' or 'km/s'. \n The third and fourth can also be set to None. In that case, the FWHM of \n the gaussian will automatically be set to the equivalent width of the\n line, calculated from the flux to be injected and the continuum \n level (measured in the grid model to which the line is injected). \n Examples:\n em_lines = {'BrG':(2.1667,'F',None, None)};\n em_lines = {'BrG':(2.1667,'LogL', 100, 'km/s')}\n em_grid: dictionary pointing to lists, opt\n Dictionary where each entry corresponds to an emission line and points\n to a list of values to inject for emission line fluxes. For computation \n efficiency, interpolation will be performed between the points of this \n grid during the MCMC sampling. Dict entries should match labels and \n em_lines.\n dlbda_obs: numpy 1d ndarray or list, optional\n Spectral channel width for the observed spectrum. It should be provided \n IF one wants to weigh each point based on the spectral \n resolution of the respective instruments (as in Olofsson et al. 2016).\n instru_corr : numpy 2d ndarray or list, optional\n Spectral correlation throughout post-processed images in which the \n spectrum is measured. It is specific to the combination of instrument, \n algorithm and radial separation of the companion from the central star.\n Can be computed using distances.spectral_correlation(). In case of\n a spectrum obtained with different instruments, build it with\n distances.combine_corrs(). If not provided, it will consider the \n uncertainties in each spectral channels are independent. See Greco & \n Brandt (2017) for details.\n instru_fwhm : float or list, optional\n The instrumental spectral fwhm provided in nm. This is used to convolve\n the model spectrum. If several instruments are used, provide a list of \n instru_fwhm values, one for each instrument whose spectral resolution\n is coarser than the model - including broad band\n filter FWHM if relevant.\n instru_idx: numpy 1d array, optional\n 1d array containing an index representing each instrument used \n to obtain the spectrum, label them from 0 to n_instru. Zero for points \n that don't correspond to any instru_fwhm provided above, and i in \n [1,n_instru] for points associated to instru_fwhm[i-1]. This parameter \n must be provided if the spectrum consists of points obtained with \n different instruments.\n filter_reader: python routine, optional\n External routine that reads a filter file and returns a 2D numpy array, \n where the first column corresponds to wavelengths, and the second \n contains transmission values. Important: if not provided, but strings \n are detected in instru_fwhm, the default format assumed for the files:\n - first row containing header\n - starting from 2nd row: 1st column: WL in mu, 2nd column: transmission\n Note: files should all have the same format and wavelength units.\n AV_bef_bb: bool, optional\n If both extinction and an extra bb component are free parameters, \n whether to apply extinction before adding the BB component (e.g. \n extinction mostly from circumplanetary dust) or after the BB component\n (e.g. mostly insterstellar extinction).\n units_obs : str, opt {'si','cgs','jy'}\n Units of observed spectrum. 'si' for W/m^2/mu; 'cgs' for ergs/s/cm^2/mu \n or 'jy' for janskys.\n units_mod: str, opt {'si','cgs','jy'}\n Units of the model. 'si' for W/m^2/mu; 'cgs' for ergs/s/cm^2/mu or 'jy'\n for janskys. If different to units_obs, the spectrum units will be \n converted.\n interp_order: int, opt, {-1,0,1} \n Interpolation mode for model interpolation.\n -1: log interpolation (i.e. linear interpolatlion on log(Flux))\n 0: nearest neighbour model.\n 1: Order 1 spline interpolation.\n priors: dictionary, opt\n If not None, sets prior estimates for each parameter of the model. Each \n entry should be set to either None (no prior) or a tuple of 2 elements \n containing prior estimate and uncertainty on the estimate.\n Missing entries (i.e. provided in bounds dictionary but not here) will\n be associated no prior.\n e.g. priors = {'Teff':(1600,100), 'logg':(3.5,0.5), 'R':(1.6,0.1), \n 'Av':(1.8,0.2), 'M':(10,3)}\n \n Important: dictionary entry names should match exactly those of bounds.\n physical: bool, opt\n In case of extra black body component(s) to a photosphere, whether to \n force lower temperature than the photosphere effective temperature.\n \n Returns\n -------\n out: float\n The probability log-function.\n \n \"\"\"\n \n lp = spec_lnprior(params, labels, bounds, priors)\n \n if np.isinf(lp):\n return -np.inf\n \n if 'Tbb1' in labels:\n condT = ('T' in labels or 'Teff' in labels)\n n_bb = 0\n for label in labels:\n if 'Tbb' in label:\n n_bb+=1\n idx_Tbb1 = labels.index(\"Tbb1\")\n for ii in range(n_bb):\n idx = ii*2\n if grid_param_list is not None and condT:\n if 'T' in labels:\n idx_Teff = labels.index(\"T\")\n else:\n idx_Teff = labels.index(\"Teff\")\n # COND 1: only allow Tbb < Teff\n if physical and params[idx_Tbb1+idx] >= params[idx_Teff]:\n return -np.inf\n elif physical:\n idx_R= labels.index(\"R\")\n R = params[idx_R]\n Rbb = params[idx_Tbb1+idx+1]\n if Rbb<=R:\n pass\n else:\n Teq = params[idx_Teff] * np.sqrt(R/(2*Rbb))\n # COND 2: only allow Tbb <= Teq at Rbb\n if params[idx_Tbb1+idx] >= Teq:\n return -np.inf\n if ii>0:\n # avoid unnecessary degenerecaies by only allowing:\n # Teff1 > Teff2, Teff2 > Teff3\n if params[idx_Tbb1+idx] >= params[idx_Tbb1+idx-2]:\n return -np.inf\n \n return lp + spec_lnlike(params, labels, grid_param_list, lbda_obs, spec_obs, \n err_obs, dist, model_grid, model_reader, em_lines,\n em_grid, dlbda_obs, instru_corr, instru_fwhm, \n instru_idx, filter_reader, AV_bef_bb, units_obs, \n units_mod, interp_order)\n\n\ndef mcmc_spec_sampling(lbda_obs, spec_obs, err_obs, dist, grid_param_list, \n initial_state, labels, bounds, resamp_before=True, \n model_grid=None, model_reader=None, em_lines={}, \n em_grid={}, dlbda_obs=None, instru_corr=None, \n instru_fwhm=None, instru_idx=None, filter_reader=None, \n AV_bef_bb=False, units_obs='si', units_mod='si', \n interp_order=1, priors=None, physical=True, \n interp_nonexist=True, ini_ball=1e-1, a=2.0, \n nwalkers=1000, niteration_min=10, niteration_limit=1000, \n niteration_supp=0, check_maxgap=20, conv_test='ac', \n ac_c=50, ac_count_thr=3, burnin=0.3, rhat_threshold=1.01, \n rhat_count_threshold=1, grid_name='resamp_grid.fits', \n output_dir='specfit/', output_file=None, nproc=1, \n display=False, verbosity=0, save=False):\n \"\"\" Runs an affine invariant MCMC sampling algorithm in order to determine\n the most likely parameters for given spectral model and observed spectrum. \n Allowed features:\n \n * Spectral models can either be read from a grid (e.g. BT-SETTL) or \\\n be purely parametric (e.g. a blackbody model). \n \n * Extinction (A_V) and total-to-selective optical extinction ratio \\\n (R_V) can be sampled. Default: A_V=0. If non-zero, default R_V=3.1 (ISM).\n \n * A dictionary of emission lines can be provided and their flux can \\\n be sampled too.\n \n * Gaussian priors can be provided for each parameter, including the \\\n mass of the object. The latter will be used if 'logg' is a parameter.\n \n * Spectral correlation between measurements will be taken into account \\ \n if provided in 'instru_corr'.\n \n * Convolution of the model spectra with instrumental FWHM or \\\n photometric filter can be performed using 'instru_fwhm' and/or \\\n 'filter_reader' (done before resampling to observed).\n \n * The weight of each observed point will be directly proportional to \\\n Delta lbda_i/lbda_i, where Delta lbda_i is either the FWHM of the \\\n photometric filter (imager) or the width of the spectral channel (IFS).\n \n * MCMC convergence criterion can either be based on auto-correlation \\\n time (default) or the Gelman-Rubin test.\n \n The result of this procedure is a chain with the samples from the posterior \n distributions of each of the free parameters in the model.\n More details in Christiaens et al. (2021).\n \n Parameters\n ----------\n lbda_obs : numpy 1d ndarray or list\n Wavelength of observed spectrum. If several instruments, should be \n ordered per instrument, not necessarily as monotonically increasing \n wavelength. Hereafter, n_ch = len(lbda_obs).\n spec_obs : numpy 1d ndarray or list\n Observed spectrum for each value of lbda_obs.\n err_obs : numpy 1d/2d ndarray or list\n Uncertainties on the observed spectrum. If 2d array, should be [2,n_ch]\n where the first (resp. second) column corresponds to lower (upper) \n uncertainty, and n_ch is the length of lbda_obs and spec_obs.\n dist : float\n Distance in parsec, used for flux scaling of the models.\n grid_param_list : list of 1d numpy arrays/lists OR None\n - If list, should contain list/numpy 1d arrays with available grid of \\\n model parameters. \n - Set to None for a pure n-blackbody fit, n=1,2,...\n - Note1: model grids should not contain grids on radius and Av, but \\\n these should still be passed in initial_state (Av optional).\n - Note2: for a combined grid model + black body, just provide \\\n the grid parameter list here, and provide values for 'Tbbn' and 'Rbbn' \\\n in initial_state, labels and bounds.\n \n initial_state: tuple of floats\n Initial guess on the best fit parameters of the spectral fit. Length of \n the tuple should match the total number of free parameters. Walkers\n will all be initialised in a small ball of parameter space around that\n first guess.\n - first all parameters related to loaded models (e.g. 'Teff', 'logg')\n - then the planet photometric radius 'R', in Jupiter radius\n - (optionally) the intensity of emission lines (labels must match \\\n those in the em_lines dict), in units of the model spectrum (x mu)\n - (optionally) the optical extinction 'Av', in mag\n - (optionally) the ratio of total to selective optical extinction 'Rv'\n - (optionally) 'Tbb1', 'Rbb1', 'Tbb2', 'Rbb2', etc. for each extra bb \\\n contribution\n \n labels: Tuple of strings\n Tuple of labels in the same order as initial_state, that is:\n - first all parameters related to loaded models (e.g. 'Teff', 'logg')\n - then the planet photometric radius 'R', in Jupiter radius\n - (optionally) the flux of emission lines (labels should match those \\\n in the em_lines dictionary), in units of the model spectrum (times mu)\n - (optionally) the optical extinction 'Av', in mag\n - (optionally) the ratio of total to selective optical extinction 'Rv'\n - (optionally) 'Tbb1', 'Rbb1', 'Tbb2', 'Rbb2', etc. for each extra bb \\\n contribution.\n \n bounds: dictionary\n Each entry should be associated with a tuple corresponding to lower and \n upper bounds respectively. Bounds should be provided for ALL model\n parameters, including 'R' (planet photometric radius). 'Av' (optical \n extinction) is optional. If provided here, Av will also be fitted.\n Example for BT-SETTL: bounds = {'Teff':(1000,2000), 'logg':(3.0,4.5),\n 'R':(0.1,5), 'Av':(0.,2.5)}\n 'M' can be used for a prior on the mass of the planet. In that case the\n corresponding prior log probability is computed from the values for \n parameters 'logg' and 'R' (if both exist).\n resamp_before: bool, optional\n Whether to prepare the whole grid of resampled models before entering \n the MCMC, i.e. to avoid doing it at every MCMC step. Recommended.\n Only reason not to: model grid is too large and individual models \n require being opened and resampled at each step.\n model_grid : numpy N-d array, optional\n If provided, should contain the grid of model spectra for each\n free parameter of the given grid. I.e. for a grid of n_T values of Teff \n and n_g values of Logg, the numpy array should be n_T x n_g x n_ch x 2, \n where n_ch is the number of wavelengths for the observed spectrum,\n and the last 2 dims are for wavelength and fluxes respectively.\n If provided, takes precedence over filename/file_reader.\n model_reader : python routine, optional\n External routine that reads a model file and returns a 2D numpy array, \n where the first column corresponds to wavelengths, and the second \n contains model values. See example routine in model_interpolation() \n description.\n em_lines: dictionary, opt\n Dictionary of emission lines to be added on top of the model spectrum.\n Each dict entry should be the name of the line, assigned to a tuple of\n 4 values: \n 1) the wavelength (in mu); \n 2) a string indicating whether line intensity is expressed in flux \n ('F'), luminosity ('L') or log(L/LSun) (\"LogL\");\n 3) the FWHM of the gaussian (or None if to be set automatically); \n 4) whether the FWHM is expressed in 'nm', 'mu' or 'km/s'. \n The third and fourth can also be set to None. In that case, the FWHM of \n the gaussian will automatically be set to the equivalent width of the\n line, calculated from the flux to be injected and the continuum \n level (measured in the grid model to which the line is injected). \n Examples: \n em_lines = {'BrG':(2.1667,'F', None, None)};\n em_lines = {'BrG':(2.1667,'LogL', 100, 'km/s')}\n em_grid: dictionary pointing to lists, opt\n Dictionary where each entry corresponds to an emission line and points\n to a list of values to inject for emission line fluxes. For computation \n efficiency, interpolation will be performed between the points of this \n grid during the MCMC sampling. Dict entries should match labels and \n em_lines.\n dlbda_obs: numpy 1d ndarray or list, optional\n Spectral channel width for the observed spectrum. It should be provided \n IF one wants to weigh each point based on the spectral \n resolution of the respective instruments (as in Olofsson et al. 2016).\n instru_corr : numpy 2d ndarray or list, optional\n Spectral correlation throughout post-processed images in which the \n spectrum is measured. It is specific to the combination of instrument, \n algorithm and radial separation of the companion from the central star.\n Can be computed using distances.spectral_correlation(). In case of\n a spectrum obtained with different instruments, build it with\n distances.combine_corrs(). If not provided, it will consider the \n uncertainties in each spectral channels are independent. See Greco & \n Brandt (2017) for details.\n instru_fwhm : float OR list of either floats or strings, optional\n The instrumental spectral fwhm provided in nm. This is used to convolve\n the model spectrum. If several instruments are used, provide a list of \n instru_fwhm values, one for each instrument whose spectral resolution\n is coarser than the model - including broad band filter FWHM if \n relevant.\n If strings are provided, they should correspond to filenames (including \n full paths) of text files containing the filter information for each \n observed wavelength. Strict format: \n instru_idx: numpy 1d array, optional\n 1d array containing an index representing each instrument used \n to obtain the spectrum, label them from 0 to n_instru. Zero for points \n that don't correspond to any instru_fwhm provided above, and i in \n [1,n_instru] for points associated to instru_fwhm[i-1]. This parameter \n must be provided if the spectrum consists of points obtained with \n different instruments.\n filter_reader: python routine, optional\n External routine that reads a filter file and returns a 2D numpy array, \n where the first column corresponds to wavelengths, and the second \n contains transmission values. Important: if not provided, but strings \n are detected in instru_fwhm, the default file reader will be used. \n It assumes the following format for the files:\n - first row containing header\n - starting from 2nd row: 1st column: wavelength, 2nd col.: transmission\n - Unit of wavelength can be provided in parentheses of first header \\\n key name: e.g. \"WL(AA)\" for angstrom, \"wavelength(mu)\" for micrometer \\\n or \"lambda(nm)\" for nanometer. Note: Only what is in parentheses \\\n matters.\n \n Important: filter files should all have the same format and WL units.\n AV_bef_bb: bool, optional\n If both extinction and an extra bb component are free parameters, \n whether to apply extinction before adding the BB component (e.g. \n extinction mostly from circumplanetary dust) or after the BB component\n (e.g. mostly insterstellar extinction).\n units_obs : str, opt {'si','cgs','jy'}\n Units of observed spectrum. 'si' for W/m^2/mu; 'cgs' for ergs/s/cm^2/mu \n or 'jy' for janskys.\n units_mod: str, opt {'si','cgs','jy'}\n Units of the model. 'si' for W/m^2/mu; 'cgs' for ergs/s/cm^2/mu or 'jy'\n for janskys. If different to units_obs, the spectrum units will be \n converted.\n interp_order: int, opt, {-1,0,1} \n Interpolation mode for model interpolation.\n -1: log interpolation (i.e. linear interpolatlion on log(Flux))\n 0: nearest neighbour model.\n 1: Order 1 spline interpolation.\n priors: dictionary, opt\n If not None, sets prior estimates for each parameter of the model. Each \n entry should be set to either None (no prior) or a tuple of 2 elements \n containing prior estimate and uncertainty on the estimate.\n Missing entries (i.e. provided in bounds dictionary but not here) will\n be associated no prior.\n e.g. priors = {'Teff':(1600,100), 'logg':(3.5,0.5), 'R':(1.6,0.1), \n 'Av':(1.8,0.2), 'M':(10,3)}\n Important: dictionary entry names should match exactly those of bounds.\n physical: bool, opt\n In case of extra black body component(s) to a photosphere, whether to \n force lower temperature than the photosphere effective temperature.\n interp_nonexist: bool, opt\n Whether to interpolate non-existing models in the grid. Only used if \n resamp_before is set to True.\n ini_ball: float or string, default=1e-1\n Size of the initial ball in parameter space from which walkers start \n their chain. If \"uniform\" is provided, a uniform ini_ball spanning\n the bounds interval will be used to initialise walkers.\n a: float, default=2.0\n The proposal scale parameter. See notes.\n nwalkers: int, default: 1000\n Number of walkers\n niteration_min: int, optional\n Steps per walker lower bound. The simulation will run at least this\n number of steps per walker.\n niteration_limit: int, optional\n Steps per walker upper bound. If the simulation runs up to\n 'niteration_limit' steps without having reached the convergence\n criterion, the run is stopped.\n niteration_supp: int, optional\n Number of iterations to run after having \"reached the convergence\".\n burnin: float, default=0.3\n The fraction of a walker which is discarded.\n rhat_threshold: float, default=0.01\n The Gelman-Rubin threshold used for the test for nonconvergence.\n rhat_count_threshold: int, optional\n The Gelman-Rubin test must be satisfied 'rhat_count_threshold' times in\n a row before claiming that the chain has converged.\n check_maxgap: int, optional\n Maximum number of steps per walker between two convergence tests.\n conv_test: str, optional {'gb','autocorr'}\n Method to check for convergence: \n - 'gb' for gelman-rubin test \\\n (http://digitalassets.lib.berkeley.edu/sdtr/ucb/text/305.pdf)\n - 'autocorr' for autocorrelation analysis \\\n (https://emcee.readthedocs.io/en/stable/tutorials/autocorr/)\n \n nproc: int, optional\n The number of processes to use for parallelization.\n grid_name: str, optional\n Name of the fits file containing the model grid (numpy array) AFTER\n convolution+resampling as the observed spectrum given as input.\n If provided, will read it if it exists (and resamp_before is set\n to True), or make it and write it if it doesn't.\n output_dir: str, optional\n The name of the output directory which contains the output files in the \n case ``save`` is True. \n output_file: str, optional\n The name of the output file which contains the MCMC results in the case\n ``save`` is True.\n display: bool, optional\n If True, the walk plot is displayed at each evaluation of the Gelman-\n Rubin test.\n verbosity: 0, 1 or 2, optional\n Verbosity level. 0 for no output and 2 for full information.\n save: bool, optional\n If True, the MCMC results are pickled.\n \n Returns\n -------\n out : numpy.array\n The MCMC samples after truncation of zeros.\n lnprobability: emcee sample object\n The corresponding probabilities for each sample\n \n Notes\n -----\n The parameter `a` must be > 1. For more theoretical information concerning\n this parameter, see Goodman & Weare, 2010, Comm. App. Math. Comp. Sci.,\n 5, 65, Eq. [9] p70.\n \n The parameter 'rhat_threshold' can be a numpy.array with individual\n threshold value for each model parameter.\n \"\"\"\n nparams = len(initial_state)\n \n if grid_param_list is not None:\n if model_grid is None and model_reader is None:\n msg = \"Either model_grid or model_reader have to be provided\"\n raise TypeError(msg)\n n_gparams = len(grid_param_list)\n gp_dims = []\n for nn in range(n_gparams):\n gp_dims.append(len(grid_param_list[nn]))\n gp_dims = tuple(gp_dims)\n else:\n n_gparams = 0\n \n # format emission line dictionary and em grid\n if len(em_grid)>0:\n n_em = len(em_grid)\n em_dims = []\n for lab in labels:\n if lab in em_grid.keys():\n em_dims.append(len(em_grid[lab]))\n em_dims = tuple(em_dims)\n # update the grids depending on input units => make it surface flux\n idx_R = labels.index('R')\n for key, val in em_lines.items():\n if val[1] == 'L':\n idx_line = labels.index(key)\n # adapt grid\n R_si = initial_state[idx_R]*con.R_jup.value\n conv_fac = 4*np.pi*R_si**2\n tmp = np.array(em_grid[key])/conv_fac\n em_grid[key] = tmp.tolist()\n # adapt ini state \n initial_state = list(initial_state)\n initial_state[idx_line] /= conv_fac\n initial_state = tuple(initial_state)\n #adapt bounds\n bounds_ori = list(bounds[key])\n bounds[key] = (bounds_ori[0]/conv_fac, bounds_ori[1]/conv_fac) \n elif val[1] == 'LogL':\n idx_line = labels.index(key)\n R_si = initial_state[idx_R]*con.R_jup.value\n conv_fac = con.L_sun.value/(4*np.pi*R_si**2)\n tmp = np.power(10,np.array(em_grid[key]))*conv_fac\n em_grid[key] = tmp.tolist() \n # adapt ini state \n initial_state = list(initial_state)\n initial_state[idx_line] = conv_fac*10**initial_state[idx_line]\n initial_state = tuple(initial_state)\n #adapt bounds\n bounds_ori = list(bounds[key])\n bounds[key] = (conv_fac*10**bounds_ori[0], \n conv_fac*10**bounds_ori[1]) \n if em_lines[key][2] is not None:\n if em_lines[key][-1] == 'km/s':\n v = em_lines[key][2]\n em_lines_tmp = list(em_lines[key])\n em_lines_tmp[2] = (1000*v/con.c.value)*em_lines[key][0]\n em_lines_tmp[3] = 'mu'\n em_lines[key] = tuple(em_lines_tmp)\n elif em_lines[key][-1] == 'nm':\n em_lines_tmp = list(em_lines[key])\n em_lines_tmp[2] = em_lines[key][2]/1000\n em_lines_tmp[3] = 'mu'\n em_lines[key] = tuple(em_lines_tmp)\n elif em_lines[key][-1] != 'mu':\n msg = \"Invalid unit of FWHM for line injection\"\n raise ValueError(msg)\n \n if model_grid is not None and grid_param_list is not None:\n if model_grid.ndim-2 != n_gparams:\n msg = \"Ndim-2 of model_grid should match len(grid_param_list)\"\n raise TypeError(msg)\n \n if verbosity > 0:\n start_time = time_ini()\n print(\" MCMC sampler for spectral fitting \")\n print(sep)\n\n\n # If required, create the output folder.\n if save or resamp_before:\n if not output_dir:\n raise ValueError('Please provide an output directory path')\n if not isdir(output_dir):\n os.makedirs(output_dir)\n if output_dir[-1] != '/':\n output_dir = output_dir+'/'\n\n #output_file_tmp = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n \n # Check model grid parameters extend beyond bounds to avoid extrapolation\n if grid_param_list is not None:\n for pp in range(n_gparams):\n if grid_param_list[pp][0]>bounds[labels[pp]][0]:\n msg= \"Grid has to extend beyond bounds for {}.\"\n msg+=\"\\n Consider increasing the lower bound to >{}.\"\n raise ValueError(msg.format(labels[pp],grid_param_list[pp][0]))\n if grid_param_list[pp][-1]bounds[labels[pp]][1]:\n msg= \"Initial state has to be within bounds for {}.\"\n msg+=\"\\n Consider decreasing the upper bound to >{}.\"\n raise ValueError(msg.format(labels[pp],initial_state[pp]))\n \n # Prepare model grid: convolve+resample models as observations \n if resamp_before and grid_param_list is not None:\n if isfile(output_dir+grid_name):\n model_grid = open_fits(output_dir+grid_name)\n # check its shape is consistent with grid_param_list\n if model_grid.shape[:n_gparams] != gp_dims:\n msg=\"the loaded model grid ({}) doesn't have expected dims ({})\"\n raise TypeError(msg.format(model_grid.shape,gp_dims))\n elif model_grid.shape[-2] != len(lbda_obs):\n msg=\"the loaded model grid doesn't have expected WL dimension\"\n raise TypeError(msg)\n elif model_grid.shape[-1] != 2:\n msg=\"the loaded model grid doesn't have expected last dimension\"\n raise TypeError(msg)\n elif len(em_grid) > 0:\n if model_grid.shape[n_gparams:n_gparams+n_em] != em_dims:\n msg=\"loaded model grid ({}) doesn't have expected dims ({})\"\n raise TypeError(msg.format(model_grid.shape,em_dims))\n else:\n model_grid = make_resampled_models(lbda_obs, grid_param_list, \n model_grid, model_reader, \n em_lines, em_grid, dlbda_obs, \n instru_fwhm, instru_idx, \n filter_reader, interp_nonexist)\n if output_dir and grid_name:\n write_fits(output_dir+grid_name, model_grid)\n # note: if model_grid is provided, it is still resampled to the \n # same wavelengths as observed spectrum. However, if a fits name is \n # provided in grid_name and that file exists, it is assumed the model \n # grid in it is already resampled to match lbda_obs.\n\n if save and output_file is None:\n output_file = 'MCMC_results'\n\n \n # #########################################################################\n # Initialization of the MCMC variables #\n # #########################################################################\n dim = len(labels)\n itermin = niteration_min\n limit = niteration_limit\n supp = niteration_supp\n maxgap = check_maxgap\n initial_state = np.array(initial_state)\n \n if itermin > limit:\n itermin = 0\n\n fraction = 0.3\n geom = 0\n lastcheck = 0\n konvergence = np.inf\n rhat_count = 0\n ac_count = 0\n chain = np.empty([nwalkers, 1, dim])\n ar_frac = np.empty([nwalkers, 1])\n nIterations = limit + supp\n rhat = np.zeros(dim)\n stop = np.inf\n \n # initialise ball of walkers\n if ini_ball == \"uniform\":\n pos = np.zeros([nwalkers, dim])\n for ii in range(dim):\n low_b = bounds[labels[ii]][0]\n up_b = (bounds[labels[ii]][1])\n pos[:,ii] = np.random.uniform(low_b + 0.01*(up_b-low_b), \n up_b, nwalkers)\n elif isinstance(ini_ball,float):\n pos = initial_state + np.random.normal(0, ini_ball, (nwalkers, dim))\n else:\n raise ValueError(\"ini_ball must be string or float\")\n \n sampler = emcee.EnsembleSampler(nwalkers, dim, spec_lnprob, a,\n args=([labels, bounds, grid_param_list, \n lbda_obs, spec_obs, err_obs, dist,\n model_grid, model_reader, em_lines,\n em_grid, dlbda_obs, instru_corr, \n instru_fwhm,instru_idx,filter_reader, \n AV_bef_bb, units_obs, units_mod, \n interp_order, priors, physical]),\n threads=nproc)\n \n start = datetime.datetime.now()\n\n # #########################################################################\n # Affine Invariant MCMC run\n # #########################################################################\n if verbosity > 1:\n print('\\nStart of the MCMC run ...')\n print('Step | Duration/step (sec) | Remaining Estimated Time (sec)')\n \n for k, res in enumerate(sampler.sample(pos, iterations=nIterations,\n storechain=True)):\n elapsed = (datetime.datetime.now()-start).total_seconds()\n if verbosity > 1:\n if k == 0:\n q = 0.5\n else:\n q = 1\n print('{}\\t\\t{:.5f}\\t\\t\\t{:.5f}'.format(k, elapsed * q,\n elapsed * (limit-k-1) * q))\n \n start = datetime.datetime.now()\n\n # ---------------------------------------------------------------------\n # Store the state manually in order to handle with dynamical sized chain\n # ---------------------------------------------------------------------\n # Check if the size of the chain is long enough.\n s = chain.shape[1]\n if k+1 > s: # if not, one doubles the chain length\n empty = np.zeros([nwalkers, 2*s, dim])\n chain = np.concatenate((chain, empty), axis=1)\n empty = np.zeros([nwalkers, 2*s])\n ar_frac = np.concatenate((ar_frac, empty), axis=1)\n # Store the state of the chain\n chain[:, k] = res[0]\n ar_frac[:,k] = sampler.acceptance_fraction\n\n # ---------------------------------------------------------------------\n # If k meets the criterion, one tests the non-convergence.\n # ---------------------------------------------------------------------\n criterion = int(np.amin([np.ceil(itermin*(1+fraction)**geom),\n lastcheck+np.floor(maxgap)]))\n if k == criterion:\n \n geom += 1\n lastcheck = k\n if display:\n spec_show_walk_plot(chain)\n \n # We only test the rhat if we have reached the min # of steps\n if (k+1) >= itermin and konvergence == np.inf:\n if verbosity > 1:\n print('\\n{} convergence test in progress...'.format(conv_test))\n if conv_test == 'gb':\n thr0 = int(np.floor(burnin*k))\n thr1 = int(np.floor((1-burnin)*k*0.25))\n \n # We calculate the rhat for each model parameter.\n for j in range(dim):\n part1 = chain[:, thr0:thr0 + thr1, j].reshape(-1)\n part2 = chain[:, thr0 + 3 * thr1:thr0 + 4 * thr1, j\n ].reshape(-1)\n series = np.vstack((part1, part2))\n rhat[j] = gelman_rubin(series)\n if verbosity > 0:\n print(' r_hat = {}'.format(rhat))\n cond = rhat <= rhat_threshold\n print(' r_hat <= threshold = {} \\n'.format(cond))\n # We test the rhat.\n if (rhat <= rhat_threshold).all():\n rhat_count += 1\n if rhat_count < rhat_count_threshold:\n if verbosity > 0:\n msg = \"Gelman-Rubin test OK {}/{}\"\n print(msg.format(rhat_count, \n rhat_count_threshold))\n elif rhat_count >= rhat_count_threshold:\n if verbosity > 0:\n print('... ==> convergence reached')\n konvergence = k\n stop = konvergence + supp\n else:\n rhat_count = 0\n elif conv_test == 'ac':\n # We calculate the auto-corr test for each model parameter.\n for j in range(dim):\n rhat[j] = autocorr_test(chain[:,:k,j])\n thr = 1./ac_c\n if verbosity > 0:\n print('Auto-corr tau/N = {}'.format(rhat))\n print('tau/N <= {} = {} \\n'.format(thr, rhat 0:\n msg = \"Auto-correlation test passed for all params!\"\n msg+= \"{}/{}\".format(ac_count,ac_count_thr)\n print(msg)\n if ac_count >= ac_count_thr:\n msg='\\n ... ==> convergence reached'\n print(msg)\n stop = k\n else:\n ac_count = 0\n else:\n raise ValueError('conv_test value not recognized')\n \n \n if save and verbosity == 3:\n ac_time = []\n for j in range(dim):\n ac_time.append(k*autocorr_test(chain[:,:k,j]))\n fname = '{d}/{f}_temp_k{k}'.format(d=output_dir,\n f=output_file, k=k)\n data = {'chain': sampler.chain,\n 'lnprob': sampler.lnprobability,\n 'ac_time': ac_time,\n 'AR': ar_frac}\n with open(fname, 'wb') as fileSave:\n pickle.dump(data, fileSave)\n\n # We have reached convergence\n if k+1 >= stop:\n if verbosity > 0:\n print('We break the loop because we have reached convergence')\n break\n # We have reached the maximum number of steps for our Markov chain.\n if k+1 >= nIterations-1:\n # break to avoid a bug related to font type\n break\n \n isamples, ln_proba, ar = spec_chain_zero_truncated(chain, \n sampler.lnprobability,\n ar_frac) \n # update units in the chain if needed\n if len(em_grid)>0:\n for key, val in em_lines.items():\n idx_line = labels.index(key)\n if val[1] == 'L':\n R_si = isamples[:,:,idx_R]*con.R_jup.value\n isamples[:,:,idx_line] *= 4*np.pi*R_si**2\n elif val[1] == 'LogL':\n R_si = isamples[:,:,idx_R]*con.R_jup.value\n conv_fac = 4*np.pi*R_si**2/con.L_sun.value\n isamples[:,:,idx_line] = np.log10(isamples[:,:,idx_line]*conv_fac)\n \n if k == nIterations-1:\n if verbosity > 0:\n print(\"We have reached the limit # of steps without convergence\")\n print(\"You may have to increase niteration_limit\")\n # #########################################################################\n # Construction of the independent samples\n # #########################################################################\n \n\n if save:\n frame = inspect.currentframe()\n args, _, _, values = inspect.getargvalues(frame)\n input_parameters = {j: values[j] for j in args[1:]}\n ac_time = []\n for j in range(dim):\n ac_time.append(isamples.shape[1]*autocorr_test(isamples[:,:,j]))\n output = {'isamples': isamples,\n #'chain': chain,\n 'input_parameters': input_parameters,\n 'AR': ar,\n 'ac_time': ac_time,\n 'lnprobability': ln_proba}\n \n with open(output_dir+output_file, 'wb') as fileSave:\n pickle.dump(output, fileSave)\n \n msg = \"\\nThe file MCMC_results has been stored in the folder {}\"\n print(msg.format(output_dir))\n\n if verbosity > 0:\n timing(start_time)\n \n return isamples, ln_proba\n\n \ndef spec_chain_zero_truncated(chain, ln_proba=None, ar=None):\n \"\"\"\n Return the Markov chain with the dimension: walkers x steps* x parameters,\n where steps* is the last step before having 0 (not yet constructed chain).\n \n Parameters\n ----------\n chain: numpy.array\n The MCMC chain.\n ln_proba: numpy.array, opt\n Corresponding ln-probabilities.\n \n Returns\n -------\n out: numpy.array\n The truncated MCMC chain, that is to say, the chain which only contains\n relevant information.\n out_ln_proba: numpy.array\n If ln_proba is provided as input, out_ln_proba contains the \n zero-truncated ln-proba (i.e. matching shape with non-zero samples)\n \"\"\"\n try:\n idxzero = np.where(chain[0, :, 0] == 0.0)[0][0]\n except:\n idxzero = chain.shape[1]\n res = [chain[:, 0:idxzero, :]]\n \n if ln_proba is not None:\n res.append(ln_proba[:,0:idxzero])\n if ar is not None:\n res.append(ar[:,0:idxzero])\n if len(res) == 1:\n return res[0]\n else:\n return tuple(res)\n \n \ndef spec_show_walk_plot(chain, labels, save=False, output_dir='', ntrunc=100,\n **kwargs):\n \"\"\"\n Display/save a figure showing the path of each walker during the MCMC run.\n \n Parameters\n ----------\n chain: numpy.array\n The Markov chain. The shape of chain must be nwalkers x length x dim.\n If a part of the chain is filled with zero values, the method will\n discard these steps.\n labels: Tuple of strings\n Tuple of labels in the same order as initial_state, that is:\n - first all parameters related to loaded models (e.g. 'Teff', 'logg')\n - next the planet photometric radius 'R',\n - (optionally) the optical extinction 'Av'.\n - (optionally) 'Tbb1', 'Rbb1', 'Tbb2', 'Rbb2', etc. for each extra bb\n contribution\n save: boolean, default: False\n If True, a pdf file is created.\n ntrunc: int, opt\n max number of walkers plotted. If too many walkers the plot will become\n too voluminous and too crowded. Plot will be truncated to only ntrunc \n first walkers\n kwargs:\n Additional attributes are passed to the matplotlib plot method.\n \n Returns\n -------\n Display the figure or create a pdf file named walk_plot.pdf in the working\n directory.\n \n \"\"\"\n npar = chain.shape[-1]\n if len(labels) != npar:\n raise ValueError(\"Labels length should match chain last dimension\")\n temp = np.where(chain[0, :, 0] == 0.0)[0]\n if len(temp) != 0:\n chain = chain[:, :temp[0], :]\n\n\n color = kwargs.pop('color', 'k')\n alpha = kwargs.pop('alpha', 0.1)\n filename = kwargs.pop('filename','walk_plot.pdf')\n #labels = kwargs.pop('labels', [\"$r$\", r\"$\\theta$\", \"$f$\"])\n fig, axes = plt.subplots(npar, 1, sharex=True,\n figsize=kwargs.pop('figsize', (8, int(2*npar))))\n if npar>1:\n axes[-1].set_xlabel(kwargs.pop('xlabel', 'step number'))\n axes[-1].set_xlim(kwargs.pop('xlim', [0, chain.shape[1]]))\n for j in range(npar):\n axes[j].plot(chain[:ntrunc, :, j].T, color=color, alpha=alpha, **kwargs)\n axes[j].yaxis.set_major_locator(MaxNLocator(5))\n axes[j].set_ylabel(labels[j])\n else:\n axes.set_xlabel(kwargs.pop('xlabel', 'step number'))\n axes.set_xlim(kwargs.pop('xlim', [0, chain.shape[1]])) \n for j in range(npar):\n axes.plot(chain[:ntrunc, :, j].T, color=color, alpha=alpha, **kwargs)\n axes.yaxis.set_major_locator(MaxNLocator(5))\n axes.set_ylabel(labels[j])\n fig.tight_layout(h_pad=0)\n if save:\n plt.savefig(output_dir+filename)\n plt.close(fig)\n else:\n plt.show()\n\n\ndef spec_show_corner_plot(chain, burnin=0.5, save=False, output_dir='', \n mcmc_res=None, units=None, ndig=None, \n labels_plot=None, plot_name='corner_plot.pdf', **kwargs):\n \"\"\"\n Display/save a figure showing the corner plot (pdfs + correlation plots).\n \n Parameters\n ----------\n chain: numpy.array\n The Markov chain. The shape of chain must be nwalkers x length x dim.\n If a part of the chain is filled with zero values, the method will\n discard these steps.\n burnin: float, default: 0\n The fraction of a walker we want to discard.\n save: boolean, default: False\n If True, a pdf file is created.\n mcmc_res: numpy array OR tuple of 2 dictionaries/np.array, opt\n Values to be printed on top of each 1d posterior distribution \n * if numpy array: \\\n - npar x 3 dimensions (where npar is the number of parameters), \\\n containing the most likely value of each parameter and the lower \\\n and upper uncertainties at the desired quantiles, resp. \n - npar x 2 dimensions: same as above but with a single value of \\\n uncertainty. E.g. output of spec_confidence() for a gaussian fit\n * if tuple of 2 dictionaries: output of spec_confidence without \\\n gaussian fit\n * if tuple of 2 np.array: output of spec_confidence() with gaussian fit\n units: tuple, opt\n Tuple of strings containing units for each parameter. If provided,\n mcmc_res will be printed on top of each 1d posterior distribution along \n with these units.\n ndig: tuple, opt\n Number of digits precision for each printed parameter\n labels_plot: tuple, opt\n Labels corresponding to parameter names, used for the plot. If None,\n will use \"labels\" passed in kwargs.\n kwargs:\n Additional attributes passed to the corner.corner() method.\n (e.g. 'labels', 'show_title')\n \n Returns\n -------\n Display the figure or create a pdf file named walk_plot.pdf in the working\n directory.\n \n Raises\n ------\n ImportError\n \n \"\"\"\n \n npar = chain.shape[-1]\n if \"labels\" in kwargs.keys():\n labels = kwargs.pop('labels')\n if labels_plot is None:\n labels_plot = labels\n else:\n labels = None\n \n # allows for different title/units on top of 1D posterior distributions\n labels_tit = kwargs.pop('labels_tit', labels_plot)\n labels_tit_unit = kwargs.pop('labels_tit_unit', units)\n \n try:\n temp = np.where(chain[0, :, 0] == 0.0)[0]\n if len(temp) != 0:\n chain = chain[:, :temp[0], :]\n length = chain.shape[1]\n indburn = int(np.floor(burnin*(length-1)))\n chain = chain[:, indburn:length, :].reshape((-1, npar))\n except IndexError:\n pass\n\n if chain.shape[0] == 0:\n raise ValueError(\"It seems the chain is empty. Have you run the MCMC?\")\n else:\n fig = corner.corner(chain, labels=labels_plot, **kwargs)\n\n \n if mcmc_res is not None and labels is not None:\n title_kwargs = kwargs.pop('title_kwargs', None)\n if isinstance(mcmc_res,tuple):\n if len(mcmc_res) != 2:\n msg = \"mcmc_res should have 2 elements\"\n raise TypeError(msg)\n if len(mcmc_res[0]) != npar or len(mcmc_res[1]) != npar:\n msg = \"dict should have as many entries as there are params\"\n raise TypeError(msg)\n if labels is None:\n msg = \"labels should be provided\"\n raise TypeError(msg) \n elif isinstance(mcmc_res,np.ndarray):\n if mcmc_res.shape[0] != npar:\n msg = \"mcmc_res first dim should be equal to number of params\"\n raise TypeError(msg) \n else:\n msg = \"type of mcmc_res not recognised\"\n raise TypeError(msg)\n # Extract the axes\n axes = np.array(fig.axes).reshape((npar, npar))\n \n # Loop over the diagonal\n for i in range(npar):\n ax = axes[i, i]\n title = None\n if isinstance(mcmc_res,tuple):\n if isinstance(mcmc_res[0],dict):\n q_50 = mcmc_res[0][labels[i]]\n q_m = mcmc_res[1][labels[i]][0]\n q_p = mcmc_res[1][labels[i]][1]\n else:\n q_50 = mcmc_res[0][i][0]\n q_m = mcmc_res[1][i][0]\n q_p = q_m\n else:\n q_50 = mcmc_res[i,0]\n q_m = mcmc_res[i,1]\n q_p = mcmc_res[i,2]\n\n # Format the quantile display.\n try:\n fmt = \"{{:.{0}f}}\".format(ndig[i]).format\n except:\n fmt = \"{{:.2f}}\".format\n title = r\"${{{0}}}_{{{1}}}^{{+{2}}}$\"\n title = title.format(fmt(q_50), fmt(q_m), fmt(q_p))\n\n # Add in the column name if it's given.\n try:\n title = \"{0} = {1} {2}\".format(labels_tit[i], title, \n labels_tit_unit[i])\n except:\n title = \"{0} = {1}\".format(labels_tit[i], title)\n \n ax.set_title(title, **title_kwargs)\n \n if save:\n plt.savefig(output_dir+plot_name)\n plt.close(fig)\n else:\n plt.show()\n\n\ndef spec_confidence(isamples, labels, cfd=68.27, bins=100, gaussian_fit=False, \n weights=None, verbose=True, save=False, output_dir='', \n bounds=None, priors=None, **kwargs):\n \"\"\"\n Determine the highly probable value for each model parameter, as well as\n the 1-sigma confidence interval.\n \n Parameters\n ----------\n isamples: numpy.array\n The independent samples for each model parameter.\n labels: Tuple of strings\n Tuple of labels in the same order as initial_state, that is:\n - first all parameters related to loaded models (e.g. 'Teff', 'logg')\n - next the planet photometric radius 'R',\n - (optionally) the optical extinction 'Av'.\n - (optionally) 'Tbb1', 'Rbb1', 'Tbb2', 'Rbb2', etc. for each extra bb \\\n contribution\n cfd: float, optional\n The confidence level given in percentage.\n bins: int, optional\n The number of bins used to sample the posterior distributions.\n gaussian_fit: boolean, optional\n If True, a gaussian fit is performed in order to determine (\\mu,\\sigma)\n weights : (n, ) numpy ndarray or None, optional\n An array of weights for each sample.\n verbose: boolean, optional\n Display information in the shell.\n save: boolean, optional\n If \"True\", a txt file with the results is saved in the output\n repository.\n bounds: dictionary, opt\n Only used if a text file is saved summarizing results+bounds+priors.\n Should be the same bounds as provided to the MCMC.\n priors: dictionary, opt\n Only used if a text file is saved summarizing results+bounds+priors.\n Should be the same priors as provided to the MCMC.\n kwargs: optional\n Additional attributes are passed to the matplotlib hist() method.\n \n Returns\n -------\n out: tuple\n A 2 elements tuple with the highly probable solution and the confidence\n interval.\n \n \"\"\"\n title = kwargs.pop('title', None)\n \n output_file = kwargs.pop('filename', 'confidence.txt')\n \n if gaussian_fit:\n output_pdf = kwargs.pop('pdfname','confi_hist_spec_params_gaussfit.pdf')\n else:\n output_pdf = kwargs.pop('pdfname','confi_hist_spec_params.pdf')\n \n try:\n l = isamples.shape[1]\n except:\n l = 1\n \n confidenceInterval = {}\n val_max = {}\n pKey = labels #['r', 'theta', 'f']\n \n if l != len(pKey):\n raise ValueError(\"Labels length should match chain last dimension\")\n \n if cfd == 100:\n cfd = 99.9\n \n #########################################\n ## Determine the confidence interval ##\n #########################################\n if gaussian_fit:\n mu = np.zeros(l)\n sigma = np.zeros_like(mu)\n \n if gaussian_fit:\n fig, ax = plt.subplots(2, l, figsize=(int(4*l),8))\n else:\n fig, ax = plt.subplots(1, l, figsize=(int(4*l),4))\n \n for j in range(l):\n \n if gaussian_fit:\n n, bin_vertices, _ = ax[0][j].hist(isamples[:,j], bins=bins,\n weights=weights, histtype='step',\n edgecolor='gray')\n else:\n n, bin_vertices, _ = ax[j].hist(isamples[:,j], bins=bins,\n weights=weights, histtype='step',\n edgecolor='gray')\n bins_width = np.mean(np.diff(bin_vertices))\n surface_total = np.sum(np.ones_like(n)*bins_width * n)\n n_arg_sort = np.argsort(n)[::-1]\n \n test = 0\n pourcentage = 0\n for k, jj in enumerate(n_arg_sort):\n test = test + bins_width*n[int(jj)]\n pourcentage = test/surface_total*100\n if pourcentage > cfd:\n if verbose:\n msg = 'percentage for {}: {}%'\n print(msg.format(pKey[j], pourcentage))\n break\n n_arg_min = int(n_arg_sort[:k].min())\n n_arg_max = int(n_arg_sort[:k+1].max())\n \n if n_arg_min == 0:\n n_arg_min += 1\n if n_arg_max == bins:\n n_arg_max -= 1\n \n val_max[pKey[j]] = bin_vertices[int(n_arg_sort[0])]+bins_width/2.\n confidenceInterval[pKey[j]] = np.array([bin_vertices[n_arg_min-1],\n bin_vertices[n_arg_max+1]]\n - val_max[pKey[j]])\n \n arg = (isamples[:, j] >= bin_vertices[n_arg_min - 1]) * \\\n (isamples[:, j] <= bin_vertices[n_arg_max + 1])\n if gaussian_fit:\n ax[0][j].hist(isamples[arg,j], bins=bin_vertices,\n facecolor='gray', edgecolor='darkgray',\n histtype='stepfilled', alpha=0.5)\n ax[0][j].vlines(val_max[pKey[j]], 0, n[int(n_arg_sort[0])],\n linestyles='dashed', color='red')\n ax[0][j].set_xlabel(pKey[j])\n if j == 0:\n ax[0][j].set_ylabel('Counts')\n\n mu[j], sigma[j] = norm.fit(isamples[:, j])\n n_fit, bins_fit = np.histogram(isamples[:, j], bins, normed=1,\n weights=weights)\n ax[1][j].hist(isamples[:, j], bins, density=1, weights=weights,\n facecolor='gray', edgecolor='darkgray',\n histtype='step')\n y = norm.pdf(bins_fit, mu[j], sigma[j])\n ax[1][j].plot(bins_fit, y, 'r--', linewidth=2, alpha=0.7)\n\n ax[1][j].set_xlabel(pKey[j])\n if j == 0:\n ax[1][j].set_ylabel('Counts')\n\n if title is not None:\n msg = r\"{} $\\mu$ = {:.4f}, $\\sigma$ = {:.4f}\"\n ax[1][j].set_title(msg.format(title, mu[j], sigma[j]),\n fontsize=10)\n\n else:\n ax[j].hist(isamples[arg,j],bins=bin_vertices, facecolor='gray',\n edgecolor='darkgray', histtype='stepfilled',\n alpha=0.5)\n ax[j].vlines(val_max[pKey[j]], 0, n[int(n_arg_sort[0])],\n linestyles='dashed', color='red')\n ax[j].set_xlabel(pKey[j])\n if j == 0:\n ax[j].set_ylabel('Counts')\n\n if title is not None:\n msg = r\"{} - {:.3f} {:.3f} +{:.3f}\"\n ax[1].set_title(msg.format(title, val_max[pKey[j]], \n confidenceInterval[pKey[j]][0], \n confidenceInterval[pKey[j]][1]),\n fontsize=10)\n\n plt.tight_layout(w_pad=0.1)\n\n if save:\n plt.savefig(output_dir+output_pdf)\n\n\n if verbose:\n for j in range(l):\n print(\"******* Results for {} ***** \".format(pKey[j]))\n print('\\n\\nConfidence intervals:')\n print('{}: {} [{},{}]'.format(pKey[j], val_max[pKey[j]],\n confidenceInterval[pKey[j]][0],\n confidenceInterval[pKey[j]][1]))\n if gaussian_fit:\n print('Gaussian fit results:')\n print('{}: {} +-{}'.format(pKey[j], mu[j], sigma[j]))\n\n ##############################################\n ## Write inference results in a text file ##\n ##############################################\n if save:\n with open(output_dir+output_file, \"w\") as f:\n f.write('######################################\\n')\n f.write('#### MCMC results (confidence) ###\\n')\n f.write('######################################\\n')\n f.write(' \\n')\n f.write('Results of the MCMC fit\\n')\n f.write('----------------------- \\n')\n f.write(' \\n')\n if bounds is not None:\n f.write('Bounds\\n')\n f.write('------')\n for j in range(l):\n f.write('\\n{}: [{},{}]'.format(pKey[j], bounds[pKey[j]][0],\n bounds[pKey[j]][1]))\n f.write(' \\n')\n f.write(' \\n')\n f.write('Priors\\n')\n f.write('------')\n if priors is not None:\n for key, prior in priors.items():\n f.write('\\n{}: {}+-{}'.format(key, prior[0], prior[1]))\n else:\n f.write('\\n None')\n f.write(' \\n')\n f.write(' \\n')\n f.write('>> Spectral parameters for a ')\n f.write('{} % confidence interval:\\n'.format(cfd))\n \n for j in range(l):\n f.write('{}: {} [{},{}]'.format(pKey[j], val_max[pKey[j]],\n confidenceInterval[pKey[j]][0],\n confidenceInterval[pKey[j]][1]))\n if gaussian_fit:\n f.write('Gaussian fit results:')\n f.write('{}: {} +-{}'.format(pKey[j], mu[j], sigma[j]))\n\n if gaussian_fit:\n return mu, sigma\n else:\n return val_max, confidenceInterval\n", "meta": {"hexsha": "60d429f9373430ad5d3f046385ec80d2cc9adb81", "size": 77259, "ext": "py", "lang": "Python", "max_stars_repo_path": "vip_hci/specfit/mcmc_sampling_spec.py", "max_stars_repo_name": "kfranson/VIP", "max_stars_repo_head_hexsha": "5975fd6ce7c02adace013c8a2412062ac2b92bbc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vip_hci/specfit/mcmc_sampling_spec.py", "max_issues_repo_name": "kfranson/VIP", "max_issues_repo_head_hexsha": "5975fd6ce7c02adace013c8a2412062ac2b92bbc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vip_hci/specfit/mcmc_sampling_spec.py", "max_forks_repo_name": "kfranson/VIP", "max_forks_repo_head_hexsha": "5975fd6ce7c02adace013c8a2412062ac2b92bbc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.4272559853, "max_line_length": 84, "alphanum_fraction": 0.577537892, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 17742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.27202456289736326, "lm_q1q2_score": 0.13813730041464575}} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nSELFIES: a robust representation of semantically constrained graphs with an\n example application in chemistry (https://arxiv.org/abs/1905.13741)\n by Mario Krenn, Florian Haese, AkshatKuman Nigam, Pascal Friederich,\n Alan Aspuru-Guzik.\n\n Variational Autoencoder (VAE) for chemistry\n comparing SMILES and SELFIES representation using reconstruction\n quality, diversity and latent space validity as metrics of\n interest\n\ninformation:\n ML framework: pytorch\n chemistry framework: RDKit\n\n get_selfie_and_smiles_encodings_for_dataset\n generate complete encoding (inclusive alphabet) for SMILES and\n SELFIES given a data file\n\n VAEEncoder\n fully connected, 3 layer neural network - encodes a one-hot\n representation of molecule (in SMILES or SELFIES representation)\n to latent space\n\n VAEDecoder\n decodes point in latent space using an RNN\n\n latent_space_quality\n samples points from latent space, decodes them into molecules,\n calculates chemical validity (using RDKit's MolFromSmiles), calculates\n diversity\n\"\"\"\n\nimport os\nimport sys\nimport time\n\nimport numpy as np\nimport pandas as pd\nimport torch\nimport yaml\nfrom rdkit import rdBase\nfrom rdkit.Chem import MolFromSmiles\nfrom torch import nn\n\nimport selfies as sf\nfrom examples.vae_example.data_loader import \\\n multiple_selfies_to_hot, multiple_smile_to_hot\n\nrdBase.DisableLog('rdApp.error')\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\ndef _make_dir(directory):\n os.makedirs(directory)\n\n\ndef save_models(encoder, decoder, epoch):\n out_dir = './saved_models/{}'.format(epoch)\n _make_dir(out_dir)\n torch.save(encoder, '{}/E'.format(out_dir))\n torch.save(decoder, '{}/D'.format(out_dir))\n\n\nclass VAEEncoder(nn.Module):\n\n def __init__(self, in_dimension, layer_1d, layer_2d, layer_3d,\n latent_dimension):\n \"\"\"\n Fully Connected layers to encode molecule to latent space\n \"\"\"\n super(VAEEncoder, self).__init__()\n self.latent_dimension = latent_dimension\n\n # Reduce dimension up to second last layer of Encoder\n self.encode_nn = nn.Sequential(\n nn.Linear(in_dimension, layer_1d),\n nn.ReLU(),\n nn.Linear(layer_1d, layer_2d),\n nn.ReLU(),\n nn.Linear(layer_2d, layer_3d),\n nn.ReLU()\n )\n\n # Latent space mean\n self.encode_mu = nn.Linear(layer_3d, latent_dimension)\n\n # Latent space variance\n self.encode_log_var = nn.Linear(layer_3d, latent_dimension)\n\n @staticmethod\n def reparameterize(mu, log_var):\n \"\"\"\n This trick is explained well here:\n https://stats.stackexchange.com/a/16338\n \"\"\"\n std = torch.exp(0.5 * log_var)\n eps = torch.randn_like(std)\n return eps.mul(std).add_(mu)\n\n def forward(self, x):\n \"\"\"\n Pass throught the Encoder\n \"\"\"\n # Get results of encoder network\n h1 = self.encode_nn(x)\n\n # latent space\n mu = self.encode_mu(h1)\n log_var = self.encode_log_var(h1)\n\n # Reparameterize\n z = self.reparameterize(mu, log_var)\n return z, mu, log_var\n\n\nclass VAEDecoder(nn.Module):\n\n def __init__(self, latent_dimension, gru_stack_size, gru_neurons_num,\n out_dimension):\n \"\"\"\n Through Decoder\n \"\"\"\n super(VAEDecoder, self).__init__()\n self.latent_dimension = latent_dimension\n self.gru_stack_size = gru_stack_size\n self.gru_neurons_num = gru_neurons_num\n\n # Simple Decoder\n self.decode_RNN = nn.GRU(\n input_size=latent_dimension,\n hidden_size=gru_neurons_num,\n num_layers=gru_stack_size,\n batch_first=False)\n\n self.decode_FC = nn.Sequential(\n nn.Linear(gru_neurons_num, out_dimension),\n )\n\n def init_hidden(self, batch_size=1):\n weight = next(self.parameters())\n return weight.new_zeros(self.gru_stack_size, batch_size,\n self.gru_neurons_num)\n\n def forward(self, z, hidden):\n \"\"\"\n A forward pass throught the entire model.\n \"\"\"\n\n # Decode\n l1, hidden = self.decode_RNN(z, hidden)\n decoded = self.decode_FC(l1) # fully connected layer\n\n return decoded, hidden\n\n\ndef is_correct_smiles(smiles):\n \"\"\"\n Using RDKit to calculate whether molecule is syntactically and\n semantically valid.\n \"\"\"\n if smiles == \"\":\n return False\n\n try:\n return MolFromSmiles(smiles, sanitize=True) is not None\n except Exception:\n return False\n\n\ndef sample_latent_space(vae_encoder, vae_decoder, sample_len):\n vae_encoder.eval()\n vae_decoder.eval()\n\n gathered_atoms = []\n\n fancy_latent_point = torch.randn(1, 1, vae_encoder.latent_dimension,\n device=device)\n hidden = vae_decoder.init_hidden()\n\n # runs over letters from molecules (len=size of largest molecule)\n for _ in range(sample_len):\n out_one_hot, hidden = vae_decoder(fancy_latent_point, hidden)\n\n out_one_hot = out_one_hot.flatten().detach()\n soft = nn.Softmax(0)\n out_one_hot = soft(out_one_hot)\n\n out_index = out_one_hot.argmax(0)\n gathered_atoms.append(out_index.data.cpu().tolist())\n\n vae_encoder.train()\n vae_decoder.train()\n\n return gathered_atoms\n\n\ndef latent_space_quality(vae_encoder, vae_decoder, type_of_encoding,\n alphabet, sample_num, sample_len):\n total_correct = 0\n all_correct_molecules = set()\n print(f\"latent_space_quality:\"\n f\" Take {sample_num} samples from the latent space\")\n\n for _ in range(1, sample_num + 1):\n\n molecule_pre = ''\n for i in sample_latent_space(vae_encoder, vae_decoder, sample_len):\n molecule_pre += alphabet[i]\n molecule = molecule_pre.replace(' ', '')\n\n if type_of_encoding == 1: # if SELFIES, decode to SMILES\n molecule = sf.decoder(molecule)\n\n if is_correct_smiles(molecule):\n total_correct += 1\n all_correct_molecules.add(molecule)\n\n return total_correct, len(all_correct_molecules)\n\n\ndef quality_in_valid_set(vae_encoder, vae_decoder, data_valid, batch_size):\n data_valid = data_valid[torch.randperm(data_valid.size()[0])] # shuffle\n num_batches_valid = len(data_valid) // batch_size\n\n quality_list = []\n for batch_iteration in range(min(25, num_batches_valid)):\n\n # get batch\n start_idx = batch_iteration * batch_size\n stop_idx = (batch_iteration + 1) * batch_size\n batch = data_valid[start_idx: stop_idx]\n _, trg_len, _ = batch.size()\n\n inp_flat_one_hot = batch.flatten(start_dim=1)\n latent_points, mus, log_vars = vae_encoder(inp_flat_one_hot)\n\n latent_points = latent_points.unsqueeze(0)\n hidden = vae_decoder.init_hidden(batch_size=batch_size)\n out_one_hot = torch.zeros_like(batch, device=device)\n for seq_index in range(trg_len):\n out_one_hot_line, hidden = vae_decoder(latent_points, hidden)\n out_one_hot[:, seq_index, :] = out_one_hot_line[0]\n\n # assess reconstruction quality\n quality = compute_recon_quality(batch, out_one_hot)\n quality_list.append(quality)\n\n return np.mean(quality_list).item()\n\n\ndef train_model(vae_encoder, vae_decoder,\n data_train, data_valid, num_epochs, batch_size,\n lr_enc, lr_dec, KLD_alpha,\n sample_num, sample_len, alphabet, type_of_encoding):\n \"\"\"\n Train the Variational Auto-Encoder\n \"\"\"\n\n print('num_epochs: ', num_epochs)\n\n # initialize an instance of the model\n optimizer_encoder = torch.optim.Adam(vae_encoder.parameters(), lr=lr_enc)\n optimizer_decoder = torch.optim.Adam(vae_decoder.parameters(), lr=lr_dec)\n\n data_train = data_train.clone().detach().to(device)\n num_batches_train = int(len(data_train) / batch_size)\n\n quality_valid_list = [0, 0, 0, 0]\n for epoch in range(num_epochs):\n\n data_train = data_train[torch.randperm(data_train.size()[0])]\n\n start = time.time()\n for batch_iteration in range(num_batches_train): # batch iterator\n\n # manual batch iterations\n start_idx = batch_iteration * batch_size\n stop_idx = (batch_iteration + 1) * batch_size\n batch = data_train[start_idx: stop_idx]\n\n # reshaping for efficient parallelization\n inp_flat_one_hot = batch.flatten(start_dim=1)\n latent_points, mus, log_vars = vae_encoder(inp_flat_one_hot)\n\n # initialization hidden internal state of RNN (RNN has two inputs\n # and two outputs:)\n # input: latent space & hidden state\n # output: one-hot encoding of one character of molecule & hidden\n # state the hidden state acts as the internal memory\n latent_points = latent_points.unsqueeze(0)\n hidden = vae_decoder.init_hidden(batch_size=batch_size)\n\n # decoding from RNN N times, where N is the length of the largest\n # molecule (all molecules are padded)\n out_one_hot = torch.zeros_like(batch, device=device)\n for seq_index in range(batch.shape[1]):\n out_one_hot_line, hidden = vae_decoder(latent_points, hidden)\n out_one_hot[:, seq_index, :] = out_one_hot_line[0]\n\n # compute ELBO\n loss = compute_elbo(batch, out_one_hot, mus, log_vars, KLD_alpha)\n\n # perform back propogation\n optimizer_encoder.zero_grad()\n optimizer_decoder.zero_grad()\n loss.backward(retain_graph=True)\n nn.utils.clip_grad_norm_(vae_decoder.parameters(), 0.5)\n optimizer_encoder.step()\n optimizer_decoder.step()\n\n if batch_iteration % 30 == 0:\n end = time.time()\n\n # assess reconstruction quality\n quality_train = compute_recon_quality(batch, out_one_hot)\n quality_valid = quality_in_valid_set(vae_encoder, vae_decoder,\n data_valid, batch_size)\n\n report = 'Epoch: %d, Batch: %d / %d,\\t(loss: %.4f\\t| ' \\\n 'quality: %.4f | quality_valid: %.4f)\\t' \\\n 'ELAPSED TIME: %.5f' \\\n % (epoch, batch_iteration, num_batches_train,\n loss.item(), quality_train, quality_valid,\n end - start)\n print(report)\n start = time.time()\n\n quality_valid = quality_in_valid_set(vae_encoder, vae_decoder,\n data_valid, batch_size)\n quality_valid_list.append(quality_valid)\n\n # only measure validity of reconstruction improved\n quality_increase = len(quality_valid_list) \\\n - np.argmax(quality_valid_list)\n if quality_increase == 1 and quality_valid_list[-1] > 50.:\n corr, unique = latent_space_quality(vae_encoder, vae_decoder,\n type_of_encoding, alphabet,\n sample_num, sample_len)\n else:\n corr, unique = -1., -1.\n\n report = 'Validity: %.5f %% | Diversity: %.5f %% | ' \\\n 'Reconstruction: %.5f %%' \\\n % (corr * 100. / sample_num, unique * 100. / sample_num,\n quality_valid)\n print(report)\n\n with open('results.dat', 'a') as content:\n content.write(report + '\\n')\n\n if quality_valid_list[-1] < 70. and epoch > 200:\n break\n\n if quality_increase > 20:\n print('Early stopping criteria')\n break\n\n\ndef compute_elbo(x, x_hat, mus, log_vars, KLD_alpha):\n inp = x_hat.reshape(-1, x_hat.shape[2])\n target = x.reshape(-1, x.shape[2]).argmax(1)\n\n criterion = torch.nn.CrossEntropyLoss()\n recon_loss = criterion(inp, target)\n kld = -0.5 * torch.mean(1. + log_vars - mus.pow(2) - log_vars.exp())\n\n return recon_loss + KLD_alpha * kld\n\n\ndef compute_recon_quality(x, x_hat):\n x_indices = x.reshape(-1, x.shape[2]).argmax(1)\n x_hat_indices = x_hat.reshape(-1, x_hat.shape[2]).argmax(1)\n\n differences = 1. - torch.abs(x_hat_indices - x_indices)\n differences = torch.clamp(differences, min=0., max=1.).double()\n quality = 100. * torch.mean(differences)\n quality = quality.detach().cpu().numpy()\n\n return quality\n\n\ndef get_selfie_and_smiles_encodings_for_dataset(file_path):\n \"\"\"\n Returns encoding, alphabet and length of largest molecule in SMILES and\n SELFIES, given a file containing SMILES molecules.\n\n input:\n csv file with molecules. Column's name must be 'smiles'.\n output:\n - selfies encoding\n - selfies alphabet\n - longest selfies string\n - smiles encoding (equivalent to file content)\n - smiles alphabet (character based)\n - longest smiles string\n \"\"\"\n\n df = pd.read_csv(file_path)\n\n smiles_list = np.asanyarray(df.smiles)\n\n smiles_alphabet = list(set(''.join(smiles_list)))\n smiles_alphabet.append(' ') # for padding\n\n largest_smiles_len = len(max(smiles_list, key=len))\n\n print('--> Translating SMILES to SELFIES...')\n selfies_list = list(map(sf.encoder, smiles_list))\n\n all_selfies_symbols = sf.get_alphabet_from_selfies(selfies_list)\n all_selfies_symbols.add('[nop]')\n selfies_alphabet = list(all_selfies_symbols)\n\n largest_selfies_len = max(sf.len_selfies(s) for s in selfies_list)\n\n print('Finished translating SMILES to SELFIES.')\n\n return selfies_list, selfies_alphabet, largest_selfies_len, \\\n smiles_list, smiles_alphabet, largest_smiles_len\n\n\ndef main():\n content = open('logfile.dat', 'w')\n content.close()\n content = open('results.dat', 'w')\n content.close()\n\n if os.path.exists(\"settings.yml\"):\n settings = yaml.safe_load(open(\"settings.yml\", \"r\"))\n else:\n print(\"Expected a file settings.yml but didn't find it.\")\n return\n\n print('--> Acquiring data...')\n type_of_encoding = settings['data']['type_of_encoding']\n file_name_smiles = settings['data']['smiles_file']\n\n print('Finished acquiring data.')\n\n if type_of_encoding == 0:\n print('Representation: SMILES')\n _, _, _, encoding_list, encoding_alphabet, largest_molecule_len = \\\n get_selfie_and_smiles_encodings_for_dataset(file_name_smiles)\n\n print('--> Creating one-hot encoding...')\n data = multiple_smile_to_hot(encoding_list, largest_molecule_len,\n encoding_alphabet)\n print('Finished creating one-hot encoding.')\n\n elif type_of_encoding == 1:\n print('Representation: SELFIES')\n encoding_list, encoding_alphabet, largest_molecule_len, _, _, _ = \\\n get_selfie_and_smiles_encodings_for_dataset(file_name_smiles)\n\n print('--> Creating one-hot encoding...')\n data = multiple_selfies_to_hot(encoding_list, largest_molecule_len,\n encoding_alphabet)\n print('Finished creating one-hot encoding.')\n\n else:\n print(\"type_of_encoding not in {0, 1}.\")\n return\n\n len_max_molec = data.shape[1]\n len_alphabet = data.shape[2]\n len_max_mol_one_hot = len_max_molec * len_alphabet\n\n print(' ')\n print(f\"Alphabet has {len_alphabet} letters, \"\n f\"largest molecule is {len_max_molec} letters.\")\n\n data_parameters = settings['data']\n batch_size = data_parameters['batch_size']\n\n encoder_parameter = settings['encoder']\n decoder_parameter = settings['decoder']\n training_parameters = settings['training']\n\n vae_encoder = VAEEncoder(in_dimension=len_max_mol_one_hot,\n **encoder_parameter).to(device)\n vae_decoder = VAEDecoder(**decoder_parameter,\n out_dimension=len(encoding_alphabet)).to(device)\n\n print('*' * 15, ': -->', device)\n\n data = torch.tensor(data, dtype=torch.float).to(device)\n\n train_valid_test_size = [0.5, 0.5, 0.0]\n data = data[torch.randperm(data.size()[0])]\n idx_train_val = int(len(data) * train_valid_test_size[0])\n idx_val_test = idx_train_val + int(len(data) * train_valid_test_size[1])\n\n data_train = data[0:idx_train_val]\n data_valid = data[idx_train_val:idx_val_test]\n\n print(\"start training\")\n train_model(**training_parameters,\n vae_encoder=vae_encoder,\n vae_decoder=vae_decoder,\n batch_size=batch_size,\n data_train=data_train,\n data_valid=data_valid,\n alphabet=encoding_alphabet,\n type_of_encoding=type_of_encoding,\n sample_len=len_max_molec)\n\n with open('COMPLETED', 'w') as content:\n content.write('exit code: 0')\n\n\nif __name__ == '__main__':\n try:\n main()\n except AttributeError:\n _, error_message, _ = sys.exc_info()\n print(error_message)\n", "meta": {"hexsha": "87f4d18abd6c2880d51f951050cee933173412f7", "size": 17324, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/vae_example/chemistry_vae.py", "max_stars_repo_name": "UnixJunkie/selfies", "max_stars_repo_head_hexsha": "9f822e175e559fa11753b715991645afe9953621", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-10-15T13:49:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-13T19:08:57.000Z", "max_issues_repo_path": "examples/vae_example/chemistry_vae.py", "max_issues_repo_name": "UnixJunkie/selfies", "max_issues_repo_head_hexsha": "9f822e175e559fa11753b715991645afe9953621", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/vae_example/chemistry_vae.py", "max_forks_repo_name": "UnixJunkie/selfies", "max_forks_repo_head_hexsha": "9f822e175e559fa11753b715991645afe9953621", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1877394636, "max_line_length": 79, "alphanum_fraction": 0.6314938813, "include": true, "reason": "import numpy", "num_tokens": 3904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2720245569956929, "lm_q1q2_score": 0.1381372974177075}} {"text": "#!/usr/bin/python3\n\n\"\"\"Swing molecules based on normal coordinates.\"\"\"\n\nimport os\nimport argparse\nimport shutil\nfrom collections import defaultdict\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom ase import Atoms\nfrom ase.calculators.orca import ORCA\nfrom cclib import ccopen\nfrom scipy.constants import physical_constants\nfrom scipy.optimize import root\nfrom scipy.optimize import minimize\nfrom scipy.optimize import minimize_scalar\n\ntry:\n from xtb.ase.calculator import XTB\nexcept ModuleNotFoundError as e:\n print(\"WARNING: won't be able to use XTB\")\n\nhartree, _, _ = physical_constants[\"Hartree energy\"]\n\nsmd2gbsa = defaultdict(\n lambda: \"none\",\n {\n \"acetone\": \"acetone\",\n \"mecn\": \"acetonitrile\",\n \"acetonitrile\": \"acetonitrile\",\n \"benzene\": \"benzene\",\n \"dichloromethane\": \"ch2cl2\",\n \"chloroform\": \"chcl3\",\n \"carbon disulfide\": \"cs2\",\n \"dmf\": \"dmf\",\n \"n,n-dimethylformamide\": \"dmf\",\n \"dmso\": \"dmso\",\n \"dimethylsulfoxide\": \"dmso\",\n \"diethyl ether\": \"ether\",\n \"water\": \"water\",\n \"methanol\": \"methanol\",\n \"n-hexane\": \"n-hexan\",\n \"thf\": \"thf\",\n \"tetrahydrofuran\": \"thf\",\n \"toluene\": \"toluene\",\n },\n)\n\n\ndef main():\n \"\"\"Run main procedure.\"\"\"\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument(\"logfile\")\n # TODO(schneiderfelipe): set charge and multiplicity\n parser.add_argument(\n \"-a\",\n \"--acc\",\n help=\"accuracy for SCC calculation, lower is better\",\n type=float,\n default=1.0,\n )\n parser.add_argument(\n \"--iterations\",\n help=\"number of iterations in SCC\",\n type=int,\n default=250,\n )\n parser.add_argument(\n \"--gfn\", help=\"specify parametrisation of GFN-xTB\", type=int\n )\n parser.add_argument(\n \"--etemp\", help=\"electronic temperature\", type=float, default=300.0\n )\n parser.add_argument(\n \"-s\",\n \"--solvent\",\n help=(\"solvent (SMD/GBSA implicit solvation models)\"),\n default=\"none\",\n )\n parser.add_argument(\n \"--do-not-cache-api\",\n dest=\"cache_api\",\n help=\"Do not reuse generate API objects (not recommended)\",\n action=\"store_false\",\n )\n\n parser.add_argument(\n \"--pm3\", help=\"use PM3\", action=\"store_true\",\n )\n parser.add_argument(\n \"--b97-3c\", help=\"use B97-3c\", action=\"store_true\",\n )\n parser.add_argument(\n \"--minimize\", action=\"store_true\",\n )\n parser.add_argument(\n \"--transition-state\", action=\"store_true\",\n )\n parser.add_argument(\"--max-omega\", type=float, default=1.0)\n parser.add_argument(\"--tol\", type=float, default=1e-3)\n parser.add_argument(\"--nprocs\", type=int, default=4)\n args = parser.parse_args()\n print(args)\n\n data = ccopen(args.logfile).parse()\n initial_positions = data.atomcoords[-1]\n atoms = Atoms(numbers=data.atomnos, positions=initial_positions)\n\n if args.gfn:\n method = f\"GFN{args.gfn}-xTB\"\n solvent = smd2gbsa[args.solvent.lower()]\n\n calc = XTB(\n method=method,\n accuracy=args.acc,\n electronic_temperature=args.etemp,\n max_iterations=args.iterations,\n solvent=solvent,\n cache_api=args.cache_api,\n )\n else:\n\n if args.b97_3c:\n method = \"B97-3c D3BJ def2-SV(P)\"\n elif args.pm3:\n method = \"PM3\"\n else:\n\n def allow_keyword(keyword):\n for forbidden in {\"freq\", \"opt\", \"irc\", \"print\"}:\n if forbidden in keyword.lower():\n return False\n return True\n\n keywords = [\n keyword\n for keyword in data.metadata[\"keywords\"]\n if allow_keyword(keyword)\n ]\n\n method = \" \".join(keywords)\n\n solvent = args.solvent\n blocks = f\"%pal\\n nprocs {args.nprocs}\\nend\\n%scf\\n maxiter {args.iterations}\\nend\"\n if solvent != \"none\" and not args.pm3:\n blocks += f'\\n%cpcm\\n smd true\\n smdsolvent \"{solvent}\"\\nend'\n\n if \"ORCA_COMMAND\" not in os.environ:\n # For parallel runs ORCA has to be called with full pathname\n os.environ[\"ORCA_COMMAND\"] = shutil.which(\"orca\")\n\n calc = ORCA(\n label=\"012345_swing\", orcasimpleinput=method, orcablocks=blocks\n )\n\n print(f\"*** {method} ***\")\n print(f\" : solvent: {solvent}\")\n\n atoms.set_calculator(calc)\n potential_min = atoms.get_potential_energy()\n print(f\"@ potential energy: {potential_min} eV\")\n\n indices = np.where(data.vibfreqs < 0)[0]\n n_indices = len(indices)\n print(f\"@ imaginary frequencies: {data.vibfreqs[indices]}\")\n if not n_indices:\n print(\" : nothing to be done, bye\")\n return\n\n ignoring = None\n if args.transition_state:\n ignoring = 0\n print(\" : transition state: ignoring first imaginary frequency\")\n\n omegas = []\n potentials = []\n\n def f(omega):\n atoms.set_positions(\n initial_positions\n + np.einsum(\"i,ijk->jk\", omega, data.vibdisps[indices])\n )\n\n potential = 1e3 * (atoms.get_potential_energy() - potential_min)\n\n omegas.append(omega)\n potentials.append(potential)\n print(f\" : omega: {omega}\")\n print(f\" : potential: {potential} meV\")\n\n return potential\n\n if args.minimize:\n guesses = [np.zeros_like(indices, dtype=float)]\n\n for i in indices:\n if ignoring is not None and i == ignoring:\n continue\n\n print(f\"@ searching in direction #{i}\")\n\n def g(w):\n z = np.zeros_like(indices, dtype=float)\n z[i] = w\n return f(z)\n\n if args.minimize:\n res = minimize_scalar(\n g,\n method=\"bounded\",\n bounds=(-args.max_omega, args.max_omega),\n tol=args.tol,\n )\n print(res)\n\n guess = np.zeros_like(indices, dtype=float)\n guess[i] = res.x\n guesses.append(guess)\n else:\n dx = args.max_omega / 100\n x = [-dx, 0.0, dx]\n y = [g(-dx), 0.0, g(dx)]\n\n # p[0] * x**2 + p[1] * x + p[2] == k * (x - x0)**2 == k * x**2 - 2 * x0 * k * x + k * x0**2\n p = np.polyfit(x, y, 2)\n print(p)\n print(np.roots(p))\n\n dp = np.polyder(p)\n print(dp)\n r = np.roots(dp)\n print(r)\n\n # k = p[0]\n # x0 = np.sqrt(p[2] / k)\n # print(k, x0)\n # print(root(lambda z: [p[0] - z[0], p[1] + 2 * z[0] * z[1], p[2] - z[0] * z[1] ** 2], [k, x0]))\n\n best_positions = initial_positions + np.einsum(\n \"i,ijk->jk\", r, data.vibdisps[indices]\n )\n\n if args.minimize:\n print(\"@ choosing initial guess for global search\")\n if n_indices > 1:\n guesses.append(np.sum(guesses, axis=0))\n x0 = guesses[np.argmin([f(guess) for guess in guesses])]\n\n print(\"@ searching in all directions\")\n constraints = ()\n if args.transition_state and ignoring is not None:\n constraints = (\n {\"type\": \"eq\", \"fun\": lambda omega: omega[ignoring]},\n )\n res = minimize(\n f,\n x0=x0,\n bounds=n_indices * [(-args.max_omega, args.max_omega)],\n constraints=constraints,\n tol=args.tol,\n )\n print(res)\n best_positions = initial_positions + np.einsum(\n \"i,ijk->jk\", res.x, data.vibdisps[indices]\n )\n\n # TODO(schneiderfelipe): correct for when using --transition-state\n omegas = np.array(omegas)\n fig, ax = plt.subplots(n_indices, 1)\n if n_indices == 1:\n ax = [ax]\n xlim = (-args.max_omega - 0.05, args.max_omega + 0.05)\n ylim = (np.min(potentials) - 2.0, 40.0)\n for i in indices:\n if ignoring is not None and i == ignoring:\n continue\n\n ax[i].plot(omegas[:, i], potentials, \"o\")\n ax[i].set_title(f\"view of normal mode #{i}\")\n ax[i].set_ylabel(r\"potential energy (meV)\")\n ax[i].set_xlabel(rf\"$\\omega_{i}$\")\n ax[i].set_ylim(ylim)\n ax[i].set_xlim(xlim)\n plt.tight_layout()\n plt.show()\n\n print(\"@ writing best geometry to swinged.xyz\")\n # TODO(schneiderfelipe): print a RMSD between initial and final structures\n atoms.set_positions(best_positions)\n atoms.write(\"swinged.xyz\", format=\"xyz\", plain=True)\n\n\nif __name__ == \"__main__\":\n main()\n", "meta": {"hexsha": "2e3f0b7b680254fd4fdb0886dd3564ca8441c28d", "size": 8811, "ext": "py", "lang": "Python", "max_stars_repo_path": "swing.py", "max_stars_repo_name": "schneiderfelipe/scripts", "max_stars_repo_head_hexsha": "43bb3d02d0b043f80a4840f4cc222944aad683c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "swing.py", "max_issues_repo_name": "schneiderfelipe/scripts", "max_issues_repo_head_hexsha": "43bb3d02d0b043f80a4840f4cc222944aad683c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "swing.py", "max_forks_repo_name": "schneiderfelipe/scripts", "max_forks_repo_head_hexsha": "43bb3d02d0b043f80a4840f4cc222944aad683c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6666666667, "max_line_length": 108, "alphanum_fraction": 0.5462490069, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.27202454519235225, "lm_q1q2_score": 0.1381372914238311}} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 20 9:35 2020\n\n@author: MCR\n\nFile containing the necessary functions to create an empirical\ninterpolated trace model in the overlap region for SOSS order 1.\n\"\"\"\n\nimport os\nimport numpy as np\nfrom astropy.io import fits\nfrom scipy.optimize import least_squares\nimport webbpsf\nfrom SOSS.trace import tracepol as tp\nfrom SOSS.extract.empirical_trace import centroid as ctd\nfrom SOSS.extract.empirical_trace import plotting as plotting\nfrom SOSS.dms.soss_engine import ExtractionEngine\nfrom SOSS.extract.engine_legacy import ThroughputSOSS, WebbKer\n\n\ndef build_empirical_trace(clear, F277W, filename='spatial_profile.fits',\n pad=(0, 0), doplot=False, verbose=False):\n ''' Procedural function to wrap around construct orders 1 and 2.\n Will do centroiding and call the functions to construct the models.\n\n ***Will eventually want clear and F277W to be the full fits with headers\n to get parameters from***\n\n Parameters\n ----------\n clear : np.array of float (2D) - eventually path\n F277W : np.array of float (2D) - eventually path\n filename : str\n pad : tuple\n doplot : bool\n verbose : bool\n '''\n\n # Print overwrite warning if output file already exists.\n if os.path.exists(filename):\n print('Output file {} already exists. It will be overwritten'.format(filename))\n # Get the centroid positions for both orders from the data.\n if verbose is True:\n print('Getting trace centroids...')\n centroids, rot_pars = ctd.get_contam_centroids(clear, doplot=doplot,\n bound=False,\n showprogress=verbose)\n\n # Overplot the data centroids on the CLEAR exposure if desired.\n if doplot is True:\n plotting._plot_centroid(clear, centroids)\n\n # Construct the first order profile.\n if verbose is True:\n print('Interpolating the first order trace...')\n o1frame = construct_order1(clear, F277W, rot_pars, centroids, pad=pad[0],\n doplot=doplot)\n # Pad the spectral axis.\n if pad[1] != 0:\n if verbose is True:\n print('Adding padding to first order spectral axis...')\n o1frame = pad_spectral_axis(o1frame, centroids['order 1'][0],\n centroids['order 1'][1], pad=pad[1])\n\n # Get the extraction parameters\n #extract_params = get_extract_params()\n #ref_file_args = get_ref_file_args(o1frame)\n # Construct the second order profile.\n #o2frame_contam = construct_order2(clear, ref_file_args, extract_params)\n # Create a mask to remove residuals from the first order.\n #o2frame = mask_order(o2frame_contam, x2, y2)\n # Set any spurious negative values to zero.\n #o2frame[o2frame < 0] = 0\n # Normalize the profile in each column.\n #o2frame /= np.nansum(o2frame, axis=0)\n\n # Write the trace model to disk.\n #hdu = fits.PrimaryHDU()\n #hdu.data = np.dstack((o1frame, o2frame))\n #hdu.writeto(filename, overwrite=True)\n\n if verbose is True:\n print('Done.')\n\n return o1frame#, o2frame\n\n\ndef calc_interp_coefs(make_psfs=False, doplot=True, F277W=True, filepath=''):\n '''Function to calculate the interpolation coefficients necessary to\n construct a monochromatic PSF profile at any wavelength between\n the two 1D PSF anchor profiles. Linear combinations of the blue and red\n anchor are iteratively fit to each intermediate wavelength to find the\n best fitting combination. The mean linear coefficients across the 10 WFE\n error realizations are returned for each wavelengths.\n When called, 2D moncochromatic PSF profiles will be generated and saved\n to disk if the user does not already have them available.\n This should not need to be called by the end user except in rare cases.\n\n Parameters\n ----------\n make_psfs : bool\n Whether or not WebbPSF will have to generate the monochromatic\n PSFs used for the fitting.\n doplot : bool\n Whether to show the diagnostic plots for the model derivation.\n F277W : bool\n Set to False if no F277W exposure is available for the observation.\n Finds coefficients for the entire 2.1 - 2.9µm region in this case.\n filepath : str\n Path to directory containing the WebbPSF monochromatic PSF fits\n files, or the directory to which they will be stored when made.\n Defaults to the current directory.\n\n Returns\n -------\n pb : np.array of float\n Polynomial coefficients of the interpolation index fits for the\n blue anchor.\n pr : np.array of float\n Polynomial coefficients of the interpolation index fits for the\n red anchor.\n '''\n\n # Red anchor is 2.8µm without an F277W exposure.\n if F277W is False:\n wave_range = np.linspace(2.1, 2.9, 7)\n # Red anchor is 2.5µm with F277W exposure.\n else:\n wave_range = np.linspace(2.1, 2.45, 7)\n\n # Read in monochromatic PSFs generated by WebbPSF.\n PSFs = []\n # Loop over all 10 available WFE realizations.\n for i in range(10):\n psf_run = []\n # Create the PSF if user has indicated to.\n if make_psfs is True:\n loicpsf(wavelist=wave_range*1e-6, wfe_real=i)\n # If user already has PSFs generated.\n for w in wave_range:\n try:\n psf_run.append(fits.open('{0:s}SOSS_os10_128x128_{1:.6f}_{2:.0f}.fits'\n .format(filepath, w, i))[0].data)\n # Generate missing PSFs if necessary.\n except FileNotFoundError:\n print('No monochromatic PSF found for {0:.2f}µm and WFE realization {1:.0f}.'\n .format(w, i))\n loicpsf(wavelist=[w*1e-6], wfe_real=i, filepath=filepath)\n psf_run.append(fits.open('{0:s}SOSS_os10_128x128_{1:.6f}_{2:.0f}.fits'\n .format(filepath, w, i))[0].data)\n PSFs.append(psf_run)\n\n # Determine specific interpolation coefficients for all WFEs\n wb, wr = [], []\n\n for E in range(10):\n # Generate the blue wavelength anchor.\n # The width of the 1D PSF has lambda/D dependence, so rescale all\n # profiles to a common wavelength to remove these chromatic effects.\n rngeb = np.linspace(0, round(1280*(2.5/2.1), 0) - 1, 1280)\n offsetb = rngeb[640] - 640\n newb = np.interp(np.arange(1280), rngeb - offsetb,\n np.sum(PSFs[E][0][600:700, :], axis=0))\n\n # Generate the red wavelength anchor.\n if F277W is False:\n # Use 2.85µm for CLEAR.\n rnger = np.linspace(0, round(1280*(2.5/2.9), 0) - 1, 1280)\n else:\n # Or 2.42µm for F277W.\n rnger = np.linspace(0, round(1280*(2.5/2.45), 0) - 1, 1280)\n offsetr = rnger[640] - 640\n # Remove lambda/D scaling.\n newr = np.interp(np.arange(1280), rnger - offsetr,\n np.sum(PSFs[E][6][600:700, :], axis=0))\n\n # Loop over all monochrmatic PSFs to determine interpolation coefs.\n for f, wave in enumerate(wave_range):\n # Lists for running counts of indicies and model residuals.\n resid, ind_i, ind_j = [], [], []\n\n # Rescale monochrmotic PSF to remove lambda/D.\n newrnge = np.linspace(0, round(1280*(2.5/wave), 0) - 1, 1280)\n newoffset = newrnge[640] - 640\n newpsf = np.interp(np.arange(1280), newrnge - newoffset,\n np.sum(PSFs[E][f][600:700, :], axis=0))\n\n # Brute force the coefficient determination.\n for i in range(1, 100):\n for j in range(1, 100):\n i /= 10\n j /= 10\n # Create a test profile which is a mix of the two anchors.\n mix = (i*newb + j*newr) / (i + j)\n\n # Save current iteration in running counts.\n resid.append(np.sum(np.abs(newpsf - mix)[450:820]))\n ind_i.append(i)\n ind_j.append(j)\n\n # Determine which combination of indices minimizes model residuals.\n ind = np.where(resid == np.min(resid))[0][0]\n # Save the normalized indices for this wavelength.\n wb.append(ind_i[ind] / (ind_i[ind] + ind_j[ind]))\n wr.append(ind_j[ind] / (ind_i[ind] + ind_j[ind]))\n\n wb = np.reshape(wb, (10, 7))\n wr = np.reshape(wr, (10, 7))\n\n # Fit a second order polynomial to the mean of the interpolation indices.\n pb = np.polyfit(wave_range, np.mean(wb, axis=0), 2)\n pr = np.polyfit(wave_range, np.mean(wr, axis=0), 2)\n\n # Show the diagnostic plot if necessary.\n if doplot is True:\n plotting._plot_interpmodel(wave_range, wb, wr, pb, pr)\n\n return pb, pr, wb, wr\n\n\ndef _chromescale(wave_start, profile, ycen, wave_end=2.5, invert=False):\n '''Remove the lambda/D chromatic PSF scaling by re-interpolating a\n monochromatic PSF function onto a rescaled axis.\n\n Parameters\n ----------\n wave_start : float\n Wavelength corresponding to the input 1D PSF profile.\n profile : np.array of float\n 1D PSF profile to be rescaled.\n ycen : float\n Y-pixel position of the order 1 trace centroid.\n wave_end : float\n Wavelength after rescaling.\n invert : bool\n If True, add back the lambda/D scaling instead of removing it.\n\n Returns\n -------\n prof_recsale : np.array of float\n Rescaled 1D PSF profile.\n '''\n\n xrange = len(profile)\n # Assume that the axis corresponding to wave_end can be constructed with\n # np.arange - this is the 'standard' axis.\n # Construct the input profile axis by rescaling the standard axis by the\n # ratio of wave_end/wave_start.\n xax = np.linspace(0, round(xrange*(wave_end/wave_start), 0) - 1, xrange)\n # Calculate the offset of the centroid y-position in the standard and\n # rescaled axis, to ensure it remains at the same pixel position.\n offset = xax[int(round(ycen, 0))] - ycen\n\n # Interpolate the profile onto the standard axis.\n if invert is False:\n prof_rescale = np.interp(np.arange(xrange), xax - offset, profile)\n # Or interpolate the profile from the standard axis to re-add\n # the lambda/D scaling.\n else:\n prof_rescale = np.interp(xax - offset, np.arange(xrange), profile)\n\n return prof_rescale\n\n\ndef construct_order1(clear, F277, rot_params, ycens, pad=0, doplot=False):\n '''This creates the full order 1 trace profile model. The region\n contaminated by the second order is interpolated from the CLEAR and F277W\n exposures, or just from the CLEAR exposure and a standard red anchor if\n no F277W exposure is available.\n The steps are as follows:\n 1. Determine the red and blue anchor profiles for the interpolation.\n 2. Construct the interpolated profile at each wavelength in the\n overlap region.\n 3. Stitch together the original CLEAR exposure and the interpolated\n trace model (as well as the F277W exposure if provided).\n 4. Mask the contamination from the second and third orders, and\n reconstruct the underlying wing structure of the first order -\n including any padding in the spatial direction.\n\n Parameters\n ----------\n clear : np.array of float (2D)\n NIRISS SOSS CLEAR exposure dataframe.\n F277 : np.array of float (2D)\n NIRISS SOSS F277W filter exposure dataframe. If no F277W exposure\n is available, pass None.\n rot_params : list of float\n List containing the rotation angle, X and Y anchor points, and X\n and Y offset required to transform OM coordinates to the detector\n frame.\n ycens : dict\n Dictionary of Y-coordinates for the trace centroids of the first three\n diffraction orders, ie. as returned by get_contam_centroids.\n pad : int\n Number of pixels of padding to add on both ends of the spatial axis.\n doplot : bool\n if True, do diagnostic plotting.\n\n Returns\n -------\n newmap : np.array of float (2D)\n Interpolated order 1 trace model with padding.\n '''\n\n # Determine the anchor profiles - blue anchor.\n # Note: Y-values returned from OM are inverted relative to the UdeM\n # coordinate system.\n ###### TODO Switch this to use wavecal ######\n xOM, yOM, tp2 = ctd.get_om_centroids()\n # Get OM centroid pixel coords at 2.1µm.\n xom22 = tp.wavelength_to_pix(2.1, tp2, 1)[0]\n yom22 = 256 - tp.wavelength_to_pix(2.1, tp2, 1)[1]\n # Use rot params to find location of the 2.1µm centroids in the data frame.\n xd22, yd22 = ctd.rot_centroids(*rot_params, xom22, yom22)\n xd22 = np.round(xd22, 0).astype(int)[0]\n yd22 = np.round(yd22, 0).astype(int)[0]\n # Extract the 2.1µm anchor profile from the data.\n Banch = clear[:, xd22]\n # Mask second and third order, reconstruct wing structure and pad.\n cens = [ycens['order 1'][1][xd22], ycens['order 2'][1][xd22],\n ycens['order 3'][1][xd22]]\n Banch = reconstruct_wings(Banch, ycens=cens, contamination=True, pad=pad,\n doplot=doplot)\n # Remove the lambda/D scaling.\n Banch = _chromescale(2.1, Banch, yd22)\n # Normalize\n Banch /= np.nansum(Banch)\n\n # Determine the anchor profiles - red anchor.\n if F277 is None:\n # If no F277W exposure is provided, interpolate out to 2.9µm.\n # Generate a simulated 2.9µm PSF.\n stand = loicpsf([2.9*1e-6], save_to_disk=False, oversampling=1,\n pixel=256, verbose=False)[0][0].data\n # Extract the spatial profile.\n Ranch = np.sum(stand[124:132, :], axis=0)\n # Detemine OM coords of 2.9µm centroid.\n xom25 = tp.wavelength_to_pix(2.9, tp2, 1)[0]\n yom25 = 256 - tp.wavelength_to_pix(2.9, tp2, 1)[1]\n # Transform into the data frame.\n yd25 = ctd.rot_centroids(*rot_params, xom25, yom25, bound=False)[1]\n yd25 = int(round(yd25[0], 0))\n # Interpolate the WebbPSF generated profile to the correct location.\n Ranch = np.interp(np.arange(256), np.arange(256)-128+yd25, Ranch)\n # Reconstruct wing structure and pad.\n Ranch = reconstruct_wings(Ranch, ycens=[yd25], contamination=False,\n pad=pad)\n # Rescale to remove chromatic effects.\n Ranch = _chromescale(2.9, Ranch, yd25)\n # Normalize\n Ranch /= np.nansum(Ranch)\n\n # Interpolation polynomial coeffs, calculated via calc_interp_coefs\n coef_b = [0.80175603, -5.27434345, 8.54474316]\n coef_r = [-0.80175603, 5.27434345, -7.54474316]\n # Pixel coords at which to start and end interpolation in OM frame.\n end = int(round(tp.wavelength_to_pix(2.1, tp2, 1)[0], 0))\n # Determine the OM coords of first pixel on detector\n start = int(round(xom25, 0))\n rlen = end - start\n\n else:\n # If an F277W exposure is provided, only interpolate out to 2.45µm.\n # Redwards of 2.45µm we have perfect knowledge of the order 1 trace.\n # Get OM centroid pixel coords at 2.45µm\n ###### TODO Switch this to use wavecal ######\n xom25 = tp.wavelength_to_pix(2.45, tp2, 1)[0]\n yom25 = 256 - tp.wavelength_to_pix(2.45, tp2, 1)[1]\n # Transform into the data frame.\n xd25, yd25 = ctd.rot_centroids(*rot_params, xom25, yom25)\n xd25 = np.round(xd25, 0).astype(int)[0]\n yd25 = np.round(yd25, 0).astype(int)[0]\n # Extract and rescale the 2.5µm profile.\n Ranch = F277[:, xd25-1]\n # Reconstruct wing structure and pad.\n cens = [ycens['order 1'][1][xd25-1]]\n Ranch = reconstruct_wings(Ranch, ycens=cens, contamination=False,\n pad=pad)\n Ranch = _chromescale(2.45, Ranch, yd25)\n # Normalize\n Ranch /= np.nansum(Ranch)\n\n # Interpolation polynomial coeffs, calculated via calc_interp_coefs\n coef_b = [1.51850915, -9.76581613, 14.80720191]\n coef_r = [-1.51850915, 9.76581613, -13.80720191]\n # Pixel coords at which to start and end interpolation in OM frame.\n end = int(round(tp.wavelength_to_pix(2.1, tp2, 1)[0], 0))\n start = int(round(tp.wavelength_to_pix(2.45, tp2, 1)[0], 0))\n rlen = end - start\n\n # Create the interpolated order 1 PSF.\n map2D = np.zeros((256+2*pad, 2048))*np.nan\n # Get OM X-pixel values for the region to be interpolated.\n cenx_om = np.arange(rlen) + start\n # Find the wavelength at each X centroid\n lmbda = tp.specpix_to_wavelength(cenx_om, tp2, 1)[0]\n # Y centroid at each wavelength\n ceny_om = 256 - tp.wavelength_to_pix(lmbda, tp2, 1)[1]\n # Transform the OM centroids onto the detector.\n cenx_d, ceny_d = ctd.rot_centroids(*rot_params, cenx_om, ceny_om,\n bound=False)\n\n # Create an interpolated 1D PSF at each required position.\n for i, vals in enumerate(zip(cenx_d, ceny_d, lmbda)):\n cenx, ceny, lbd = vals[0], vals[1], vals[2]\n # Evaluate the interpolation polynomials at the current wavelength.\n wb_i = np.polyval(coef_b, lbd)\n wr_i = np.polyval(coef_r, lbd)\n # Recenter the profile of both anchors on the correct Y-centroid.\n bax = np.arange(256+2*pad)-yd22+ceny\n Banch_i = np.interp(np.arange(256+2*pad), bax, Banch)\n rax = np.arange(256+2*pad)-yd25+ceny\n Ranch_i = np.interp(np.arange(256+2*pad), rax, Ranch)\n # Construct the interpolated profile.\n prof_int = (wb_i * Banch_i + wr_i * Ranch_i)\n # Re-add the lambda/D scaling.\n prof_int_cs = _chromescale(lbd, prof_int, ceny, invert=True)\n # Put the interpolated profile on the detector.\n map2D[:, int(round(cenx, 0))] = prof_int_cs\n\n # Note detector coordinates of the edges of the interpolated region.\n bend = int(round(cenx, 0))\n if i == 0:\n # 2.85µm (i=0) limit may be off the end of the detector.\n rend = np.max([int(round(cenx, 0)), 0])\n\n # Stitch together the interpolation and data.\n newmap = np.zeros((256+2*pad, 2048))\n # Insert interpolated data\n newmap[:, rend:bend] = map2D[:, rend:bend]\n # Bluer region is known from the CLEAR exposure.\n # Mask contamination from second and third orders and reconstruct wings.\n for col in range(bend, 2048):\n cens = [ycens['order 1'][1][col], ycens['order 2'][1][col],\n ycens['order 3'][1][col]]\n newmap[:, col] = reconstruct_wings(clear[:, col], ycens=cens, pad=pad)\n if F277 is not None:\n # Add on the F277W frame to the red of the model.\n # Reconstruct wing structure and pad.\n for col in range(rend):\n cens = [ycens['order 1'][1][col]]\n newmap[:, col] = reconstruct_wings(F277[:, col], ycens=cens,\n contamination=False, pad=pad)\n # Insert interpolated data to the red of the data.\n else:\n newmap[:, 0:rend] = map2D[:, 0:rend]\n\n # Column normalize.\n newmap /= np.nansum(newmap, axis=0)\n # Add noise floor to prevent arbitrarily low values in padded wings.\n floor = np.nanpercentile(newmap[pad:(-1-pad), :], 2)\n newmap += floor\n\n return newmap\n\n\ndef construct_order2(clear, ref_file_args, extract_params):\n '''Preforms an extraction and reconstructs the detector with only the\n first order trace profile. The second order profile is then isolated\n through the difference of the original and reconstructed detector.\n\n Parameters\n ----------\n clear : np.array of float (2D)\n CLEAR data frame.\n ref_file_args : list\n List of parameters of the reference files.\n extract_params : dict\n Dictionary of arguments required by the extraction algorithm.\n\n Returns\n -------\n residual : np.array of float (2D)\n Detector with only the order 2 trace profile.\n '''\n\n # Set up the extraction.\n extra = ExtractionEngine(*ref_file_args, **extract_params)\n # Preform the extraction with only the first order.\n f_k = extra.extract(data=clear)\n # Rebuild the detector.\n rebuilt = extra.rebuild(f_k)\n rebuilt[np.isnan(rebuilt)] = 0\n # Isolate the second order by subtracting the reconstructed first\n # order from the data\n residual = clear - rebuilt\n\n return residual\n\n\ndef get_extract_params():\n '''\n '''\n params = {}\n # Map of expected noise (sig)\n bkgd_noise = 20.\n # Oversampling\n params[\"n_os\"] = 1\n # Threshold on the spatial profile\n params[\"thresh\"] = 1e-6\n\n return params\n\n\ndef get_ref_file_args(o1frame):\n '''\n '''\n path = '/Users/michaelradica/Documents/GitHub/jwst-mtl/SOSS/'\n # List of orders to consider in the extraction\n order_list = [1]\n\n # Wavelength solution\n wave_maps = []\n wave_maps.append(fits.getdata(path+\"extract/Ref_files/wavelengths_m1.fits\"))\n\n # Spatial profiles\n spat_pros = []\n spat_pros.append(o1frame)\n\n # Convert data from fits files to float (fits precision is 1e-8)\n wave_maps = [wv.astype('float64') for wv in wave_maps]\n spat_pros = [p_ord.astype('float64') for p_ord in spat_pros]\n\n # Throughputs\n thrpt_list = [ThroughputSOSS(order) for order in order_list]\n\n # Convolution kernels\n ker_list = [WebbKer(wv_map) for wv_map in wave_maps]\n\n # Put all inputs from reference files in a list\n ref_file_args = [wave_maps, spat_pros, thrpt_list, ker_list]\n\n return ref_file_args\n\n\ndef loicpsf(wavelist=None, wfe_real=None, filepath='', save_to_disk=True,\n oversampling=10, pixel=128, verbose=True):\n '''Calls the WebbPSF package to create monochromatic PSFs for NIRISS\n SOSS observations and save them to disk.\n\n Parameters\n ----------\n wavelist : list\n List of wavelengths (in meters) for which to generate PSFs.\n wfe_real : int\n Index of wavefront realization to use for the PSF (if non-default\n WFE realization is desired).\n filepath : str\n Path to the directory to which the PSFs will be written.\n Defaults to the current directory.\n save_to_disk : bool\n Whether to save PSFs to disk, or return them from the function.\n oversampling : int\n Oversampling pixels scale for the PSF.\n pixel : int\n Width of the PSF in native pixels.\n verbose : bool\n Whether to print explanatory comments.\n\n Returns\n -------\n psf_list : list\n If save_to_disk is False, a list of the generated PSFs.\n '''\n\n psf_list = []\n\n if wavelist is None:\n # List of wavelengths to generate PSFs for\n wavelist = np.linspace(0.5, 5.2, 95) * 1e-6\n # Dimension of the PSF in native pixels\n pixel = pixel\n\n # Select the NIRISS instrument\n niriss = webbpsf.NIRISS()\n\n # Override the default minimum wavelength of 0.6 microns\n niriss.SHORT_WAVELENGTH_MIN = 0.5e-6\n # Set correct filter and pupil wheel components\n niriss.filter = 'CLEAR'\n niriss.pupil_mask = 'GR700XD'\n\n # Change the WFE realization if desired\n if wfe_real is not None:\n niriss.pupilopd = ('OPD_RevW_ote_for_NIRISS_predicted.fits.gz',\n wfe_real)\n\n # Loop through all wavelengths to generate PSFs\n for wave in wavelist:\n if verbose is True:\n print('Calculating PSF at wavelength ',\n round(wave/1e-6, 2), ' microns')\n psf = niriss.calc_psf(monochromatic=wave, fov_pixels=pixel,\n oversample=oversampling, display=False)\n psf_list.append(psf)\n\n if save_to_disk is True:\n # Save psf realization to disk\n text = '{0:5f}'.format(wave*1e+6)\n psf.writeto(str(filepath)+'SOSS_os'+str(oversampling)+'_'+str(pixel)\n + 'x'+str(pixel)+'_'+text+'_'+str(wfe_real)+'.fits',\n overwrite=True)\n\n if save_to_disk is False:\n return psf_list\n\n\ndef mask_order(frame, xpix, ypix):\n '''\n Depreciated!\n Create a pixel mask to isolate only the detector pixels belonging to\n a specific diffraction order.\n\n Parameters\n ----------\n frame : np.array of float (2D)\n Science data frame.\n xpix : np.array\n Data x centroids for the desired order\n ypix : np.array\n Data y centroids for the desired order\n\n Returns\n -------\n O1frame : np.array of float (2D)\n The input data frame, with all pixels other than those within\n +/- 20 pixels of ypix masked.\n '''\n\n mask = np.zeros([256, 2048])\n xx = np.round(xpix, 0).astype(int)\n yy = np.round(ypix, 0).astype(int)\n xr = np.linspace(np.min(xx), np.max(xx), np.max(xx)+1).astype(int)\n\n # Set all pixels within the extent of the spatial profile to 1\n for xxx, yyy in zip(xr, yy):\n # Ensure that we stay on the detector\n p_max = np.min([yyy+20, 255])\n p_min = np.max([yyy-21, 0])\n mask[p_min:p_max, xxx] = 1\n\n # Mask pixels not in the order we want\n O1frame = (mask * frame)\n\n return O1frame\n\n\ndef pad_spectral_axis(frame, xcens, ycens, pad=0):\n '''Add padding to the spectral axis by interpolating the corresponding\n edge profile onto a set of extrapolated centroids.\n\n Parameters\n ----------\n frame : np.array (2D)\n Data frame.\n xcens : list\n X-coordinates of the trace centroids.\n ycens : list\n Y-coordinates of the trace centroids.\n pad : int\n Amount of padding to add along either end of the spectral axis (in\n pixels).\n\n Returns\n -------\n newframe : np.array (2D)\n Data frame with padding on the spectral axis.\n '''\n\n ylen = int(frame.shape[0])\n xlen = int(frame.shape[1])\n pp = np.polyfit(xcens, ycens, 5)\n xax_pad = np.arange(xlen+2*pad)-pad\n ycens_pad = np.polyval(pp, xax_pad)\n\n newframe = np.zeros((ylen, xlen+2*pad))\n newframe[:, (pad):(xlen+pad)] = frame\n\n for col in range(pad):\n yax = np.arange(ylen)\n newframe[:, col] = np.interp(yax+ycens[5]-ycens_pad[col], yax,\n frame[:, 5])\n\n for col in range(xlen+pad, xlen+2*pad):\n yax = np.arange(ylen)\n newframe[:, col] = np.interp(yax+ycens[-10]-ycens_pad[col], yax,\n frame[:, -10])\n\n return newframe\n\n\ndef reconstruct_wings(profile, ycens=None, contamination=True, pad=0,\n doplot=False):\n '''Masks the second and third diffraction orders and reconstructs the\n underlying wing structure of the first order. Also adds padding in the\n spatial direction if required.\n\n Parameters\n ----------\n profile : np.array\n Spectral trace spatial profile.\n ycens : list\n Y-coordinates of the trace centroids. Must include all three\n diffraction orders if contamination is True, or only the first order if\n False.\n contamination : bool\n If True, profile has contamination from the second and third\n diffraction orders.\n pad : int\n Amount to pad each end of the spartial axis (in pixels).\n doplot : bool\n If True, does diagnostic plotting.\n\n Returns\n -------\n newprof : np.array\n Input spatial profile with reconstructed wings and padding.\n\n Raises\n ------\n ValueError\n If centroids are not provided for all three orders when contamination\n is set to True.\n '''\n\n # Convert Y-centroid positions to indices\n ycens = np.atleast_1d(ycens)\n ycens = np.round(ycens, 0).astype(int)\n if contamination is True and ycens.size != 3:\n raise ValueError('Centroids must be provided for first three orders if there is contamination.')\n\n # ====== Reconstruct left wing ======\n # Get the left wing of the trace profile in log space.\n prof_l = np.log10(profile[0:(ycens[0]-12)])\n # and corresponding axis.\n axis_l = np.arange(256)[0:(ycens[0]-12)]\n\n # === Outlier masking ===\n # Mask the cores of each order.\n for order, ycen in enumerate(ycens):\n if order == 0:\n start = ycen-25\n end = len(profile)\n elif order == 1:\n start = np.max([ycen-15, 0])\n end = np.max([ycen+15, 1])\n else:\n start = np.max([ycen-10, 0])\n end = np.max([ycen+10, 1])\n # Set core of each order to NaN.\n prof_l[start:end] = np.nan\n\n # Fit the unmasked part of the wing to determine the mean trend.\n inds = np.where(np.isfinite(prof_l))[0]\n pp = _robust_linefit(axis_l[inds], prof_l[inds], (0, 0))\n wing_mean = pp[0]+pp[1]*axis_l[inds]\n # Calculate the standard dev of unmasked points from the mean trend.\n stddev = np.sqrt(np.median((prof_l[inds] - wing_mean)**2))\n # Find all outliers that are >3-sigma deviant from the mean.\n inds2 = np.where(prof_l[inds] - wing_mean > 3*stddev)\n\n # === Wing fit ===\n # Get fresh left wing profile.\n prof_l2 = np.log10(profile[0:(ycens[0]-12)])\n # Mask second and third orders.\n if contamination is True:\n for order, ycen in enumerate(ycens):\n if order == 1:\n start = np.max([ycen-15, 0])\n end = np.max([ycen+15, 1])\n elif order == 2:\n start = np.max([ycen-10, 0])\n end = np.max([ycen+10, 1])\n # Set core of each order to NaN.\n prof_l2[start:end] = np.nan\n # Mask outliers\n prof_l2[inds[inds2]] = np.nan\n\n # Indices of all unmasked points in the left wing.\n inds3 = np.isfinite(prof_l2)\n # Fit with a 7th order polynomial.\n pp_l = np.polyfit(axis_l[inds3], prof_l2[inds3], 7)\n\n # ====== Reconstruct right wing ======\n # Get the profile for the right wing in log space.\n prof_r = np.log10(profile[(ycens[0]+12):])\n # and corresponding axis.\n axis_r = np.arange(256)[(ycens[0]+12):]\n # Fit with third order polynomial.\n pp_r = np.polyfit(axis_r, prof_r, 3)\n\n # ===== Stitching =====\n # Find pixel to stitch right wing fit.\n jjr = ycens[0]+15\n iir = np.where(axis_r == jjr)[0][0]\n # Pad the right axis.\n axis_r_pad = np.linspace(axis_r[0], axis_r[-1]+pad, len(axis_r)+pad)\n # Join right wing to old trace profile.\n newprof = np.concatenate([profile[:jjr], 10**np.polyval(pp_r, axis_r_pad)[iir:]])\n\n # Find pixel to stitch left wing fit.\n jjl = ycens[0]-15\n # Pad the left axis.\n axis_l_pad = np.linspace(axis_l[0]-pad, axis_l[-1], len(axis_l)+pad)\n iil = np.where(axis_l_pad == jjl)[0][0]\n # Join left wing to old trace profile.\n newprof = np.concatenate([10**np.polyval(pp_l, axis_l_pad)[:iil], newprof[jjl:]])\n\n if doplot is True:\n plotting._plot_wing_reconstruction(profile, ycens, axis_l, axis_l_pad,\n axis_r_pad, pp_l, pp_r, prof_l2,\n newprof)\n\n return newprof\n\n\ndef reconstruct_wings2(frame, ycen, pad_factor=1):\n '''\n Depreciated!\n Takes a reconstructed trace profile which has been truncated about the\n centroid and reconstructs the extended wing structure using an exponential\n profile. Also adds padding in the spatial direction by extending the\n exponetial fit.\n\n Parameters\n ----------\n frame : np.ndarray of float (2D)\n Empirical trace model.\n ycen : np.array of float\n Y-pixel centroid positions.\n pad_factor : int\n Multiplicative padding factor on the spatial axis. Defaults to 1 (no\n padding).\n\n Returns\n -------\n newframe : np.ndarray of float (2D)\n Trace model with reconstructed extended wing structure, and required\n padding.\n '''\n\n # Create new detector array and spatial axis taking into account padding.\n newframe = np.zeros(((pad_factor)*frame.shape[0], frame.shape[1]))\n fullax = np.arange(frame.shape[0])\n fullax_pad = np.arange((pad_factor)*frame.shape[0]) - (frame.shape[0]/2)*(pad_factor-1)\n\n # Loop over each column on the detector.\n for col in range(frame.shape[1]):\n\n # Temporary hack for NaN columns\n if np.any(np.isnan(frame[:, col])):\n continue\n\n # Get the centroid Y-position.\n cen = int(round(ycen[col], 0))\n\n # Extract the left wing\n start = np.max([0, cen-75])\n ax_l = np.arange(start, cen-9)\n lwing = np.log10(frame[start:(cen-9), col])\n # Find where the log is finite\n lwing_noi = lwing[np.isfinite(lwing)]\n ax_l_noi = ax_l[np.isfinite(lwing)]\n # Fit a first order polynomial to the finite value of the log wing.\n # Equivalent to fitting an exponential to the wing.\n pp_l = np.polyfit(ax_l_noi, lwing_noi, 1)\n\n # Locate pixels for stitching - where the left wing goes to zero.\n ii_l = np.where(np.isinf(lwing))[0][-1]\n # Location in full axis.\n jj_l = np.where(fullax == ax_l[ii_l])[0][0]\n # Location in padded axis.\n kk_l = np.where(fullax_pad == ax_l[ii_l])[0][0]\n\n # Extract the right wing\n end = np.min([cen+50, 255])\n ax_r = np.arange(cen+9, end)\n rwing = np.log10(frame[(cen+9):end, col])\n # Find where the log is finite\n rwing_noi = rwing[np.isfinite(rwing)]\n ax_r_noi = ax_r[np.isfinite(rwing)]\n # Fit a first order polynomial to the finite value of the log wing.\n # Equivalent to fitting an exponential to the wing.\n pp_r = np.polyfit(ax_r_noi, rwing_noi, 1)\n\n # Locate pixels for stitching - where the right wing goes to zero.\n ii_r = np.where(np.isinf(rwing))[0][0]\n jj_r = np.where(fullax == ax_r[ii_r])[0][0]\n kk_r = np.where(fullax_pad == ax_r[ii_r])[0][0]\n\n # Stitch the wings to the original profile, add padding if necessary.\n newcol = np.concatenate([10**(np.polyval(pp_l, fullax_pad[:kk_l])),\n frame[jj_l:jj_r, col],\n 10**(np.polyval(pp_r, fullax_pad[kk_r:]))])\n\n try:\n # Find any remaining pixels where the profile is zero.\n inds = np.where(newcol == 0)[0][0]\n # If there are remainining zeros, replace with mean of neighbours.\n newcol[inds] = np.mean([newcol[inds-1], newcol[inds+1]])\n except IndexError:\n pass\n\n # Renormalize the column.\n newframe[:, col] = newcol / np.nansum(newcol)\n\n return newframe\n\n\ndef _robust_linefit(x, y, p0):\n '''Wrapper around scipy's least_squares line fitting routine implementing\n the Huber loss function - to be more resistant to outliers.\n\n Parameters\n ----------\n x : list\n Data describing dependant variable.\n y : list\n Data describing independant variable.\n p0 : tuple\n Initial guess straight line parameters.\n\n Returns\n -------\n res.x : list\n Best fitting parameters of a straight line.\n '''\n\n def line_res(p, x, y):\n '''Residuals from a straight line'''\n return p[0]+p[1]*x-y\n\n # Preform outlier resistant fitting.\n res = least_squares(line_res, p0, loss='huber', f_scale=0.1, args=(x, y))\n\n return res.x\n", "meta": {"hexsha": "fa06c934e1633b1fd318133469021dd6005717e8", "size": 35336, "ext": "py", "lang": "Python", "max_stars_repo_path": "SOSS/extract/Empirical_Trace/construct_trace.py", "max_stars_repo_name": "njcuk9999/jwst-mtl", "max_stars_repo_head_hexsha": "81d3e7ec6adc5dae180cd9d3bff8e4a2a7292596", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-04T13:59:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T13:59:18.000Z", "max_issues_repo_path": "SOSS/extract/Empirical_Trace/construct_trace.py", "max_issues_repo_name": "njcuk9999/jwst-mtl", "max_issues_repo_head_hexsha": "81d3e7ec6adc5dae180cd9d3bff8e4a2a7292596", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-09-17T20:14:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T21:16:43.000Z", "max_forks_repo_path": "SOSS/extract/Empirical_Trace/construct_trace.py", "max_forks_repo_name": "njcuk9999/jwst-mtl", "max_forks_repo_head_hexsha": "81d3e7ec6adc5dae180cd9d3bff8e4a2a7292596", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-18T15:25:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-18T15:25:52.000Z", "avg_line_length": 37.5914893617, "max_line_length": 104, "alphanum_fraction": 0.6202173421, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 9374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725051, "lm_q2_score": 0.2538610069692489, "lm_q1q2_score": 0.13781181971280465}} {"text": "# -*- coding:utf-8 -*-\n\n\"\"\" Tensorflow Implementation of Variational Autoencoder for sentences.\n\tPaper: Generating Sentences from a Continuous Space\n\t(https://arxiv.org/abs/1511.06349)\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\n\nclass VAE(object):\n\tdef __init__(self, hparam, word_to_index, index_to_word):\n\t\tself.hparam = hparam\n\t\tself.word_to_index = word_to_index\n\t\tself.index_to_word = index_to_word\n\n\t\tself.seq_len = hparam.seq_len\n\t\tself.vocab_size = hparam.vocab_size\n\t\tself.embedding_dim = hparam.embedding_dim\n\t\tself.hidden_dim = hparam.hidden_dim\n\t\tself.latent_dim = hparam.latent_dim\n\t\tself.clip_norm = hparam.clip_norm\n\t\tself.num_layers = hparam.num_layers\n\t\tself.beam_width = hparam.beam_width\n\t\tself.rnn_type = hparam.rnn_type\n\t\tself.anneal_max = hparam.anneal_max\n\t\tself.anneal_bias = hparam.anneal_bias\n\t\tself.anneal_slope = hparam.anneal_slope\n\n\t\tself.SOS_ID = word_to_index[\"\"]\n\t\tself.EOS_ID = word_to_index[\"\"]\n\t\tself.UNK_ID = word_to_index[\"\"]\n\t\tself.PAD_ID = word_to_index[\"\"]\n\n\t\tself._build_global_helper()\n\t\tself._build_graph()\n\t\tself._build_summary()\n\n\t\tself.merged_summary = tf.summary.merge_all()\n\t\tself.init = tf.global_variables_initializer()\n\n\tdef _build_global_helper(self):\n\t\tself.inputs = tf.placeholder(tf.int32, [None, self.seq_len])\n\t\tself.targets = tf.placeholder(tf.int32, [None, self.seq_len])\n\n\t\tself.enc_inputs = self.inputs\n\t\tself.dec_inputs = self.inputs\n\t\tself.dec_targets = self.targets\n\t\tself.enc_lengths = tf.count_nonzero(self.enc_inputs, 1, dtype=tf.int32)\n\t\tself.dec_lengths = self.enc_lengths\n\t\tself.batch_size = tf.shape(self.inputs)[0]\n\n\t\tself.lr = tf.Variable(0.0, trainable=False)\n\t\tself.new_lr = tf.placeholder(tf.float32, [])\n\t\tself.lr_update = tf.assign(self.lr, self.new_lr)\n\n\t\tself.global_step = tf.Variable(0, trainable=False)\n\t\tself.saver = tf.train.Saver()\n\n\tdef _build_graph(self):\n\t\tself._build_forward_graph()\n\t\tself._build_backward_graph()\n\n\tdef _build_forward_graph(self):\n\t\twith tf.variable_scope(\"encoder\", reuse=None):\n\t\t\tembedding = tf.get_variable(\"embedding\", [self.vocab_size, self.embedding_dim], dtype=tf.float32)\n\t\t\tself.embedded_enc_inputs = tf.nn.embedding_lookup(embedding, self.enc_inputs)\n\t\t\tself.embedded_dec_inputs = tf.nn.embedding_lookup(embedding, self.dec_inputs)\n\n\t\t\tenc_cell = self.create_rnn_cell(reuse=None)\n\t\t\tenc_init = enc_cell.zero_state(self.batch_size, tf.float32)\n\t\t\tenc_outputs, enc_states = tf.nn.dynamic_rnn(cell = enc_cell,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tinitial_state = enc_init,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tinputs = self.embedded_enc_inputs,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tsequence_length = self.enc_lengths,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tdtype = tf.float32)\n\t\t\tif self.rnn_type == \"gru\":\n\t\t\t\tenc_vector = enc_states[-1]\n\t\t\telif self.rnn_type == \"block\" or self.rnn_type == \"basic\":\n\t\t\t\tenc_vector = tf.concat([enc_states[-1].c, enc_states[-1].h], 1)\n\n\t\t\tself.enc_mean = tf.layers.dense(enc_vector, self.latent_dim, name=\"enc_mean\")\n\t\t\tself.enc_logvar = tf.layers.dense(enc_vector, self.latent_dim, name=\"enc_logvar\")\n\t\t\tepsilon = tf.truncated_normal(tf.shape(self.enc_mean))\n\t\t\tself.latent_sample = self.enc_mean + tf.exp(0.5 * self.enc_logvar) * epsilon\n\n\t\tself.training_rnn_outputs, self.training_logits = self.decoder_training(self.latent_sample)\n\t\tself.reconstructions = tf.argmax(self.training_logits, 2)\n\t\tself.predicted_ids = self.decoder_inference(self.latent_sample)\n\n\tdef _build_backward_graph(self):\n\t\tself.nll_loss = self.nll_loss_fn()\n\t\tself.kl_w = self.kl_w_fn()\n\t\tself.kl_loss = self.kl_loss_fn()\n\t\tself.total_loss = self.nll_loss + self.kl_loss * self.kl_w\n\n\t\tparams = tf.trainable_variables()\n\t\tgradients = tf.gradients(self.total_loss, params)\n\t\tclipped_gradients, _ = tf.clip_by_global_norm(gradients, self.clip_norm)\n\t\tself.train_op = tf.train.AdamOptimizer(self.lr).apply_gradients(\n\t\t\tzip(clipped_gradients, params), global_step=self.global_step)\n\n\tdef create_rnn_cell(self, reuse):\n\t\tdef create_single_cell(reuse):\n\t\t\tif self.rnn_type == \"gru\":\n\t\t\t\tcell = tf.contrib.rnn.GRUCell(self.hidden_dim, \n\t\t\t\t\t\t\t\t\t\t \t kernel_initializer=tf.orthogonal_initializer(),\n\t\t\t\t\t\t\t\t\t\t \t reuse=reuse)\n\t\t\telif self.rnn_type == \"block\":\n\t\t\t\tcell = tf.contrib.rnn.LSTMBlockCell(self.hidden_dim, forget_bias=0.0, reuse=reuse)\n\t\t\telif self.rnn_type == \"basic\":\n\t\t\t\tcell = tf.contrib.rnn.BasicLSTMCell(self.hidden_dim, forget_bias=0.0, state_is_tuple=True, reuse=reuse)\n\t\t\telse:\n\t\t\t\tValueError(\"Unsupported rnn_type.\")\n\t\t\treturn cell\n\t\tcell = tf.contrib.rnn.MultiRNNCell([create_single_cell(reuse) for _ in range(self.num_layers)], state_is_tuple=True)\n\t\treturn cell\n\n\n\tdef _build_summary(self):\n\t\ttf.summary.scalar(\"total_loss\", self.total_loss)\n\t\ttf.summary.scalar(\"nll_loss\", self.nll_loss)\n\t\ttf.summary.scalar(\"kl_loss\", self.kl_loss)\n\t\ttf.summary.scalar(\"kl_w\", self.kl_w)\n\t\t# tf.summary.scalar(\"ratio\", self.nll_loss / self.kl_loss)\n\n\n\tdef decoder_training(self, latent_sample):\n\t\twith tf.variable_scope(\"encoder\", reuse=True):\n\t\t\tembedding = tf.get_variable(\"embedding\", [self.vocab_size, self.embedding_dim], dtype=tf.float32)\n\t\twith tf.variable_scope(\"decoder\", reuse=None):\n\t\t\tif self.rnn_type == \"gru\":\n\t\t\t\tinit_state = tuple([tf.layers.dense(latent_sample, self.hidden_dim, tf.nn.elu, name=\"trans0\")] * self.num_layers)\n\t\t\telse:\n\t\t\t\tc = tf.layers.dense(latent_sample, self.hidden_dim, tf.nn.elu, name=\"trans1\")\n\t\t\t\th = tf.layers.dense(latent_sample, self.hidden_dim, tf.nn.elu, name=\"trans2\")\n\t\t\t\tinit_state = tuple([tf.contrib.rnn.LSTMStateTuple(c=c, h=h)] * self.num_layers)\n\n\t\t\tlin_proj = tf.layers.Dense(self.vocab_size, _scope='decoder/dense', _reuse=None)\n\t\t\tdec_cell = self.create_rnn_cell(reuse=None)\n\t\t\thelper = tf.contrib.seq2seq.TrainingHelper(inputs = self.embedded_dec_inputs,\n\t\t\t\t\t\t\t\t\t\t\t\t\t sequence_length = self.dec_lengths)\n\t\t\tdecoder = tf.contrib.seq2seq.BasicDecoder(cell = dec_cell,\n\t\t\t\t\t\t\t\t\t\t\t\t\t helper = helper,\n\t\t\t\t\t\t\t\t\t\t\t\t\t initial_state = init_state)\n\t\t\tdecoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(decoder = decoder)\n\t\treturn decoder_output.rnn_output, lin_proj.apply(decoder_output.rnn_output)\n\n\n\tdef decoder_inference(self, latent_sample):\n\t\twith tf.variable_scope(\"encoder\", reuse=True):\n\t\t\tembedding = tf.get_variable(\"embedding\", [self.vocab_size, self.embedding_dim], dtype=tf.float32)\n\t\twith tf.variable_scope(\"decoder\", reuse=True):\n\t\t\tif self.rnn_type == \"gru\":\n\t\t\t\tinit_state = tuple([tf.layers.dense(latent_sample, self.hidden_dim, tf.nn.elu, name=\"trans0\")] * self.num_layers)\n\t\t\telse:\n\t\t\t\tc = tf.layers.dense(latent_sample, self.hidden_dim, tf.nn.elu, name=\"trans1\")\n\t\t\t\th = tf.layers.dense(latent_sample, self.hidden_dim, tf.nn.elu, name=\"trans2\")\n\t\t\t\tinit_state = tuple([tf.contrib.rnn.LSTMStateTuple(c=c, h=h)] * self.num_layers)\n\t\t\t\n\t\t\tlin_proj = tf.layers.Dense(self.vocab_size, _scope='decoder/dense', _reuse=True)\n\t\t\tdec_cell = self.create_rnn_cell(reuse=True)\n\t\t\tdecoder = tf.contrib.seq2seq.BeamSearchDecoder(cell=dec_cell,\n\t\t\t\t\t\t\t\t\t\t\t\t\t embedding=embedding,\n\t\t\t\t\t\t\t\t\t\t\t\t\t start_tokens=tf.tile(tf.constant([self.SOS_ID], dtype=tf.int32), [self.batch_size]),\n\t\t\t\t\t\t\t\t\t\t\t\t\t end_token = tf.constant(self.EOS_ID, dtype=tf.int32),\n\t\t\t\t\t\t\t\t\t\t\t\t\t initial_state = tf.contrib.seq2seq.tile_batch(init_state, self.beam_width),\n\t\t\t\t\t\t\t\t\t\t\t\t\t beam_width = self.beam_width,\n\t\t\t\t\t\t\t\t\t\t\t\t\t output_layer = lin_proj)\n\t\t\tdecoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(decoder = decoder,\n\t\t\t\t\t\t\t\t\t\t\tmaximum_iterations = 2 * tf.reduce_max(self.enc_lengths))\n\t\treturn decoder_output.predicted_ids[:, :, 0]\n\n\n\tdef nll_loss_fn(self):\n\t\tmask = tf.sequence_mask(self.dec_lengths, tf.reduce_max(self.dec_lengths), dtype=tf.float32)\n\t\treturn tf.reduce_sum(tf.contrib.seq2seq.sequence_loss(\n\t\t\t\t\tlogits = self.training_logits,\n\t\t\t\t\ttargets = self.dec_targets,\n\t\t\t\t\tweights = mask,\n\t\t\t\t\taverage_across_timesteps = False,\n\t\t\t\t\taverage_across_batch = True))\n\t\n\n\tdef kl_w_fn(self):\n\t\treturn self.anneal_max * tf.sigmoid((self.anneal_slope) * (tf.cast(self.global_step, tf.float32) - tf.constant(self.anneal_bias / 2)))\n\n\n\tdef kl_loss_fn(self):\n\t\treturn 0.5 * tf.reduce_sum(tf.exp(self.enc_logvar) + tf.square(self.enc_mean) - 1 - self.enc_logvar) / tf.to_float(self.batch_size)\n\n\n\tdef train_session(self, sess, inputs, targets):\n\t\tfeed_dict = {self.inputs: inputs,\n\t\t\t\t\t self.targets: targets}\n\t\tfetches = [self.train_op,\n\t\t\t\t self.nll_loss,\n\t\t\t\t self.kl_loss,\n\t\t\t\t self.kl_w,\n\t\t\t\t self.total_loss,\n\t\t\t\t self.global_step,\n\t\t\t\t self.merged_summary]\n\t\t_, nll_loss, kl_loss, kl_w, total_loss, step, summary = sess.run(fetches, feed_dict)\n\t\treturn {\"nll_loss\": nll_loss,\n\t\t\t\t\"kl_loss\": kl_loss,\n\t\t\t\t\"kl_w\": kl_w,\n\t\t\t\t\"total_loss\": total_loss,\n\t\t\t\t\"step\": step,\n\t\t\t\t\"summary\": summary}\n\n\n\tdef test_session(self, sess, inputs, targets):\n\t\tfeed_dict = {self.inputs: inputs,\n\t\t\t\t\t self.targets: targets}\n\t\tnll_loss, total_loss, kl_loss = sess.run([self.nll_loss, self.total_loss, self.kl_loss], feed_dict)\n\t\treturn {\"nll_loss\": nll_loss, \n\t\t\t\t\"total_loss\": total_loss,\n\t\t\t\t\"kl_loss\": kl_loss}\n\n\n\n\tdef random_generate_session(self, sess):\n\t\tfeed_dict = {self.latent_sample: np.random.randn(1, self.latent_dim),\n\t\t\t\t\t self.enc_lengths: [self.seq_len],\n\t\t\t\t\t self.batch_size: 1}\n\t\tpredicted_ids = sess.run(self.predicted_ids, feed_dict)[0]\n\t\tret = 'Random Generation: %s' % ' '.join([self.index_to_word[index] for index in predicted_ids])\n\t\treturn ret\n\n\n\tdef reconstruct_session(self, sess, sentence):\n\t\tidx_list = [self.get_word_index(w) for w in sentence.lower().split()][:self.seq_len]\n\t\tidx_list = idx_list + [self.PAD_ID] * (self.seq_len - len(idx_list))\n\t\tret1 = 'Original: %s' % ' '.join([self.index_to_word[index] for index in idx_list])\n\t\t\n\t\tpredicted_ids = sess.run(self.reconstructions, {self.inputs: np.atleast_2d(idx_list)})[0]\n\t\tret2 = 'Reconstr: %s' % ' '.join([self.index_to_word[index] for index in predicted_ids])\n\t\treturn ret1, ret2\n\n\n\tdef get_word_index(self, word):\n\t\tindex = self.word_to_index[word]\n\t\treturn index if index < self.vocab_size else self.UNK_ID\n\n\n\tdef get_parameter_size(self):\n\t\tall_vars = tf.global_variables()\n\t\ttotal_count = 0\n\t\tfor item in all_vars:\n\t\t\tif \"Adam\" in item.name:\n\t\t\t\tcontinue\n\t\t\tshape = item.get_shape().as_list()\n\t\t\tif len(shape) == 0:\n\t\t\t\ttotal_count += 1\n\t\t\telse:\n\t\t\t\tsize = 1\n\t\t\t\tfor val in shape:\n\t\t\t\t\tsize *= val\n\t\t\t\ttotal_count += size\n\t\treturn total_count", "meta": {"hexsha": "744531e3abeb92cf5f201902a3ea5e7b2e5aee14", "size": 10365, "ext": "py", "lang": "Python", "max_stars_repo_path": "models/vae.py", "max_stars_repo_name": "zheng-yanan/hierarchical-deep-generative-models", "max_stars_repo_head_hexsha": "3a92d2ce69a51f4da55a18b09ca4c246f6f6ed43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-06T02:55:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-06T02:55:45.000Z", "max_issues_repo_path": "models/vae.py", "max_issues_repo_name": "zheng-yanan/hierarchical-deep-generative-model", "max_issues_repo_head_hexsha": "3a92d2ce69a51f4da55a18b09ca4c246f6f6ed43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/vae.py", "max_forks_repo_name": "zheng-yanan/hierarchical-deep-generative-model", "max_forks_repo_head_hexsha": "3a92d2ce69a51f4da55a18b09ca4c246f6f6ed43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2613636364, "max_line_length": 136, "alphanum_fraction": 0.7179932465, "include": true, "reason": "import numpy", "num_tokens": 2753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.26284184314569564, "lm_q1q2_score": 0.13757676925438656}} {"text": "# Based on code from astropy\n# Licensed under a 3-clause BSD style license\n\nimport warnings\n\nimport os\nimport ctypes\nfrom functools import partial\n\nimport numpy as np\nfrom numpy.ctypeslib import ndpointer, load_library\n\nfrom .utils import KernelSizeError, has_even_axis, raise_even_kernel_exception\n\nLIBRARY_PATH = os.path.dirname(__file__)\n\ntry:\n _convolve = load_library(\"_convolve\", LIBRARY_PATH)\nexcept Exception:\n raise ImportError(\"Convolution C extension is missing. Try re-building astropy.\")\n\n# The GIL is automatically released by default when calling functions imported\n# from libraries loaded by ctypes.cdll.LoadLibrary()\n\n# Declare prototypes\n# Boundary None\n_convolveNd_c = _convolve.convolveNd_c\n_convolveNd_c.restype = None\n_convolveNd_c.argtypes = [ndpointer(ctypes.c_double, flags={\"C_CONTIGUOUS\", \"WRITEABLE\"}), # return array\n ndpointer(ctypes.c_double, flags=\"C_CONTIGUOUS\"), # input array\n ctypes.c_uint, # N dim\n # size array for input and result unless\n # embed_result_within_padded_region is False,\n # in which case the result array is assumed to be\n # input.shape - 2*(kernel.shape//2). Note: integer division.\n ndpointer(ctypes.c_size_t, flags=\"C_CONTIGUOUS\"),\n ndpointer(ctypes.c_double, flags=\"C_CONTIGUOUS\"), # kernel array\n ndpointer(ctypes.c_size_t, flags=\"C_CONTIGUOUS\"), # size array for kernel\n ctypes.c_bool, # nan_interpolate\n ctypes.c_bool, # embed_result_within_padded_region\n ctypes.c_uint] # n_threads\n\n# Disabling all doctests in this module until a better way of handling warnings\n# in doctests can be determined\n__doctest_skip__ = ['*']\n\nBOUNDARY_OPTIONS = [None, 'fill', 'wrap', 'extend']\n\nMAX_NORMALIZATION = 100\n\ndef _copy_input_if_needed(input, dtype=float, order='C', nan_treatment=None,\n mask=None, fill_value=None):\n # strip quantity attributes\n if hasattr(input, 'unit'):\n input = input.value\n output = input\n # Copy input\n try:\n # Anything that's masked must be turned into NaNs for the interpolation.\n # This requires copying. A copy is also needed for nan_treatment == 'fill'\n # A copy prevents possible function side-effects of the input array.\n if nan_treatment == 'fill' or np.ma.is_masked(input) or mask is not None:\n if np.ma.is_masked(input):\n # ``np.ma.maskedarray.filled()`` returns a copy, however there\n # is no way to specify the return type or order etc. In addition\n # ``np.nan`` is a ``float`` and there is no conversion to an\n # ``int`` type. Therefore, a pre-fill copy is needed for non\n # ``float`` masked arrays. ``subok=True`` is needed to retain\n # ``np.ma.maskedarray.filled()``. ``copy=False`` allows the fill\n # to act as the copy if type and order are already correct.\n output = np.array(input, dtype=dtype, copy=False, order=order, subok=True)\n output = output.filled(fill_value)\n else:\n # Since we're making a copy, we might as well use `subok=False` to save,\n # what is probably, a negligible amount of memory.\n output = np.array(input, dtype=dtype, copy=True, order=order, subok=False)\n\n if mask is not None:\n # mask != 0 yields a bool mask for all ints/floats/bool\n output[mask != 0] = fill_value\n else:\n # The call below is synonymous with np.asanyarray(array, ftype=float, order='C')\n # The advantage of `subok=True` is that it won't copy when array is an ndarray subclass. If it\n # is and `subok=False` (default), then it will copy even if `copy=False`. This uses less memory\n # when ndarray subclasses are passed in.\n output = np.array(input, dtype=dtype, copy=False, order=order, subok=True)\n except (TypeError, ValueError) as e:\n raise TypeError('input should be a Numpy array or something '\n 'convertible into a float array', e)\n return output\n\n\ndef convolve(array, kernel, boundary='fill', fill_value=0.,\n nan_treatment='interpolate', normalize_kernel=True, mask=None,\n preserve_nan=False, normalization_zero_tol=1e-8):\n \"\"\"\n Convolve an array with a kernel.\n\n This routine differs from `scipy.ndimage.convolve` because\n it includes a special treatment for ``NaN`` values. Rather than\n including ``NaN`` values in the array in the convolution calculation, which\n causes large ``NaN`` holes in the convolved array, ``NaN`` values are\n replaced with interpolated values using the kernel as an interpolation\n function.\n\n Parameters\n ----------\n array : `numpy.ndarray`\n The array to convolve. This should be a 1, 2, or 3-dimensional array\n or a list or a set of nested lists representing a 1, 2, or\n 3-dimensional array.\n kernel : `numpy.ndarray`\n The convolution kernel. The number of dimensions should match those for\n the array, and the dimensions should be odd in all directions. If a\n masked array, the masked values will be replaced by ``fill_value``.\n boundary : str, optional\n A flag indicating how to handle boundaries:\n * `None`\n Set the ``result`` values to zero where the kernel\n extends beyond the edge of the array.\n * 'fill'\n Set values outside the array boundary to ``fill_value`` (default).\n * 'wrap'\n Periodic boundary that wrap to the other side of ``array``.\n * 'extend'\n Set values outside the array to the nearest ``array``\n value.\n fill_value : float, optional\n The value to use outside the array when using ``boundary='fill'``\n normalize_kernel : bool, optional\n Whether to normalize the kernel to have a sum of one.\n nan_treatment : {'interpolate', 'fill'}\n interpolate will result in renormalization of the kernel at each\n position ignoring (pixels that are NaN in the image) in both the image\n and the kernel.\n 'fill' will replace the NaN pixels with a fixed numerical value (default\n zero, see ``fill_value``) prior to convolution\n Note that if the kernel has a sum equal to zero, NaN interpolation\n is not possible and will raise an exception.\n preserve_nan : bool\n After performing convolution, should pixels that were originally NaN\n again become NaN?\n mask : `None` or `numpy.ndarray`\n A \"mask\" array. Shape must match ``array``, and anything that is masked\n (i.e., not 0/`False`) will be set to NaN for the convolution. If\n `None`, no masking will be performed unless ``array`` is a masked array.\n If ``mask`` is not `None` *and* ``array`` is a masked array, a pixel is\n masked of it is masked in either ``mask`` *or* ``array.mask``.\n normalization_zero_tol: float, optional\n The absolute tolerance on whether the kernel is different than zero.\n If the kernel sums to zero to within this precision, it cannot be\n normalized. Default is \"1e-8\".\n\n Returns\n -------\n result : `numpy.ndarray`\n An array with the same dimensions and as the input array,\n convolved with kernel. The data type depends on the input\n array type. If array is a floating point type, then the\n return array keeps the same data type, otherwise the type\n is ``numpy.float``.\n\n Notes\n -----\n For masked arrays, masked values are treated as NaNs. The convolution\n is always done at ``numpy.float`` precision.\n \"\"\"\n\n if boundary not in BOUNDARY_OPTIONS:\n raise ValueError(\"Invalid boundary option: must be one of {}\"\n .format(BOUNDARY_OPTIONS))\n\n if nan_treatment not in ('interpolate', 'fill'):\n raise ValueError(\"nan_treatment must be one of 'interpolate','fill'\")\n\n # OpenMP support is disabled at the C src code level, changing this will have\n # no effect.\n n_threads = 1\n\n # Keep refs to originals\n passed_kernel = kernel\n passed_array = array\n\n # The C routines all need float type inputs (so, a particular\n # bit size, endianness, etc.). So we have to convert, which also\n # has the effect of making copies so we don't modify the inputs.\n # After this, the variables we work with will be array_internal, and\n # kernel_internal. However -- we do want to keep track of what type\n # the input array was so we can cast the result to that at the end\n # if it's a floating point type. Don't bother with this for lists --\n # just always push those as float.\n # It is always necessary to make a copy of kernel (since it is modified),\n # but, if we just so happen to be lucky enough to have the input array\n # have exactly the desired type, we just alias to array_internal\n # Convert kernel to ndarray if not already\n\n # Copy or alias array to array_internal\n array_internal = _copy_input_if_needed(passed_array, dtype=float, order='C',\n nan_treatment=nan_treatment, mask=mask,\n fill_value=np.nan)\n array_dtype = getattr(passed_array, 'dtype', array_internal.dtype)\n # Copy or alias kernel to kernel_internal\n kernel_internal = _copy_input_if_needed(passed_kernel, dtype=float, order='C',\n nan_treatment=None, mask=None,\n fill_value=fill_value)\n\n # Make sure kernel has all odd axes\n if has_even_axis(kernel_internal):\n raise_even_kernel_exception()\n\n # -----------------------------------------------------------------------\n # From this point onwards refer only to ``array_internal`` and\n # ``kernel_internal``.\n # Assume both are base np.ndarrays and NOT subclasses e.g. NOT\n # ``Kernel`` nor ``np.ma.maskedarray`` classes.\n # -----------------------------------------------------------------------\n\n # Check dimensionality\n if array_internal.ndim == 0:\n raise Exception(\"cannot convolve 0-dimensional arrays\")\n elif array_internal.ndim > 3:\n raise NotImplementedError('convolve only supports 1, 2, and 3-dimensional '\n 'arrays at this time')\n elif array_internal.ndim != kernel_internal.ndim:\n raise Exception('array and kernel have differing number of '\n 'dimensions.')\n\n array_shape = np.array(array_internal.shape)\n kernel_shape = np.array(kernel_internal.shape)\n pad_width = kernel_shape//2\n\n # For boundary=None only the center space is convolved. All array indices within a\n # distance kernel.shape//2 from the edge are completely ignored (zeroed).\n # E.g. (1D list) only the indices len(kernel)//2 : len(array)-len(kernel)//2\n # are convolved. It is therefore not possible to use this method to convolve an\n # array by a kernel that is larger (see note below) than the array - as ALL pixels would be ignored\n # leaving an array of only zeros.\n # Note: For even kernels the correctness condition is array_shape > kernel_shape.\n # For odd kernels it is:\n # array_shape >= kernel_shape OR array_shape > kernel_shape-1 OR array_shape > 2*(kernel_shape//2).\n # Since the latter is equal to the former two for even lengths, the latter condition is complete.\n if boundary is None and not np.all(array_shape > 2*pad_width):\n raise KernelSizeError(\"for boundary=None all kernel axes must be smaller than array's - \"\n \"use boundary in ['fill', 'extend', 'wrap'] instead.\")\n\n # NaN interpolation significantly slows down the C convolution\n # computation. Since nan_treatment = 'interpolate', is the default\n # check whether it is even needed, if not, don't interpolate.\n # NB: np.isnan(array_internal.sum()) is faster than np.isnan(array_internal).any()\n nan_interpolate = (nan_treatment == 'interpolate') and np.isnan(array_internal.sum())\n\n # Check if kernel is normalizable\n if normalize_kernel or nan_interpolate:\n kernel_sum = kernel_internal.sum()\n kernel_sums_to_zero = np.isclose(kernel_sum, 0, atol=normalization_zero_tol)\n\n if kernel_sum < 1. / MAX_NORMALIZATION or kernel_sums_to_zero:\n raise ValueError(\"The kernel can't be normalized, because its sum is \"\n \"close to zero. The sum of the given kernel is < {}\"\n .format(1. / MAX_NORMALIZATION))\n\n # Mark the NaN values so we can replace them later if interpolate_nan is\n # not set\n if preserve_nan or nan_treatment == 'fill':\n initially_nan = np.isnan(array_internal)\n if nan_treatment == 'fill':\n array_internal[initially_nan] = fill_value\n\n # Avoid any memory allocation within the C code. Allocate output array\n # here and pass through instead.\n result = np.zeros(array_internal.shape, dtype=float, order='C')\n\n embed_result_within_padded_region = True\n array_to_convolve = array_internal\n if boundary in ('fill', 'extend', 'wrap'):\n embed_result_within_padded_region = False\n if boundary == 'fill':\n # This method is faster than using numpy.pad(..., mode='constant')\n array_to_convolve = np.full(array_shape + 2*pad_width, fill_value=fill_value, dtype=float, order='C')\n # Use bounds [pad_width[0]:array_shape[0]+pad_width[0]] instead of [pad_width[0]:-pad_width[0]]\n # to account for when the kernel has size of 1 making pad_width = 0.\n if array_internal.ndim == 1:\n array_to_convolve[pad_width[0]:array_shape[0]+pad_width[0]] = array_internal\n elif array_internal.ndim == 2:\n array_to_convolve[pad_width[0]:array_shape[0]+pad_width[0],\n pad_width[1]:array_shape[1]+pad_width[1]] = array_internal\n else:\n array_to_convolve[pad_width[0]:array_shape[0]+pad_width[0],\n pad_width[1]:array_shape[1]+pad_width[1],\n pad_width[2]:array_shape[2]+pad_width[2]] = array_internal\n else:\n np_pad_mode_dict = {'fill': 'constant', 'extend': 'edge', 'wrap': 'wrap'}\n np_pad_mode = np_pad_mode_dict[boundary]\n pad_width = kernel_shape // 2\n\n if array_internal.ndim == 1:\n np_pad_width = (pad_width[0],)\n elif array_internal.ndim == 2:\n np_pad_width = ((pad_width[0],), (pad_width[1],))\n else:\n np_pad_width = ((pad_width[0],), (pad_width[1],), (pad_width[2],))\n\n array_to_convolve = np.pad(array_internal, pad_width=np_pad_width,\n mode=np_pad_mode)\n\n _convolveNd_c(result, array_to_convolve,\n array_to_convolve.ndim,\n np.array(array_to_convolve.shape, dtype=ctypes.c_size_t, order='C'),\n kernel_internal,\n np.array(kernel_shape, dtype=ctypes.c_size_t, order='C'),\n nan_interpolate, embed_result_within_padded_region,\n n_threads)\n\n # So far, normalization has only occured for nan_treatment == 'interpolate'\n # because this had to happen within the C extension so as to ignore\n # any NaNs\n if normalize_kernel:\n if not nan_interpolate:\n result /= kernel_sum\n elif nan_interpolate:\n result *= kernel_sum\n\n if nan_interpolate and not preserve_nan and np.isnan(result.sum()):\n warnings.warn(\"nan_treatment='interpolate', however, NaN values detected \"\n \"post convolution. A contiguous region of NaN values, larger \"\n \"than the kernel size, are present in the input array. \"\n \"Increase the kernel size to avoid this.\")\n\n if preserve_nan:\n result[initially_nan] = np.nan\n\n # Convert result to original data type\n if array_dtype.kind == 'f':\n # Try to preserve the input type if it's a floating point type\n # Avoid making another copy if possible\n try:\n return result.astype(array_dtype, copy=False)\n except TypeError:\n return result.astype(array_dtype)\n else:\n return result\n\n\n\n", "meta": {"hexsha": "ebc0b3e35ef8f9e8df50f96726216baba23206ad", "size": 16747, "ext": "py", "lang": "Python", "max_stars_repo_path": "hexrd/convolution/convolve.py", "max_stars_repo_name": "glemaitre/hexrd", "max_stars_repo_head_hexsha": "b68b1ba72e0f480d29bdaae2adbd6c6e2380cc7c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2020-02-18T12:15:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T17:53:46.000Z", "max_issues_repo_path": "hexrd/convolution/convolve.py", "max_issues_repo_name": "glemaitre/hexrd", "max_issues_repo_head_hexsha": "b68b1ba72e0f480d29bdaae2adbd6c6e2380cc7c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 259, "max_issues_repo_issues_event_min_datetime": "2020-02-02T22:18:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T19:59:58.000Z", "max_forks_repo_path": "hexrd/convolution/convolve.py", "max_forks_repo_name": "glemaitre/hexrd", "max_forks_repo_head_hexsha": "b68b1ba72e0f480d29bdaae2adbd6c6e2380cc7c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-02-18T12:14:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T16:19:11.000Z", "avg_line_length": 48.5420289855, "max_line_length": 113, "alphanum_fraction": 0.6305009853, "include": true, "reason": "import numpy,from numpy,from astropy", "num_tokens": 3712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.25683199138751883, "lm_q1q2_score": 0.13743039501250476}} {"text": "# Copyright 2019 PyFLOSIC developers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nimport time\nimport copy\nimport numpy as np\nfrom ase import neighborlist as NL\nfrom flosic_os import xyz_to_nuclei_fod,ase2pyscf\nfrom ase import io, units, Atoms, Atom\nfrom ase.utils import natural_cutoffs\nfrom pyscf import gto, dft\nfrom flosic_scf import FLOSIC\nfrom ase.constraints import FixAtoms\nimport sys\n\n\n\n# >>> mol = gto.M(atom='H 0 0 0; H 0 0 1.1')\n# >>> grids = dft.gen_grid.Grids(mol)\n# >>> grids.level = 4\n# >>> grids.build()\n\n\n\n# We want to have\n# - a list of all neigbors of each atom\n# - a list of FOD's that correspond to each atom\n# - a list of all neigbors for each FOD'\n\n# - different dft mesh's for each subgroup of a molecule\n\nclass ON(object):\n \"\"\"Provides functionality to implement O(N) scaling FLOSIC\"\"\"\n def __init__(self, mol, fod, grid_level=9):\n super(ON, self).__init__()\n self.mol = mol\n self.nspin = len(fod)\n self._fod = fod # list of positions, Angst\n self.grid_level = grid_level\n self.eps_cutoff = 1.0e-10\n self.is_init = True\n self.add_ghosts = False\n self.nshell = 2\n #print(self.grid_level)\n #sys.exit()\n \n def build(self):\n \"\"\"build the required data structures (e.g. neigbor lists)\"\"\"\n # convert to Bohr as internal unit\n self.onatoms = list()\n for s in range(self.nspin):\n self.onatoms.append(dict())\n \n self.fod = list()\n self.nfod = [0,0]\n for s in range(self.nspin):\n self.fod.append( self._fod[s].copy())\n self.nfod[s] = self._fod[s].shape[0]\n #print np.array_str(self.fod[s],precision=4)\n \n # build atom object (make sure to enter ccors in Angst)\n acoord = self.mol.atom_coords()\n self.atoms = Atoms()\n for na in range(self.mol.natm):\n aa = Atom(symbol=self.mol.atom_symbol(na),\n position=acoord[na]*units.Bohr)\n self.atoms.extend(aa)\n \n cutoffs = natural_cutoffs(self.atoms)\n \n ##print cutoffs\n self.nl = NL.NeighborList(cutoffs,\n self_interaction=False, bothways=True) \n self.nl.update(self.atoms)\n \n ##print self.nl.get_neighbors(1)\n \n # cut out the H atoms from the distances\n #non_H_ids = list()\n #for atmid in range(self.mol.natm):\n # if self.mol.atom_pure_symbol(atmid) == 'H': continue\n # non_H_ids.append(atmid)\n #\n #non_H_pos = np.zeros((len(non_H_ids),3), dtype=np.float64)\n #for atmid,i in zip(non_H_ids,range(len(non_H_ids))):\n # non_H_pos[i,:] = self.atoms.positions[atmid,:]\n \n \n #self.fod_atm = [[[-1,0.0,'C']*4],[[-2,0.0,'C']*4]]\n #print self.fod_atm[0]\n #self.fod[0].shape[0],self.fod[1].shape[0]\n self.fod_atm = list()\n # find out the nearest atom for each FOD and deciced\n # if its a core FOD or not\n for s in range(self.nspin):\n lfod_atm = list()\n for i in range(self.fod[s].shape[0]):\n fpos = self.fod[s][i]\n # distance to atoms\n dists = np.linalg.norm(fpos - self.atoms.positions,\n axis=1)\n # do not use H-Atoms as nearest atoms\n ite = 0\n nearest_atom = np.argsort(dists)[ite]\n while self.mol.atom_pure_symbol(nearest_atom) == 'H':\n ite += 1\n nearest_atom = np.argsort(dists)[ite]\n \n \n #print self.fod_atm\n #print self.fod_atm[s]\n #self.fod_atm[s][i][0] = nearest_atom\n #self.fod_atm[s][i][1] = dists[nearest_atom]\n #print dists[nearest_atom]\n fodtype = 'V'\n if dists[nearest_atom] < 0.175:\n fodtype = 'C'\n if dists[nearest_atom] < 1.0e-4:\n fodtype = 'C1s'\n #self.fod_atm[s][i][2] = fodtype\n #print fodtype\n #sys.exit()\n lfod_atm.append(\n (nearest_atom,dists[nearest_atom],fodtype))\n self.fod_atm.append(lfod_atm)\n #print len(self.fod_atm)\n \n # make a list of all fods that correspond to a specific atom\n self.atm_fod = list()\n for na in range(self.mol.natm):\n lfodlist = [[],[]]\n for s in range(self.nspin):\n for i in range(self.nfod[s]):\n if self.fod_atm[s][i][0] == na:\n #print \"fod\", i, \"belongs to atom\", na\n lfodlist[s].append(i)\n self.atm_fod.append(lfodlist)\n #print self.atm_fod\n \n # prepare the ao slices\n self.fod_ao_slc = list()\n for s in range(self.nspin):\n lfod_slc = list()\n for i in range(self.nfod[s]):\n slc = self.get_nbas_slices(s,i)\n lfod_slc.append(slc)\n self.fod_ao_slc.append(lfod_slc)\n #print len(self.fod_ao_slc[0]), len(self.fod_ao_slc)\n \n # prepare the ongrids\n print(\"Generating O(N) meshes: nshell={}, grid level={}\"\\\n .format(self.nshell, self.grid_level))\n self.fod_onmsh = list()\n self.fod_onmol = list()\n for s in range(self.nspin):\n lfod_onmsh = list()\n lfod_onmol = list()\n for i in range(self.nfod[s]):\n omol, ogrid = self.get_grid(s,i,lfod_onmsh)\n lfod_onmsh.append(ogrid)\n lfod_onmol.append(omol)\n self.fod_onmsh.append(lfod_onmsh)\n self.fod_onmol.append(lfod_onmol)\n \n print(\"Generating O(N) FOD lists ...\")\n #print self.fod_onmsh \n #print self.onatoms\n #sys.exit()\n \n # prepare a list that contains all fods that\n # correspond to a given fod\n self.fod_fod = [[],[]]\n for s in range(self.nspin):\n for i in range(self.nfod[s]):\n # get the atom numbers that corresponds to the fod\n #print self.fod_atm[s][i]\n #print self.atm_fod[s][i]\n atids = self.onatoms[s][i]\n lfod_fod = list()\n for atid in atids:\n # now find out which of all the other fods\n # correspond to these atoms\n for j in range(self.nfod[s]):\n if i == j: continue\n atnr = self.fod_atm[s][j][0]\n if atnr in atids:\n lfod_fod.append(j)\n # remove duplicates\n lfod_fod = list(set(lfod_fod))\n #print(lfod_fod)\n #print i, len(lfod_fod)\n self.fod_fod[s].append(lfod_fod)\n #print self.fod_fod[0]\n #print self.fod_fod[1]\n #sys.exit()\n \n # finally, build a fod-grp list\n # this list orders all fod that have the same mesh\n self.fodlist2group()\n \n \n def update(self,s,fpos):\n '''update the class according to the given (new) fod positions [in Angst.]'''\n pass\n \n \n def fodlist2group(self):\n \"\"\"docstring for fodlist2group\"\"\"\n print('generate fodgroup list')\n # pre-generate the data structure\n self.fodgrps = list()\n for s in range(self.nspin):\n self.fodgrps.append(list())\n \n #print(self.fodgrps)\n #print(len(self.fodgrps))\n \n #for j in range(self.nfod[0]):\n # print(self.onatoms[0][j])\n #sys.exit()\n \n # self.onatoms hält zu jedem fod id die entsprechenden\n # atome, die das mesh definieren\n for s in range(self.nspin):\n ttable = [False for i in range(self.nfod[s])]\n #print(ttable)\n grpcnt = 0\n for j in range(self.nfod[s]):\n if ttable[j]: continue\n self.fodgrps[s].append([j])\n jonatoms = self.onatoms[s][j]\n jonatoms.sort()\n for jj in range(j+1,self.nfod[s]):\n if ttable[jj]: continue\n cpmonatoms = self.onatoms[s][jj]\n cpmonatoms.sort()\n if jonatoms == cpmonatoms:\n #print('fod {} and {} have same onatoms {}'.format(j, jj, jonatoms))\n self.fodgrps[s][grpcnt].append(jj)\n ttable[jj] = True\n grpcnt += 1\n #print(self.fodgrps[s])\n #sys.exit()\n return\n \n def get_grid(self,s,fodid,lmsh,level=None,verbose=False):\n \"\"\"Generate a grid object that corresponds to the\n O(N) structure for the given FOD\n \"\"\"\n print(' -> building Vxc-Grid for FOD {} ...'.format(fodid), flush=True)\n #mol.atom_pure_symbol\n if level == None:\n level = self.grid_level\n onatoms = self.onatoms[s][fodid]\n #print(onatoms)\n \n #print('onatoms:', onatoms)\n #sys.exit()\n fodtype = self.fod_atm[s][fodid][2]\n ongrid = None\n \n # check if we already have meshes available\n # with the same onatoms\n #self.mf.on.fod_onmsh[self.s][fgrp[0]]\n onatoms = list(sorted(onatoms))\n pmshid = -1\n for j in range(fodid):\n #qq = list(sorted(self.onatoms[s][j]))\n #print(j, onatoms, qq)\n #print(lmsh)\n #self.fod_onmsh\n #print(onatoms)\n #print(self.onatoms[s][j].sort())\n if onatoms == list(sorted(self.onatoms[s][j])):\n ## we already have a mesh generated\n ongrid = lmsh[j]\n pmshid = j\n #sys.exit()\n # build string to generate Mole object\n mstr = ''\n for na in onatoms:\n sym = self.mol.atom_pure_symbol(na)\n pos = self.atoms.positions[na]\n #print sym, pos\n mstr += \"{0} {1:0.12f} {2:0.12f} {3:0.12f};\".format(\n sym,pos[0],pos[1],pos[2])\n \n # add ghost atom for valence descriptors\n if (fodtype == 'V') and (self.add_ghosts):\n sym = 'ghost:H'\n pos = self.fod[s][fodid]\n #print sym, pos\n mstr += \"{0} {1:0.12f} {2:0.12f} {3:0.12f};\".format(\n sym,pos[0],pos[1],pos[2])\n \n print(' type {}, na {}: atoms in msh {}'.format(fodtype, self.fod_atm[s][fodid][0], onatoms))\n \n \n # build a Mole object from subsystem\n #isinstance(o, str):\n #if type(self.mol.basis) == dict:\n # b = self.mol.basis\n # b['ghost'] = gto.basis.load('sto3g', 'H')\n #else:\n # b = {'default':self.mol.basis, 'ghost': gto.basis.load('sto3g', 'H')}\n \n b = self.mol.basis\n \n #print(mstr)\n #print(\"{0} {1}\".format(fodid,b))\n \n #sys.exit()\n \n try:\n onmol = gto.M(atom=mstr,basis=b)\n except RuntimeError:\n onmol = gto.M(atom=mstr, basis=b, spin=1)\n onmol.verbose=0\n onmol.max_memory=1000\n #print(onmol.atom)\n # build the meshes\n if ongrid is None:\n _mdft = dft.UKS(onmol)\n _mdft.max_cycle = 0\n _mdft.grids.level = level\n _mdft.kernel()\n ongrid = copy.copy(_mdft.grids)\n else:\n print(' (mesh was already generated for fod {})'.format(pmshid))\n #ongrid = dft.gen_grid.Grids(onmol)\n #ongrid.prune = dft.gen_grid.nwchem_prune\n #ongrid.level = level\n #ongrid.build()\n \n \n \n #print(level)\n #print(ongrid.coords.shape)\n #print onmol\n #sys.exit()\n \n return (onmol,ongrid)\n \n \n # now we want to find out the basis functions that are \n # really needed for each FO\n # - we check the nearest atom\n # - we find the neigbors to that atom\n # - we find the nbas indices for those atoms (start, stop)\n # and store them in a list\n def get_nbas_slices(self,s,fodid,verbose=False):\n \"\"\"docstring for get_nbas_slices\"\"\"\n slices = list()\n near_atm = self.fod_atm[s][fodid]\n onatoms = [near_atm[0]]\n if (near_atm[2] == 'C') or (near_atm[2] == 'C1s'):\n if self.nshell == 2:\n nei_atm = self.get_neighbors(near_atm[0], nshell=1)\n for na in nei_atm:\n onatoms.append(na)\n\n if near_atm[2] == 'V':\n nei_atm = self.get_neighbors(near_atm[0], nshell=self.nshell)\n for na in nei_atm:\n onatoms.append(na)\n \n # remove duplicates\n onatoms = list(set(onatoms))\n \n if self.nshell == -1:\n onatoms = list(range(self.mol.natm))\n \n # update class onatoms dict\n self.onatoms[s][fodid] = onatoms\n \n all_slices=self.mol.aoslice_by_atom()\n #print all_slices\n onnbas = 0\n for na in onatoms:\n lslice=(all_slices[na,2],all_slices[na,3])\n slices.append(lslice)\n onnbas += lslice[1]-lslice[0]\n \n # print all_slices[-1][-1]\n pc = 100.0 - onnbas / (all_slices[-1,-1] / 100.0)\n \n if verbose:\n print(\"Sparsity: {0} / {1} ({2:0.2f} %)\"\n .format(onnbas,all_slices[-1,-1], pc))\n \n return slices\n \n #sys.exit()\n \n def get_on_dm(self,s,fodid,dm,flo=None):\n \"\"\"Mask out all basis functions that are not required\n return FLO's and dm were unused ebtries are set to zero\n \n if condense is set to True, return dm and FLO's with only\n the size needed for the O(N) method (e.g. reduced)\n \n \"\"\"\n if dm.shape[-1] != self.mol.aoslice_by_atom()[-1,-1]:\n print(\"DM has wrong shape\")\n print(self.mol.aoslice_by_atom()[-1,-1])\n sys.exit()\n \n # find out which indices in the density matrix\n # belong to a given fod\n slcs = self.fod_ao_slc[s][fodid]\n slc = list()\n for sl in slcs:\n slc += list(range(sl[0],sl[1]))\n \n dmout = dm.copy()\n #floout = flo.copy()\n \n # zero out the dm\n for i in range(dm.shape[-1]):\n if i in slc: continue\n for j in range(dm.shape[-1]):\n if j in slc: continue\n #print \"set dm zero\", i, j\n dmout[i,j] = 0.0\n \n nchk = np.sum(dmout)\n if np.isnan(nchk):\n print('Got it')\n sys.exit()\n\n return dmout\n \n def get_neighbors(self, atmid, nshell=1):\n \"\"\"\n Return the indices of the neighbor atoms to a given atom id.\n \n Args:\n atmid : int\n id of the atom for which the neigbors shall be returned\n \n Kwargs:\n nshell : int\n number of shells around the given atom that should be \n considered as neigbors\n 1 -> means include only 'nearest neigbors'\n 2 -> include nearest and next-nearest neigbors\n 3 -> (and larger not yet implemented!)\n \n Returns:\n List of integers which are the indices of the neigbor atoms\n to atmid.\n \"\"\"\n #if (nshell < 1) or (nshell > 2):\n # raise ValueError(\"nshell must be 1 or 2\")\n if nshell == -1:\n ret = list(range(self.mol.natm))\n return ret\n \n if nshell == 1:\n ret = list(self.nl.get_neighbors(atmid)[0])\n else:\n base = list(self.nl.get_neighbors(atmid)[0])\n nn = []\n for aid in base:\n nn += list(self.nl.get_neighbors(aid)[0])\n base.extend(nn)\n \n # remove duplicates\n ret = list(dict.fromkeys(base))\n \n return ret\n \n def print_stats(self):\n '''Print out statistics'''\n print(' --- O(N) stats ---')\n print('{:>4} {:>4} : {:>7} {:>7} {:>12}'.format('spin','nfod', 'nmsh', 'nbas', 'onatoms'))\n _nmshs = 0\n _nbas = 0\n for s in range(self.nspin):\n for j in range(self.nfod[s]):\n onmsh = self.fod_onmsh[s][j]\n nonmsh = onmsh.coords.shape[0]\n onat = self.onatoms[s][j]\n nbas = self.fod_onmol[s][j].aoslice_by_atom()[-1,-1]\n _nbas += nbas\n _nmshs += nonmsh\n print('{:4d} {:4d} : {:7d} {:7d} {}'.format(s,j,nonmsh,nbas, onat))\n print(' ----------------')\n _nbas = float(_nbas)/(np.sum(self.nfod))\n _tnbas = self.mol.aoslice_by_atom()[-1,-1]\n _nmshs = float(_nmshs)/(np.sum(self.nfod))\n #print(_tnbas)\n print('vsic parameters\\n')\n print('nmsh: avg {:7d}'.format(int(_nmshs)))\n print('nbas: avg {:7d}'.format(int(_nbas)))\n print('spar: {:11.1f} %'.format(100.0 - _nbas/(_tnbas*0.01)))\n print('')\n print('Number of fod-groups with identical mesh: {}'.format(len(self.fodgrps[0])))\n print(' ----------------')\n\ndef C1s_FixPos(on, s):\n '''Returns an ASE constraint that fixes the 1s core descriptor positions\n \n Args:\n on : ON object\n the object that corresponds to the mol/fod structure\n \n s : spin index\n \n Returns:\n ase.constraint object if there are C1s to fix, None otherwise\n '''\n c1sidx = list()\n mol = on.mol\n for fodid in range(on.nfod[s]):\n _na = mol.atom_pure_symbol(on.fod_atm[s][fodid][0])\n _ft = on.fod_atm[s][fodid][2]\n if (_ft == 'C1s'):\n c1sidx.append(fodid)\n \n c1score = None\n if len(c1sidx) > 0:\n c1score = FixAtoms(indices=c1sidx)\n \n return c1score\n\n\nif __name__ == '__main__':\n CH3SH = '''\n C -0.04795000 +1.14952000 +0.00000000\n S -0.04795000 -0.66486000 +0.00000000\n H +1.28308000 -0.82325000 +0.00000000\n H -1.09260000 +1.46143000 +0.00000000\n H +0.43225000 +1.55121000 +0.89226000\n H +0.43225000 +1.55121000 -0.89226000\n '''\n # this are the spin-up descriptors\n fod1 = Atoms([\n Atom('X', (-0.04795000, -0.66486000, +0.00000000)),\n Atom('X', (-0.04795000, +1.14952000, +0.00000000)),\n Atom('X', (-1.01954312, +1.27662578, +0.00065565)),\n Atom('X', (+1.01316012, -0.72796570, -0.00302478)),\n Atom('X', (+0.41874165, +1.34380502, +0.80870475)),\n Atom('X', (+0.42024357, +1.34411742, -0.81146545)),\n Atom('X', (-0.46764078, -0.98842277, -0.72314717)),\n Atom('X', (-0.46848962, -0.97040067, +0.72108036)),\n Atom('X', (+0.01320210, +0.30892333, +0.00444147)),\n Atom('X', (-0.28022018, -0.62888360, -0.03731204)),\n Atom('X', (+0.05389371, -0.57381853, +0.19630494)),\n Atom('X', (+0.09262866, -0.55485889, -0.15751914)),\n Atom('X', (-0.05807583, -0.90413106, -0.00104673))])\n \n # this are the spin-down descriptors\n fod2 = Atoms([\n Atom('He',( -0.04795000, -0.66486000, +0.0000000)),\n Atom('He',( -0.04795000, +1.14952000, +0.0000000)),\n Atom('He',( +1.12523084, -0.68699049, +0.0301970)),\n Atom('He',( +0.40996981, +1.33508869, +0.8089839)),\n Atom('He',( +0.40987059, +1.34148952, -0.8106910)),\n Atom('He',( -0.49563876, -0.99517303, +0.6829207)),\n Atom('He',( -0.49640020, -0.89986161, -0.6743094)),\n Atom('He',( +0.00073876, +0.28757089, -0.0298617)),\n Atom('He',( -1.03186573, +1.29783767, -0.0035536)),\n Atom('He',( +0.04235081, -0.54885843, +0.1924678)),\n Atom('He',( +0.07365725, -0.59150454, -0.1951675)),\n Atom('He',( -0.28422422, -0.61466396, -0.0087913)),\n Atom('He',( -0.02352948, -1.0425011 ,+0.01253239))])\n \n \n b = 'ccpvdz'\n spin = 0\n charge = 0\n \n mol = gto.M(atom=CH3SH, \n basis=b,\n spin=spin,\n charge=charge)\n\n grid_level = 7\n mol.verbose = 4\n mol.max_memory = 2000\n mol.build()\n xc = 'LDA,PW'\n \n \n # quick dft calculation\n mdft = dft.UKS(mol)\n mdft.xc = xc\n mdft.kernel()\n \n # build O(N) stuff\n myon = ON(mol,[fod1.positions,fod2.positions], grid_level=grid_level)\n myon.nshell = 2\n myon.build()\n \n # enable ONMSH\n m = FLOSIC(mol,xc=xc,fod1=fod1,fod2=fod2,grid_level=grid_level, init_dm=mdft.make_rdm1())\n m.max_cycle = 40\n m.set_on(myon)\n m.conv_tol = 1e-5\n \n m.preopt = False\n m.preopt_start_cycle=0\n m.preopt_fix1s = True\n m.preopt_fmin = 0.005\n \n m.kernel()\n \n print(m.fod_gradients())\n print(m.get_fforces())\n \n", "meta": {"hexsha": "4a32f86595d2992ec1176c0c0e97f72b66ba4879", "size": 21486, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/onstuff.py", "max_stars_repo_name": "pyflosic/pyflosic", "max_stars_repo_head_hexsha": "4245fe89ecc06868efe60c52391d2592ce49c473", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2019-05-24T11:29:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T09:41:20.000Z", "max_issues_repo_path": "src/onstuff.py", "max_issues_repo_name": "pyflosic/pyflosic", "max_issues_repo_head_hexsha": "4245fe89ecc06868efe60c52391d2592ce49c473", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-01T09:45:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-10T12:05:19.000Z", "max_forks_repo_path": "src/onstuff.py", "max_forks_repo_name": "pyflosic/pyflosic", "max_forks_repo_head_hexsha": "4245fe89ecc06868efe60c52391d2592ce49c473", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-03-01T21:02:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-03T13:19:06.000Z", "avg_line_length": 34.4879614767, "max_line_length": 106, "alphanum_fraction": 0.5178721028, "include": true, "reason": "import numpy", "num_tokens": 6147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.23934933647101647, "lm_q1q2_score": 0.13730954617150762}} {"text": "#! /usr/bin/env python\n\n\"\"\"\nModule with ADI algorithm (median psf subtraction).\nCarlos A. Gomez / ULg\n\"\"\"\n\nfrom __future__ import division \n\n__author__ = 'C. Gomez @ ULg'\n__all__ = ['adi']\n\nimport numpy as np\nfrom ..conf import time_ini, timing\nfrom ..var import get_annulus, mask_circle\nfrom ..preproc import cube_derotate, cube_collapse, check_PA_vector\nfrom ..pca.pca_local import define_annuli\n\n\ndef adi(cube, angle_list, fwhm=4, radius_int=0, asize=2, delta_rot=1, \n mode='fullfr', nframes=4, collapse='median', full_output=False, \n verbose=True):\n \"\"\" Algorithm based on Marois et al. 2006 on Angular Differential Imaging. \n First the median frame is subtracted, then the median of the four closest \n frames taking into account the pa_threshold (field rotation).\n \n Parameters\n ----------\n cube : array_like, 3d\n Input cube.\n angle_list : array_like, 1d\n Corresponding parallactic angle for each frame.\n fwhm : float\n Known size of the FHWM in pixels to be used. Default is 4.\n radius_int : int, optional\n The radius of the innermost annulus. By default is 0, if >0 then the \n central circular area is discarded.\n asize : int, optional\n The size of the annuli, in FWHM. Default is 2.\n delta_rot : int, optional\n Factor for increasing the parallactic angle threshold, expressed in FWHM.\n Default is 1 (excludes 1 FHWM on each side of the considered frame).\n mode : {\"fullfr\",\"annular\"}, str optional\n In \"simple\" mode only the median frame is subtracted, in \"annular\" mode\n also the 4 closest frames given a PA threshold (annulus-wise) are \n subtracted.\n nframes : even int optional\n Number of frames to be used for building the optimized reference PSF \n when working in annular mode. \n collapse : {'median', 'mean', 'sum', 'trimmean'}, str optional\n Sets the way of collapsing the frames for producing a final image.\n full_output: boolean, optional\n Whether to return the final median combined image only or with other \n intermediate arrays. \n verbose : {True, False}, bool optional\n If True prints to stdout intermediate info.\n \n Returns\n -------\n frame : array_like, 2d\n Median combination of the de-rotated cube.\n If full_output is True: \n cube_out : array_like, 3d\n The cube of residuals.\n cube_der : array_like, 3d\n The derotated cube of residuals.\n \n \"\"\"\n def find_indices(angle_list, frame, thr, nframes): \n \"\"\" Returns the indices to be left in frames library for optimized ADI.\n To find a more pythonic way to do this!\n \"\"\"\n n = angle_list.shape[0]\n index_prev = 0 \n index_foll = frame \n for i in range(0, frame):\n if np.abs(angle_list[frame]-angle_list[i]) < thr:\n index_prev = i\n break\n else:\n index_prev += 1\n for k in range(frame, n):\n if np.abs(angle_list[k]-angle_list[frame]) > thr:\n index_foll = k\n break\n else:\n index_foll += 1\n\n window = int(nframes/2)\n ind1 = index_prev-window\n ind1 = max(ind1, 0)\n ind2 = index_prev\n ind3 = index_foll\n ind4 = index_foll+window\n ind4 = min(ind4, n)\n indices = np.array(range(ind1,ind2)+range(ind3,ind4))\n #print ind1, ind2, ind3, ind4, indices\n return indices\n \n #***************************************************************************\n array = cube\n \n if not array.ndim == 3:\n raise TypeError('Input array is not a cube or 3d array.')\n if not array.shape[0] == angle_list.shape[0]:\n raise TypeError('Input vector or parallactic angles has wrong length.')\n if not nframes%2==0:\n raise TypeError('nframes argument must be even value.')\n \n n, y, _ = array.shape\n \n if verbose: start_time = time_ini()\n \n angle_list = check_PA_vector(angle_list)\n \n #***************************************************************************\n # The median frame (basic psf reference) is first subtracted from each frame.\n #*************************************************************************** \n ref_psf = np.median(array, axis=0)\n array = array - ref_psf\n \n if mode=='fullfr':\n if radius_int>0:\n cube_out = mask_circle(array, radius_int)\n else:\n cube_out = array\n if verbose: print 'Median psf reference subtracted'\n \n elif mode=='annular': \n annulus_width = int(asize * fwhm) # equal size for all annuli\n n_annuli = int(np.floor((y/2-radius_int)/annulus_width)) \n if verbose: print 'N annuli =', n_annuli, ', FWHM =', fwhm, '\\n'\n #***********************************************************************\n # The annuli are built, and the corresponding PA thresholds for frame \n # rejection are calculated. The PA rejection is calculated at center of \n # the annulus.\n #***********************************************************************\n cube_out = np.zeros_like(array) \n for ann in range(n_annuli):\n pa_threshold,inner_radius,_= define_annuli(angle_list, ann, n_annuli, \n fwhm, radius_int, \n annulus_width, delta_rot,\n verbose) \n \n indices = get_annulus(array[0], inner_radius, annulus_width, \n output_indices=True)\n yy = indices[0]\n xx = indices[1]\n \n matrix = array[:, yy, xx] # shape [nframes x npx_annulus]\n \n #*******************************************************************\n # A second optimized psf reference is subtracted from each frame. \n # For each frame we find *nframes*, depending on the PA threshold, \n # to construct this optimized psf reference.\n #*******************************************************************\n for frame in range(n):\n if pa_threshold != 0:\n indices_left = find_indices(angle_list, frame, pa_threshold, \n nframes)\n matrix_disc = matrix[indices_left]\n else:\n matrix_disc = matrix\n \n ref_psf_opt = np.median(matrix_disc, axis=0)\n curr_frame = matrix[frame]\n subtracted = curr_frame - ref_psf_opt\n cube_out[frame][yy, xx] = subtracted\n if verbose: print 'Optimized median psf reference subtracted'\n \n else:\n raise RuntimeError('Mode not recognized')\n \n cube_der = cube_derotate(cube_out, angle_list)\n frame = cube_collapse(cube_der, mode=collapse)\n if verbose:\n print 'Done derotating and combining'\n timing(start_time)\n if full_output:\n return cube_out, cube_der, frame \n else:\n return frame \n\n", "meta": {"hexsha": "7baa63a7792b66e1ec315b76eb8fc4c64a77017c", "size": 7295, "ext": "py", "lang": "Python", "max_stars_repo_path": "vip/madi/adi_source.py", "max_stars_repo_name": "VChristiaens/VIP2.7", "max_stars_repo_head_hexsha": "92ce75f1004b4dd1480c3688124225ce8a98aca2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vip/madi/adi_source.py", "max_issues_repo_name": "VChristiaens/VIP2.7", "max_issues_repo_head_hexsha": "92ce75f1004b4dd1480c3688124225ce8a98aca2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vip/madi/adi_source.py", "max_forks_repo_name": "VChristiaens/VIP2.7", "max_forks_repo_head_hexsha": "92ce75f1004b4dd1480c3688124225ce8a98aca2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6467391304, "max_line_length": 96, "alphanum_fraction": 0.5394105552, "include": true, "reason": "import numpy", "num_tokens": 1600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.2658804847339313, "lm_q1q2_score": 0.13709327313090416}} {"text": "\"\"\" Main implementation of parcel model.\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nfrom builtins import zip\nfrom builtins import range\nfrom builtins import object\n\nimport os\n\nfrom scipy.optimize import bisect\n\n# Parcel model imports\nfrom . import constants as c\nfrom . import output\nfrom . aerosol import AerosolSpecies\n# from . integrator import Integrator\nfrom . thermo import *\n\n__all__ = ['ParcelModel', ]\n\n\nclass ParcelModelError(Exception):\n \"\"\" Custom exception to throw during parcel model execution.\n \"\"\"\n def __init__(self, error_str):\n self.error_str = error_str\n\n def __str__(self):\n return repr(self.error_str)\n\n\nclass ParcelModel(object):\n \"\"\" Wrapper class for instantiating and running the parcel model.\n\n The parcel model has been implemented in an object-oriented format to facilitate\n easy extensibility to different aerosol and meteorological conditions. A\n typical use case would involve specifying the initial conditions such as:\n\n >>> import pyrcel as pm\n >>> P0 = 80000.\n >>> T0 = 283.15\n >>> S0 = 0.0\n >>> V = 1.0\n >>> aerosol1 = pm.AerosolSpecies('sulfate',\n ... Lognorm(mu=0.025, sigma=1.3, N=2000.),\n ... bins=200, kappa=0.54)\n >>> initial_aerosols = [aerosol1, ]\n >>> z_top = 50.\n >>> dt = 0.01\n\n which initializes the model with typical conditions at the top of the boundary\n layer (800 hPa, 283.15 K, 100% Relative Humidity, 1 m/s updraft), and a simple\n sulfate aerosol distribution which will be discretized into 200 size bins to\n track. Furthermore the model was specified to simulate the updraft for 50\n meters (`z_top`) and use a time-discretization of 0.01 seconds. This\n timestep is used in the model output -- the actual ODE solver will generally\n calculate the trace of the model at many more times.\n\n Running the model and saving the output can be accomplished by invoking::\n\n >>> model = pm.ParcelModel(initial_aerosols, V, T0, S0, P0)\n >>> par_out, aer_out = pm.run(z_top, dt)\n\n This will yield `par_out`, a :class:`pandas.DataFrame` containing the meteorological\n conditions in the parcel, and `aerosols`, a dictionary of :class:`DataFrame` objects\n for each species in `initial_aerosols` with the appropriately tracked size\n bins and their evolution over time.\n\n Attributes\n ----------\n V, T0, S0, P0, aerosols : floats\n Initial parcel settings (see **Parameters**).\n _r0s : array_like of floats\n Initial equilibrium droplet sizes.\n _r_drys : array_like of floats\n Dry radii of aerosol population.\n _kappas : array_like of floats\n Hygroscopicity of each aerosol size.\n _Nis : array_like of floats\n Number concentration of each aerosol size.\n _nr : int\n Number of aerosol sizes tracked in model.\n _model_set : boolean\n Flag indicating whether or not at any given time the model\n initialization/equilibration routine has been run with the current\n model settings.\n _y0 : array_like\n Initial state vector.\n\n Methods\n -------\n run(t_end, dt, max_steps=1000, solver=\"odeint\", output_fmt=\"dataframes\",\\\n terminate=False, solver_args={})\n Execute model simulation.\n set_initial_conditions(V=None, T0=None, S0=None, P0=None, aerosols=None)\n Re-initialize a model simulation in order to run it.\n\n See Also\n --------\n _setup_run : companion routine which computes equilibrium droplet sizes\n and sets the model's state vectors.\n\n \"\"\"\n\n def __init__(self, aerosols, V, T0, S0, P0, console=False, accom=c.ac,\n truncate_aerosols=False):\n \"\"\" Initialize the parcel model.\n\n Parameters\n ----------\n aerosols : array_like sequence of :class:`AerosolSpecies`\n The aerosols contained in the parcel.\n V, T0, S0, P0 : floats\n The updraft speed and initial temperature (K), pressure (Pa),\n supersaturation (percent, with 0.0 = 100% RH).\n console : boolean, optional\n Enable some basic debugging output to print to the terminal.\n accom : float, optional (default=:const:`constants.ac`)\n Condensation coefficient\n truncate_aerosols : boolean, optional (default=**False**)\n Eliminate extremely small aerosol which will cause numerical problems\n\n \"\"\"\n self._model_set = False\n self.console = console\n self.trunc = truncate_aerosols\n\n self.V = V\n self.T0 = T0\n self.S0 = S0\n self.P0 = P0\n if self.trunc:\n self.aerosols = self._replace_aerosol(aerosols)\n else:\n self.aerosols = aerosols\n self.accom = accom\n\n # To be set by call to \"self._setup_run()\"\n self._r0s = None\n self._r_drys = None\n self._kappas = None\n self._Nis = None\n self._nr = None\n\n self._setup_run()\n\n def set_initial_conditions(self, V=None, T0=None, S0=None, P0=None, aerosols=None):\n \"\"\" Set the initial conditions and parameters for a new parcel\n model run without having to create a new :class:`ParcelModel` instance.\n\n Based on the aerosol population which has been stored in the model, this\n method will finish initializing the model. This has three major parts:\n\n 1. concatenate the aerosol population information (their dry radii,\n hygroscopicities, etc) into single arrays which can be placed into the\n state vector for forward integration.\n 2. Given the initial ambient water vapor concentration (computed from the\n temperature, pressure, and supersaturation), determine how much water\n must already be coated on the aerosol particles in order for their\n size to be in equilibrium.\n 3. Set-up the state vector with these initial conditions.\n\n Once the state vector has been set up, the setup routine will record\n attributes in the parent instance of the :class:`ParcelModel`.\n\n Parameters\n ----------\n V, T0, S0, P0 : floats\n The updraft speed and initial temperature (K), pressure (Pa),\n supersaturation (percent, with 0.0 = 100% RH).\n aerosols : array_like sequence of :class:`AerosolSpecies`\n The aerosols contained in the parcel.\n\n Raises\n ------\n ParcelModelError\n If an equilibrium droplet size distribution could not be calculated.\n\n Notes\n -----\n The actual setup occurs in the private method `_setup_run()`; this\n method is simply an interface that can be used to modify an existing\n :class:`ParcelModel`.\n\n \"\"\"\n\n if V:\n self.V = V\n if T0:\n self.T0 = T0\n if P0:\n self.P0 = P0\n if S0:\n self.S0 = S0\n if aerosols:\n if self.trunc:\n self.aerosols = self._replace_aerosol(aerosols)\n else:\n self.aerosols = aerosols\n\n if T0 or P0 or S0 or aerosols:\n self._setup_run()\n\n def _replace_aerosol(self, aerosols, smallest_rdry=1e-10):\n \"\"\" Truncates the bins with the smallest particles so that none\n have a dry radius of less than 0.1 nm.\n\n Parameters\n ----------\n aerosols : array_like sequence of :class:`AerosolSpecies`\n The aerosols contained in the parcel.\n smallest_rdry: float\n Smallest allowable dry radius bin.\n\n Returns\n -------\n fixed_aerosols : array_like sequence of :class:`AerosolSpecies`\n The modified sequence of aerosols.\n\n \"\"\"\n fixed_aerosols = []\n\n for aer in aerosols:\n N_old = np.sum(aer.Nis)\n bin_count = np.count_nonzero(aer.r_drys[aer.r_drys < smallest_rdry])\n if bin_count > 0:\n aer_new = AerosolSpecies(aer.species,\n aer.distribution,\n kappa=aer.kappa,\n bins=aer.bins,\n r_min=smallest_rdry*1e6)\n N_new = np.sum(aer_new.Nis)\n if self.console:\n print(\"%s: Removed %03d bins, N change: %5.1f -> %5.1f (%2.1f%%)\" %\n (aer.species, bin_count, N_old, N_new, (N_new-N_old)/N_new))\n fixed_aerosols.append(aer_new)\n else:\n fixed_aerosols.append(aer)\n\n return fixed_aerosols\n\n def _setup_run(self):\n \"\"\" Perform equilibration and initialization calculations for the\n parcel model simulation.\n\n .. note:: See `set_initial_conditions` for full details.\n\n \"\"\"\n T0, S0, P0 = self.T0, self.S0, self.P0\n z0 = 0.0\n out = dict()\n\n if self.console:\n print(\"Setting up parcel model initial conditions...\")\n\n # 1) Setup aerosols\n # a) grab all the initial aerosol size/concentrations\n species = []\n r_drys, Nis, kappas = [], [], []\n for aerosol in self.aerosols:\n r_drys.extend(aerosol.r_drys)\n kappas.extend([aerosol.kappa]*aerosol.nr)\n Nis.extend(aerosol.Nis)\n species.extend([aerosol.species]*aerosol.nr)\n\n r_drys = np.array(r_drys)\n kappas = np.array(kappas)\n Nis = np.array(Nis)\n\n out['r_drys'] = r_drys\n out['kappas'] = kappas\n out['Nis'] = Nis\n\n if self.console:\n # TODO: Fix print table formatting\n print(\"AEROSOL DISTRIBUTION\")\n print(\"%8s %6s\" % (\"r\", \"N\"))\n for sp, r, N in zip(species, r_drys, Nis):\n print(\"%10s %2.2e %4.1f\" % (sp, r, N))\n print(\"\\n\"+\"-\"*44)\n\n # 2) Setup parcel initial conditions\n # a) water vapor\n # RH * (Rd/Rv = epsilon) * ( es / P - es )\n wv0 = (S0 + 1.)*(c.epsilon*es(T0-273.15)/(P0-es(T0-273.15))) # Water Vapor mixing ratio, kg/kg\n\n # b) find equilibrium wet particle radius\n # wrapper function for quickly computing deviation from chosen\n # equilibrium supersaturation given current size and dry size\n f = lambda r, r_dry, kappa: Seq(r, r_dry, T0, kappa) - S0\n # Compute the equilibrium wet particle radii\n r0s = []\n # r_b, _ = kohler_crit(T0, r_drys[-1], kappas[-1])\n # for r_dry , kappa in zip(r_drys, kappas)[::-1]:\n for r_dry, kappa in zip(reversed(r_drys), reversed(kappas)):\n # Locate the critical value (f(r_crit) > 0), and use bisection from it and\n # r_dry (f(r_dry) < 0) to find equilibrium wet particle radius for a given S0\n r_b, _ = kohler_crit(T0, r_dry, kappa)\n r_a = r_dry\n\n r0 = bisect(f, r_a, r_b, args=(r_dry, kappa), xtol=1e-30, maxiter=500)\n r0s.append(r0)\n\n r0s = np.array(r0s[::-1])\n\n # Console logging output, if requested, of the equilibrium calcuations. Useful for\n # checking if the computations worked\n raised = False\n for (r, r_dry, sp, kappa) in zip(r0s, r_drys, species, kappas):\n ss = Seq(r, r_dry, T0, kappa)\n # rc, _ = kohler_crit(T0, r_dry, kappa)\n if r < 0:\n if self.console:\n print(\"Found bad r\", r, r_dry, sp)\n raised = True\n if np.abs(ss-S0) > 1e-4:\n if self.console:\n print(\"Found S discrepancy\", ss, S0, r_dry)\n raised = True\n if raised:\n raise ParcelModelError(\"Couldn't calculate initial aerosol population wet sizes.\")\n out['r0s'] = r0s\n\n # c) compute equilibrium droplet water content\n water_vol = lambda r0, r_dry, Ni: (4.*np.pi/3.)*rho_w*Ni*(r0**3 - r_dry**3)\n wc0 = np.sum([water_vol(r0, r_dry, Ni) for r0, r_dry, Ni in zip(r0s, r_drys, Nis)])\n wc0 /= rho_air(T0, P0, 0.)\n\n # d) compute initial ice water content\n wi0 = 0.0\n\n # e) concatenate into initial conditions arrays\n y0 = [z0, P0, T0, wv0, wc0, wi0, S0]\n if self.console:\n print(\"PARCEL INITIAL CONDITIONS\")\n print((\" \" + \"{:>9} \"*6).format(\"P (hPa)\", \"T (K)\", \"wv (g/kg)\",\n \"wc (g/kg)\", \"wi (g/kg)\", \"S\"))\n print(\" \" + \"{:9.1f} {:9.2f} {:9.1e} {:9.1e} {:9.1e} {:9.3f}\".format(\n P0/100., T0, wv0*1e3, wc0*1e3, wi0*1e3, S0))\n y0.extend(r0s)\n y0 = np.array(y0)\n out['y0'] = y0\n self.y0 = y0\n\n # Store the model configuration\n self._r0s = r0s\n self._r_drys = r_drys\n self._kappas = kappas\n self._Nis = Nis\n self._nr = len(r_drys)\n\n self._model_set = True\n\n if self.console:\n print(\"Initial conditions set successfully.\")\n\n def run(self, t_end,\n output_dt=1., solver_dt=None,\n max_steps=1000, solver=\"odeint\", output_fmt=\"dataframes\",\n terminate=False, terminate_depth=100., **solver_args):\n \"\"\" Run the parcel model simulation.\n\n Once the model has been instantiated, a simulation can immediately be\n performed by invoking this method. The numerical details underlying the\n simulation and the times over which to integrate can be flexibly set\n here.\n\n **Time** -- The user must specify two timesteps: `output_dt`, which is the\n timestep between output snapshots of the state of the parcel model, and\n `solver_dt`, which is the the interval of time before the ODE integrator\n is paused and re-started. It's usually okay to use a very large `solver_dt`,\n as `output_dt` can be interpolated from the simulation. In some cases though\n a small `solver_dt` could be useful to force the solver to use smaller\n internal timesteps.\n\n **Numerical Solver** -- By default, the model will use the `odeint` wrapper\n of LSODA shipped by default with scipy. Some fine-tuning of the solver tolerances\n is afforded here through the `max_steps`. For other solvers, a set of optional\n arguments `solver_args` can be passed.\n\n **Solution Output** -- Several different output formats are available by default.\n Additionally, the output arrays are saved with the `ParcelModel` instance so they\n can be used later.\n\n Parameters\n ----------\n t_end : float\n Total time over interval over which the model should be integrated\n output_dt : float\n Timestep intervals to report model output.\n solver_dt : float\n Timestep interval for calling solver integration routine.\n max_steps : int\n Maximum number of steps allowed by solver to satisfy error tolerances\n per timestep.\n solver : {'odeint', 'lsoda', 'lsode', 'vode', cvode'}\n Choose which numerical solver to use:\n * `'odeint'`: LSODA implementation from ODEPACK via\n SciPy's integrate module\n * `'lsoda'`: LSODA implementation from ODEPACK via odespy\n * `'lsode'`: LSODE implementation from ODEPACK via odespy\n * `'vode'` : VODE implementation from ODEPACK via odespy\n * `'cvode'` : CVODE implementation from Sundials via Assimulo\n * `'lsodar'` : LSODAR implementation from Sundials via Assimulo\n output_fmt : str, one of {'dataframes', 'arrays', 'smax'}\n Choose format of solution output.\n terminate : boolean\n End simulation at or shortly after a maximum supersaturation has been achieved\n terminate_depth : float, optional (default=100.)\n Additional depth (in meters) to integrate after termination criterion\n eached.\n\n Returns\n -------\n DataFrames, array, or float\n Depending on what was passed to the *output* argument, different\n types of data might be returned:\n\n - `dataframes': (default) will process the output into\n two pandas DataFrames - the first one containing profiles\n of the meteorological quantities tracked in the model,\n and the second a dictionary of DataFrames with one for\n each AerosolSpecies, tracking the growth in each bin\n for those species.\n - 'arrays': will return the raw output from the solver\n used internally by the parcel model - the state vector\n `y` and the evaluated timesteps converted into height\n coordinates.\n - 'smax': will only return the maximum supersaturation\n value achieved in the simulation.\n\n Raises\n ------\n ParcelModelError\n The parcel model failed to complete successfully or failed to initialize.\n\n See Also\n --------\n der : right-hand side derivative evaluated during model integration.\n\n \"\"\"\n from . integrator import Integrator\n\n if output_fmt not in [\"dataframes\", \"arrays\", \"smax\"]:\n raise ParcelModelError(\"Invalid value ('%s') specified for output format.\" % output)\n\n if solver_dt is None:\n solver_dt = 10.*output_dt\n\n if not self._model_set:\n self._setup_run()\n\n y0 = self.y0\n r_drys = self._r_drys\n kappas = self._kappas\n Nis = self._Nis\n nr = self._nr\n\n # Setup/run integrator\n try:\n from .parcel_aux import der as der_fcn\n except ImportError:\n print(\"Could not load Cython derivative; using Python version.\")\n from .parcel import der as der_fcn\n # Hack in Python derivative function\n # der_fcn = der\n\n # Is the updraft speed a function of time?\n v_is_func = hasattr(self.V, '__call__')\n if v_is_func: # Re-wrap the function to correctly figure out V\n orig_der_fcn = der_fcn\n\n def der_fcn(y, t, *args):\n V_t = self.V(t)\n args[3] = V_t\n return orig_der_fcn(y, t, *args)\n\n # Will the simulation terminate early?\n if not terminate:\n terminate_depth = 0.\n else:\n if terminate_depth <= 0.:\n raise ParcelModelError(\"`terminate_depth` must be greater than 0!\")\n\n if self.console:\n print()\n print(\"Integration control\")\n print(\"----------------------------\")\n print(\" output dt: \", output_dt)\n print(\" max solver dt: \", solver_dt)\n print(\" solver int steps: \", int(solver_dt/output_dt))\n print(\" termination: %r (%5dm)\" % (terminate, terminate_depth))\n\n args = [nr, r_drys, Nis, self.V, kappas, self.accom]\n integrator_type = Integrator.solver(solver)\n integrator = integrator_type(der_fcn, output_dt, solver_dt, y0, args,\n terminate=terminate, terminate_depth=terminate_depth,\n console=self.console,\n **solver_args)\n success = False\n try:\n # Pack args as tuple for solvers\n args = tuple(args)\n\n if self.console:\n print(\"\\nBEGIN INTEGRATION ->\\n\")\n x, t, success = integrator.integrate(t_end)\n except ValueError as e:\n raise ParcelModelError(\"Something failed during model integration: %r\" % e)\n finally:\n if not success:\n raise ParcelModelError(\"Something failed during model integration.\")\n\n # Success if reached this point!\n if self.console:\n print(\"\\nEND INTEGRATION <-\\n\")\n\n self.x = x\n self.heights = self.x[:, c.STATE_VAR_MAP['z']]\n self.time = t\n\n if output_fmt == \"dataframes\":\n return output.parcel_to_dataframes(self)\n elif output_fmt == \"arrays\":\n return self.x, self.heights\n elif output_fmt == \"smax\":\n S = self.x[:, c.STATE_VAR_MAP['S']]\n return S.max()\n\n def write_summary(self, parcel_data, aerosol_data, out_filename):\n \"\"\" Write a quick and dirty summary of given parcel model output to the\n terminal.\n \"\"\"\n from .activation import lognormal_activation\n # Check if parent dir of out_filename exists, and if not,\n # create it\n out_dir = os.path.dirname(out_filename)\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n\n # Open a file to write to\n with open(out_filename, 'w') as out_file:\n # Write header\n out_file.write(\"PARCEL MODEL\\n\")\n out_file.write(\"--------------------------------------\\n\")\n\n # Write initial conditions\n out_file.write(\"V = %f\\n\" % self.V)\n out_file.write(\"P0 = %f\\n\" % self.P0)\n out_file.write(\"T0 = %f\\n\" % self.T0)\n out_file.write(\"S0 = %f\\n\" % self.S0)\n out_file.write(\"--------------------------------------\\n\")\n\n # Write aerosol details\n for aerosol in self.aerosols:\n out_file.write(aerosol.species+\" = \"+aerosol.summary_str()+\"\\n\")\n out_file.write(\"--------------------------------------\\n\")\n\n # Write simulation summary results\n # 1) Maximum supersaturation in parcel\n S_max = parcel_data['S'].max()\n S_max_idx = np.argmax(parcel_data.S)\n out_file.write(\"S_max = %f\\n\" % S_max)\n\n # 2) Activated fraction of each species\n T_at_S_max = parcel_data['T'].ix[S_max_idx]\n total_number = 0.0\n total_activated = 0.0\n for aerosol in self.aerosols:\n act_frac = lognormal_activation(S_max, aerosol.mu*1e-6, aerosol.sigma,\n aerosol.N, aerosol.kappa, T=T_at_S_max)\n act_num = act_frac*aerosol.N\n out_file.write(\"%s - eq_act_frac = %f (%3.2f/%3.2f)\\n\" %\n (aerosol.species, act_frac, act_num, aerosol.N))\n\n total_number += aerosol.N\n total_activated += act_num\n total_act_frac = total_activated/total_number\n out_file.write(\"Total activated fraction = %f (%3.2f/%3.2f)\\n\" %\n (total_act_frac, total_activated, total_number))\n\n def save(self, filename=None, format=\"nc\", other_dfs=None):\n output.write_parcel_output(filename=filename, format=format, parcel=self,\n other_dfs=other_dfs)\n\n @staticmethod\n def write_csv(parcel_data, aerosol_data, output_dir=None):\n \"\"\"Write output to CSV files.\n\n Utilize pandas fast output procedures to write the model run output to a\n set of CSV files. Written as a static method so that any prior saved\n parcel model output can be saved to disk in batch, even after its\n associated model has been destroyed.\n\n **Args:\n * *parcel_data* -- Pandas DataFrame of the parcel thermodynamic profile\n * *aerosol_data* -- dictionary of pandas DataFrames with the aerosol radii \\\n at each model step\n * *output_dir* -- String to location where output should be saved; if not \\\n provided then the model will save to the current path.\n\n \"\"\"\n if not output_dir:\n output_dir = os.getcwd()\n\n # Write parcel data\n parcel_data.to_csv(os.path.join(output_dir, \"parcel.csv\"))\n\n # Write aerosol data\n for species, data in list(aerosol_data.items()):\n data.to_csv(os.path.join(output_dir, \"%s.csv\" % species))\n\n\ndef der(y, t, nr, r_drys, Nis, V, kappas, accom=c.ac):\n \"\"\" Calculates the instantaneous time-derivate of the parcel model system.\n\n Given a current state vector `y` of the parcel model, computes the tendency\n of each term including thermodynamic (pressure, temperature, etc) and aerosol\n terms. The basic aerosol properties used in the model must be passed along\n with the state vector (i.e. if being used as the callback function in an ODE\n solver).\n\n This function is implemented in NumPy and Python, and is likely *very* slow\n compared to the available Cython version.\n\n Parameters\n ----------\n y : array_like\n Current state of the parcel model system,\n * y[0] = altitude, m\n * y[1] = Pressure, Pa\n * y[2] = temperature, K\n * y[3] = water vapor mass mixing ratio, kg/kg\n * y[4] = cloud liquid water mass mixing ratio, kg/kg\n * y[5] = cloud ice water mass mixing ratio, kg/kg\n * y[6] = parcel supersaturation\n * y[7:] = aerosol bin sizes (radii), m\n t : float\n Current simulation time, in seconds.\n nr : Integer\n Number of aerosol radii being tracked.\n r_drys : array_like\n Array recording original aerosol dry radii, m.\n Nis : array_like\n Array recording aerosol number concentrations, 1/(m**3).\n V : float\n Updraft velocity, m/s.\n kappas : array_like\n Array recording aerosol hygroscopicities.\n accom : float, optional (default=:const:`constants.ac`)\n Condensation coefficient.\n\n Returns\n -------\n x : array_like\n Array of shape (``nr``+7, ) containing the evaluated parcel model\n instaneous derivative.\n\n Notes\n -----\n This Python sketch of the derivative function shouldn't really be used for\n any computational purposes. Instead, see the cythonized version in the auxiliary\n file, **parcel_aux.pyx**. In the default configuration, once the code has been\n built, you can set the environmental variable **OMP_NUM_THREADS** to control\n the parallel for loop which calculates the condensational growth rate for each\n bin.\n\n \"\"\"\n z = y[0]\n P = y[1]\n T = y[2]\n wv = y[3]\n wc = y[4]\n wi = y[5]\n S = y[6]\n rs = np.asarray(y[c.N_STATE_VARS:])\n\n T_c = T - 273.15 # convert temperature to Celsius\n pv_sat = es(T-T_c) # saturation vapor pressure\n wv_sat = wv/(S+1.) # saturation mixing ratio\n Tv = (1.+0.61*wv)*T # virtual temperature given parcel humidity\n e = (1. + S)*pv_sat # water vapor pressure\n rho_air = P/(Rd*Tv) # current air density accounting for humidity\n rho_air_dry = (P-e)/Rd/T # dry air density\n\n # 1) Pressure\n dP_dt = -1.*rho_air*g*V\n\n # 2/3) Wet particle growth rates and droplet liquid water\n drs_dt = np.zeros(shape=(nr, ))\n dwc_dt = 0.\n for i in range(nr):\n r = rs[i]\n r_dry = r_drys[i]\n kappa = kappas[i]\n\n dv_r = dv(T, r, P, accom)\n ka_r = ka(T, rho_air, r)\n\n G_a = (rho_w*R*T)/(pv_sat*dv_r*Mw)\n G_b = (L*rho_w*((L*Mw/(R*T))-1.))/(ka_r*T)\n G = 1./(G_a + G_b)\n\n delta_S = S - Seq(r, r_dry, T, kappa)\n dr_dt = (G/r)*delta_S\n Ni = Nis[i]\n dwc_dt += Ni*(r*r)*dr_dt\n drs_dt[i] = dr_dt\n\n # if i == nr-1:\n # print 1, r, r_dry, Ni\n # print 2, dv(T, r, P, accom), ka(T, rho_air, r)\n # print 3, G_a, G_b\n # print 4, Seq(r, r_dry, T, kappa, 1.0)\n # print 5, dr_dt\n\n dwc_dt *= 4.*np.pi*rho_w/rho_air_dry\n\n # 4) ice water content\n dwi_dt = 0.0\n\n # 5) Water vapor content\n dwv_dt = -1.*(dwc_dt + dwi_dt)\n\n # 6) Temperature\n dT_dt = -g*V/Cp - L*dwv_dt/Cp\n\n # 7) Supersaturation\n alpha = (g*Mw*L)/(Cp*R*(T**2)) - (g*Ma)/(R*T)\n gamma = (P*Ma)/(Mw*es(T-273.15)) + (Mw*L*L)/(Cp*R*T*T)\n dS_dt = alpha*V - gamma*dwc_dt\n\n dz_dt = V\n\n # Repackage tendencies for feedback to numerical solver\n x = np.zeros(shape=(nr+c.N_STATE_VARS, ))\n x[0] = dz_dt\n x[1] = dP_dt\n x[2] = dT_dt\n x[3] = dwv_dt\n x[4] = dwc_dt\n x[5] = dwi_dt\n x[6] = dS_dt\n x[c.N_STATE_VARS:] = drs_dt[:]\n\n return x\n", "meta": {"hexsha": "2914a64e57297265ea09953a0b1895000f7f999c", "size": 28285, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyrcel/parcel.py", "max_stars_repo_name": "claresinger/pyrcel", "max_stars_repo_head_hexsha": "614ded9ae8b3e1618fe0547bd07be9af05051a45", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyrcel/parcel.py", "max_issues_repo_name": "claresinger/pyrcel", "max_issues_repo_head_hexsha": "614ded9ae8b3e1618fe0547bd07be9af05051a45", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyrcel/parcel.py", "max_forks_repo_name": "claresinger/pyrcel", "max_forks_repo_head_hexsha": "614ded9ae8b3e1618fe0547bd07be9af05051a45", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.814171123, "max_line_length": 103, "alphanum_fraction": 0.5828531024, "include": true, "reason": "from scipy", "num_tokens": 7055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.26588047891687405, "lm_q1q2_score": 0.13709327013151362}} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n策略值网络实现\n依赖TensorFlow 1.10.0版本\n\n@author: CoderJie\n@email: coderjie@outlook.com\n\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\n\n\nclass PolicyValueNet:\n \"\"\"\n 策略值网络\n \"\"\"\n def __init__(self, board_width, board_height, model_file=None):\n \"\"\"\n 构造函数\n :param board_width: 棋盘宽度\n :param board_height: 棋盘高度\n \"\"\"\n\n self.__board_width = board_width\n self.__board_height = board_height\n\n # 定义模型输入占位符, 张量形状为[?, 4, height, width]\n # None表示张量的第一维为任意长度, 第一维即代表样本数量, 就是表示模型接收任意的样本数,\n # 并且每个样本包含4个 board_height*board_width 的表格\n self.__input_data = tf.placeholder(tf.float32,\n shape=[None, 4, board_height, board_width])\n\n # 定义训练所用的状态值占位符\n self.__train_value = tf.placeholder(tf.float32,\n shape=[None, 1])\n\n # 定义训练所用的动作概率值占位符\n self.__train_prob = tf.placeholder(tf.float32,\n shape=[None, board_height * board_width])\n\n # 定义学习速度占位符\n self.__learning_rate = tf.placeholder(tf.float32)\n\n # 组建神经网络\n self.__build_net()\n\n # 创建一个会话, 并进行初始化动作\n self.__session = tf.Session()\n self.__session.run(tf.global_variables_initializer())\n\n # 保存器, 用于保存或者恢复模型\n self.__saver = tf.train.Saver()\n\n # 从文件中恢复模型\n if model_file is not None:\n self.restore_model(model_file)\n\n def __del__(self):\n \"\"\"\n 析构函数\n \"\"\"\n self.__session.close()\n\n def train(self, batch_states, batch_probs, batch_values, lr):\n \"\"\"\n 训练模型\n :param batch_states: 批量状态(形状为[?, 4, height, width])\n :param batch_probs: 批量概率(形状为[?, height*width])\n :param batch_values: 批量状态值(形状为[?, 1])\n :param lr: 学习速度(浮点数)\n :return: 损失值, 熵\n \"\"\"\n loss, entropy, _ = self.__session.run(\n [self.__total_loss, self.__entropy, self.__optimizer],\n feed_dict={self.__input_data: batch_states,\n self.__train_prob: batch_probs,\n self.__train_value: batch_values,\n self.__learning_rate: lr})\n return loss, entropy\n\n def policy_value(self, board):\n \"\"\"\n 获取策略(动作概率), 状态值\n :param board: 棋盘对象\n :return: 策略(动作概率), 状态值\n \"\"\"\n state = board.state()\n input_data = state.reshape(-1, 4, self.__board_height, self.__board_width)\n acts_prob, state_value = self.__policy_value(input_data)\n\n # 只获取有效动作的概率\n avl_acts = board.avl_actions\n acts_prob = list(zip(avl_acts, acts_prob[0][avl_acts]))\n return acts_prob, state_value[0][0]\n\n def save_model(self, path):\n \"\"\"\n 保存模型\n :param path: 模型路径\n \"\"\"\n self.__saver.save(self.__session, path)\n\n def restore_model(self, path):\n \"\"\"\n 恢复模型\n :param path: 模型路径\n \"\"\"\n self.__saver.restore(self.__session, path)\n\n def __build_net(self):\n \"\"\"\n 组建卷积神经网络\n :return:\n \"\"\"\n # 转置输入数据, 输出张量形状[?, height, width, 4]\n # [0, 2, 3, 1] 0 代表原始数据第一维, 1 代表原始数据第二维, 2 代表原始数据第三维, 3 代表原始数据第四维\n # 转置后可以把棋盘数据看作是通道数为4, 大小为height*width的图片\n input_trans = tf.transpose(self.__input_data, [0, 2, 3, 1])\n\n # 第一层卷积层, 32个卷积核, 输出张量形状[?, height, width, 32]\n # 卷积核数量32, 卷积核大小 3*3, 卷积核的通道数就是输入数据的通道数4, 卷积步长默认为1\n # 填充方式为\"same\" 表示边界填充0\n # channels_last表示通道为最后一维\n # 默认加上偏置, 偏置初始值默认为0\n # 激活函数选择斜坡函数\n conv1 = tf.layers.conv2d(inputs=input_trans,\n filters=32,\n kernel_size=[3, 3],\n padding=\"same\",\n data_format=\"channels_last\",\n activation=tf.nn.relu)\n\n # 第二层卷积层, 64个卷积核, 输出张量形状[?, height, width, 64]\n conv2 = tf.layers.conv2d(inputs=conv1,\n filters=64,\n kernel_size=[3, 3],\n padding=\"same\",\n data_format=\"channels_last\",\n activation=tf.nn.relu)\n\n # 第三层卷积层, 128个卷积核, 输出张量形状[?, height, width, 128]\n conv3 = tf.layers.conv2d(inputs=conv2,\n filters=128,\n kernel_size=[3, 3],\n padding=\"same\",\n data_format=\"channels_last\",\n activation=tf.nn.relu)\n\n # 策略端降维, 输出张量形状[?, height, width, 4]\n policy_conv = tf.layers.conv2d(inputs=conv3,\n filters=4,\n kernel_size=[1, 1],\n padding=\"same\",\n data_format=\"channels_last\",\n activation=tf.nn.relu)\n\n # 策略端修改数据维度, 输出张量形状[?, 4 * height * width]\n policy_flat = tf.reshape(policy_conv,\n [-1, 4 * self.__board_height * self.__board_width])\n\n # 策略端全连接层, 输出张量形状[?, height * width]\n # units代表输出大小\n # 默认加上偏置, 偏置初始值默认为0\n # 使用log_softmax激活函数\n self.__policy_fc = tf.layers.dense(inputs=policy_flat,\n units=self.__board_height * self.__board_width,\n activation=tf.nn.log_softmax)\n\n # 价值端降维, 输出张量形状[?, height, width, 2]\n value_conv = tf.layers.conv2d(inputs=conv3,\n filters=2,\n kernel_size=[1, 1],\n padding=\"same\",\n data_format=\"channels_last\",\n activation=tf.nn.relu)\n\n # 价值端修改数据维度, 输出张量形状[?, 2 * height * width]\n value_flat = tf.reshape(value_conv,\n [-1, 2 * self.__board_height * self.__board_width])\n\n # 价值端64个神经元的全连接层, 输出张量形状[?, 64]\n # 使用斜坡激活函数\n value_fc1 = tf.layers.dense(inputs=value_flat,\n units=64,\n activation=tf.nn.relu)\n\n # 价值端1个神经元的全连接层, 输出张量形状[?, 1]\n # 使用双曲正切激活函数, 双曲正切函数的值域是(-1, 1)\n self.__value_fc2 = tf.layers.dense(inputs=value_fc1,\n units=1,\n activation=tf.nn.tanh)\n\n # 定义状态值损失函数(平方差)\n value_loss = tf.losses.mean_squared_error(self.__train_value, self.__value_fc2)\n\n # 定义策略损失函数\n policy_loss = tf.negative(tf.reduce_mean(tf.reduce_sum(\n tf.multiply(self.__train_prob, self.__policy_fc), 1)))\n\n # l2正则化系数\n l2_beta = 1e-4\n # 获取所有可训练变量\n vs = tf.trainable_variables()\n # 定义正则项\n l2_penalty = l2_beta * tf.add_n(\n [tf.nn.l2_loss(v) for v in vs if 'bias' not in v.name.lower()])\n\n # 定义总损失函数\n self.__total_loss = value_loss + policy_loss + l2_penalty\n\n # 定义优化器\n self.__optimizer = tf.train.AdamOptimizer(\n learning_rate=self.__learning_rate).minimize(self.__total_loss)\n\n # 计算策略的熵值, 用于监控网络\n self.__entropy = tf.negative(tf.reduce_mean(\n tf.reduce_sum(tf.exp(self.__policy_fc) * self.__policy_fc, 1)))\n\n def __policy_value(self, states):\n \"\"\"\n 获取策略(动作概率), 状态值\n :param states: 批量状态二值数据, 数据形状应该为[?, 4, height, width]\n :return: 策略(形状: [?, height*width]), 状态值(形状: [?, 1])\n \"\"\"\n log_probs, values = self.__session.run([self.__policy_fc, self.__value_fc2],\n feed_dict={self.__input_data: states})\n acts_probs = np.exp(log_probs)\n return acts_probs, values\n\n", "meta": {"hexsha": "c777747a811aa9dde4adfa072b3506e540ccefba", "size": 8001, "ext": "py", "lang": "Python", "max_stars_repo_path": "Test/TaiChiGomoku/policy_value_net.py", "max_stars_repo_name": "BurnellLiu/TinyML", "max_stars_repo_head_hexsha": "3acc757567fb3ef276d79260142cfe0e79f85552", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2018-01-19T07:06:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T06:59:40.000Z", "max_issues_repo_path": "Test/TaiChiGomoku/policy_value_net.py", "max_issues_repo_name": "BurnellLiu/TinyML", "max_issues_repo_head_hexsha": "3acc757567fb3ef276d79260142cfe0e79f85552", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Test/TaiChiGomoku/policy_value_net.py", "max_forks_repo_name": "BurnellLiu/TinyML", "max_forks_repo_head_hexsha": "3acc757567fb3ef276d79260142cfe0e79f85552", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2017-09-29T07:52:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-04T11:40:59.000Z", "avg_line_length": 34.339055794, "max_line_length": 90, "alphanum_fraction": 0.5034370704, "include": true, "reason": "import numpy", "num_tokens": 2428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.2422056341953392, "lm_q1q2_score": 0.13709287828348868}} {"text": "\"\"\"\nCode for parsing Spice Double-Array Files (DAF). This is a superset of CK and SPK files. Note that while this\nparses Spice files, it only makes minimal use of the spice libraries (date conversion only)\n\"\"\"\n\nimport struct\nfrom spiceypy import etcal as cspice_etcal\nfrom spiceypy import scdecd as cspice_scdecd\nfrom spiceypy import sct2e as cspice_sct2e\n\nclass daf_summary:\n @staticmethod\n def make(sr,daf,buf,name):\n if daf.subtype==\"SPK\":\n return daf_SPKsummary(sr,daf,buf,name)\n elif daf.subtype==\"CK\":\n return daf_CKsummary(sr,daf,buf,name)\n else:\n raise ValueError(\"Unrecognized subtype %s\"%daf.subtype)\n def __init__(self,sr,daf,buf,name):\n \"\"\"\n\n :param sr: Summary record which this summary is part of\n :param daf: Double-array file which holds the header (ND, NI) and can read the file\n :param buf: Data for this summary\n \"\"\"\n self.sr=sr\n self.daf=daf\n self.D=[0.0]*self.daf.ND\n self.I=[0]*self.daf.NI\n self.name=name\n for i in range(self.daf.ND):\n self.D[i]=struct.unpack(self.daf.dformat,buf[i*8:(i+1)*8])[0]\n for i in range(self.daf.NI):\n self.I[i]=struct.unpack(self.daf.iformat,buf[self.daf.ND*8+i*4:self.daf.ND*8+(i+1)*4])[0]\n def __str__(self):\n result=\"%s\\nD:\\n\" % self.name\n for i,D in enumerate(self.D):\n if i!=0:\n result+=\",\"\n result+=\"%20.15e\"%D\n result+=\"\\nI:\\n\"\n for i,I in enumerate(self.I):\n if i!=0:\n result+=\",\"\n result+=\"%d\"%I\n return result\n\nclass daf_SPKsummary(daf_summary):\n def __init__(self,sr,daf,buf,name):\n super().__init__(sr,daf,buf,name)\n def getet0(self): return self.D[0]\n def getet1(self): return self.D[1]\n def gettarget(self): return self.I[0]\n def getcenter(self): return self.I[1]\n def getframe (self): return self.I[2]\n def gettype (self): return self.I[3]\n def getaddr0 (self): return self.I[4]\n def getaddr1 (self): return self.I[5]\n et0 =property(fget=getet0 ,doc=\"Ephemeris time of beginning of segment\")\n et1 =property(fget=getet1 ,doc=\"Ephemeris time of end of segment\")\n target=property(fget=gettarget,doc=\"Target NAIF code\")\n center=property(fget=getcenter,doc=\"Center NAIF code\")\n frame =property(fget=getframe ,doc=\"Reference frame NAIF code\")\n type =property(fget=gettype ,doc=\"SPK segment type\")\n addr0 =property(fget=getaddr0 ,doc=\"Address of first element of segment data\")\n addr1 =property(fget=getaddr1 ,doc=\"Address of last element of segment data\")\n def __str__(self):\n result=((\"%s\\n\"+\n \"ET0: %30.14f (%s)\\n\"+\n \"ET1: %30.14f (%s)\\n\"+\n \"Target: %d\\n\"+\n \"Center: %d\\n\"+\n \"Frame: %d\\n\"+\n \"Type: %d\\n\"+\n \"Addr0: %d\\n\"+\n \"Addr1: %d\") %\n (self.name,self.et0,cspice_etcal(self.et0),self.et1,cspice_etcal(self.et1),self.target,self.center,self.frame,self.type,self.addr0,self.addr1))\n return result\n def segment(self):\n return daf_SPKSegment(self,self.daf)\n\nclass daf_CKsummary(daf_summary):\n def __init__(self,sr,daf,buf,name):\n super().__init__(sr,daf,buf,name)\n def sclk(self):return self.target // 1000 + (0 if self.target % 1000 == 0 else 1)\n def getsclk0(self): return self.D[0]\n def getsclk1(self): return self.D[1]\n def getet0(self): return cspice_sct2e(self.sclk(),self.sclk0)\n def getet1(self): return cspice_sct2e(self.sclk(),self.sclk1)\n def gettarget(self): return self.I[0]\n def getframe (self): return self.I[1]\n def gettype (self): return self.I[2]\n def getrates (self): return self.I[3]\n def getaddr0 (self): return self.I[4]\n def getaddr1 (self): return self.I[5]\n sclk0 =property(fget=getsclk0 ,doc=\"DP encoded sclk of beginning of segment\")\n sclk1 =property(fget=getsclk1 ,doc=\"DP encoded sclk of end of segment\")\n et =property(fget=getet0 ,doc=\"ephemeris time of beginning of segment\")\n et0 =property(fget=getet0 ,doc=\"ephemeris time of beginning of segment\")\n et1 =property(fget=getet1 ,doc=\"ephemeris time of end of segment\")\n target=property(fget=gettarget,doc=\"Target NAIF code\")\n frame =property(fget=getframe ,doc=\"Reference frame NAIF code\")\n type =property(fget=gettype ,doc=\"CK segment type\")\n rates =property(fget=getrates ,doc=\"Angular Rates Flag\")\n addr0 =property(fget=getaddr0 ,doc=\"Address of first element of segment data\")\n addr1 =property(fget=getaddr1 ,doc=\"Address of last element of segment data\")\n def __str__(self):\n result =\"%s\\n\"%self.name\n result+=\"SCLK0: %20.15e\" %self.sclk0\n try:\n et=cspice_sct2e(self.sclk(),self.sclk0)\n scdecd=cspice_scdecd(self.sclk(),self.sclk0)\n result+=\" (%s ET=%16.6f %s)\"%(scdecd,et,cspice_etcal(et))\n except:\n pass #If there is an error, it means that the correct kernels aren't available.\n result+=\"\\n\"\n result+=\"SCLK1: %20.15e\" %self.sclk1\n try:\n et=cspice_sct2e(self.sclk(),self.sclk1)\n scdecd=cspice_scdecd(self.sclk(),self.sclk1)\n result+=\" (%s ET=%16.6f %s)\"%(scdecd,et,cspice_etcal(et))\n except:\n pass #If there is an error, it means that the correct kernels aren't available.\n result+=\"\\n\"\n result+=((\"Inst: %7d\\n\"+\n \"Frame: %7d\\n\"+\n \"Type: %7d\\n\"+\n \"Rates? %7d\\n\"+\n \"Addr0: %7d\\n\"+\n \"Addr1: %7d\") %\n (self.target,self.frame,self.type,self.rates,self.addr0,self.addr1))\n return result\n def segment(self):\n return daf_CKSegment(self,self.daf)\n\nclass daf_SPKSegment:\n def __init__(self,summary,daf):\n self.summary=summary\n self.daf=daf\n daf.inf.seek(8*(summary.addr0-1))\n segment_size=summary.addr1-summary.addr0+1\n format=\"%s%d%s\"%(daf.dformat[0],segment_size,daf.dformat[1])\n self.buf=struct.unpack(format,daf.inf.read(segment_size*8))\n self.N=int(self.buf[-1]) if self.summary.type not in (15,17) else 1\n result=self.line(0)\n self.csvheader = result.csvheader\n def line(self,i):\n if self.summary.type==1:\n return daf_SPK01line(self.N,i,self.buf)\n elif self.summary.type==2:\n return daf_SPK02line(self.N,i,self.buf)\n elif self.summary.type==3:\n return daf_SPK03line(self.N,i,self.buf)\n elif self.summary.type==9:\n return daf_SPK09line(self.N,i,self.buf)\n elif self.summary.type == 13:\n return daf_SPK13line(self.N, i, self.buf)\n elif self.summary.type == 15:\n return daf_SPK15line(self.N, i, self.buf)\n elif self.summary.type == 17:\n return daf_SPK17line(self.N, i, self.buf)\n else:\n raise ValueError(\"Unhandled SPK type %d\"%self.summary.type)\n def __iter__(self):\n for i in range(self.N):\n result = self.line(i)\n yield result\n def __str__(self):\n result=((\"N: %d\") %\n (self.N))\n return result\n\nclass daf_CKSegment:\n def __init__(self,summary,daf):\n self.summary=summary\n self.daf=daf\n daf.inf.seek(8*(summary.addr0-1))\n segment_size=summary.addr1-summary.addr0+1\n format=\"%s%d%s\"%(daf.dformat[0],segment_size,daf.dformat[1])\n self.buf=struct.unpack(format,daf.inf.read(segment_size*8))\n result = self.line(0)\n self.csvheader = result.csvheader\n def getN(self):\n if self.summary.type==1:\n return int(self.buf[-1])\n elif self.summary.type==2:\n return int(1+len(self.buf)/10.01)\n elif self.summary.type==3:\n return int(self.buf[-1])\n else:\n raise ValueError(\"Unknown CK type %d\"%self.summary.type)\n N=property(fget=getN ,doc=\"Number of pointing intervals in file\")\n def line(self,i):\n sclk=self.summary.target//1000+(0 if self.summary.target%1000==0 else 1)\n if self.summary.type==1:\n return daf_CK01line(sclk,self.N,i,self.buf,self.summary.rates)\n elif self.summary.type==2:\n return daf_CK02line(sclk,self.N,i,self.buf)\n elif self.summary.type == 3:\n return daf_CK03line(sclk,self.N,i,self.buf,self.summary.rates)\n else:\n raise ValueError(\"Unknown CK type %d\" % self.summary.type)\n def __iter__(self):\n for i in range(self.N):\n result = self.line(i)\n yield result\n def __str__(self):\n result=((\"N: %d\") %\n (self.N))\n return result\n\n\nclass daf_SPKStateline:\n def __init__(self,N,i,buf):\n self.x =buf[i*6+0]\n self.y =buf[i*6+1]\n self.z =buf[i*6+2]\n self.dxdt=buf[i*6+3]\n self.dydt=buf[i*6+4]\n self.dzdt=buf[i*6+5]\n self.et=buf[N*6+i]\n self.csvheader=\"ET,ETCAL*,x,y,z,dxdt,dydt,dzdt\"\n def __str__(self):\n result=\"%30.14f,%s,%25.15e,%25.15e,%25.15e,%25.15e,%25.15e,%25.15e\"%(self.et,cspice_etcal(self.et),self.x,self.y,self.z,self.dxdt,self.dydt,self.dzdt)\n return result\n\nclass daf_SPK09line(daf_SPKStateline):\n def __init__(self,N,i,buf):\n super().__init__(N,i,buf)\n\nclass daf_SPK13line(daf_SPKStateline):\n def __init__(self,N,i,buf):\n super().__init__(N,i,buf)\n\nclass daf_SPK02line:\n def __init__(self,N,i,buf):\n self.RSIZE=int(buf[-2])\n self.asize=(self.RSIZE-2)//3 #Number of elements in each component array\n self.INTLEN=buf[-3]\n self.INIT=buf[-4]\n self.mid =buf[i*self.RSIZE+0]\n self.radius=buf[i*self.RSIZE+1]\n self.et=self.mid-self.radius\n self.x =buf[i*self.RSIZE+2+self.asize*0:i*self.RSIZE+2+self.asize*1]\n self.y =buf[i*self.RSIZE+2+self.asize*1:i*self.RSIZE+2+self.asize*2]\n self.z =buf[i*self.RSIZE+2+self.asize*2:i*self.RSIZE+2+self.asize*3]\n self.csvheader=\"ET*,ETCAL*,ETEND*,ETCALEND*,MID,MIDCAL*,RADIUS\"\n for i in range(self.asize):\n self.csvheader+=\",x[%02d]\"%i\n for i in range(self.asize):\n self.csvheader+=\",y[%02d]\" % i\n for i in range(self.asize):\n self.csvheader+=\",z[%02d]\" % i\n def __str__(self):\n result=\"%30.14f,%s,%30.14f,%s,%30.14f,%s,%30.14f\"%(self.et,cspice_etcal(self.et),self.mid+self.radius,cspice_etcal(self.mid+self.radius),self.mid,cspice_etcal(self.mid),self.radius)\n for x in self.x:\n result+=\",%25.15e\"%x\n for y in self.y:\n result+=\",%25.15e\"%y\n for z in self.z:\n result+=\",%25.15e\"%z\n return result\n def eval(self,ET):\n pass\n\nclass daf_SPK03line:\n def __init__(self,N,i,buf):\n self.RSIZE=int(buf[-2])\n self.asize=(self.RSIZE-2)//6 #Number of elements in each component array\n self.INTLEN=buf[-3]\n self.INIT=buf[-4]\n self.mid =buf[i*self.RSIZE+0]\n self.radius=buf[i*self.RSIZE+1]\n self.et=self.mid-self.radius\n self.x =buf[i*self.RSIZE+2+self.asize*0:i*self.RSIZE+2+self.asize*1]\n self.y =buf[i*self.RSIZE+2+self.asize*1:i*self.RSIZE+2+self.asize*2]\n self.z =buf[i*self.RSIZE+2+self.asize*2:i*self.RSIZE+2+self.asize*3]\n self.dx =buf[i*self.RSIZE+2+self.asize*3:i*self.RSIZE+2+self.asize*4]\n self.dy =buf[i*self.RSIZE+2+self.asize*4:i*self.RSIZE+2+self.asize*5]\n self.dz =buf[i*self.RSIZE+2+self.asize*5:i*self.RSIZE+2+self.asize*6]\n self.csvheader=\"ET*,ETCAL*,ETEND*,ETCALEND*,MID,MIDCAL*,RADIUS\"\n for i in range(self.asize):\n self.csvheader+=\",x[%02d]\"%i\n for i in range(self.asize):\n self.csvheader+=\",y[%02d]\" % i\n for i in range(self.asize):\n self.csvheader+=\",z[%02d]\" % i\n for i in range(self.asize):\n self.csvheader+=\",dx[%02d]\"%i\n for i in range(self.asize):\n self.csvheader+=\",dy[%02d]\" % i\n for i in range(self.asize):\n self.csvheader+=\",dz[%02d]\" % i\n def __str__(self):\n result=\"%30.14f,%s,%30.14f,%s,%30.14f,%s,%30.14f\"%(self.et,cspice_etcal(self.et),self.mid+self.radius,cspice_etcal(self.mid+self.radius),self.mid,cspice_etcal(self.mid),self.radius)\n for x in self.x:\n result+=\",%25.15e\"%x\n for y in self.y:\n result+=\",%25.15e\"%y\n for z in self.z:\n result+=\",%25.15e\"%z\n for dx in self.dx:\n result+=\",%25.15e\"%dx\n for dy in self.dy:\n result+=\",%25.15e\"%dy\n for dz in self.dz:\n result+=\",%25.15e\"%dz\n return result\n def eval(self,ET):\n pass\n\nclass daf_SPK15line:\n def __init__(self,N,i,buf):\n self.et =buf[0]\n self.polex =buf[1]\n self.poley =buf[2]\n self.polez =buf[3]\n self.perix =buf[4]\n self.periy =buf[5]\n self.periz =buf[6]\n self.l=buf[7]\n self.e =buf[8]\n self.j2flag=buf[9]\n self.centx=buf[10]\n self.centy=buf[11]\n self.centz=buf[12]\n self.centgm=buf[13]\n self.centj2=buf[14]\n self.centre=buf[15]\n self.csvheader=\"ETPERI,ETPERICAL*,polex,poley,polez,perix,periy,periz,l,e,j2flag,centx,centy,centz,centgm,centj2,centre\"\n def __str__(self):\n result=\"%30.14f,%s,%.15f,%.15f,%.15f,%.15f,%.15f,%.15f,%.15e,%.15e,%1.0f,%17.14f,%17.14f,%17.14f,%.15e,%.15e,%.15e\"%(\n self.et,cspice_etcal(self.et),\n self.polex,self.poley,self.polez,self.perix,self.periy,self.periz,\n self.l,self.e,self.j2flag,\n self.centx, self.centy, self.centz,\n self.centgm,self.centj2,self.centre\n )\n return result\n def eval(self,ET):\n pass\n\nclass daf_SPK17line:\n def __init__(self,N,i,buf):\n self.et =buf[0]\n self.a =buf[1]\n self.h =buf[2]\n self.k =buf[3]\n self.L =buf[4]\n self.p =buf[5]\n self.q =buf[6]\n self.omegabardot=buf[7]\n self.Ldot =buf[8]\n self.Omegadot=buf[9]\n self.polera=buf[10]\n self.poledec=buf[11]\n self.csvheader=\"ETPERI,ETPERICAL*,a,h,k,L,p,q,omegabardot,Ldot,Omegadot,polera,poledec\"\n def __str__(self):\n result=\"%30.14f,%s,%30.14f,%30.14f,%30.14f,%30.14f,%30.14f,%30.14f,%30.14f,%30.14f,%30.14f,%30.14f,%30.14f\"%(\n self.et,cspice_etcal(self.et),\n self.a,self.h,self.k,self.L,self.p,self.q,\n self.omegabardot,self.Ldot,self.Omegadot,\n self.polera,self.poledec\n )\n return result\n def eval(self,ET):\n pass\n\nclass daf_SPK01line:\n n_elements=71\n def __init__(self,N,i,buf):\n self.e =buf[i*self.n_elements:(i+1)*self.n_elements]\n self.et=buf[N*self.n_elements+i]\n import numpy as np\n self.FD=np.zeros(15)*float('nan')\n\n # initialize arrays for spke01\n self.G = np.zeros(15)\n self.REFPOS = np.zeros(3)\n self.REFVEL = np.zeros(3)\n self.KQ = np.array([0, 0, 0])\n self.FC = np.zeros(15)\n self.FC[0] = 1.0\n self.WC = np.zeros(13)\n self.W = np.zeros(17)\n\n self.spke01(self.e[0],self.e)\n self.csvheader= \"ET,ETCAL*,TL\"\n for i in range(15):\n self.csvheader += \",G[%02d]\" % (i)\n self.csvheader += \",X,DXDT,Y,DYDT,Z,DZDT\"\n for i in range(3):\n for j in range(15):\n self.csvheader += \",DT[%02d%02d]\" % (i, j)\n self.csvheader += \",KQMAX1,KQ[0],KQ[1],KQ[2]\"\n\n # self.eval(self.TL)\n def __str__(self):\n result=\"%30.14f,%s\" %(self.et,cspice_etcal(self.et))\n for i in range(self.n_elements):\n result+=\",%25.15e\"%self.e[i]\n return result\n \"\"\"\n def getTL(self): return self.e[0]\n def getG (self): return self.e[1:15+1]\n def getREFPOS(self): return self.e[16:22:2]\n def getREFVEL(self): return self.e[17:23:2]\n def getDT (self): return self.e[22:22+45]\n def getKQMAX1(self): return int(self.e[67])\n def getKQ (self): return self.e[68:71]\n TL =property(fget=getTL ,doc=\"Ephemeris time of end of segment\")\n G =property(fget=getG ,doc=\"Stepsize function vector\")\n REFPOS=property(fget=getREFPOS,doc=\"Reference position vector\")\n REFVEL=property(fget=getREFVEL,doc=\"Reference velocity vector\")\n DT =property(fget=getDT ,doc=\"Modified divided difference arrays\")\n KQMAX1=property(fget=getKQMAX1,doc=\"Maximum integration order plus 1\")\n KQ =property(fget=getKQ ,doc=\"Integration order array\")\n \"\"\"\n def getFC(self,J):\n print(\"Accessing element %d, value %f\"%(J,self.FD[J]))\n return self.FD[J]\n def setFC(self,J,val):\n print(\"Writing element %d, was value %f, will be value %f\"%(J,self.FD[J],val))\n self.FD[J]=val\n def eval(self,ET):\n import numpy as np\n STATE=np.zeros(6)\n DELTA = ET - self.TL\n TP = DELTA\n MQ2 = self.KQMAX1 - 2\n KS = self.KQMAX1 - 1\n self.setFC(0,1.0)\n WC = np.zeros(13)\n W = np.zeros(17)\n\n # This is clearly collecting some kind of coefficients.\n # The problem is that we have no idea what they are...\n #\n # The G coefficients are supposed to be some kind of step size\n # vector.\n #\n # TP starts out as the delta t between the request time\n # and the time for which we last had a state in the MDL file.\n # We then change it from DELTA by the components of the stepsize\n # vector G.\n for J in range(1, MQ2 + 1):\n self.setFC(J,TP / self.G[J-1])\n WC[J-1] = DELTA / self.G[J-1]\n TP = DELTA + self.G[J-1]\n # Collect KQMAX1 reciprocals.\n for J in range(1, self.KQMAX1 + 1):\n W[J-1] = 1.0 / float(J)\n\n # Compute the W(K) terms needed for the position interpolation\n # (Note, it is assumed throughout this routine that KS, which\n # starts out as KQMAX1-1 (the ``maximum integration'')\n # is at least 2.\n JX = 0\n KS1 = KS - 1\n while KS >= 2:\n JX = JX + 1\n for J in range(1, JX + 1):\n W[J + KS - 1] = self.getFC(J) * W[J + KS1 - 1] - WC[J - 1] * W[J + KS - 1]\n KS = KS1\n KS1 = KS1 - 1\n\n # Perform position interpolation: (Note that KS = 1 right now.\n # We don't know much more than that.)\n for I in range(3):\n KQQ = int(self.KQ[I])\n SUM = 0.0\n for J in range(KQQ, 0, -1):\n SUM = SUM + self.DT[J - 1+I*15] * W[J + KS - 1]\n STATE[I] = self.REFPOS[I] + DELTA * (self.REFVEL[I] + DELTA * SUM)\n\n # Again we need to compute the W(K) coefficients that are\n # going to be used in the velocity interpolation.\n # (Note, at this point, KS = 1, KS1 = 0.)\n for J in range(1, JX + 1):\n W[J + KS - 1] = self.getFC(J) * W[J + KS1 - 1] - WC[J - 1] * W[J + KS - 1]\n KS = KS - 1\n\n # Perform velocity interpolation:\n for I in range(1, 3 + 1):\n KQQ = int(self.KQ[I])\n SUM = 0.0\n\n for J in range(KQQ, 0, -1):\n SUM = SUM + self.DT[J - 1+I*15] * W[J + KS - 1]\n\n STATE[I + 3] = self.REFVEL[I] + DELTA * SUM\n\n # That's all folks. We don't know why we did anything, but\n # at least we can tell structurally what we did.\n return STATE\n def test(self,et0,N=100):\n \"\"\"\n Compare the calculation of the state in pure python to that provided by spiceypy (which is an interface\n to the cspice library). This should be near bit-perfect.\n :param ET0: Time to begin at. Since the record only contains the end time, we need a beginning time. The\n beginning time *might* be encoded in the DeltaT's, but this isn't known for sure yet\n :param N: Number of points to evaluate at. If you pass 100, you will get the point at the beginning,\n 99 points in between, and the point at the end, so a total of 101 points.\n :return: Sum of squares of differences of position components. Ideally should be zero, should be only a couple\n of ulps.\n \"\"\"\n from spiceypy import spkezr as cspice_spkezr\n import numpy as np\n et1=self.et\n result=0.0\n for i in range(N):\n et=et0+i*(et1-et0)/N\n #et=et1\n ref=cspice_spkezr(\"-189\",et,\"J2000\",\"NONE\",\"399\")[0][0:3]\n test=np.array(self.spke01(et,self.e)[0:3])\n result+=np.sum((ref-test)**2)\n return result\n def spke01(self, ET, RECORD):\n import numpy as np\n \"\"\"Compute position and velocity from a Modified Difference Array record\n\n Inputs:\n ET: Epoch time to evaluate position and velocity (seconds since J2000)\n RECORD: A record of Modified Difference Array\n Returns: STATE\n STATE: A numpy array which contains position and velocity\n \"\"\"\n\n # This method has been translated from SPKE01 of SPICE Toolkit and\n # modified by Shushi Uetsuki.\n #\n # SPICE Toolkit for FORTRAN : http://naif.jpl.nasa.gov/naif/toolkit_FORTRAN.html\n # SPK Required Reading : http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/req/spk.html\n #\n # Original FORTRAN code uses 'SAVE' directive, and it means all variable\n # should be saved for next call. So i decided to make almost all\n # variables to be instance variable. Some of them are initialized in\n # __init__ method.\n\n STATE = np.zeros(6)\n\n # Variable I/O Description\n # -------- --- --------------------------------------------------\n # ET I Target epoch.\n # RECORD I Data record.\n # STATE O State (position and velocity).\n #\n # $ Detailed_Input\n #\n # ET is a target epoch, at which a state vector is to\n # be computed.\n #\n # RECORD is a data record which, when evaluated at epoch ET,\n # will give the state (position and velocity) of some\n # body, relative to some center, in some inertial\n # reference frame.\n #\n # $ Detailed_Output\n #\n # STATE is the state. Units are km and km/sec.\n #\n # $ Parameters\n #\n # None.\n #\n # $ Exceptions\n #\n # None.\n #\n # $ Files\n #\n # None.\n #\n # $ Particulars\n #\n # The exact format and structure of type 1 (difference lines)\n # segments are described in the SPK Required Reading file.\n #\n # Difference lines (DL's) are generated by JPL navigation\n # system programs P and PV. Each data record is equivalent\n # to the (slightly rearranged) 'P' portion of a NAVIO PV file\n # data record.\n #\n # SPKE01 is a specialized version of Fred Krogh's subroutine DAINT.\n # Only the calling sequence has been changed.\n #\n # Because the original version was undocumented, only Fred\n # knows how this really works.\n #\n # $ Examples\n #\n # None.\n #\n # $ Restrictions\n #\n # Unknown.\n #\n # $ Literature_References\n #\n # NAIF Document 168.0, \"S- and P- Kernel (SPK) Specification and\n # User's Guide\"\n #\n # $ Author_and_Institution\n #\n # F.T. Krogh (JPL)\n # I.M. Underwood (JPL)\n #\n # $ Version\n #\n # - SPICELIB Version 1.1.0, 14-FEB-1997 (WLT)\n #\n # The goto's were removed and loop and if structures\n # revealed. We still don't know exactly what's going\n # on, but at least the bones of this routine have been\n # cleaned off and are ready for assembly. (WLT)\n #\n # - SPICELIB Version 1.0.4, 30-OCT-1996 (WLT)\n #\n # Removed redundant SAVE statements from the declaration\n # section. Thanks to Steve Schlaifer for finding this\n # error.\n #\n # - SPICELIB Version 1.0.3, 10-MAR-1992 (WLT)\n #\n # Comment section for permuted index source lines was added\n # following the header.\n #\n # - SPICELIB Version 1.0.2, 23-AUG-1991 (HAN)\n #\n # SPK01 was removed from the Required_Reading section of the\n # header. The information in the SPK01 Required Reading file\n # is now part of the SPK Required Reading file.\n #\n # - SPICELIB Version 1.0.1, 22-MAR-1990 (HAN)\n #\n # Literature references added to the header.\n #\n # - SPICELIB Version 1.0.0, 31-JAN-1990 (IMU) (FTK)\n #\n # -&\n #\n # $ Index_Entries\n #\n # evaluate type_1 spk segment\n #\n # -&\n\n\n\n #\n # Unpack the contents of the MDA array.\n #\n # Name Dimension Description\n # ------ --------- -------------------------------\n # TL 1 Final epoch of record\n # G 15 Stepsize function vector\n # REFPOS 3 Reference position vector\n # REFVEL 3 Reference velocity vector\n # DT 15,NTE Modified divided difference arrays\n # KQMAX1 1 Maximum integration order plus 1\n # KQ NTE Integration order array\n #\n # For our purposes, NTE is always 3.\n #\n self.TL = RECORD[0]\n self.G = RECORD[1:1 + 15]\n #\n # Collect the reference position and velocity.\n #\n self.REFPOS[0] = RECORD[16]\n self.REFVEL[0] = RECORD[17]\n\n self.REFPOS[1] = RECORD[18]\n self.REFVEL[1] = RECORD[19]\n\n self.REFPOS[2] = RECORD[20]\n self.REFVEL[2] = RECORD[21]\n\n self.DT = np.reshape(RECORD[22:22 + 45], (15, 3), order='F')\n\n self.KQMAX1 = int(RECORD[67])\n self.KQ[0] = int(RECORD[68])\n self.KQ[1] = int(RECORD[69])\n self.KQ[2] = int(RECORD[70])\n #\n # Next we set up for the computation of the various differences\n #\n self.DELTA = ET - self.TL\n self.TP = self.DELTA\n self.MQ2 = self.KQMAX1 - 2\n self.KS = self.KQMAX1 - 1\n #\n # This is clearly collecting some kind of coefficients.\n # The problem is that we have no idea what they are...\n #\n # The G coefficients are supposed to be some kind of step size\n # vector.\n #\n # TP starts out as the delta t between the request time\n # and the time for which we last had a state in the MDL file.\n # We then change it from DELTA by the components of the stepsize\n # vector G.\n #\n for J in range(1, self.MQ2 + 1):\n self.FC[J] = self.TP / self.G[J - 1]\n self.WC[J - 1] = self.DELTA / self.G[J - 1]\n self.TP = self.DELTA + self.G[J - 1]\n #\n # Collect KQMAX1 reciprocals.\n #\n for J in range(1, self.KQMAX1 + 1):\n self.W[J - 1] = 1.0 / float(J)\n #\n # Compute the W(K) terms needed for the position interpolation\n # (Note, it is assumed throughout this routine that KS, which\n # starts out as KQMAX1-1 (the ``maximum integration'')\n # is at least 2.\n #\n self.JX = 0\n self.KS1 = self.KS - 1\n\n while self.KS >= 2:\n\n self.JX = self.JX + 1\n\n for J in range(1, self.JX + 1):\n self.W[J + self.KS - 1] = self.FC[J] * self.W[J + self.KS1 - 1] - self.WC[J - 1] * self.W[\n J + self.KS - 1]\n\n self.KS = self.KS1\n self.KS1 = self.KS1 - 1\n #\n # Perform position interpolation: (Note that KS = 1 right now.\n # We don't know much more than that.)\n #\n for I in range(1, 3 + 1):\n\n self.KQQ = self.KQ[I - 1]\n self.SUM = 0.0\n\n for J in range(self.KQQ, 0, -1):\n self.SUM = self.SUM + self.DT[J - 1, I - 1] * self.W[J + self.KS - 1]\n\n #x=x0+delta*dx0+delta**2*sum\n STATE[I - 1] = self.REFPOS[I - 1] + self.DELTA * (self.REFVEL[I - 1] + self.DELTA * self.SUM)\n #\n # Again we need to compute the W(K) coefficients that are\n # going to be used in the velocity interpolation.\n # (Note, at this point, KS = 1, KS1 = 0.)\n #\n for J in range(1, self.JX + 1):\n self.W[J + self.KS - 1] = self.FC[J] * self.W[J + self.KS1 - 1] - self.WC[J - 1] * self.W[J + self.KS - 1]\n\n self.KS = self.KS - 1\n\n #\n # Perform velocity interpolation:\n #\n for I in range(1, 3 + 1):\n self.KQQ = self.KQ[I - 1]\n self.SUM = 0.0\n\n for J in range(self.KQQ, 0, -1):\n self.SUM = self.SUM + self.DT[J - 1, I - 1] * self.W[J + self.KS - 1]\n\n STATE[I + 3 - 1] = self.REFVEL[I - 1] + self.DELTA * self.SUM\n\n #\n # That's all folks. We don't know why we did anything, but\n # at least we can tell structurally what we did.\n #\n\n return STATE\n\nclass daf_CK01line:\n def __init__(self,clknum,N,i,buf,rates):\n self.clknum=clknum\n self.rates=rates\n self.csvheader=\"SCLK,SCLK*,ET*,ETCAL*,q0,q1,q2,q3\"\n if self.rates:\n self.n_elements = 7\n self.w = buf[i * self.n_elements+4:(i + 1) * self.n_elements]\n self.csvheader+=\",wx,wy,wz\"\n else:\n self.n_elements=4\n self.q = buf[i * self.n_elements:i * self.n_elements+4]\n\n self.sclk=buf[N*self.n_elements+i]\n self.et =cspice_sct2e(self.clknum,self.sclk)\n def __str__(self):\n result=\"%25.15e\"%self.sclk\n try:\n et=cspice_sct2e(self.clknum, self.sclk)\n result+=\",%s,%16.6f,%s\" %(cspice_scdecd(self.clknum,self.sclk),et,cspice_etcal(et))\n except:\n result+=\",,,\"\n for i in range(4):\n result+=\",%25.15e\"%self.q[i]\n if self.rates:\n for i in range(3):\n result += \",%25.15e\" % self.w[i]\n else:\n result+=\",,,\"\n return result\n\nclass daf_CK02line:\n def __init__(self,clknum,N,i,buf):\n self.clknum=clknum\n self.n_elements = 8\n self.w = buf[i * self.n_elements+4:i * self.n_elements+7]\n self.q = buf[i * self.n_elements:i * self.n_elements+4]\n self.rate=buf[i*self.n_elements+7]\n self.sclk=buf[N*self.n_elements+i]\n self.sclk1=buf[N*self.n_elements+N+i]\n self.et =cspice_sct2e(self.clknum,self.sclk)\n self.et1 =cspice_sct2e(self.clknum,self.sclk1)\n self.csvheader=\"SCLK,SCLK*,SCLK1,SCLK1*,ET*,ETCAL*,ET1*,ETCAL1*,q0,q1,q2,q3,wx,wy,wz,rate\"\n def __str__(self):\n result=\"%25.15e\"%self.sclk\n result+=\",%s,%25.15e,%s,%16.6f,%s,%16.6f,%s\" %(cspice_scdecd(self.clknum,self.sclk),self.sclk1,cspice_scdecd(self.clknum,self.sclk1),self.et,cspice_etcal(self.et),self.et1,cspice_etcal(self.et1))\n for i in range(4):\n result+=\",%25.15e\"%self.q[i]\n for i in range(3):\n result += \",%25.15e\" % self.w[i]\n result += \",%25.15e\" % self.rate\n return result\n\nclass daf_CK03line:\n def __init__(self,clknum,N,i,buf,rates):\n self.clknum=clknum\n self.rates=rates\n self.csvheader=\"SCLK,SCLK*,ET*,ETCAL*,q0,q1,q2,q3\"\n if self.rates:\n self.n_elements = 7\n self.w = buf[i * self.n_elements+4:(i + 1) * self.n_elements]\n self.csvheader+=\",wx,wy,wz\"\n else:\n self.n_elements=4\n self.q = buf[i * self.n_elements:i * self.n_elements+4]\n\n self.sclk=buf[N*self.n_elements+i]\n self.et =cspice_sct2e(self.clknum,self.sclk)\n def __str__(self):\n result=\"%25.15e\"%self.sclk\n try:\n et=cspice_sct2e(self.clknum, self.sclk)\n result+=\",%s,%16.6f,%s\" %(cspice_scdecd(self.clknum,self.sclk),et,cspice_etcal(et))\n except:\n result+=\",,,\"\n for i in range(4):\n result+=\",%25.15e\"%self.q[i]\n if self.rates:\n for i in range(3):\n result += \",%25.15e\" % self.w[i]\n else:\n result+=\",,,\"\n return result\n\nclass daf_summary_record:\n def __init__(self,parent):\n \"\"\"\n Read a record from a file-like object opened in binary mode\n :param parent: object of class daf\n \"\"\"\n self.parent=parent\n self.dformat=self.parent.dformat\n self.buf=self.read(1024) #Read the whole block first\n self.namebuf=self.read(1024) #Read the name record next\n self.NEXT=int(struct.unpack(self.dformat,self.buf[ 0: 0+8])[0]) #Address of next summary record in file (zero if last)\n self.PREV=int(struct.unpack(self.dformat,self.buf[ 8: 8+8])[0]) #Address of prev summary record in file (zero if first)\n self.NSUM=int(struct.unpack(self.dformat,self.buf[16:16+8])[0]) #Number of summaries actually in this summary record\n self.SS=self.parent.SS\n def read(self,len):\n return self.parent.inf.read(len)\n def tell(self):\n return self.parent.inf.tell()\n def __iter__(self):\n for i in range(self.NSUM):\n result = daf_summary.make(self,self.parent,self.buf[8*(3+i*self.SS):8*(3+(i+1)*self.SS)],str(self.namebuf[i*self.parent.NC:(i+1)*self.parent.NC],encoding=\"cp437\").strip(\" \\t\\n\\r\\0\"))\n yield result\n def __str__(self):\n result=((\"NEXT: %d\\n\" +\n \"PREV: %s\\n\" +\n \"NSUM: %d\") %\n (self.NEXT,self.PREV,self.NSUM))\n return result\n\nclass double_array_file:\n def __init__(self,inf):\n \"\"\"\n Read a double-array file. This class reads the DAF header itself, and delegates reading the\n records, comments, and data. It therefore has fields representing the header, and lists\n of other class objects representing the data.\n :param inf: string filename or file-like object\n \"\"\"\n try:\n self.inf=open(inf,\"rb\")\n self.needToClose=True\n except TypeError:\n self.inf=inf\n self.needToClose=False\n buf=self.inf.read(1024) #Read the whole header record first\n self.LOCIDW=str(buf[0:0+8],encoding='ASCII')\n if self.LOCIDW[0:4]==\"NAIF\":\n print(\"Old kernel type - guessing \")\n self.subtype=\"CK\"\n elif self.LOCIDW[0:4]!=\"DAF/\":\n raise ValueError(\"Not a DAF: Header is %s\"%self.LOCIDW)\n else:\n self.subtype=self.LOCIDW[4:8].strip(\" \\t\\n\\r\\0\")\n self.LOCFMT=str(buf[88:88+8],encoding='ASCII') #IEEE format string\n if self.LOCFMT==\"LTL-IEEE\":\n self.endian=\"<\"\n elif self.LOCFMT==\"BIG-IEEE\":\n self.endian=\">\"\n else:\n raise ValueError(\"Unknown double-precision format %s\"%self.LOCFMT)\n self.iformat=self.endian+\"i\"\n self.dformat=self.endian+\"d\"\n self.ND=struct.unpack(self.iformat,buf[ 8: 8+4])[0] #Address 8, number of components in each array summary\n self.NI=struct.unpack(self.iformat,buf[12:12+4])[0] #Address 12, number of integer components in each array summary\n self.LOCIFN=str(buf[16:16+60],encoding='ASCII') #Address 16, internal name or description of array file\n self.FWARD=struct.unpack(self.iformat,buf[76:76+4])[0] #Address 76, record number of initial summary in the file\n self.BWARD=struct.unpack(self.iformat,buf[80:80+4])[0] #Address 80, record number of final summary in the file\n self.FREE=struct.unpack(self.iformat,buf[84:84+4])[0] #Address 84, first free address in file\n self.FTPSTR=str(buf[700:700+28],encoding='cp437') #Address 700, FTP validation string\n self.NC = 8 * (self.ND + (self.NI + 1) // 2)\n self.SS = self.ND + (self.NI + 1) // 2 # Size of a summary\n self.NS = 125 // self.SS # Maximum number of summaries per summary record\n def __enter__(self):\n return self\n def __exit__(self,type,value,traceback):\n if self.needToClose:\n self.inf.close()\n def __str__(self):\n result=((\"LOCIDW: %s\\n\"+\n \"ND: %d\\n\"+\n \"NI: %d\\n\" +\n \"NC*: %d\\n\"+\n \"SS*: %d\\n\" +\n \"NS*: %d\\n\"+\n \"LOCIFN: %s\\n\" +\n \"FWARD: %d\\n\" +\n \"BWARD: %d\\n\" +\n \"FREE: %d\\n\" +\n \"LOCFMT: %s\") %\n (self.LOCIDW,self.ND,self.NI,self.NC,self.SS,self.NS,self.LOCIFN,self.FWARD,self.BWARD,self.FREE,self.LOCFMT))\n return result\n def __iter__(self):\n #Seek to the first summary record\n self.inf.seek((self.FWARD-1)*1024) #One for one-based, one for header record at beginning of file\n done=False\n while not done:\n result=daf_summary_record(self)\n yield result\n if result.NEXT==0:\n done=True\n else:\n self.inf.seek((result.NEXT-1)*1024)\n def dump(self,dump_lines=True,dump_comments=True):\n print(str(self))\n if dump_comments:\n for line in self.comments():\n print('\"'+line+'\"')\n for i,sr in enumerate(self):\n print(\"Summary record %d\"%i)\n print(str(sr))\n for j,sum in enumerate(sr):\n print(\"Summary %d\" % j)\n print(str(sum))\n print(str(sum.segment()))\n if dump_lines:\n print(\"i*,dt,\" + sum.segment().csvheader)\n et0=sum.et0\n for k,line in enumerate(sum.segment()):\n dt=line.et-et0\n print(k,\",%15.6f,\"%dt,str(line))\n# tval=line.test(et0)\n# if True: #(tval>1e-10):\n# print(line.et-et0,\",\",tval)\n et0=line.et\n def comments(self):\n block=1\n done=False\n line=\"\"\n while not done:\n self.inf.seek(block*1024)\n bb=self.inf.read(1000)\n for b in bb:\n if b==0:\n yield line\n line=\"\"\n elif b==4:\n yield line\n return\n else:\n line+=chr(b)\n block+=1\n\ndef spkdump():\n import argparse\n parser=argparse.ArgumentParser(description=\"Translate a Spice Double-Array File (DAF) into plain text\")\n parser.add_argument('-x','--records',action='store_true',help=\"Dump all data records. May result in a very large amount of output!\")\n parser.add_argument('-r','--comment',action='store_true',help=\"Dump file comments.\")\n parser.add_argument('-a','--all',action='store_true',help=\"Dump everything that can be dumped\")\n parser.add_argument('inf',nargs=1,help=\"Kernel to translate. Must be a bc or bsp kernel.\")\n parser.add_argument('kernel',nargs='*',help=\"Kernels to furnish. Typically these are sclk and/or lsk files, needed to interpret bc timestamps\")\n result=parser.parse_args()\n dump_lines=result.records or result.all\n dump_comments=result.comment or result.all\n inf=result.inf[0]\n\n from spiceypy import furnsh as cspice_furnsh\n for furnsh in result.kernel:\n cspice_furnsh(furnsh)\n with double_array_file(inf) as in_daf:\n cspice_furnsh(inf) #Just to run the test\n in_daf.dump(dump_lines=dump_lines,dump_comments=dump_comments)\n# with double_array_file(\"../../Data/spice/insight/insight_nom_2016e09o_edl_v1.bsp\") as in_daf:\n# in_daf.dump(dump_lines)\n# with double_array_file(\"../../Data/spice/phoenix/phx_edl_rec_traj.bsp\") as in_daf:\n# in_daf.dump(dump_lines)\n\nif __name__==\"__main__\":\n spkdump()\n", "meta": {"hexsha": "9d2f73a0de2f881ac9e19549dac7758338385192", "size": 40821, "ext": "py", "lang": "Python", "max_stars_repo_path": "kwanspice/daf.py", "max_stars_repo_name": "kwan3217/kwanspice", "max_stars_repo_head_hexsha": "38303ff516dabf965cdc754c48290187cc237da3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kwanspice/daf.py", "max_issues_repo_name": "kwan3217/kwanspice", "max_issues_repo_head_hexsha": "38303ff516dabf965cdc754c48290187cc237da3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kwanspice/daf.py", "max_forks_repo_name": "kwan3217/kwanspice", "max_forks_repo_head_hexsha": "38303ff516dabf965cdc754c48290187cc237da3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7478091529, "max_line_length": 203, "alphanum_fraction": 0.5511868891, "include": true, "reason": "import numpy", "num_tokens": 11739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961013, "lm_q2_score": 0.24220562872535945, "lm_q1q2_score": 0.13709287518737873}} {"text": "#!/usr/bin/env python\n\nimport os\nimport sys\nimport time\nimport pdb\nimport argparse\nimport numpy\nimport crowdsource.psf as psfmod\nfrom astropy.io import fits\nimport crowdsource\nfrom unwise_psf import unwise_psf\n# implicit dependency for WISE runs only\n# https://github.com/legacysurvey/unwise_psf\nimport crowdsource.unwise_primary as unwise_primary\nfrom astropy import wcs\nfrom collections import OrderedDict\nfrom pkg_resources import resource_filename\n\n\nextrabits = {'crowdsat': 2**25,\n 'nebulosity': 2**26,\n 'w1brightoffedge': 2**7,\n 'w2brightoffedge': 2**8,\n 'hyperleda': 2**9}\n\nnodeblend_bits = extrabits['hyperleda']\nsharp_bits = (extrabits['w1brightoffedge'] | extrabits['w2brightoffedge'])\n\n\ndef wise_filename(basedir, coadd_id, band, _type, uncompressed=False,\n drop_first_dir=False, epoch=-1):\n # type should be one of:\n # 'img-u', 'img-m', 'invvar-u', 'invvar-m', 'std-u', 'std-m'\n # 'n-u', 'n-m', 'frames', 'msk'\n\n # -msk is special because the info for both W1/W2 is in same file\n\n fname = 'unwise-' + coadd_id\n if _type != 'msk':\n fname += '-w' + str(band)\n\n fname += ('-' + _type + '.fits')\n\n path = [basedir, coadd_id[0:3], coadd_id, fname]\n if drop_first_dir:\n del path[1]\n if epoch >= 0:\n epochstr = 'e%03d' % epoch if _type != 'msk' else 'fulldepth'\n path = path[0:1] + [epochstr] + path[1:]\n fname = os.path.join(*path)\n\n if not uncompressed or _type == 'msk':\n if (_type != 'img-u') and (_type != 'img-m') and (_type != 'frames'):\n fname += '.gz'\n\n return fname\n\n\ndef read_blist(brightstars, raim, decim, hdr, maxsep):\n from astropy.coordinates.angle_utilities import angular_separation\n sep = angular_separation(numpy.radians(brightstars['ra']),\n numpy.radians(brightstars['dec']),\n numpy.radians(raim),\n numpy.radians(decim))\n sep = numpy.degrees(sep)\n m = (sep < 3) & (brightstars['k_m'] < 5)\n brightstars = brightstars[m]\n wcs0 = wcs.WCS(hdr)\n yy, xx = wcs0.all_world2pix(brightstars['ra'], brightstars['dec'], 0)\n m = (xx > 0) & (xx < hdr['NAXIS1']) & (yy > 0) & (yy < hdr['NAXIS2'])\n xx, yy = xx[m], yy[m]\n mag = brightstars['k_m'][m]\n if not numpy.any(m):\n return None\n else:\n return [xx, yy, mag]\n\n\ndef massage_isig_and_dim(isig, im, flag, band, nm, nu, fac=None):\n \"\"\"Construct a WISE inverse sigma image and add saturation to flag.\n\n unWISE provides nice inverse variance maps. These however have no\n contribution from Poisson noise from sources, and so underestimate\n the uncertainties dramatically in bright regions. This can pull the\n whole fit awry in bright areas, since the sky model means that every\n pixel feels every other pixel.\n\n It's not clear what the best solution is. We make a goofy inverse\n sigma image from the original image and the inverse variance image. It\n is intended to be sqrt(ivar) for the low count regime and grow like\n sqrt(1/im) for the high count regime. The constant of proportionality\n should in principle be worked out; here I set it to 0.15, which worked\n once, and it doesn't seem like this should depend much on which\n WISE exposure the image came from? It's ultimately something like the gain\n or zero point...\n \"\"\"\n\n if fac is None:\n bandfacs = {1: 0.15, 2: 0.3}\n bandfloors = {1: 0.5, 2: 2}\n fac = bandfacs[band]\n floor = bandfloors[band]\n\n satbit = 16 if band == 1 else 32\n satlimit = 85000 # if band == 1 else 130000\n msat = ((flag & satbit) != 0) | (im > satlimit) | ((nm == 0) & (nu > 1))\n from scipy.ndimage import morphology\n # dilate = morphology.iterate_structure(\n # morphology.generate_binary_structure(2, 1), 3)\n xx, yy = numpy.mgrid[-3:3+1, -3:3+1]\n dilate = xx**2+yy**2 <= 3**2\n msat = morphology.binary_dilation(msat, dilate)\n isig[msat] = 0\n flag = flag.astype('i8')\n # zero out these bits; we claim them for our own purposes.\n massagebits = (extrabits['crowdsat'] | crowdsource.nodeblend_maskbit |\n crowdsource.sharp_maskbit | extrabits['nebulosity'])\n flag &= ~massagebits\n flag[msat] |= extrabits['crowdsat']\n flag[(flag & nodeblend_bits) != 0] |= crowdsource.nodeblend_maskbit\n flag[(flag & sharp_bits) != 0] |= crowdsource.sharp_maskbit\n\n sigma = numpy.sqrt(1./(isig + (isig == 0))**2 + floor**2 +\n fac**2*numpy.clip(im, 0, numpy.inf))\n sigma[msat] = numpy.inf\n sigma[isig == 0] = numpy.inf\n return (1./sigma).astype('f4'), flag\n\n\ndef wise_psf_stamp(band, nosmooth=False):\n # psf noise: ~roughly 0.1 count in outskirts of W1 and W2\n if band >= 3:\n raise ValueError('Need to stare at W3+ PSF more!')\n psfnoise = 0.1\n stampfn = resource_filename('unwise_psf',\n 'data/psf_model_w'+str(band)+'.fits')\n stamp = fits.getdata(stampfn)\n edges = numpy.concatenate([stamp[0, 1:-1], stamp[-1, 1:-1],\n stamp[1:-1, 0], stamp[1:-1, -1]])\n medval = numpy.median(edges[edges != 0]) / 2\n stamp[stamp == 0] = medval\n stamp -= medval\n from scipy import signal\n stamp[stamp < 0] = 0.\n # suppress spurious warnings in signal.wiener\n olderr = numpy.seterr(invalid='ignore', divide='ignore')\n # update to scipy.signal means that Wiener filter uses an FFT\n # to perform the various convolutions, which causes bad errors\n # here unless we cast to f8. It's not that hard to do something\n # a bit better than scipy.signal.wiener---morally we really want to do\n # something like smooth in log space on radial lines---but I don't\n # want to go further down that rabbit hole today.\n stamp = signal.wiener(stamp.astype('f8'), 11, psfnoise)\n stamp = stamp.astype('f4')\n numpy.seterr(**olderr)\n # taper linearly over outer 60 pixels?\n stampszo2 = stamp.shape[0] // 2\n xx, yy = numpy.mgrid[-stampszo2:stampszo2+1, -stampszo2:stampszo2+1]\n edgedist = numpy.clip(stampszo2-numpy.abs(xx), 0,\n stampszo2-numpy.abs(yy))\n stamp = stamp * numpy.clip(edgedist / 60., stamp < 10, 1)\n import psf\n stamp = psf.center_psf(stamp, censize=19)\n stamp = stamp / numpy.sum(stamp)\n return stamp\n\n\ndef wise_psf(band, coadd_id):\n stamp = wise_psf_stamp(band)\n stamp = unwise_psf.rotate_using_rd(stamp, coadd_id)\n psf = psfmod.SimplePSF(stamp)\n from functools import partial\n psf.fitfun = partial(psfmod.wise_psf_fit, psfstamp=stamp)\n return psf\n\n\ndef wise_psf_grid(band, coadd_id, basedir, uncompressed=False,\n drop_first_dir=False, ngrid=None, epoch=-1):\n imagefn = wise_filename(basedir, coadd_id, band, 'img-m',\n uncompressed=uncompressed,\n drop_first_dir=drop_first_dir, epoch=epoch)\n hdr = fits.getheader(imagefn)\n if ngrid is None:\n rr, dd = hdr['CRVAL1'], hdr['CRVAL2']\n from astropy.coordinates import SkyCoord\n from astropy import units as u\n coord = SkyCoord(ra=rr*u.deg, dec=dd*u.deg, frame='icrs')\n coord = coord.geocentrictrueecliptic\n lam, bet = coord.lon.deg, coord.lat.deg\n dlam = 1.4/(numpy.abs(numpy.cos(numpy.radians(bet)))+1e-6)\n ngrid = numpy.floor(numpy.clip(dlam / 1, 4, 16)).astype('i4')\n x = numpy.linspace(0, 2047, ngrid)\n y = numpy.linspace(0, 2047, ngrid)\n wcs0 = wcs.WCS(hdr)\n stamp = wise_psf_stamp(band).astype('f4')\n stamps = numpy.zeros((len(x), len(y))+stamp.shape, dtype=stamp.dtype)\n unwise_psf.rotate_using_convolution.cache = None # clear cache\n for i in range(len(x)):\n for j in range(len(y)):\n rr, dd = wcs0.all_pix2world(y[j], x[i], 0)\n stamps[i, j, ...] = unwise_psf.rotate_using_rd(\n stamp, coadd_id, ra=rr, dec=dd, cache=True)\n psf = psfmod.GridInterpPSF(stamps, x, y)\n from functools import partial\n psf.fitfun = partial(psfmod.wise_psf_fit, psfstamp=(stamps, x, y),\n grid=True)\n return psf\n\n\ndef read_wise(coadd_id, band, basedir, uncompressed=False,\n drop_first_dir=False, epoch=-1):\n assert((band == 1) or (band == 2))\n assert(len(coadd_id) == 8)\n\n imagefn = wise_filename(basedir, coadd_id, band, 'img-m',\n uncompressed=uncompressed,\n drop_first_dir=drop_first_dir, epoch=epoch)\n ivarfn = wise_filename(basedir, coadd_id, band, 'invvar-m',\n uncompressed=uncompressed,\n drop_first_dir=drop_first_dir, epoch=epoch)\n flagfn = wise_filename(basedir, coadd_id, band, 'msk',\n uncompressed=uncompressed,\n drop_first_dir=drop_first_dir, epoch=epoch)\n nmfn = wise_filename(basedir, coadd_id, band, 'n-m',\n uncompressed=uncompressed,\n drop_first_dir=drop_first_dir, epoch=epoch)\n nufn = wise_filename(basedir, coadd_id, band, 'n-u',\n uncompressed=uncompressed,\n drop_first_dir=drop_first_dir, epoch=epoch)\n\n im, hdr = fits.getdata(imagefn, header=True)\n sqivar = numpy.sqrt(fits.getdata(ivarfn))\n flag = fits.getdata(flagfn)\n nm = fits.getdata(nmfn)\n nu = fits.getdata(nufn)\n sqivar, flag = massage_isig_and_dim(sqivar, im, flag, band, nm, nu)\n return im, sqivar, flag, hdr\n\n\ndef ivarmap(isig, psfstamp):\n from scipy.signal import fftconvolve\n ivarim = fftconvolve(isig**2., psfstamp[::-1, ::-1]**2., mode='same')\n return ivarim\n\n\ndef brightlist(brightstars, coadd_id, band, basedir, uncompressed=False,\n drop_first_dir=False, epoch=-1):\n imagefn = wise_filename(basedir, coadd_id, band, 'img-m',\n uncompressed=uncompressed,\n drop_first_dir=drop_first_dir, epoch=epoch)\n hdr = fits.getheader(imagefn)\n blist = read_blist(brightstars, hdr['CRVAL1'], hdr['CRVAL2'], hdr, 3)\n return blist\n\n\ndef collapse_unwise_bitmask(bitmask, band):\n # 2^0 = bright star core and wings\n # 2^1 = PSF-based diffraction spike\n # 2^2 = optical ghost\n # 2^3 = first latent\n # 2^4 = second latent\n # 2^5 = AllWISE-like circular halo\n # 2^6 = bright star saturation\n # 2^7 = geometric diffraction spike\n\n assert((band == 1) or (band == 2))\n\n bits_w1 = OrderedDict([('core_wings', 2**0 + 2**1),\n ('psf_spike', 2**27),\n ('ghost', 2**25 + 2**26),\n ('first_latent', 2**13 + 2**14),\n ('second_latent', 2**17 + 2**18),\n ('circular_halo', 2**23),\n ('saturation', 2**4),\n ('geom_spike', 2**29)])\n\n bits_w2 = OrderedDict([('core_wings', 2**2 + 2**3),\n ('psf_spike', 2**28),\n ('ghost', 2**11 + 2**12),\n ('first_latent', 2**15 + 2**16),\n ('second_latent', 2**19 + 2**20),\n ('circular_halo', 2**24),\n ('saturation', 2**5),\n ('geom_spike', 2**30)])\n\n bits = (bits_w1 if (band == 1) else bits_w2)\n\n # hack to handle both scalar and array inputs\n result = 0*bitmask\n\n for i, feat in enumerate(bits.keys()):\n result += (2**i)*(numpy.bitwise_and(bitmask, bits[feat]) != 0)\n\n # int8 would be fine here, but astropy.io.fits seems to read this\n # as a boolean... so we waste the extra 8 bits.\n return result.astype('i2')\n\n\ndef collapse_extraflags(bitmask, band):\n bits_w1 = OrderedDict([('bright_off_edge', 2**7),\n ('resolved_galaxy', 2**9),\n ('big_object', 2**10),\n ('possible_bright_star_centroid', 2**21),\n ('crowdsat', extrabits['crowdsat']),\n ('nebulosity', extrabits['nebulosity']),\n ('nodeblend', crowdsource.nodeblend_maskbit),\n ('sharp', crowdsource.sharp_maskbit)])\n\n bits_w2 = OrderedDict([('bright_off_edge', 2**8),\n ('resolved_galaxy', 2**9),\n ('big_object', 2**10),\n ('possible_bright_star_centroid', 2**22),\n ('crowdsat', extrabits['crowdsat']),\n ('nebulosity', extrabits['nebulosity']),\n ('nodeblend', crowdsource.nodeblend_maskbit),\n ('sharp', crowdsource.sharp_maskbit)])\n\n bits = (bits_w1 if (band == 1) else bits_w2)\n\n # hack to handle both scalar and array inputs\n result = 0*bitmask\n\n for i, feat in enumerate(bits.keys()):\n result += (2**i)*(numpy.bitwise_and(bitmask, bits[feat]) != 0)\n\n # could fit in a byte, but astropy.io.fits reads these as booleans,\n # so we waste the byte...\n return result.astype('i2')\n\n\nif __name__ == \"__main__\":\n try:\n print('Running on host: ' + str(os.environ.get('HOSTNAME')))\n except Exception:\n print(\"Couldn't retrieve hostname!\")\n\n parser = argparse.ArgumentParser(description='Run crowdsource on unWISE coadd image')\n parser.add_argument('coadd_id', type=str, nargs=1)\n parser.add_argument('band', type=int, nargs=1)\n parser.add_argument('outfn', type=str, nargs=1)\n\n parser.add_argument('basedir', type=str, nargs='?', default='/global/projecta/projectdirs/cosmo/work/wise/outputs/merge/neo4/fulldepth')\n parser.add_argument('--refit-psf', '-r', default=False, action='store_true')\n parser.add_argument('--verbose', '-v', default=False, action='store_true')\n parser.add_argument('--uncompressed', '-u', default=False, action='store_true')\n parser.add_argument('--brightcat', '-b',\n default=os.environ.get('TMASS_BRIGHT', ''), type=str)\n parser.add_argument('--modelfn', '-m', default='', type=str,\n help='file name for model image, if desired')\n parser.add_argument('--infoimfn', '-i', default='', type=str,\n help='file name for info image, if desired')\n parser.add_argument('--masknebulosity', '-n', action='store_true')\n parser.add_argument('--forcecat', type=str, default='')\n parser.add_argument('--startsky', type=str, default='')\n parser.add_argument('--startpsf', type=str, default='')\n parser.add_argument('--noskyfit', default=False, action='store_true')\n parser.add_argument('--threshold', default=5, type=float,\n help='find sources down to threshold*sigma')\n parser.add_argument('--epoch', type=int, default=-1,\n help='epoch number of time-resolved WISE coadd')\n parser.add_argument('--release', type=str, default='')\n\n args = parser.parse_args()\n\n coadd_id = args.coadd_id[0]\n band = args.band[0]\n basedir = args.basedir\n\n im, sqivar, flag, hdr = read_wise(coadd_id, band, basedir,\n uncompressed=args.uncompressed,\n epoch=args.epoch)\n if len(args.startsky) > 0:\n startsky = fits.getdata(args.startsky, 'SKY')\n else:\n startsky = numpy.nan\n flag_orig = fits.getdata(wise_filename(basedir, coadd_id, band, 'msk',\n uncompressed=args.uncompressed,\n epoch=args.epoch))\n\n if args.masknebulosity:\n import nebulosity_mask\n nebfn = os.path.join(os.environ['WISE_DIR'], 'dat', 'nebnet',\n 'weights1', '1st_try')\n nebmod = nebulosity_mask.load_model(nebfn)\n nebmask = nebulosity_mask.gen_mask_wise(nebmod, im) == 2\n if numpy.any(nebmask):\n flag |= nebmask * extrabits['nebulosity']\n flag |= nebmask * crowdsource.sharp_maskbit\n print('Masking nebulosity, %5.2f' % (\n numpy.sum(nebmask)/1./numpy.sum(numpy.isfinite(nebmask))))\n\n psf = wise_psf_grid(band, coadd_id, basedir, epoch=args.epoch)\n if len(args.startpsf) > 0:\n startpsf = fits.getdata(args.startpsf, 'PSF').astype('f4')\n # there can be some endianness issues; astype('f4') converts to native\n modpsf = psf(1024, 1024, stampsz=psf.stamp.shape[-1])\n resid = startpsf-modpsf\n # need not sum to zero.\n newstamps = psf.stamp / psf.normstamp[:, :, None, None]\n newstamps += resid\n psf = psfmod.GridInterpPSF(newstamps, psf.x, psf.y)\n from functools import partial\n psf.fitfun = partial(psfmod.wise_psf_fit,\n psfstamp=(newstamps, psf.x, psf.y), grid=True)\n\n if len(args.brightcat) > 0:\n brightstars = fits.getdata(args.brightcat)\n blist = brightlist(brightstars, coadd_id, band, basedir,\n uncompressed=args.uncompressed, epoch=args.epoch)\n else:\n print('No bright star catalog, not marking bright stars.')\n blist = None\n\n if args.verbose:\n t0 = time.time()\n print('Starting %s, band %d, at %s' % (coadd_id, band, time.ctime()))\n sys.stdout.flush()\n\n if len(args.forcecat) == 0:\n res = crowdsource.fit_im(\n im, psf, weight=sqivar, dq=flag, refit_psf=args.refit_psf,\n verbose=args.verbose, ntilex=4, ntiley=4, derivcentroids=True,\n maxstars=30000*16, fewstars=50*16, blist=blist,\n threshold=args.threshold, psfvalsharpcutfac=0.5,\n psfsharpsat=0.8)\n else:\n forcecat = fits.getdata(args.forcecat, 1)\n x, y = forcecat['x'], forcecat['y']\n res = crowdsource.fit_im_force(\n im, x, y, psf, weight=sqivar, dq=flag, refit_psf=args.refit_psf,\n blist=blist, refit_sky=(not args.noskyfit),\n startsky=startsky, psfderiv=False, psfvalsharpcutfac=0.5,\n psfsharpsat=0.8)\n cat, model, sky, psf = res\n print('Finishing %s, band %d; %d sec elapsed.' %\n (coadd_id, band, time.time()-t0))\n\n outfn = args.outfn[0]\n\n x = cat['x']\n y = cat['y']\n\n wcs0 = wcs.WCS(hdr)\n ra, dec = wcs0.all_pix2world(y, x, 0)\n coadd_ids = numpy.zeros(len(ra), dtype='a8')\n bands = numpy.zeros(len(ra), dtype='i4')\n ids = numpy.zeros(len(ra), dtype='U20')\n coadd_ids[:] = coadd_id\n bands[:] = band\n if len(args.release) == 0:\n ids = ['%sw%1do%07d' % (coadd_id, band, num) for num in range(len(ra))]\n else:\n ids = ['%sw%1do%07dr%s' % (coadd_id, band, num, args.release)\n for num in range(len(ra))]\n\n nmfn = wise_filename(basedir, coadd_id, band, 'n-m',\n uncompressed=args.uncompressed, epoch=args.epoch)\n nmim = fits.getdata(nmfn)\n nms = crowdsource.extract_im(cat['x'], cat['y'], nmim)\n flags_unwise = crowdsource.extract_im(\n cat['x'], cat['y'], collapse_unwise_bitmask(flag_orig, band))\n flags_infoim = collapse_extraflags(flag, band)\n flags_info = crowdsource.extract_im(cat['x'], cat['y'], flags_infoim)\n # cast to i2; astropy.io.fits seems to fail for bools?\n primary = unwise_primary.is_primary(coadd_id, ra, dec).astype('i2')\n\n import numpy.lib.recfunctions as rfn\n cat = rfn.drop_fields(cat, ['flags'])\n cat = rfn.append_fields(\n cat, ['ra', 'dec', 'coadd_id', 'band', 'unwise_detid', 'nm',\n 'primary', 'flags_unwise', 'flags_info'],\n [ra, dec, coadd_ids, bands, ids, nms, primary, flags_unwise,\n flags_info])\n\n hdr['EXTNAME'] = 'PRIMARY'\n fits.writeto(outfn, None, hdr)\n fits.append(outfn, cat)\n if len(args.modelfn) > 0:\n hdulist = fits.open(args.modelfn, mode='append')\n compkw = {'compression_type': 'GZIP_1',\n 'quantize_method': 2, 'quantize_level': -0.5,\n 'tile_size': model.shape}\n hdr['EXTNAME'] = 'model'\n hdulist.append(fits.CompImageHDU(model, hdr, **compkw))\n hdr['EXTNAME'] = 'sky'\n hdulist.append(fits.CompImageHDU(sky, hdr, **compkw))\n hdulist.close(closed=True)\n\n if len(args.infoimfn) > 0:\n psffluxivar = ivarmap(sqivar, psf(1024, 1024, stampsz=59)).astype('f4')\n psfstamp = psf(1024, 1024, stampsz=325)\n hdulist = fits.open(args.infoimfn, mode='append')\n compkw = {'compression_type': 'GZIP_1',\n 'quantize_method': 2,\n 'tile_size': psffluxivar.shape}\n hdr['EXTNAME'] = 'psffluxivar'\n hdulist.append(fits.CompImageHDU(psffluxivar, hdr, **compkw))\n hdr['EXTNAME'] = 'infoflags'\n compkw = {'compression_type': 'GZIP_1',\n 'tile_size': flags_infoim.shape}\n # must recast flags_infoim as a u1; unsigned isn't supported\n # in tables, but signed int8 isn't supported in CompImageHDU.\n # ugh.\n hdulist.append(fits.CompImageHDU(flags_infoim.astype('u1'),\n hdr, **compkw))\n hdulist.append(fits.ImageHDU(psfstamp, None, name='psf'))\n hdulist.close(closed=True)\n", "meta": {"hexsha": "421274671b11208f066c6d4a2867687c2cfb8345", "size": 21298, "ext": "py", "lang": "Python", "max_stars_repo_path": "crowdsource/wise_proc.py", "max_stars_repo_name": "andrew-saydjari/crowdsource", "max_stars_repo_head_hexsha": "b88074f65d3887c0dfecd83814a8552902d8436a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2016-11-07T18:43:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-18T17:43:16.000Z", "max_issues_repo_path": "crowdsource/wise_proc.py", "max_issues_repo_name": "schlafly/crowdsource", "max_issues_repo_head_hexsha": "7b71ec60d9e3b2ab5992a915e42bb48bde148279", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-05-01T05:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T23:50:36.000Z", "max_forks_repo_path": "crowdsource/wise_proc.py", "max_forks_repo_name": "andrew-saydjari/crowdsource", "max_forks_repo_head_hexsha": "b88074f65d3887c0dfecd83814a8552902d8436a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2016-11-07T18:43:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-02T04:57:33.000Z", "avg_line_length": 41.8428290766, "max_line_length": 140, "alphanum_fraction": 0.5918865621, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 5917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.25982563796098374, "lm_q1q2_score": 0.13701035209446405}} {"text": "# Standard library\nimport os\nimport pickle\nfrom glob import glob\n\n# Third-party\nimport numpy as np\nfrom astropy import units as u\nfrom astropy.table import Table\n\n# Project\nfrom . import data_dir\n\n\n__all__ = ['phot_system_list',\n 'FilterSystem',\n 'get_filter_names',\n 'get_filter_properties',\n 'phot_system_lookup',\n 'load_zero_point_converter']\n\n\n# list of photometric systems with pre-calculated filter properties\nphot_system_list = [\n 'HST_WFC3', 'HST_ACSWF', 'SDSSugriz', 'CFHTugriz', 'DECam', 'HSC',\n 'JWST', 'LSST', 'UBVRIplus', 'UKIDSS', 'WFIRST'\n]\n\n\nclass FilterSystem(object):\n \"\"\"\n Class for calculating filter parameters from throughput curves.\n The parameter definitions are taken from\n `Fukugita et al. (1996) AJ 111, 1748.\n `_\n\n Parameters\n ----------\n filter_curve_files : list\n List of the file names of the filter curves.\n filter_names : str\n Names of filters. Must be the same length as ``filter_curve_files``.\n **kwargs\n Optional argumnets for `~numpy.loadtxt`, which is used to load the\n filter curve files.\n \"\"\"\n\n def __init__(self, filter_curve_files, filter_names, **kwargs):\n\n self.filter_names = filter_names\n for fn, name in zip(filter_curve_files, filter_names):\n data = np.loadtxt(fn, **kwargs)\n table = Table(data=data, names=['wave', 'trans'])\n setattr(self, name, table)\n self.filter_names.append(name)\n\n def _get_trans(self, bandpass):\n \"\"\"\n Get the filter throughput curve for the given bandpass.\n \"\"\"\n lam = getattr(self, bandpass)['wave']\n trans = getattr(self, bandpass)['trans']\n return lam, trans\n\n def effective_throughput(self, bandpass):\n \"\"\"\n Calculate the effective throughput for the given bandpass.\n\n Parameters\n ----------\n bandpass : str\n The name of the filter.\n\n Returns\n -------\n theff : float\n Effective effective throughput.\n \"\"\"\n lam, trans = self._get_trans(bandpass)\n theff = np.trapz(trans, np.log(lam))\n return theff\n\n def lam_eff(self, bandpass):\n \"\"\"\n Calculate effective wavelength for the given bandpass.\n\n Parameters\n ----------\n bandpass : str\n The name of the filter.\n\n Returns\n -------\n leff : float\n The effective wavelength.\n \"\"\"\n lam, trans = self._get_trans(bandpass)\n log_leff = np.trapz(np.log(lam) * trans, np.log(lam))\n log_leff /= np.trapz(trans, np.log(lam))\n leff = np.exp(log_leff) * u.angstrom\n return leff\n\n def lam_pivot(self, bandpass):\n \"\"\"\n Calculate pivot wavelength for the given bandpass.\n\n Parameters\n ----------\n bandpass : str\n The name of the filter.\n\n Returns\n -------\n lpivot : float\n The pivot wavelength.\n \"\"\"\n lam, trans = self._get_trans(bandpass)\n lpivot = np.trapz(lam * trans, lam)\n lpivot /= np.trapz(trans, np.log(lam))\n lpivot = np.sqrt(lpivot) * u.angstrom\n return lpivot\n\n def dlam(self, bandpass):\n \"\"\"\n Calculate the bandpass width.\n\n Parameters\n ----------\n bandpass : str\n The name of the filter.\n\n Returns\n -------\n width : float\n The bandpass width.\n \"\"\"\n lam, trans = self._get_trans(bandpass)\n norm = np.trapz(trans, lam)\n width = (norm / trans.max()) * u.angstrom\n return width\n\n\nclass ZeroPointConverter(object):\n \"\"\"\n Help class for converting between AB, ST, and Vega magnitudes & colors.\n\n Parameters\n ----------\n zpt_table : `~astropy.table.Table`\n MIST zero point table, which can be `downloaded here\n `_.\n \"\"\"\n\n def __init__(self, zpt_table):\n for f, system, v_to_st, v_to_ab in zpt_table:\n setattr(self, f, [system, v_to_st, v_to_ab])\n self.zpt_table = zpt_table\n\n def to_vega(self, bandpass):\n \"\"\"\n Convert to Vega magnitudes.\n\n Parameters\n ----------\n bandpass : str\n The name of the filter.\n\n Returns\n -------\n zpt_convert : float\n Zero point conversion magnitude.\n \"\"\"\n system, v_to_st, v_to_ab = getattr(self, bandpass)\n if system == 'Vega':\n zpt_convert = 0.\n elif system == 'AB':\n zpt_convert = -v_to_ab\n return zpt_convert\n\n def to_ab(self, bandpass):\n \"\"\"\n Convert to AB magnitudes.\n\n Parameters\n ----------\n bandpass : str\n The name of the filter.\n\n Returns\n -------\n zpt_convert : float\n Zero point conversion magnitude.\n \"\"\"\n system, v_to_st, v_to_ab = getattr(self, bandpass)\n if system == 'AB':\n zpt_convert = 0.\n elif system == 'Vega':\n zpt_convert = v_to_ab\n return zpt_convert\n\n def to_st(self, bandpass):\n \"\"\"\n Convert to ST magnitudes.\n\n Parameters\n ----------\n bandpass : str\n The name of the filter.\n\n Returns\n -------\n zpt_convert : float\n Zero point conversion magnitude.\n \"\"\"\n system, v_to_st, v_to_ab = getattr(self, bandpass)\n if system == 'AB':\n zpt_convert = v_to_st - v_to_ab\n elif system == 'Vega':\n zpt_convert = v_to_st\n return zpt_convert\n\n def color_to_vega(self, blue, red):\n \"\"\"\n Convert to Vega colors.\n\n Parameters\n ----------\n blue : str\n The name of the blue filter.\n red : str\n The name of the red filter.\n\n Returns\n -------\n zpt_convert : float\n Zero point conversion magnitude.\n \"\"\"\n blue_convert = self.to_vega(blue)\n red_convert = self.to_vega(red)\n return blue_convert - red_convert\n\n def color_to_ab(self, blue, red):\n \"\"\"\n Convert to AB colors.\n\n Parameters\n ----------\n blue : str\n The name of the blue filter.\n red : str\n The name of the red filter.\n\n Returns\n -------\n zpt_convert : float\n Zero point conversion magnitude.\n \"\"\"\n blue_convert = self.to_ab(blue)\n red_convert = self.to_ab(red)\n return blue_convert - red_convert\n\n def color_to_st(self, blue, red):\n \"\"\"\n Convert to ST colors.\n\n Parameters\n ----------\n blue : str\n The name of the blue filter.\n red : str\n The name of the red filter.\n\n Returns\n -------\n zpt_convert : float\n Zero point conversion magnitude.\n \"\"\"\n blue_convert = self.to_st(blue)\n red_convert = self.to_st(red)\n return blue_convert - red_convert\n\n\ndef get_filter_names(phot_system=None):\n \"\"\"\n Get MIST photometric systems and filter names.\n\n Parameters\n ----------\n phot_system : str or None\n The desired photometric system.\n\n Returns\n -------\n mist_filter_names : list or dict\n If ``phot_system`` given, then a list of filter names is returned. If\n ``phot_system`` is ``None``, then a dict of all photometric systems\n and filters is returned.\n \"\"\"\n fn = os.path.join(data_dir, 'mist_filter_names.pkl')\n pickle_in = open(fn, 'rb')\n mist_filter_names = pickle.load(pickle_in)\n pickle_in.close()\n if phot_system is not None:\n if type(phot_system) == str:\n phot_system = [phot_system]\n names = []\n for p in phot_system:\n names.extend(mist_filter_names[p])\n mist_filter_names = names\n return mist_filter_names\n\n\ndef get_filter_properties():\n \"\"\"\n\n \"\"\"\n pkl_fn = os.path.join(data_dir, 'filter_properties.pkl')\n with open(pkl_fn, 'rb') as pkl_file:\n data = pickle.load(pkl_file)\n props = Table(data)\n props['dlam'] *= u.angstrom\n props['lam_eff'] *= u.angstrom\n return props\n\n\ndef phot_system_lookup(filter_name=None):\n \"\"\"\n Lookup the photometric system name associated with a given filter name.\n\n Parameters\n ----------\n filter_name : str, optional\n Filter name to lookup.\n\n Returns\n -------\n lookup : dict or str\n If ``filter_name`` is ``None``, a dictionary with the filter names as\n keywords and the photometric systems as values. If ``filter_name`` is\n not ``None``, its photometric system is returned.\n \"\"\"\n fn = os.path.join(data_dir, 'phot_system_lookup.pkl')\n pickle_in = open(fn, 'rb')\n lookup = pickle.load(pickle_in)\n pickle_in.close()\n if filter_name is not None:\n lookup = lookup[filter_name]\n return lookup\n\n\ndef load_zero_point_converter():\n \"\"\"\n Create and return a `~artpop.filters.ZeroPointConverter` object.\n \"\"\"\n from astropy.io import ascii\n fn = os.path.join(data_dir, 'zeropoints.txt')\n table= ascii.read(fn)\n return ZeroPointConverter(table)\n", "meta": {"hexsha": "be0859e3fad6920471fee8e784686e1d61ab0af4", "size": 9430, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/artpop/filters.py", "max_stars_repo_name": "eteq/ArtPop", "max_stars_repo_head_hexsha": "c510d409196c4296024214c2e01766d1ca97b3dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2021-09-22T21:28:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T02:52:46.000Z", "max_issues_repo_path": "src/artpop/filters.py", "max_issues_repo_name": "eteq/ArtPop", "max_issues_repo_head_hexsha": "c510d409196c4296024214c2e01766d1ca97b3dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-12-16T17:43:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-07T20:12:13.000Z", "max_forks_repo_path": "src/artpop/filters.py", "max_forks_repo_name": "eteq/ArtPop", "max_forks_repo_head_hexsha": "c510d409196c4296024214c2e01766d1ca97b3dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-12-17T03:50:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T16:58:57.000Z", "avg_line_length": 26.2674094708, "max_line_length": 77, "alphanum_fraction": 0.5626723224, "include": true, "reason": "import numpy,from astropy", "num_tokens": 2163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.2598256264980406, "lm_q1q2_score": 0.1370103421897173}} {"text": "# coding: utf-8\n# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License\n\n\nimport re\nimport numpy as np\nimport warnings\nimport collections\nimport os\nfrom monty.io import zopen\nimport fnmatch\nfrom collections import defaultdict\nfrom pymatgen.electronic_structure.core import Spin, Orbital\nfrom pymatgen.io.vasp.outputs import Vasprun\nfrom pymatgen.electronic_structure.dos import Dos, LobsterCompleteDos\nfrom pymatgen.core.structure import Structure\nfrom pymatgen.electronic_structure.bandstructure import Kpoint\nfrom pymatgen.io.vasp.inputs import Kpoints\nfrom collections import OrderedDict\nfrom pymatgen.electronic_structure.bandstructure import LobsterBandStructureSymmLine\n\n\"\"\"\nModule for reading Lobster output files. For more information\non LOBSTER see www.cohp.de.\n\"\"\"\n\n__author__ = \"Marco Esters, Janine George\"\n__copyright__ = \"Copyright 2017, The Materials Project\"\n__version__ = \"0.2\"\n__maintainer__ = \"Marco Esters, Janine George\"\n__email__ = \"esters@uoregon.edu, janine.george@uclouvain.be\"\n__date__ = \"Dec 13, 2017\"\n\n\nclass Cohpcar:\n \"\"\"\n Class to read COHPCAR/COOPCAR files generated by LOBSTER.\n\n Args:\n are_coops: Determines if the file is a list of COHPs or COOPs.\n Default is False for COHPs.\n\n filename: Name of the COHPCAR file. If it is None, the default\n file name will be chosen, depending on the value of are_coops.\n\n\n .. attribute: cohp_data\n\n Dict that contains the COHP data of the form:\n {bond: {\"COHP\": {Spin.up: cohps, Spin.down:cohps},\n \"ICOHP\": {Spin.up: icohps, Spin.down: icohps},\n \"length\": bond length,\n \"sites\": sites corresponding to the bond}\n Also contains an entry for the average, which does not have\n a \"length\" key.\n\n .. attribute: efermi\n\n The Fermi energy in eV.\n\n .. attribute: energies\n\n Sequence of energies in eV. Note that LOBSTER shifts the energies\n so that the Fermi energy is at zero.\n\n .. attribute: is_spin_polarized\n\n Boolean to indicate if the calculation is spin polarized.\n\n .. attribute: orb_res_cohp\n\n orb_cohp[label] = {bond_data[\"orb_label\"]: {\"COHP\": {Spin.up: cohps, Spin.down:cohps},\n \"ICOHP\": {Spin.up: icohps, Spin.down: icohps},\n \"orbitals\": orbitals,\n \"length\": bond lengths,\n \"sites\": sites corresponding to the bond}}\n\n \"\"\"\n\n def __init__(self, are_coops=False, filename=None):\n self.are_coops = are_coops\n if filename is None:\n filename = \"COOPCAR.lobster\" if are_coops \\\n else \"COHPCAR.lobster\"\n\n with zopen(filename, \"rt\") as f:\n contents = f.read().split(\"\\n\")\n\n # The parameters line is the second line in a COHPCAR file. It\n # contains all parameters that are needed to map the file.\n parameters = contents[1].split()\n # Subtract 1 to skip the average\n num_bonds = int(parameters[0]) - 1\n self.efermi = float(parameters[-1])\n if int(parameters[1]) == 2:\n spins = [Spin.up, Spin.down]\n self.is_spin_polarized = True\n else:\n spins = [Spin.up]\n self.is_spin_polarized = False\n\n # The COHP data start in row num_bonds + 3\n data = np.array([np.array(row.split(), dtype=float)\n for row in contents[num_bonds + 3:]]).transpose()\n self.energies = data[0]\n\n cohp_data = {\"average\": {\"COHP\": {spin: data[1 + 2 * s * (num_bonds + 1)]\n for s, spin in enumerate(spins)},\n \"ICOHP\": {spin: data[2 + 2 * s * (num_bonds + 1)]\n for s, spin in enumerate(spins)}}}\n orb_cohp = {}\n\n # present for Lobster versions older than Lobster 2.2.0\n veryold = False\n # the labeling had to be changed: there are more than one COHP for each atom combination\n # this is done to make the labeling consistent with ICOHPLIST.lobster\n bondnumber = 0\n for bond in range(num_bonds):\n bond_data = self._get_bond_data(contents[3 + bond])\n\n label = str(bondnumber)\n\n orbs = bond_data[\"orbitals\"]\n cohp = {spin: data[2 * (bond + s * (num_bonds + 1)) + 3]\n for s, spin in enumerate(spins)}\n\n icohp = {spin: data[2 * (bond + s * (num_bonds + 1)) + 4]\n for s, spin in enumerate(spins)}\n if orbs is None:\n bondnumber = bondnumber + 1\n label = str(bondnumber)\n cohp_data[label] = {\"COHP\": cohp, \"ICOHP\": icohp,\n \"length\": bond_data[\"length\"],\n \"sites\": bond_data[\"sites\"]}\n\n elif label in orb_cohp:\n orb_cohp[label].update({bond_data[\"orb_label\"]:\n {\"COHP\": cohp,\n \"ICOHP\": icohp,\n \"orbitals\": orbs,\n \"length\": bond_data[\"length\"],\n \"sites\": bond_data[\"sites\"]}})\n else:\n # present for Lobster versions older than Lobster 2.2.0\n if bondnumber == 0:\n veryold = True\n if veryold:\n bondnumber += 1\n label = str(bondnumber)\n\n orb_cohp[label] = {bond_data[\"orb_label\"]: {\"COHP\": cohp,\n \"ICOHP\": icohp,\n \"orbitals\": orbs,\n \"length\": bond_data[\"length\"],\n \"sites\": bond_data[\"sites\"]}}\n\n # present for lobster older than 2.2.0\n if veryold:\n for bond in orb_cohp:\n cohp_data[bond] = {\"COHP\": None, \"ICOHP\": None,\n \"length\": bond_data[\"length\"],\n \"sites\": bond_data[\"sites\"]}\n\n self.orb_res_cohp = orb_cohp if orb_cohp else None\n self.cohp_data = cohp_data\n\n @staticmethod\n def _get_bond_data(line):\n \"\"\"\n Subroutine to extract bond label, site indices, and length from\n a LOBSTER header line. The site indices are zero-based, so they\n can be easily used with a Structure object.\n\n Example header line: No.4:Fe1->Fe9(2.4524893531900283)\n Example header line for orbtial-resolved COHP:\n No.1:Fe1[3p_x]->Fe2[3d_x^2-y^2](2.456180552772262)\n\n Args:\n line: line in the COHPCAR header describing the bond.\n\n Returns:\n Dict with the bond label, the bond length, a tuple of the site\n indices, a tuple containing the orbitals (if orbital-resolved),\n and a label for the orbitals (if orbital-resolved).\n \"\"\"\n\n orb_labs = [\"s\", \"p_y\", \"p_z\", \"p_x\", \"d_xy\", \"d_yz\", \"d_z^2\",\n \"d_xz\", \"d_x^2-y^2\", \"f_y(3x^2-y^2)\", \"f_xyz\",\n \"f_yz^2\", \"f_z^3\", \"f_xz^2\", \"f_z(x^2-y^2)\", \"f_x(x^2-3y^2)\"]\n\n line = line.rsplit(\"(\", 1)\n # bondnumber = line[0].replace(\"->\", \":\").replace(\".\", \":\").split(':')[1]\n length = float(line[-1][:-1])\n\n sites = line[0].replace(\"->\", \":\").split(\":\")[1:3]\n site_indices = tuple(int(re.split(r\"\\D+\", site)[1]) - 1\n for site in sites)\n\n # species = tuple(re.split(r\"\\d+\", site)[0] for site in sites)\n if \"[\" in sites[0]:\n orbs = [re.findall(r\"\\[(.*)\\]\", site)[0] for site in sites]\n orbitals = [tuple((int(orb[0]), Orbital(orb_labs.index(orb[1:]))))\n for orb in orbs]\n orb_label = \"%d%s-%d%s\" % (orbitals[0][0], orbitals[0][1].name,\n orbitals[1][0], orbitals[1][1].name)\n\n else:\n orbitals = None\n orb_label = None\n\n # a label based on the species alone is not feasible, there can be more than one bond for each atom combination\n # label = \"%s\" % (bondnumber)\n\n bond_data = {\"length\": length, \"sites\": site_indices,\n \"orbitals\": orbitals, \"orb_label\": orb_label}\n return bond_data\n\n\nclass Icohplist:\n \"\"\"\n Class to read ICOHPLIST/ICOOPLIST files generated by LOBSTER.\n\n Args:\n are_coops: Determines if the file is a list of ICOHPs or ICOOPs.\n Defaults to False for ICOHPs.\n\n filename: Name of the ICOHPLIST file. If it is None, the default\n file name will be chosen, depending on the value of are_coops.\n\n\n .. attribute: are_coops\n Boolean to indicate if the populations are COOPs or COHPs.\n\n .. attribute: is_spin_polarized\n Boolean to indicate if the calculation is spin polarized.\n\n .. attribute: Icohplist\n Dict containing the listfile data of the form:\n {bond: \"length\": bond length,\n \"number_of_bonds\": number of bonds\n \"icohp\": {Spin.up: ICOHP(Ef) spin up, Spin.down: ...}}\n\n .. attribute: IcohpCollection\n IcohpCollection Object\n\n \"\"\"\n\n def __init__(self, are_coops=False, filename=None):\n\n self.are_coops = are_coops\n if filename is None:\n filename = \"ICOOPLIST.lobster\" if are_coops \\\n else \"ICOHPLIST.lobster\"\n\n # LOBSTER list files have an extra trailing blank line\n # and we don't need the header.\n with zopen(filename) as f:\n data = f.read().split(\"\\n\")[1:-1]\n if len(data) == 0:\n raise IOError(\"ICOHPLIST file contains no data.\")\n\n # Which Lobster version?\n if len(data[0].split()) == 8:\n version = '3.1.1'\n elif len(data[0].split()) == 6:\n version = '2.2.1'\n warnings.warn('Please consider using the new Lobster version. See www.cohp.de.')\n else:\n raise ValueError\n\n # If the calculation is spin polarized, the line in the middle\n # of the file will be another header line.\n if \"distance\" in data[len(data) // 2]:\n num_bonds = len(data) // 2\n if num_bonds == 0:\n raise IOError(\"ICOHPLIST file contains no data.\")\n self.is_spin_polarized = True\n else:\n num_bonds = len(data)\n self.is_spin_polarized = False\n\n list_labels = []\n list_atom1 = []\n list_atom2 = []\n list_length = []\n list_translation = []\n list_num = []\n list_icohp = []\n for bond in range(num_bonds):\n line = data[bond].split()\n icohp = {}\n if version == '2.2.1':\n label = \"%s\" % (line[0])\n atom1 = str(line[1])\n atom2 = str(line[2])\n length = float(line[3])\n icohp[Spin.up] = float(line[4])\n num = int(line[5])\n translation = [0, 0, 0]\n if self.is_spin_polarized:\n icohp[Spin.down] = float(data[bond + num_bonds + 1].split()[4])\n\n\n elif version == '3.1.1':\n label = \"%s\" % (line[0])\n atom1 = str(line[1])\n atom2 = str(line[2])\n length = float(line[3])\n translation = [int(line[4]), int(line[5]), int(line[6])]\n icohp[Spin.up] = float(line[7])\n num = int(1)\n\n if self.is_spin_polarized:\n icohp[Spin.down] = float(data[bond + num_bonds + 1].split()[7])\n\n list_labels.append(label)\n list_atom1.append(atom1)\n list_atom2.append(atom2)\n list_length.append(length)\n list_translation.append(translation)\n list_num.append(num)\n list_icohp.append(icohp)\n\n # to avoid circular dependencies\n from pymatgen.electronic_structure.cohp import IcohpCollection\n self._icohpcollection = IcohpCollection(are_coops=are_coops, list_labels=list_labels, list_atom1=list_atom1,\n list_atom2=list_atom2, list_length=list_length,\n list_translation=list_translation, list_num=list_num,\n list_icohp=list_icohp, is_spin_polarized=self.is_spin_polarized)\n\n @property\n def icohplist(self):\n \"\"\"\n Returns: icohplist compatible with older version of this class\n \"\"\"\n icohplist_new = {}\n for key, value in self._icohpcollection._icohplist.items():\n icohplist_new[key] = {\"length\": value._length, \"number_of_bonds\": value._num,\n \"icohp\": value._icohp, \"translation\": value._translation}\n return icohplist_new\n\n @property\n def icohpcollection(self):\n \"\"\"\n Returns: IcohpCollection object\n \"\"\"\n return self._icohpcollection\n\n\nclass Doscar:\n \"\"\"\n Class to deal with Lobster's projected DOS and local projected DOS.\n The beforehand quantum-chemical calculation was performed with VASP\n\n Args:\n doscar: DOSCAR filename, typically \"DOSCAR.lobster\"\n vasprun: vasprun filename, typically \"vasprun.xml\"\n dftprogram: so far only \"vasp\" is implemented\n\n .. attribute:: completedos\n\n LobsterCompleteDos Object\n\n .. attribute:: pdos\n List of Dict including numpy arrays with pdos. Access as pdos[atomindex]['orbitalstring']['Spin.up/Spin.down']\n\n .. attribute:: tdos\n Dos Object of the total density of states\n\n .. attribute:: energies\n numpy array of the energies at which the DOS was calculated (in eV, relative to Efermi)\n\n .. attribute:: tdensities\n tdensities[Spin.up]: numpy array of the total density of states for the Spin.up contribution at each of the energies\n tdensities[Spin.down]: numpy array of the total density of states for the Spin.down contribution at each of the energies\n\n if is_spin_polarized=False:\n tdensities[Spin.up]: numpy array of the total density of states\n\n .. attribute:: is_spin_polarized\n Boolean. Tells if the system is spin polarized\n\n\n \"\"\"\n\n def __init__(self, doscar=\"DOSCAR.lobster\", vasprun=\"vasprun.xml\", dftprogram=\"Vasp\"):\n\n self._doscar = doscar\n if dftprogram == \"Vasp\":\n self._vasprun = vasprun\n self._VASPRUN = Vasprun(filename=self._vasprun, ionic_step_skip=None,\n ionic_step_offset=0, parse_dos=False,\n parse_eigen=False, parse_projected_eigen=False,\n parse_potcar_file=False, occu_tol=1e-8,\n exception_on_bad_xml=True)\n self._final_structure = self._VASPRUN.final_structure\n self._is_spin_polarized = self._VASPRUN.is_spin\n\n self._parse_doscar()\n\n def _parse_doscar(self):\n doscar = self._doscar\n\n tdensities = {}\n f = open(doscar)\n natoms = int(f.readline().split()[0])\n efermi = float([f.readline() for nn in range(4)][3].split()[17])\n dos = []\n orbitals = []\n for atom in range(natoms + 1):\n line = f.readline()\n ndos = int(line.split()[2])\n orbitals.append(line.split(';')[-1].split())\n line = f.readline().split()\n cdos = np.zeros((ndos, len(line)))\n cdos[0] = np.array(line)\n for nd in range(1, ndos):\n line = f.readline().split()\n cdos[nd] = np.array(line)\n dos.append(cdos)\n f.close()\n\n doshere = np.array(dos[0])\n energies = doshere[:, 0]\n if not self._is_spin_polarized:\n tdensities[Spin.up] = doshere[:, 1]\n pdoss = []\n spin = Spin.up\n for atom in range(natoms):\n pdos = defaultdict(dict)\n data = dos[atom + 1]\n _, ncol = data.shape\n orbnumber = 0\n for j in range(1, ncol):\n orb = orbitals[atom + 1][orbnumber]\n pdos[orb][spin] = data[:, j]\n orbnumber = orbnumber + 1\n pdoss.append(pdos)\n else:\n tdensities[Spin.up] = doshere[:, 1]\n tdensities[Spin.down] = doshere[:, 2]\n pdoss = []\n for atom in range(natoms):\n pdos = defaultdict(dict)\n data = dos[atom + 1]\n _, ncol = data.shape\n orbnumber = 0\n for j in range(1, ncol):\n if j % 2 == 0:\n spin = Spin.down\n else:\n spin = Spin.up\n orb = orbitals[atom + 1][orbnumber]\n pdos[orb][spin] = data[:, j]\n if j % 2 == 0:\n orbnumber = orbnumber + 1\n pdoss.append(pdos)\n self._efermi = efermi\n self._pdos = pdoss\n self._tdos = Dos(efermi, energies, tdensities)\n self._energies = energies\n self._tdensities = tdensities\n final_struct = self._final_structure\n\n pdossneu = {final_struct[i]: pdos for i, pdos in enumerate(self._pdos)}\n\n self._completedos = LobsterCompleteDos(final_struct, self._tdos, pdossneu)\n\n @property\n def completedos(self):\n return self._completedos\n\n @property\n def pdos(self):\n return self._pdos\n\n @property\n def tdos(self):\n return self._tdos\n\n @property\n def energies(self):\n return self._energies\n\n @property\n def tdensities(self):\n return self._tdensities\n\n @property\n def is_spin_polarized(self):\n return self._is_spin_polarized\n\n\nclass Charge:\n \"\"\"Class to read CHARGE files generated by LOBSTER\n Args:\n filename: filename for the CHARGE file, typically \"CHARGE.lobster\"\n\n .. attribute: atomlist\n List of atoms in CHARGE.lobster\n .. attribute: types\n List of types of atoms in CHARGE.lobster\n .. attribute: Mulliken\n List of Mulliken charges of atoms in CHARGE.lobster\n .. attribute: Loewdin\n List of Loewdin charges of atoms in CHARGE.Loewdin\n .. attribute: num_atoms\n Number of atoms in CHARGE.lobster\n\n \"\"\"\n\n def __init__(self, filename=\"CHARGE.lobster\"):\n with zopen(filename) as f:\n data = f.read().split(\"\\n\")[3:-3]\n if len(data) == 0:\n raise IOError(\"CHARGES file contains no data.\")\n\n self.num_atoms = len(data)\n self.atomlist = []\n self.types = []\n self.Mulliken = []\n self.Loewdin = []\n for atom in range(0, self.num_atoms):\n line = data[atom].split()\n self.atomlist.append(line[1] + line[0])\n self.types.append(line[1])\n self.Mulliken.append(float(line[2]))\n self.Loewdin.append(float(line[3]))\n\n def get_structure_with_charges(self, structure_filename):\n \"\"\"\n get a Structure with Mulliken and Loewdin charges as site properties\n Args:\n structure_filename: filename of POSCAR\n Returns:\n Structure Object with Mulliken and Loewdin charges as site properties\n \"\"\"\n\n struct = Structure.from_file(structure_filename)\n Mulliken = self.Mulliken\n Loewdin = self.Loewdin\n site_properties = {\"Mulliken Charges\": Mulliken, \"Loewdin Charges\": Loewdin}\n new_struct = struct.copy(site_properties=site_properties)\n return new_struct\n\n\nclass Lobsterout:\n \"\"\"\n Class to read in the lobsterout and evaluate the spilling, save the basis, save warnings, save infos\n Args:\n filename: filename of lobsterout\n\n .. attribute: basis_functions\n list of basis functions that were used in lobster run as strings\n\n .. attribute: basis_type\n list of basis type that were used in lobster run as strings\n\n .. attribute: chargespilling\n list of charge spilling (first entry: result for spin 1, second entry: result for spin 2 or not present)\n\n .. attribute: dftprogram\n string representing the dft program used for the calculation of the wave function\n\n .. attribute: elements\n list of strings of elements that were present in lobster calculation\n\n .. attribute: has_CHARGE\n Boolean, indicates that CHARGE.lobster is present\n\n .. attribute: has_COHPCAR\n Boolean, indicates that COHPCAR.lobster and ICOHPLIST.lobster are present\n\n .. attribute: has_COOPCAR\n Boolean, indicates that COOPCAR.lobster and ICOOPLIST.lobster are present\n\n .. attribute: has_DOSCAR\n Boolean, indicates that DOSCAR.lobster is present\n\n .. attribute: has_Projection\n Boolean, indcates that projectionData.lobster is present\n\n .. attribute: has_bandoverlaps\n Boolean, indcates that bandOverlaps.lobster is present\n\n .. attribute: has_density_of_energies\n Boolean, indicates that DensityOfEnergy.lobster is present\n\n .. attribute: has_fatbands\n Boolean, indicates that fatband calculation was performed\n\n .. attribute: has_grosspopulation\n Boolean, indicates that GROSSPOP.lobster is present\n\n .. attribute: info_lines\n string with additional infos on the run\n\n .. attribute: info_orthonormalization\n string with infos on orthonormalization\n\n .. attribute: is_restart_from_projection\n Boolean that indicates that calculation was restartet from existing projection file\n\n .. attribute: lobster_version\n string that indicates Lobster version\n\n .. attribute: number_of_spins\n Integer indicating the number of spins\n\n .. attribute: number_of_threads\n integer that indicates how many threads were used\n\n .. attribute: timing\n dict with infos on timing\n\n .. attribute: totalspilling\n list of values indicating the total spilling for spin channel 1 (and spin channel 2)\n\n .. attribute: warninglines\n string with all warnings\n\n\n \"\"\"\n\n def __init__(self, filename=\"lobsterout\"):\n\n warnings.warn(\"Make sure the lobsterout is read in correctly. This is a brand new class.\")\n # read in file\n with zopen(filename) as f:\n data = f.read().split(\"\\n\") # [3:-3]\n if len(data) == 0:\n raise IOError(\"lobsterout does not contain any data\")\n\n LobsterDict = {}\n # check if Lobster starts from a projection\n self.is_restart_from_projection = self._starts_from_projection(data=data)\n\n self.lobster_version = self._get_lobster_version(data=data)\n\n self.number_of_threads = int(self._get_threads(data=data))\n self.dftprogram = self._get_dft_program(data=data)\n\n self.number_of_spins = self._get_number_of_spins(data=data)\n chargespilling, totalspilling = self._get_spillings(data=data, number_of_spins=self.number_of_spins)\n self.chargespilling = chargespilling\n self.totalspilling = totalspilling\n\n elements, basistype, basisfunctions = self._get_elements_basistype_basisfunctions(data=data)\n self.elements = elements\n self.basis_type = basistype\n self.basis_functions = basisfunctions\n\n wall_time, user_time, sys_time = self._get_timing(data=data)\n timing = {}\n timing['walltime'] = wall_time\n timing['usertime'] = user_time\n timing['sys_time'] = sys_time\n self.timing = timing\n\n warninglines = self._get_all_warning_lines(data=data)\n self.warninglines = warninglines\n\n orthowarning = self._get_warning_orthonormalization(data=data)\n self.info_orthonormalization = orthowarning\n # print(orthowarning)\n\n infos = self._get_all_info_lines(data=data)\n self.info_lines = infos\n\n self.has_DOSCAR = self._has_DOSCAR(data=data)\n self.has_COHPCAR = self._has_COOPCAR(data=data)\n self.has_COOPCAR = self._has_COHPCAR(data=data)\n self.has_CHARGE = self._has_CHARGE(data=data)\n self.has_Projection = self._has_projection(data=data)\n self.has_bandoverlaps = self._has_bandoverlaps(data=data)\n self.has_fatbands = self._has_fatband(data=data)\n self.has_grosspopulation = self._has_grosspopulation(data=data)\n self.has_density_of_energies = self._has_density_of_energies(data=data)\n\n def get_doc(self):\n \"\"\"\n\n Returns: LobsterDict with all the information stored in lobsterout\n \"\"\"\n\n LobsterDict = {}\n # check if Lobster starts from a projection\n LobsterDict['restart_from_projection'] = self.is_restart_from_projection\n LobsterDict['lobster_version'] = self.lobster_version\n LobsterDict['threads'] = self.number_of_threads\n LobsterDict['Dftprogram'] = self.dftprogram\n\n number_of_spins = self.number_of_spins\n LobsterDict['chargespilling'] = self.chargespilling\n LobsterDict['totalspilling'] = self.totalspilling\n\n LobsterDict['elements'] = self.elements\n LobsterDict['basistype'] = self.basis_type\n LobsterDict['basisfunctions'] = self.basis_functions\n\n LobsterDict['timing'] = self.timing\n\n LobsterDict['warnings'] = self.warninglines\n\n LobsterDict['orthonormalization'] = self.info_orthonormalization\n\n LobsterDict['infos'] = self.info_lines\n\n LobsterDict['hasDOSCAR'] = self.has_DOSCAR\n LobsterDict['hasCOHPCAR'] = self.has_COHPCAR\n LobsterDict['hasCOOPCAR'] = self.has_COOPCAR\n LobsterDict['hasCHARGE'] = self.has_CHARGE\n LobsterDict['hasProjection'] = self.has_Projection\n LobsterDict['hasbandoverlaps'] = self.has_bandoverlaps\n LobsterDict['hasfatband'] = self.has_fatbands\n LobsterDict['hasGrossPopuliation'] = self.has_grosspopulation\n LobsterDict['hasDensityOfEnergies'] = self.has_density_of_energies\n\n return LobsterDict\n\n def _get_lobster_version(self, data):\n for row in data:\n splitrow = row.split()\n if len(splitrow) > 1:\n if splitrow[0] == \"LOBSTER\":\n return splitrow[1]\n\n def _has_bandoverlaps(self, data):\n if 'WARNING: I dumped the band overlap matrices to the file bandOverlaps.lobster.' in data:\n return True\n else:\n return False\n\n def _starts_from_projection(self, data):\n if 'loading projection from projectionData.lobster...' in data:\n return True\n else:\n return False\n\n def _has_DOSCAR(self, data):\n if 'writing DOSCAR.lobster...' in data and not 'SKIPPING writing DOSCAR.lobster...' in data:\n return True\n else:\n return False\n\n def _has_COOPCAR(self, data):\n if 'writing COOPCAR.lobster and ICOOPLIST.lobster...' in data and not 'SKIPPING writing COOPCAR.lobster and ICOOPLIST.lobster...' in data:\n return True\n else:\n return False\n\n def _has_COHPCAR(self, data):\n if 'writing COHPCAR.lobster and ICOHPLIST.lobster...' in data and not 'SKIPPING writing COHPCAR.lobster and ICOHPLIST.lobster...' in data:\n return True\n else:\n return False\n\n def _has_CHARGE(self, data):\n # weitere optionen testen -> auch hier kann uebersprungen werden\n if not 'SKIPPING writing CHARGE.lobster...' in data:\n return True\n else:\n return False\n\n def _has_grosspopulation(self, data):\n if 'writing CHARGE.lobster and GROSSPOP.lobster...' in data:\n return True\n else:\n return False\n\n def _has_projection(self, data):\n if 'saving projection to projectionData.lobster...' in data:\n return True\n else:\n return False\n\n def _has_fatband(self, data):\n for row in data:\n splitrow = row.split()\n if len(splitrow) > 1:\n if splitrow[1] == 'FatBand':\n return True\n return False\n\n def _has_density_of_energies(self, data):\n if \"writing DensityOfEnergy.lobster...\" in data:\n return True\n else:\n return False\n\n def _get_dft_program(self, data):\n for row in data:\n splitrow = row.split()\n if len(splitrow) > 4:\n if splitrow[3] == \"program...\":\n return splitrow[4]\n\n def _get_number_of_spins(self, data):\n if \"spillings for spin channel 2\" in data:\n # print('two spin channels')\n return 2\n else:\n return 1\n\n def _get_threads(self, data):\n for row in data:\n splitrow = row.split()\n if len(splitrow) > 11:\n if (splitrow[11]) == \"threads\":\n return splitrow[10]\n\n def _get_spillings(self, data, number_of_spins):\n charge_spilling = []\n total_spilling = []\n\n for row in data:\n splitrow = row.split()\n\n if len(splitrow) > 2:\n if splitrow[2] == 'spilling:':\n # print(splitrow)\n if splitrow[1] == 'charge':\n charge_spilling.append(np.float(splitrow[3].replace('%', '')) / 100.0)\n if splitrow[1] == 'total':\n total_spilling.append(np.float(splitrow[3].replace('%', '')) / 100.0)\n\n if len(charge_spilling) == number_of_spins and len(total_spilling) == number_of_spins:\n break;\n\n return charge_spilling, total_spilling\n\n def _get_elements_basistype_basisfunctions(self, data):\n begin = False\n end = False\n elements = []\n basistype = []\n basisfunctions = []\n for row in data:\n\n if begin and not end:\n # print(row)\n splitrow = row.split()\n if splitrow[0] not in ['INFO:', 'WARNING:', 'setting', 'calculating', 'post-processing', 'saving',\n 'spillings', 'writing']:\n\n elements.append(splitrow[0])\n basistype.append(splitrow[1].replace('(', '').replace(')', ''))\n # last sign is a ''\n basisfunctions.append(splitrow[2:])\n else:\n end = True\n if \"setting up local basis functions...\" in row:\n begin = True\n # print(row)\n return elements, basistype, basisfunctions\n\n def _get_timing(self, data):\n # will give back wall, user and sys time\n begin = False\n # end=False\n # time=[]\n\n for row in data:\n splitrow = row.split()\n if 'finished' in splitrow:\n begin = True\n if begin:\n if 'wall' in splitrow:\n wall_time = (splitrow[2:10])\n if 'user' in splitrow:\n user_time = (splitrow[0:8])\n if 'sys' in splitrow:\n sys_time = (splitrow[0:8])\n\n wall_time_dict = {\"h\": wall_time[0], \"min\": wall_time[2], \"s\": wall_time[4], \"ms\": wall_time[6]}\n user_time_dict = {\"h\": user_time[0], \"min\": user_time[2], \"s\": user_time[4], \"ms\": user_time[6]}\n sys_time_dict = {\"h\": sys_time[0], \"min\": sys_time[2], \"s\": sys_time[4], \"ms\": sys_time[6]}\n\n return wall_time_dict, user_time_dict, sys_time_dict\n\n def _get_warning_orthonormalization(self, data):\n orthowarning = []\n for row in data:\n splitrow = row.split()\n if 'orthonormalized' in splitrow:\n orthowarning.append(\" \".join(splitrow[1:]))\n return orthowarning\n\n def _get_all_warning_lines(self, data):\n warnings = []\n for row in data:\n splitrow = row.split()\n if len(splitrow) > 0:\n if splitrow[0] == 'WARNING:':\n warnings.append(\" \".join(splitrow[1:]))\n\n return warnings\n # print(warnings)\n\n def _get_all_info_lines(self, data):\n infos = []\n for row in data:\n splitrow = row.split()\n if len(splitrow) > 0:\n if splitrow[0] == 'INFO:':\n infos.append(\" \".join(splitrow[1:]))\n\n return infos\n\n\nclass Fatband:\n \"\"\"\n reads in FATBAND_x_y.lobster files\n Args:\n filenames (list or string): can be a list of file names or a path to a folder folder from which all \"FATBAND_*\" files will be read\n vasprun: corresponding vasprun file\n Kpointsfile: KPOINTS file for bandstructure calculation, typically \"KPOINTS\"\n\n .. attribute: efermi\n efermi that was read in from vasprun.xml\n\n .. attribute: eigenvals\n {Spin.up:[][],Spin.down:[][]}, the first index of the array\n [][] refers to the band and the second to the index of the\n kpoint. The kpoints are ordered according to the order of the\n kpoints array. If the band structure is not spin polarized, we\n only store one data set under Spin.up.\n\n .. attribute: is_spinpolarized\n Boolean that tells you whether this was a spin-polarized calculation\n\n .. attribute: kpoints_array\n list of kpoint as numpy arrays, in frac_coords of the\n given lattice by default\n \n .. attribute: label_dict\n (dict) of {} this link a kpoint (in frac coords or\n cartesian coordinates depending on the coords).\n\n .. attribute: lattice\n lattice object of reciprocal lattice as read in from vasprun.xml\n\n .. attribute: nbands\n number of bands used in the calculation\n\n .. attribute: p_eigenvals\n dict of orbital projections as {spin: array of dict}. \n The indices of the array are [band_index, kpoint_index]. \n The dict is then built the following way: \n {\"string of element\": \"string of orbital as read in from FATBAND file\"}\n If the band structure is not spin polarized, we only store one data set under Spin.up.\n\n .. attribute: structure\n structure read in from vasprun.xml\n\n\n \"\"\"\n\n def __init__(self, filenames=\".\", vasprun='vasprun.xml', Kpointsfile='KPOINTS'):\n\n warnings.warn('Make sure all relevant FATBAND files were generated and read in!')\n warnings.warn('Use Lobster 3.2.0 or newer for fatband calculations!')\n\n VASPRUN = Vasprun(filename=vasprun, ionic_step_skip=None,\n ionic_step_offset=0, parse_dos=True,\n parse_eigen=False, parse_projected_eigen=False,\n parse_potcar_file=False, occu_tol=1e-8,\n exception_on_bad_xml=True)\n self.structure = VASPRUN.final_structure\n self.lattice = self.structure.lattice.reciprocal_lattice\n self.efermi = VASPRUN.efermi\n kpoints_object = Kpoints.from_file(Kpointsfile)\n\n atomtype = []\n atomnames = []\n orbital_names = []\n\n if type(filenames) is not type([]) or filenames is None:\n filenames_new = []\n if filenames is None:\n filenames = '.'\n for file in os.listdir(filenames):\n if fnmatch.fnmatch(file, 'FATBAND_*.lobster'):\n filenames_new.append(os.path.join(filenames, file))\n filenames = filenames_new\n if (len(filenames)) == 0:\n raise ValueError(\"No FATBAND files in folder or given\")\n for ifilename, filename in enumerate(filenames):\n with zopen(filename, \"rt\") as f:\n contents = f.read().split(\"\\n\")\n\n # TODO: could be replaced for future versions of Lobster, get atomname from filename\n atomnames.append(os.path.split(filename)[1].split('_')[1].capitalize())\n parameters = contents[0].split()\n atomtype.append(re.split(r\"[0-9]+\", parameters[3])[0].capitalize())\n orbital_names.append(parameters[4])\n\n # get atomtype orbital dict\n atom_orbital_dict = {}\n for iatom, atom in enumerate(atomnames):\n if atom not in atom_orbital_dict:\n atom_orbital_dict[atom] = []\n atom_orbital_dict[atom].append(orbital_names[iatom])\n # test if there are the same orbitals twice or if two different formats were used or if all necessary orbitals are there\n for key, items in atom_orbital_dict.items():\n if len(set(items)) != len(items):\n raise (ValueError(\"The are two FATBAND files for the same atom and orbital. The program will stop.\"))\n split = []\n for item in items:\n split.append(item.split(\"_\")[0])\n for orb, number in collections.Counter(split).items():\n if number != 1 and number != 3 and number != 5 and number != 7:\n raise (ValueError(\n \"Make sure all relevant orbitals were generated and that no duplicates (2p and 2p_x) are present\"))\n\n kpoints_array = []\n for ifilename, filename in enumerate(filenames):\n with zopen(filename, \"rt\") as f:\n contents = f.read().split(\"\\n\")\n\n if ifilename == 0:\n self.nbands = int(parameters[6])\n self.number_kpts = kpoints_object.num_kpts - int(contents[1].split()[2]) + 1\n\n if len(contents[1:]) == self.nbands + 2:\n self.is_spinpolarized = False\n elif len(contents[1:]) == self.nbands * 2 + 2:\n self.is_spinpolarized = True\n else:\n linenumbers = []\n for iline, line in enumerate(contents[1:self.nbands * 2 + 4]):\n # print(line)\n # if line in ['\\n', '\\r\\n']:\n # linenumbers.append(iline)\n if line.split()[0] == '#':\n linenumbers.append(iline)\n\n if ifilename == 0:\n if len(linenumbers) == 2:\n self.is_spinpolarized = True\n else:\n self.is_spinpolarized = False\n\n if ifilename == 0:\n eigenvals = {}\n eigenvals[Spin.up] = [[collections.defaultdict(float)\n for i in range(self.number_kpts)]\n for j in range(self.nbands)]\n if self.is_spinpolarized:\n eigenvals[Spin.down] = [[collections.defaultdict(float)\n for i in range(self.number_kpts)]\n for j in range(self.nbands)]\n\n p_eigenvals = {}\n p_eigenvals[Spin.up] = [\n [{str(e): {str(orb): collections.defaultdict(float) for orb in atom_orbital_dict[e]}\n for e in atomnames}\n for i in range(self.number_kpts)]\n for j in range(self.nbands)]\n\n if self.is_spinpolarized:\n p_eigenvals[Spin.down] = [\n [{str(e): {str(orb): collections.defaultdict(float) for orb in atom_orbital_dict[e]}\n for e in atomnames}\n for i in range(self.number_kpts)]\n for j in range(self.nbands)]\n\n ikpoint = -1\n for iline, line in enumerate(contents[1:-1]):\n if line.split()[0] == '#':\n Kpointnumber = int(line.split()[2])\n KPOINT = np.array([float(line.split()[4]), float(line.split()[5]), float(line.split()[6])])\n if ifilename == 0:\n kpoints_array.append(KPOINT)\n\n linenumber = 0\n iband = 0\n ikpoint += 1\n if linenumber == self.nbands:\n iband = 0\n if line.split()[0] != '#':\n\n if linenumber < self.nbands:\n if ifilename == 0:\n eigenvals[Spin.up][iband][ikpoint] = float(line.split()[1]) + self.efermi\n\n p_eigenvals[Spin.up][iband][ikpoint][atomnames[ifilename]][orbital_names[ifilename]] = float(\n line.split()[2])\n if linenumber >= self.nbands and self.is_spinpolarized:\n # print(line.split())\n # print(iband)\n if ifilename == 0:\n eigenvals[Spin.down][iband][ikpoint] = float(line.split()[1]) + self.efermi\n p_eigenvals[Spin.down][iband][ikpoint][atomnames[ifilename]][\n orbital_names[ifilename]] = float(line.split()[2])\n\n linenumber += 1\n iband += 1\n\n self.kpoints_array = kpoints_array\n self.eigenvals = eigenvals\n self.p_eigenvals = p_eigenvals\n\n label_dict = {}\n for ilabel, label in enumerate(kpoints_object.labels[-self.number_kpts:], start=0):\n\n if label is not None:\n label_dict[label] = kpoints_array[ilabel]\n\n self.label_dict = label_dict\n\n def get_bandstructure(self):\n \"\"\"\n returns a LobsterBandStructureSymmLine object which can be plotted with a normal BSPlotter\n \"\"\"\n\n return LobsterBandStructureSymmLine(kpoints=self.kpoints_array, eigenvals=self.eigenvals, lattice=self.lattice,\n efermi=self.efermi, labels_dict=self.label_dict,\n structure=self.structure,\n projections=self.p_eigenvals)\n", "meta": {"hexsha": "d77d077fe1d948f0989b0d3ee84e19d8555904e5", "size": 42378, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymatgen/io/lobster.py", "max_stars_repo_name": "dongsenfo/pymatgen", "max_stars_repo_head_hexsha": "ffc635e7674acc01b3ddfb67f8d135dd82aae243", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-02-26T00:08:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-26T00:08:13.000Z", "max_issues_repo_path": "pymatgen/io/lobster.py", "max_issues_repo_name": "dongsenfo/pymatgen", "max_issues_repo_head_hexsha": "ffc635e7674acc01b3ddfb67f8d135dd82aae243", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pymatgen/io/lobster.py", "max_forks_repo_name": "dongsenfo/pymatgen", "max_forks_repo_head_hexsha": "ffc635e7674acc01b3ddfb67f8d135dd82aae243", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7700534759, "max_line_length": 146, "alphanum_fraction": 0.562839209, "include": true, "reason": "import numpy", "num_tokens": 9970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.26284183159693775, "lm_q1q2_score": 0.13655193581555047}} {"text": "\"\"\"Contains code for generating single polynucleotides.\"\"\"\n\nfrom collections import OrderedDict\n\nimport numpy\nfrom tools.geometry import (angle_between_vectors, unit_vector, find_foot,\n Quaternion, dihedral, find_transformations,\n cylindrical_to_cartesian, Axis)\nfrom ampal.base_ampal import Atom\nfrom ampal.nucleic_acid import Polynucleotide, Nucleotide\n\n_helix_parameters = {\n # nucleotides_per_turn, rise_per_nucleotide\n 'a_dna': (11.0, 2.6),\n 'b_dna': (10.2, 3.4),\n 'z_dna': (12.3, 3.7)\n}\n\n\n_helix_handedness = {\n 'a_dna': 'r',\n 'b_dna': 'r',\n 'z_dna': 'r'\n}\n\n\n_backbone_properties = {\n # helix_type : {atom_type: [radius, angular_offset (in radians), z-shift]}\n 'a_dna': {\n 'P': [8.92, 0, 0], # P\n },\n 'b_dna': {\n 'mol_code_format': 'D{}',\n 'labels': [\"P\", \"OP1\", \"OP2\", \"O5'\", \"C5'\", \"C4'\",\n \"O4'\", \"C3'\", \"O3'\", \"C2'\", \"C1'\"],\n 'atoms': [\n (8.92, 0.0, 0.0),\n (10.23, 0.07, 0.21),\n (9.0, -0.14, 0.77),\n (7.72, -0.5, -3.11),\n (7.68, -0.36, -4.05),\n (7.57, -0.17, -3.33),\n (6.22, -0.11, -3.17),\n (8.19, -0.19, -1.93),\n (8.74, -0.04, -1.55),\n (7.02, -0.25, -1.06),\n (5.79, -0.14, -1.83),\n (4.58, -0.30, -1.83)\n ]\n },\n 'z_dna': {\n 'P': [8.92, 0, 0], # P\n }\n}\n\n_bases = {\n 'G': {\n 'labels': [\"O4'\", \"C1'\", \"N9\", \"C8\", \"N7\", \"C5\",\n \"C6\", \"O6\", \"N1\", \"C2\", \"N2\", \"N3\", \"C4\"],\n 'ref_atom': \"N9\",\n 'rot_adj': 15.0,\n 'atoms': [\n (33.930, 30.325, 17.814),\n (34.631, 29.403, 17.056),\n (35.908, 29.190, 17.720),\n (36.117, 28.636, 18.964),\n (37.376, 28.606, 19.309),\n (38.040, 29.196, 18.238),\n (39.419, 29.435, 18.041),\n (40.348, 29.171, 18.808),\n (39.672, 30.068, 16.810),\n (38.706, 30.393, 15.889),\n (39.131, 30.975, 14.756),\n (37.406, 30.170, 16.069),\n (37.150, 29.567, 17.255)\n ]\n },\n 'C': {\n 'labels': [\"O4'\", \"C1'\", \"N1\", \"C2\", \"O2\", \"N3\",\n \"C4\", \"N4\", \"C5\", \"C6\"],\n 'ref_atom': \"N1\",\n 'rot_adj': 47.0,\n 'atoms': [\n (35.422, 27.992, 13.920),\n (36.655, 27.383, 13.630),\n (37.240, 26.863, 14.903),\n (38.622, 26.960, 15.116),\n (39.337, 27.469, 14.237),\n (39.137, 26.506, 16.285),\n (38.336, 25.972, 17.205),\n (38.892, 25.545, 18.338),\n (36.925, 25.864, 17.008),\n (36.426, 26.317, 15.853)\n ]\n },\n 'A': {\n 'labels': [\"O4'\", \"C1'\", \"N9\", \"C8\", \"N7\", \"C5\",\n \"C6\", \"N6\", \"N1\", \"C2\", \"N3\", \"C4\"],\n 'ref_atom': \"N9\",\n 'rot_adj': 5.0,\n 'atoms': [\n (39.099, 26.091, 9.763),\n (39.785, 24.859, 9.897),\n (39.558, 24.371, 11.250),\n (38.407, 23.814, 11.737),\n (38.478, 23.462, 12.998),\n (39.769, 23.803, 13.357),\n (40.461, 23.687, 14.561),\n (39.913, 23.168, 15.662),\n (41.745, 24.130, 14.598),\n (42.280, 24.652, 13.481),\n (41.715, 24.823, 12.282),\n (40.447, 24.374, 12.291)\n ]\n },\n 'T': {\n 'labels': [\"O4'\", \"C1'\", \"N1\", \"C2\", \"O2\", \"N3\",\n \"C4\", \"O4\", \"C5\", \"C7\", \"C6\"],\n 'ref_atom': \"N1\",\n 'rot_adj': 30.0,\n 'atoms': [\n (43.43, 23.953, 9.349),\n (44.116, 22.801, 9.767),\n (43.234, 22.076, 10.744),\n (43.702, 21.817, 12.016),\n (44.824, 22.102, 12.389),\n (42.814, 21.185, 12.840),\n (41.527, 20.804, 12.542),\n (40.808, 20.241, 13.364),\n (41.084, 21.115, 11.196),\n (39.697, 20.746, 10.751),\n (41.948, 21.737, 10.374)\n ]\n }\n}\n\n\nclass NucleicAcidStrand(Polynucleotide):\n \"\"\"Generates a `Polynucleotide` from a sequence of bases.\n\n Parameters\n ----------\n sequence: str\n The nucleotide sequence of the nucleic acid.\n helix_type: str, optional\n The type of nucleic acid helix to generate.\n phos_3_prime: bool, optional\n If false the 5' and the 3' phosphor will be omitted.\n\n Attributes\n ----------\n base_sequence : str\n Nucleotide sequence for the nucleic acid.\n num_monomers : int\n Number of bases in the sequence.\n helix_type : str\n The type of nucleic acid helix. Currently only b-DNA is\n implemented.\n phos_3_prime : bool\n If `true`, the 3' end of the strand will have a phosphate.\n nucleotides_per_turn : float\n Number of nucleotides per turn of the nucleic acid super\n helix.\n rise_per_nucleotide : float\n Rise along the nucleic acid super helix per base.\n handedness : str\n Handedness of the super helix.\n helix_start : 3D Vector (tuple or list or numpy.array)\n Initial coordinate of the backbone primitive.\n helix_end : 3D Vector (tuple or list or numpy.array)\n Last coordinate of the backbone primitive.\n\n Raises\n ------\n ValueError\n Raised if a sequence is not provided.\n \"\"\"\n\n def __init__(self, sequence='GATC', helix_type='b_dna', phos_3_prime=False):\n super().__init__()\n if not sequence:\n raise ValueError(\n 'A sequence must be provided to build a region of DNA.')\n self.base_sequence = sequence\n self.num_monomers = len(sequence)\n self.helix_type = helix_type\n self.phos_3_prime = phos_3_prime\n self.nucleotides_per_turn, self.rise_per_nucleotide = _helix_parameters[\n self.helix_type]\n self.handedness = _helix_handedness[self.helix_type]\n self.helix_start = numpy.array([0.0, 0.0, 0.0])\n self.helix_end = self.helix_length * numpy.array([0.0, 0.0, 1.0])\n self.build()\n\n @classmethod\n def from_start_and_end(cls, start, end, sequence, helix_type='b_dna',\n phos_3_prime=False):\n \"\"\"Generates a helical `Polynucleotide` that is built along an axis.\n\n Parameters\n ----------\n start: [float, float, float]\n Start of the build axis.\n end: [float, float, float]\n End of build axis.\n sequence: str\n The nucleotide sequence of the nucleic acid.\n helix_type: str\n The type of nucleic acid helix to generate.\n phos_3_prime: bool\n If false the 5' and the 3' phosphor will be omitted.\n \"\"\"\n start = numpy.array(start)\n end = numpy.array(end)\n instance = cls(sequence, helix_type=helix_type,\n phos_3_prime=phos_3_prime)\n instance.move_to(start=start, end=end)\n return instance\n\n @property\n def axis(self):\n \"\"\"The super-helical axis.\"\"\"\n return Axis(start=self.helix_start, end=self.helix_end)\n\n @property\n def ax_unit(self):\n \"\"\"The unit tangent of the super-helical axis.\"\"\"\n return self.axis.unit_tangent\n\n @property\n def rad_unit(self):\n \"\"\"The unit normal of the super-helical axis.\"\"\"\n return self.axis.unit_normal\n\n @property\n def tan_unit(self):\n \"\"\"The unit binormal of the super-helical axis.\"\"\"\n return self.axis.unit_binormal\n\n @property\n def helix_length(self):\n \"\"\"Length of the helix in Ångstroms.\"\"\"\n return self.num_monomers * self.rise_per_nucleotide\n\n def translate(self, vector):\n super(Polynucleotide, self).translate(vector=vector)\n self.helix_start += vector\n self.helix_end += vector\n return\n\n def rotate(self, angle, axis, point=None, radians=False):\n super(Polynucleotide, self).rotate(\n angle=angle, axis=axis, point=point, radians=radians)\n # modify helix_start and helix_end accordingly.\n q = Quaternion.angle_and_axis(angle=angle, axis=axis, radians=radians)\n self.helix_start = q.rotate_vector(v=self.helix_start, point=point)\n self.helix_end = q.rotate_vector(v=self.helix_end, point=point)\n return\n\n def build(self):\n \"\"\"Build single DNA strand along z-axis, starting with P on x-axis\"\"\"\n ang_per_res = (2 * numpy.pi) / self.nucleotides_per_turn\n atom_offset_coords = _backbone_properties[self.helix_type]['atoms']\n if self.handedness == 'l':\n handedness = -1\n else:\n handedness = 1\n base_atom_labels = _backbone_properties[self.helix_type]['labels']\n monomers = []\n mol_code_format = _backbone_properties[self.helix_type]['mol_code_format']\n for i, b in enumerate(self.base_sequence):\n nucleotide = Nucleotide(\n mol_code=mol_code_format.format(b), ampal_parent=self)\n atoms_dict = OrderedDict()\n if (i == (len(self.base_sequence) - 1)) and not self.phos_3_prime:\n # Do not include phosphate on last nucleotide\n atom_labels = base_atom_labels[3:] + [_bases[b]['labels'][2]]\n atom_offsets = {k: v for k, v in zip(\n atom_labels, atom_offset_coords[3:])}\n else:\n atom_labels = base_atom_labels + [_bases[b]['labels'][2]]\n atom_offsets = {k: v for k, v in zip(\n atom_labels, atom_offset_coords)}\n for atom_label in atom_labels:\n r, zeta, z_shift = atom_offsets[atom_label]\n rot_ang = ((i * ang_per_res) + zeta) * handedness\n z = (self.rise_per_nucleotide * i) + z_shift\n coords = cylindrical_to_cartesian(\n radius=r, azimuth=rot_ang, z=z, radians=True)\n atom = Atom(\n coordinates=coords, element=atom_label[0],\n ampal_parent=nucleotide, res_label=atom_label)\n atoms_dict[atom_label] = atom\n base_ref = _bases[b]['ref_atom']\n rot_adj = _bases[b]['rot_adj']\n base_dict = OrderedDict(\n zip(_bases[b]['labels'], _bases[b]['atoms']))\n translation, angle, axis, point = find_transformations(\n base_dict[base_ref], base_dict[\"C1'\"],\n atoms_dict[base_ref]._vector, atoms_dict[\"C1'\"]._vector)\n q1 = Quaternion.angle_and_axis(angle, axis)\n # Align N9 C1'\n for k, v in base_dict.items():\n base_dict[k] = q1.rotate_vector(v, point) + translation\n # Rotate to align O4'\n axis = numpy.array(base_dict[\"C1'\"]) - base_dict[base_ref]\n angle = dihedral(base_dict[\"O4'\"], base_dict[base_ref],\n base_dict[\"C1'\"], atoms_dict[\"O4'\"]) - rot_adj\n q2 = Quaternion.angle_and_axis(angle, axis)\n for k, v in list(base_dict.items()):\n if k not in atoms_dict:\n atom = Atom(q2.rotate_vector(v, base_dict[base_ref]),\n element=k[0], ampal_parent=nucleotide,\n res_label=k)\n atoms_dict[k] = atom\n nucleotide.atoms = atoms_dict\n monomers.append(nucleotide)\n self._monomers = monomers\n self.relabel_monomers()\n self.relabel_atoms()\n return\n\n def move_to(self, start, end):\n \"\"\"Moves the `Polynucleotide` to lie on the `start` and `end` vector.\n\n Parameters\n ----------\n start : 3D Vector (tuple or list or numpy.array)\n The coordinate of the start of the helix primitive.\n end : 3D Vector (tuple or list or numpy.array)\n The coordinate of the end of the helix primitive.\n\n Raises\n ------\n ValueError\n Raised if `start` and `end` are very close together.\n \"\"\"\n start = numpy.array(start)\n end = numpy.array(end)\n if numpy.allclose(start, end):\n raise ValueError('start and end must NOT be identical')\n translation, angle, axis, point = find_transformations(\n self.helix_start, self.helix_end, start, end)\n if not numpy.isclose(angle, 0.0):\n self.rotate(angle=angle, axis=axis, point=point, radians=False)\n self.translate(vector=translation)\n return\n\n\n__author__ = 'Jack W. Heal, Christopher W. Wood'\n", "meta": {"hexsha": "ab067e3fac9bbef5c4ed01df0d7440d53d3e0b94", "size": 12568, "ext": "py", "lang": "Python", "max_stars_repo_path": "isambard/ampal/specifications/polymer_specs/nucleic_acid_strand.py", "max_stars_repo_name": "woolfson-group/isambard", "max_stars_repo_head_hexsha": "ebc33b48a28ad217e18f93b910dfba46e6e71e07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2016-11-08T15:00:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-18T09:02:55.000Z", "max_issues_repo_path": "isambard/ampal/specifications/polymer_specs/nucleic_acid_strand.py", "max_issues_repo_name": "woolfson-group/isambard", "max_issues_repo_head_hexsha": "ebc33b48a28ad217e18f93b910dfba46e6e71e07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2016-11-08T17:25:51.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-11T10:51:33.000Z", "max_forks_repo_path": "isambard/ampal/specifications/polymer_specs/nucleic_acid_strand.py", "max_forks_repo_name": "woolfson-group/isambard", "max_forks_repo_head_hexsha": "ebc33b48a28ad217e18f93b910dfba46e6e71e07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-01-04T12:47:41.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-28T01:45:20.000Z", "avg_line_length": 35.8062678063, "max_line_length": 82, "alphanum_fraction": 0.5303946531, "include": true, "reason": "import numpy", "num_tokens": 3640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.23934934732271165, "lm_q1q2_score": 0.13639386018609523}} {"text": "\"\"\"\nThe main logic for building side chain with Monte Carlo Side Chain Ensemble algorithm,\n as defined in Bhowmick, Asmit, and Teresa Head-Gordon.\n \"A Monte Carlo method for generating side chain structural ensembles.\"\n Structure 23.1 (2015): 44-55.\n\nCoded by Jie Li\nDate created: Jul 29, 2021\n\"\"\"\n\nimport numpy as np\nimport numba as nb\nfrom numba import jit, njit\n\nfrom mcsce.core.rotamer_library import DunbrakRotamerLibrary\nfrom mcsce.core.definitions import aa3to1\nfrom mcsce.core.build_definitions import sidechain_templates\nfrom mcsce.libs.libcalc import calc_torsion_angles, place_sidechain_template\nfrom mcsce.libs.libscbuild import rotate_sidechain\nfrom tqdm import tqdm\nfrom copy import deepcopy\nfrom functools import partial\n\nfrom mcsce.libs.libstructure import Structure\n\n\n_rotamer_library = DunbrakRotamerLibrary()\n\nsidechain_placeholders = []\nenergy_calculators = []\n\n@jit(nb.int32(nb.float64[:]), nopython=True, nogil=True)\ndef choose_random(array):\n cumulative = [np.sum(array[:i + 1]) for i in range(len(array))]\n pointer = np.random.random() * cumulative[-1]\n for idx, num in enumerate(cumulative):\n if num > pointer:\n return idx\n return len(array) - 1\n\ndef initialize_func_calc(efunc_creator, aa_seq=None, structure=None):\n \"\"\"\n Helper function for initializing the energy function calculators according to the specified\n amino acid sequence or a structure object.\n\n Parameters\n ----------\n efunc_creator: partial function\n A partial function for creating energy functions for evaluating the generated conformations\n It should accept atom_label, res_num and res_label as inputs\n\n aa_seq: list\n List of 3-letter codes for the amino acid sequence\n\n structure: Structure object\n The structure with backbone atoms only\n \"\"\"\n # declare global variabales\n global sidechain_placeholders\n global energy_calculators\n\n sidechain_placeholders = []\n energy_calculators = []\n print(\"Start preparing energy calculators at different sidechain completion levels\")\n if structure is None:\n # create structure object according to the amino acid sequence\n fasta = \"\".join(aa3to1.get(res, 'X') for res in aa_seq)\n structure = Structure(fasta=fasta)\n structure.build()\n elif aa_seq is None:\n # extract amino acid sequence from structure object\n aa_seq = structure.residue_types\n structure = deepcopy(structure)\n sidechain_placeholders.append(deepcopy(structure))\n energy_calculators.append(efunc_creator(structure.atom_labels, \n structure.res_nums,\n structure.res_labels))\n for idx, resname in tqdm(enumerate(aa_seq), total=len(aa_seq)):\n template = sidechain_templates[resname]\n structure.add_side_chain(idx + 1, template)\n sidechain_placeholders.append(deepcopy(structure))\n if resname not in [\"GLY\", \"ALA\"]:\n n_sidechain_atoms = len(template[1])\n all_indices = np.arange(len(structure.atom_labels))\n energy_func = efunc_creator(structure.atom_labels, \n structure.res_nums,\n structure.res_labels,\n partial_indices=[all_indices[-n_sidechain_atoms:],\n all_indices[:-n_sidechain_atoms]])\n energy_calculators.append(energy_func)\n else:\n energy_calculators.append(None)\n print(\"Finished preparing all energy functions. Now start conformer generation\")\n\ndef create_side_chain_structure(inputs):\n \"\"\"\n A function that takes a backbone-only structure and generates a conformation using the Monte Carlo approach\n\n Parameters\n ----------\n (parameters are packaged into a list to allow multiprocessing)\n backbone_coords: np.array with shape (N, 3)\n Backbone atom coordinates that defines the conformation for growing side chains\n Order of atoms are assumed to be [\"N\", \"CA\", \"C\", \"O\", \"H1\", \"H2\", \"H3\"] for N-terminal residue,\n [\"N\", \"CA\", \"C\", \"O\", \"H\"] for middle residues, and \n then [\"N\", \"CA\", \"C\", \"O\", \"H\", \"OXT\"] for C-terminal residue\n\n beta: float\n The beta value used for Boltzmann weighting\n\n save_addr: str or None\n The path for saving the generated structure. When None, the structure is not saved locally\n\n Returns\n ----------\n all_atom_structure: Structure object\n The structure including side chain atoms\n\n succeeded: bool\n Whether the side chain growth completed successfully\n\n energy:\n The energy for the generated conformation\n \"\"\"\n backbone_coords, beta, save_addr = inputs\n assert len(sidechain_placeholders) > 0, \"Energy functions have not yet initialized!\"\n structure = deepcopy(sidechain_placeholders[0])\n structure.coords = backbone_coords\n N_CA_C_coords = structure.get_sorted_minimal_backbone_coords()\n all_backbone_dihedrals = calc_torsion_angles(N_CA_C_coords)\n all_phi = np.concatenate([[np.nan], all_backbone_dihedrals[2::3]]) * 180 / np.pi\n all_psi = np.concatenate([all_backbone_dihedrals[::3], [np.nan]]) * 180 / np.pi\n structure_coords = backbone_coords\n accumulated_energy = energy_calculators[0](structure_coords[None], structure_coords[None, :0])[0] # energies of backbone only\n for idx, resname in enumerate(structure.residue_types):\n # copy coordinates from the previous growing step to the current placeholder\n previous_coords = structure_coords\n # structure = deepcopy(sidechain_placeholders[idx])\n template_struc, sidechain_atom_idx = sidechain_templates[resname]\n n_sidechain_atoms = len(sidechain_atom_idx)\n new_coords = sidechain_placeholders[idx + 1].coords\n new_coords[:-n_sidechain_atoms] = previous_coords\n structure_coords = new_coords\n # coords = structure.coords\n residue_bb_coords = N_CA_C_coords[idx * 3: (idx + 1) * 3]\n if resname in [\"GLY\", \"ALA\"]:\n # For glycine and alanine, no degrees of freedom for bond rotations, so just move side chain to appropriate position\n sc_conformation = place_sidechain_template(residue_bb_coords, template_struc.coords)\n structure_coords[-n_sidechain_atoms:] = sc_conformation[sidechain_atom_idx]\n continue\n energy_func = energy_calculators[idx + 1]\n # get all candidate conformations (rotamers) for this side chain\n candidiate_conformations, candidate_probs = _rotamer_library.retrieve_torsion_and_prob(resname, all_phi[idx], all_psi[idx])\n # perturb chi angles of the side chains by ~0.5 degrees\n candidiate_conformations += np.random.normal(scale=0.5, size=candidiate_conformations.shape)\n \n energies = []\n \n all_coords = np.tile(structure_coords[None], (len(candidiate_conformations), 1, 1))\n # for each rotamer, decide the resulting conformation and calculate its energy\n for tor_idx, tors in enumerate(candidiate_conformations):\n sidechain_with_specific_chi = rotate_sidechain(resname, tors) # THIS STEP MIGHT BE SLOW\n sc_conformation = place_sidechain_template(residue_bb_coords, sidechain_with_specific_chi[0])\n all_coords[tor_idx, -n_sidechain_atoms:] = sc_conformation[sidechain_atom_idx]\n energies = energy_func(all_coords[:, -n_sidechain_atoms:], all_coords[:, : -n_sidechain_atoms])\n minimum_energy = min(energies) # Keep track of the minimum energy so that the renormalized energies can be converted back\n \n # print(idx, resname, len(candidate_probs), (~np.isinf(energies)).sum())\n # If all energies are inf, end this growth\n if np.isinf(energies).all():\n return None, False, None, None\n\n # renormalize energies to avoid numerical issues\n energies -= minimum_energy\n adjusted_weights = candidate_probs * np.exp(-beta * energies)\n selected_idx = choose_random(adjusted_weights)\n\n # set the coordinates of the actual structure that has side chain for this residue grown\n structure_coords = all_coords[selected_idx]\n accumulated_energy += energies[selected_idx] + minimum_energy # The raw energy for this step\n\n # all side chains have been created, then reorder all atoms and return the final structure\n structure = deepcopy(sidechain_placeholders[-1])\n structure.coords = structure_coords\n structure.reorder_with_resnum()\n if save_addr is not None:\n structure.write_PDB(save_addr)\n return structure, True, accumulated_energy, save_addr\n\ndef create_side_chain(structure, n_trials, temperature, parallel_worker=16, return_first_valid=False):\n \"\"\"\n Using the MCSCE workflow to add sidechains to a backbone-only PDB structure. The building process will be repeated for n_trial times, but only the lowest energy conformation will be returned \n\n Parameters\n ----------\n structure: Structure object\n The structure with backbone atoms only\n\n n_trials: int\n The total number of trials for the generation procedure\n if n_trials <=0, then sequentially generate structures until the first valid structure is generated\n\n efunc_creator: partial function\n A partial function for creating energy functions for evaluating the generated conformations\n It should accept atom_label, res_num and res_label as inputs\n\n temperature: float\n The temperature value used for Boltzmann weighting\n\n parallel_worker: int\n Number of workers for parallel execution\n\n return_first_valid: bool\n Controls the behavior of whether execute parallel building and return the first valid structure (no clashes), instead of generating a collection of structures and return the lowest energy one\n\n Returns\n ----------\n lowest_energy_conformation: Structure object\n The generated lowest-energy conformation structure with sidechains, or None when every trial of the conformation generation failed\n \"\"\"\n # convert temperature to beta\n beta = 1 / (temperature * 0.008314462) # k unit: kJ/mol/K\n\n conformations = []\n energies = []\n if return_first_valid:\n # Sequential execution with maximal n_trial times, but return the first valid structure\n for _ in range(n_trials):\n conf, succeeded, energy, _ = create_side_chain_structure([structure.coords, beta, None])\n if succeeded:\n return conf\n return None\n else:\n # Emsemble building with either sequential execution or parallelization\n if parallel_worker == 1:\n # sequential execution\n for idx in tqdm(range(n_trials)):\n conf, succeeded, energy, _ = create_side_chain_structure([structure.coords, beta, None])\n if succeeded:\n conformations.append(conf)\n energies.append(energy)\n else:\n import multiprocessing\n pool = multiprocessing.Pool(parallel_worker)\n\n with tqdm(total=n_trials) as pbar:\n for result in pool.imap_unordered(\n create_side_chain_structure, \\\n [[structure.coords, beta, None]] * n_trials):\n conf, succeeded, energy, _ = result\n if succeeded:\n conformations.append(conf)\n energies.append(energy)\n pbar.update()\n\n pool.close()\n pool.join()\n \n # define the lowest energy conformation and return\n if len(energies) == 0:\n return None\n else:\n lowest_energy_idx = np.argmin(energies)\n return conformations[lowest_energy_idx]\n\n\ndef create_side_chain_ensemble(structure, n_conformations, temperature, save_path, parallel_worker=16):\n \"\"\"\n Create a given number of conformation ensemble for the backbone-only structure of a protein\n\n Parameters\n ----------\n structure: Structure object\n The structure with backbone atoms only\n\n n_conformations: int\n The total number of conformations to be generated\n\n temperature: float\n The temperature value used for Boltzmann weighting\n\n save_path: str\n The folder path for saving all succeessfully generated PDB files\n\n Returns\n ----------\n conformations: list of Structure object\n The generated conformation structures\n\n all_success_count: int\n Total number of the generated structures that are not early-stopped due to unresolvable clashes\n \"\"\"\n\n\n # convert temperature to beta\n beta = 1 / (temperature * 0.008314462) # k unit: kJ/mol/K\n \n conformations = []\n success_indicator = []\n energies = {}\n\n if parallel_worker == 1:\n for idx in tqdm(range(n_conformations)):\n conf, succeeded, energy, save_dir = create_side_chain_structure([structure.coords, beta, save_path + f\"/{idx}.pdb\"])\n conformations.append(conf)\n success_indicator.append(succeeded)\n if succeeded:\n energies[save_dir] = energy\n else:\n # import pathos\n import multiprocessing\n # pool = pathos.multiprocessing.ProcessPool(parallel_worker)\n pool = multiprocessing.Pool(parallel_worker)\n # result_iterator = pool.starmap(create_side_chain_structure, \n # [[beta, save_path + f\"/{n}.pdb\"] for n in range(n_conformations)])\n # result_iterator = pool.uimap(create_side_chain_structure, \n # [beta] * n_conformations, [save_path + f\"/{n}.pdb\" for n in range(n_conformations)])\n \n with tqdm(total=n_conformations) as pbar:\n for result in pool.imap_unordered(create_side_chain_structure,\\\n [[structure.coords, beta, save_path + f\"/{n}.pdb\"] for n in range(n_conformations)]):\n conformations.append(result[0])\n success_indicator.append(result[1])\n if result[1]:\n # A succeeded case\n energies[result[3]] = result[2]\n pbar.update()\n\n pool.close()\n pool.join()\n with open(save_path + \"/energies.csv\", \"w\") as f:\n f.write(\"File name,Energy(kJ/mol)\\n\")\n for item in energies:\n f.write(\"%s,%f\\n\" % (item, energies[item]))\n return conformations, success_indicator\n\n", "meta": {"hexsha": "34fbfb60bbe3debc2155c71bc2be130e1c715539", "size": 14559, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/mcsce/core/side_chain_builder.py", "max_stars_repo_name": "THGLab/MCSCE", "max_stars_repo_head_hexsha": "3378631771113075fdd88bffea31f721e32df5d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mcsce/core/side_chain_builder.py", "max_issues_repo_name": "THGLab/MCSCE", "max_issues_repo_head_hexsha": "3378631771113075fdd88bffea31f721e32df5d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mcsce/core/side_chain_builder.py", "max_forks_repo_name": "THGLab/MCSCE", "max_forks_repo_head_hexsha": "3378631771113075fdd88bffea31f721e32df5d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.2017804154, "max_line_length": 199, "alphanum_fraction": 0.6716120613, "include": true, "reason": "import numpy,import numba,from numba", "num_tokens": 3108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.22815649166448124, "lm_q1q2_score": 0.13608009416414532}} {"text": "#!/usr/bin/env python\n\n\"\"\"GETPSF.PY - Determine the PSF by fitting to multiple stars in an image\n\n\"\"\"\n\n__authors__ = 'David Nidever =bbox.ixmin-xcen) & (x<=bbox.ixmax-1-xcen)\n xmin,xmax = dln.minmax(np.where(xcover)[0])\n ycover = (y>=bbox.iymin-ycen) & (y<=bbox.iymax-1-ycen)\n ymin,ymax = dln.minmax(np.where(ycover)[0]) \n im2[ymin:ymax+1,xmin:xmax+1] = f(y[ycover],x[xcover],grid=True)\n # Stuff it into 3D array\n cube[:,:,i] = im2\n return cube\n\ndef mkempirical(cube,order=0,coords=None,shape=None,rect=False,lookup=False):\n \"\"\"\n Take a star cube and collapse it to make an empirical PSF using median\n and outlier rejection.\n\n Parameters\n ----------\n cube : numpy array\n Three-dimensional cube of star images (or residual images) of shape\n (Npix,Npix,Nstars).\n order : int, optional\n The order of the variations. 0-constant, 1-linear terms. If order=1,\n Then coords and shape must be input.\n coords : tuple, optional\n Two-element tuple of the X/Y coordinates of the stars. This is needed\n to generate the linear empirical model (order=1).\n shape : tuple, optional\n Two-element tuple giving the shape (Ny,Nx) of the image. This is\n needed to generate the linear empirical model (order=1).\n rect : boolean, optional\n Return a list of RectBivariateSpline functions rather than a numpy array.\n lookup : boolean, optional\n Parameter to indicate if this is a lookup table. If lookup=False, then\n the constant term is constrained to be non-negative. Default is False.\n\n Returns\n -------\n epsf : numpy array\n The empirical PSF model If order=0, then this is just a 2D image. If\n order=1, then it will be a 3D cube (Npix,Npix,4) where the four terms\n are [constant, X-term, Y-term, X*Y-term]. If rect=True, then a list\n of RectBivariateSpline functions are returned.\n\n Example\n -------\n\n epsf = mkempirical(cube,order=0)\n\n or\n\n epsf = mkempirical(cube,order=1,coords=coords,shape=im.shape)\n\n \"\"\"\n\n ny,nx,nstar = cube.shape\n npix = ny\n nhpix = ny//2\n \n # Do outlier rejection in each pixel\n med = np.nanmedian(cube,axis=2)\n bad = ~np.isfinite(med)\n if np.sum(bad)>0:\n med[bad] = np.nanmedian(med)\n sig = dln.mad(cube,axis=2)\n bad = ~np.isfinite(sig)\n if np.sum(bad)>0:\n sig[bad] = np.nanmedian(sig) \n # Mask outlier points\n outliers = ((np.abs(cube-med.reshape((med.shape)+(-1,)))>3*sig.reshape((med.shape)+(-1,)))\n & np.isfinite(cube))\n nbadstar = np.sum(outliers,axis=(0,1))\n goodmask = ((np.abs(cube-med.reshape((med.shape)+(-1,)))<3*sig.reshape((med.shape)+(-1,)))\n & np.isfinite(cube)) \n # Now take the mean of the unmasked pixels\n macube = np.ma.array(cube,mask=~goodmask)\n medim = macube.mean(axis=2)\n medim = medim.data\n \n # Check how well each star fits the median\n goodpix = macube.count(axis=(0,1))\n rms = np.sqrt(np.nansum((cube-medim.reshape((medim.shape)+(-1,)))**2,axis=(0,1))/goodpix)\n\n xx,yy = np.meshgrid(np.arange(npix)-nhpix,np.arange(npix)-nhpix)\n rr = np.sqrt(xx**2+yy**2) \n x = xx[0,:]\n y = yy[:,0]\n mask = (rr<=nhpix)\n \n # Constant\n if order==0:\n # Make sure it goes to zero at large radius\n medim *= mask # mask corners\n # Make sure values are positive\n if lookup==False:\n medim = np.maximum(medim,0.0)\n if rect:\n fpars = [RectBivariateSpline(y,x,medim)]\n else:\n fpars = medim\n \n # Linear\n elif order==1:\n if coords is None or shape is None:\n raise ValueError('Need coords and shape with order=1')\n pars = np.zeros((ny,nx,4),float)\n # scale coordinates to -1 to +1\n xcen,ycen = coords\n relx,rely = models.relcoord(xcen,ycen,shape)\n # Loop over pixels and fit line to x/y\n for i in range(ny):\n for j in range(nx):\n data1 = cube[i,j,:]\n # maybe use a small maxiter\n pars1,perror1 = utils.poly2dfit(relx,rely,data1)\n pars[i,j,:] = pars1\n # Make sure it goes to zero at large radius\n if rect:\n fpars = []\n for i in range(4):\n # Make sure edges are zero on average for higher-order terms\n outer = np.median(pars[rr>nhpix*0.8,i])\n pars[:,:,i] -= outer\n # Mask corners\n pars[:,:,i] *= mask\n # Each higher-order term must have ZERO total volume\n # Set up the spline function that we can use to do\n # the interpolation\n fpars.append(RectBivariateSpline(y,x,pars[:,:,i]))\n else:\n fpars = pars\n \n return fpars,nbadstar,rms\n\ndef findpsfnei(allcat,psfcat,npix):\n \"\"\"\n Find stars near PSF stars.\n\n Parameters\n ----------\n allcat : table\n Catalog of all sources in the image.\n psfcat : table\n Catalog of PSF stars.\n npix : int\n Search radius in pixels.\n\n Returns\n -------\n indall : numpy array\n List of indices into allcat that are neighbors to\n the PSF stars (within radius of npix), and are not\n PSF stars themselves.\n\n Example\n -------\n\n indall = findpsfnei(allcat,psfcat,npix)\n\n \"\"\"\n # Returns distance and index of closest neighbor\n \n nallcat = len(allcat)\n npsfcat = len(psfcat)\n \n # Use KD-tree\n X1 = np.vstack((allcat['x'].data,allcat['y'].data)).T\n X2 = np.vstack((psfcat['x'].data,psfcat['y'].data)).T\n kdt = cKDTree(X1)\n # Get distance for 2 closest neighbors\n dist, ind = kdt.query(X2, k=50, distance_upper_bound=np.sqrt(2)*npix//2)\n # closest neighbor is always itself, remove it \n dist = dist[:,1:]\n ind = ind[:,1:]\n # Add up all the stars\n gdall, = np.where(np.isfinite(dist.ravel()))\n indall = ind.ravel()[gdall]\n # Get unique ones\n indall = np.unique(indall)\n\n # Make sure none of them are our psf stars\n ind1,ind2,dist = coords.xmatch(allcat['x'][indall],allcat['y'][indall],psfcat['x'],psfcat['y'],5)\n # Remove any matches\n if len(ind1)>0:\n indall = np.delete(indall,ind1)\n \n return indall\n\ndef subtractnei(image,allcat,psfcat,psf):\n \"\"\"\n Subtract neighboring stars to PSF stars from the image.\n\n Parameters\n ----------\n image : CCDDdata object\n The input image from which to subtract PSF neighbor stars.\n allcat : table\n Catalog of all sources in the image.\n psfcat : table\n Catalog of PSF stars.\n psf : PSF object\n The PSF model.\n\n Returns\n -------\n resid : CCDData object\n The input images with the PSF neighbor stars subtracted.\n\n Example\n -------\n\n subim = subtractnei(image,allcat,psfcat,psf)\n\n \"\"\"\n\n indnei = findpsfnei(allcat,psfcat,psf.npix)\n nnei = len(indnei)\n\n flux = image.data-image.sky\n resid = image.copy()\n fitradius = psf.fwhm()*0.5\n \n # Loop over neighboring stars and fit just the core\n for i in range(nnei):\n x1 = allcat['x'][indnei[i]]\n xp1 = int(np.minimum(np.maximum(np.round(x1),0),image.shape[1]-1))\n y1 = allcat['y'][indnei[i]]\n yp1 = int(np.minimum(np.maximum(np.round(y1),0),image.shape[0]-1))\n if 'amp' in allcat.columns:\n h1 = allcat['amp'][indnei[i]]\n elif 'peak' in allcat.columns:\n h1 = allcat['peak'][indnei[i]]\n else:\n h1 = flux[yp1,xp1]\n initpars = [h1,x1,y1] #image.sky[yp1,xp1]]\n bbox = psf.starbbox((initpars[1],initpars[2]),image.shape,psf.radius)\n # Fit amp empirically with central pixels\n flux1 = flux[bbox.slices]\n err1 = image[bbox.slices].error\n model1 = psf(pars=initpars,bbox=bbox)\n good = ((flux1/err1>2) & (flux1>0) & (model1/np.max(model1)>0.25))\n amp = np.median(flux1[good]/model1[good]) * initpars[0]\n pars = [amp, x1, y1]\n #starcat,perror = psf.fit(flux,pars=initpars,radius=fitradius,recenter=False,niter=2)\n #pars = [starcat['amp'][0],starcat['x'][0],starcat['y'][0]]\n im1 = psf(pars=pars,bbox=bbox)\n resid[bbox.slices].data -= im1\n return resid\n\nclass PSFFitter(object):\n\n def __init__(self,psf,image,cat,fitradius=None,verbose=False):\n self.verbose = verbose\n self.psf = psf\n self.image = image\n self.cat = cat\n self.nstars = np.size(cat)\n self.niter = 0\n self.npsfpix = psf.npix\n ny,nx = image.data.shape\n self.nx = nx\n self.ny = ny\n if fitradius is None:\n if type(psf)==models.PSFPenny:\n fitradius = psf.fwhm()*1.5\n else:\n fitradius = psf.fwhm()\n self.fitradius = fitradius\n self.nfitpix = int(np.ceil(fitradius)) # +/- nfitpix\n self.staramp = np.zeros(self.nstars,float)\n if 'amp' in cat.colnames:\n self.staramp[:] = cat['amp'].copy()\n else:\n # estimate amp from flux and fwhm\n # area under 2D Gaussian is 2*pi*A*sigx*sigy\n amp = cat['flux']/(2*np.pi*(cat['fwhm']/2.35)**2)\n self.staramp[:] = np.maximum(amp,0) # make sure it's positive\n # Original X/Y values\n self.starxcenorig = np.zeros(self.nstars,float)\n self.starxcenorig[:] = cat['x'].copy()\n self.starycenorig = np.zeros(self.nstars,float)\n self.starycenorig[:] = cat['y'].copy()\n # current best-fit values\n self.starxcen = np.zeros(self.nstars,float)\n self.starxcen[:] = cat['x'].copy()\n self.starycen = np.zeros(self.nstars,float)\n self.starycen[:] = cat['y'].copy() \n self.starchisq = np.zeros(self.nstars,float)\n self.starrms = np.zeros(self.nstars,float) \n self.starnpix = np.zeros(self.nstars,int)\n \n # Get xdata, ydata, error\n imdata = []\n bboxdata = []\n npixdata = []\n xlist = []\n ylist = []\n pixstart = []\n imflatten = np.zeros(self.nstars*(2*self.nfitpix+1)**2,float)\n errflatten = np.zeros(self.nstars*(2*self.nfitpix+1)**2,float)\n count = 0\n for i in range(self.nstars):\n xcen = self.starxcen[i]\n ycen = self.starycen[i]\n bbox = psf.starbbox((xcen,ycen),image.shape,radius=self.nfitpix)\n im = image[bbox.slices]\n flux = image.data[bbox.slices]-image.sky[bbox.slices]\n err = image.error[bbox.slices]\n imdata.append(im)\n bboxdata.append(bbox)\n # Trim to only the pixels that we want to fit\n #flux = im.data.copy()-im.sky.copy()\n #err = im.error.copy()\n # Zero-out anything beyond the fitting radius\n x,y = psf.bbox2xy(bbox)\n rr = np.sqrt( (x-xcen)**2 + (y-ycen)**2 )\n # Use image mask\n # mask=True for bad values\n if image.mask is not None: \n gdmask = (rr<=self.fitradius) & (image.mask[y,x]==False)\n else:\n gdmask = rr<=self.fitradius \n x = x[gdmask] # raveled\n y = y[gdmask]\n flux = flux[gdmask]\n err = err[gdmask]\n npix = len(flux)\n self.starnpix[i] = npix\n imflatten[count:count+npix] = flux\n errflatten[count:count+npix] = err\n pixstart.append(count)\n xlist.append(x)\n ylist.append(y)\n npixdata.append(npix)\n count += npix\n\n self.imdata = imdata\n self.bboxdata = bboxdata \n imflatten = imflatten[0:count] # remove extra elements\n errflatten = errflatten[0:count]\n self.imflatten = imflatten\n self.errflatten = errflatten\n self.ntotpix = count\n self.xlist = xlist\n self.ylist = ylist\n self.npix = npixdata\n self.pixstart = pixstart\n\n \n def model(self,x,*args,refit=True,verbose=False):\n \"\"\" model function.\"\"\"\n # input the model parameters\n \n if self.verbose:\n print('model: '+str(self.niter)+' '+str(args))\n \n psf = self.psf.copy()\n if type(psf)!=models.PSFEmpirical:\n psf._params = list(args)\n\n # Limit the parameters to the boundaries\n if type(psf)!=models.PSFEmpirical:\n lbnds,ubnds = psf.bounds\n for i in range(len(psf.params)):\n psf._params[i] = np.minimum(np.maximum(args[i],lbnds[i]),ubnds[i])\n \n # Loop over the stars and generate the model image\n allim = np.zeros(self.ntotpix,float)\n pixcnt = 0\n for i in range(self.nstars):\n image = self.imdata[i]\n amp = self.staramp[i]\n xcenorig = self.starxcenorig[i] \n ycenorig = self.starycenorig[i]\n xcen = self.starxcen[i] \n ycen = self.starycen[i] \n bbox = self.bboxdata[i]\n x = self.xlist[i]\n y = self.ylist[i]\n pixstart = self.pixstart[i]\n npix = self.npix[i]\n flux = self.imflatten[pixstart:pixstart+npix]\n err = self.errflatten[pixstart:pixstart+npix]\n \n #xy = self.xydata[i]\n #x = np.arange(xy[0][0],xy[0][1]+1).astype(float)\n #y = np.arange(xy[1][0],xy[1][1]+1).astype(float)\n #rr = np.sqrt( (x-xcen).reshape(-1,1)**2 + (y-ycen).reshape(1,-1)**2 )\n #mask = rr>self.fitradius\n\n x0orig = xcenorig - bbox.ixmin\n y0orig = ycenorig - bbox.iymin\n x0 = xcen - bbox.ixmin\n y0 = ycen - bbox.iymin \n \n # Fit amp/xcen/ycen if niter=1\n if refit:\n #if (self.niter<=1): # or self.niter%3==0):\n if self.niter>-1:\n # force the positions to stay within +/-2 pixels of the original values\n bounds = (np.array([0,np.maximum(x0orig-2,0),np.maximum(y0orig-2,0),-np.inf]),\n np.array([np.inf,np.minimum(x0orig+2,bbox.shape[1]-1),np.minimum(y0orig+2,bbox.shape[0]-1),np.inf]))\n # the image still has sky in it, use sky (nosky=False)\n if np.isfinite(psf.fwhm())==False:\n print('nan fwhm')\n import pdb; pdb.set_trace()\n pars,perror,model = psf.fit(image,[amp,x0,y0],nosky=False,retpararray=True,niter=5,bounds=bounds)\n xcen += (pars[1]-x0)\n ycen += (pars[2]-y0)\n amp = pars[0] \n self.staramp[i] = amp\n self.starxcen[i] = xcen\n self.starycen[i] = ycen\n model = psf(x,y,pars=[amp,xcen,ycen])\n if verbose:\n print('Star '+str(i)+' Refitting all parameters')\n print(str([amp,xcen,ycen]))\n\n #pars2,model2,mpars2 = psf.fit(image,[amp,x0,y0],nosky=False,niter=5,allpars=True)\n #import pdb; pdb.set_trace()\n \n # Only fit amp if niter>1\n # do it empirically\n else:\n #im1 = psf(pars=[1.0,xcen,ycen],bbox=bbox)\n #wt = 1/image.error**2\n #amp = np.median(image.data[mask]/im1[mask]) \n model1 = psf(x,y,pars=[1.0,xcen,ycen])\n wt = 1/err**2\n amp = np.median(flux/model1)\n #amp = np.median(wt*flux/model1)/np.median(wt)\n\n\n #count = 0\n #percdiff = 1e30\n #while (count<3 and percdiff>0.1): \n # m,jac = psf.jac(np.vstack((x,y)),*[amp,xcen,ycen],retmodel=True)\n # jac = np.delete(jac,[1,2],axis=1)\n # dy = flux-m\n # dbeta = lsq.jac_solve(jac,dy,method='cholesky',weight=wt)\n # print(count,amp,dbeta)\n # amp += dbeta\n # percdiff = np.abs(dbeta)/np.abs(amp)*100\n # count += 1\n \n #pars2,perror2,model2 = psf.fit(image,[amp,x0,y0],nosky=False,retpararray=True,niter=5)\n #amp = pars2[0]\n #model = psf(x,y,pars=[amp,xcen,ycen])\n \n self.staramp[i] = amp\n model = model1*amp\n #self.starxcen[i] = pars2[1]+xy[0][0]\n #self.starycen[i] = pars2[2]+xy[1][0] \n #print(count,self.starxcen[i],self.starycen[i])\n # updating the X/Y values after the first iteration\n # causes problems. bounces around too much\n\n if verbose:\n print('Star '+str(i)+' Refitting amp empirically')\n print(str(amp))\n \n #if i==1: print(amp)\n #if self.niter==2:\n # import pdb; pdb.set_trace()\n\n # No refit of stellar parameters\n else:\n model = psf(x,y,pars=[amp,xcen,ycen])\n\n #if self.niter>1:\n # import pdb; pdb.set_trace()\n \n # Relculate reduced chi squared\n chisq = np.sum((flux-model.ravel())**2/err**2)/npix\n self.starchisq[i] = chisq\n # chi value, RMS of the residuals as a fraction of the amp\n rms = np.sqrt(np.mean(((flux-model.ravel())/self.staramp[i])**2))\n self.starrms[i] = rms\n \n #model = psf(x,y,pars=[amp,xcen,ycen])\n # Zero-out anything beyond the fitting radius\n #im[mask] = 0.0\n #npix = im.size\n #npix = len(x)\n allim[pixcnt:pixcnt+npix] = model.flatten()\n pixcnt += npix\n\n #import pdb; pdb.set_trace()\n \n self.niter += 1\n \n return allim\n\n \n def jac(self,x,*args,retmodel=False,refit=True):\n \"\"\" jacobian.\"\"\"\n # input the model parameters\n\n if self.verbose:\n print('jac: '+str(self.niter)+' '+str(args))\n \n psf = self.psf.copy()\n psf._params = list(args)\n # Loop over the stars and generate the derivatives\n #-------------------------------------------------\n\n # Initalize output arrays\n allderiv = np.zeros((self.ntotpix,len(psf.params)),float)\n if retmodel:\n allim = np.zeros(self.ntotpix,float)\n pixcnt = 0\n\n # Need to run model() to calculate amp/xcen/ycen for first couple iterations\n #if self.niter<=1 and refit:\n # dum = self.model(x,*args,refit=refit)\n dum = self.model(x,*args,refit=True) #,verbose=True) \n \n for i in range(self.nstars):\n amp = self.staramp[i]\n xcen = self.starxcen[i] \n ycen = self.starycen[i]\n bbox = self.bboxdata[i]\n x = self.xlist[i]\n y = self.ylist[i]\n pixstart = self.pixstart[i]\n npix = self.npix[i]\n flux = self.imflatten[pixstart:pixstart+npix]\n err = self.errflatten[pixstart:pixstart+npix]\n xdata = np.vstack((x,y))\n \n #xy = self.xydata[i]\n #x2,y2 = psf.bbox2xy(bbox)\n #xdata = np.vstack((x2.ravel(),y2.ravel()))\n\n #x0 = xcen - bbox.ixmin\n #y0 = ycen - bbox.iymin\n\n #import pdb; pdb.set_trace()\n \n # Get the model and derivative\n allpars = np.concatenate((np.array([amp,xcen,ycen]),np.array(args)))\n m,deriv = psf.jac(xdata,*allpars,allpars=True,retmodel=True)\n #if retmodel:\n # m,deriv = psf.jac(xdata,*allpars,allpars=True,retmodel=True)\n #else:\n # deriv = psf.jac(xdata,*allpars,allpars=True) \n deriv = np.delete(deriv,[0,1,2],axis=1) # remove stellar ht/xc/yc columns\n\n # Solve for the best amp, and then scale the derivatives (all scale with amp)\n #if self.niter>1 and refit:\n # newamp = amp*np.median(flux/m)\n # self.staramp[i] = newamp\n # m *= (newamp/amp)\n # deriv *= (newamp/amp)\n\n #if i==1: print(amp,newamp)\n #import pdb; pdb.set_trace()\n\n npix,dum = deriv.shape\n allderiv[pixcnt:pixcnt+npix,:] = deriv\n if retmodel:\n allim[pixcnt:pixcnt+npix] = m\n pixcnt += npix\n \n if retmodel:\n return allim,allderiv\n else:\n return allderiv\n\n def linesearch(self,xdata,bestpar,dbeta,m,jac):\n # Perform line search along search gradient\n flux = self.imflatten\n # Weights\n wt = 1/self.errflatten**2\n \n start_point = bestpar\n search_gradient = dbeta\n def obj_func(pp,m=None):\n \"\"\" chisq given the parameters.\"\"\"\n if m is None:\n m = self.model(xdata,*pp) \n chisq = np.sum((flux.ravel()-m.ravel())**2 * wt.ravel())\n #print('obj_func: pp=',pp)\n #print('obj_func: chisq=',chisq)\n return chisq\n def obj_grad(pp,m=None,jac=None):\n \"\"\" Gradient of chisq wrt the parameters.\"\"\"\n if m is None or jac is None:\n m,jac = self.jac(xdata,*pp,retmodel=True)\n # d chisq / d parj = np.sum( 2*jac_ij*(m_i-d_i))/sig_i**2)\n dchisq = np.sum( 2*jac * (m.ravel()-flux.ravel()).reshape(-1,1)\n * wt.ravel().reshape(-1,1),axis=0)\n #print('obj_grad: pp=',pp)\n #print('obj_grad: dchisq=',dchisq) \n return dchisq\n\n # Inside model() the parameters are limited to the PSF bounds()\n f0 = obj_func(start_point,m=m)\n # Do our own line search with three points and a quadratic fit.\n f1 = obj_func(start_point+0.5*search_gradient)\n f2 = obj_func(start_point+search_gradient)\n alpha = dln.quadratic_bisector(np.array([0.0,0.5,1.0]),np.array([f0,f1,f2]))\n alpha = np.minimum(np.maximum(alpha,0.0),1.0) # 0=0\n \n # Add the lookup table to the PSF model\n self.psf.lookup = lookup\n\n #import pdb; pdb.set_trace()\n \n \n def starmodel(self,star=None,pars=None):\n \"\"\" Generate 2D star model images that can be compared to the original cutouts.\n if star=None, then it will return all of them as a list.\"\"\"\n\n psf = self.psf.copy()\n if pars is not None:\n psf._params = pars\n \n model = []\n if star is None:\n star = np.arange(self.nstars)\n else:\n star = [star]\n\n for i in star:\n image = self.imdata[i]\n amp = self.staramp[i]\n xcen = self.starxcen[i] \n ycen = self.starycen[i]\n bbox = self.bboxdata[i]\n model1 = psf(pars=[amp,xcen,ycen],bbox=bbox)\n model.append(model1)\n return model\n\n \ndef fitpsf(psf,image,cat,fitradius=None,method='qr',maxiter=10,minpercdiff=1.0,\n verbose=False):\n \"\"\"\n Fit PSF model to stars in an image.\n\n Parameters\n ----------\n psf : PSF object\n PSF object with initial parameters to use.\n image : CCDData object\n Image to use to fit PSF model to stars.\n cat : table\n Catalog with initial amp/x/y values for the stars to use to fit the PSF.\n fitradius : float, table\n The fitting radius. If none is input then the initial PSF FWHM will be used.\n method : str, optional\n Method to use for solving the non-linear least squares problem: \"qr\",\n \"svd\", \"cholesky\", and \"curve_fit\". Default is \"qr\".\n maxiter : int, optional\n Maximum number of iterations to allow. Only for methods \"qr\", \"svd\", and \"cholesky\".\n Default is 10.\n minpercdiff : float, optional\n Minimum percent change in the parameters to allow until the solution is\n considered converged and the iteration loop is stopped. Only for methods\n \"qr\" and \"svd\". Default is 1.0.\n verbose : boolean, optional\n Verbose output.\n\n Returns\n -------\n newpsf : PSF object\n New PSF object with the best-fit model parameters.\n pars : numpy array\n Array of best-fit model parameters\n perror : numpy array\n Uncertainties in \"pars\".\n psfcat : table\n Table of best-fitting amp/xcen/ycen values for the PSF stars.\n\n Example\n -------\n\n newpsf,pars,perror,psfcat = fitpsf(psf,image,cat)\n\n \"\"\"\n\n t0 = time.time()\n print = utils.getprintfunc() # Get print function to be used locally, allows for easy logging \n\n # Initialize the output catalog best-fitting values for the PSF stars\n dt = np.dtype([('id',int),('amp',float),('x',float),('y',float),('npix',int),('rms',float),\n ('chisq',float),('ixmin',int),('ixmax',int),('iymin',int),('iymax',int)])\n psfcat = np.zeros(len(cat),dtype=dt)\n if 'id' in cat.colnames:\n psfcat['id'] = cat['id']\n else:\n psfcat['id'] = np.arange(len(cat))+1\n \n\n # Fitting the PSF to the stars\n #-----------------------------\n\n # Empirical PSF - done differently\n if type(psf)==models.PSFEmpirical:\n cube1 = starcube(cat,image,npix=psf.npix,fillvalue=np.nan)\n coords = (cat['x'].data,cat['y'].data)\n epsf1,nbadstar1,rms1 = mkempirical(cube1,order=psf.order,coords=coords,shape=psf._shape)\n initpsf = models.PSFEmpirical(epsf1,imshape=image.shape,order=psf.order)\n pf = PSFFitter(initpsf,image,cat,fitradius=fitradius,verbose=False)\n # Fit the amp, xcen, ycen properly\n xdata = np.arange(pf.ntotpix)\n out = pf.model(xdata,[])\n # Put information into the psfcat table\n psfcat['amp'] = pf.staramp\n psfcat['x'] = pf.starxcen\n psfcat['y'] = pf.starycen\n psfcat['chisq'] = pf.starchisq\n psfcat['rms'] = pf.starrms\n psfcat['npix'] = pf.starnpix \n for i in range(len(cat)):\n bbox = pf.bboxdata[i]\n psfcat['ixmin'][i] = bbox.ixmin\n psfcat['ixmax'][i] = bbox.ixmax\n psfcat['iymin'][i] = bbox.iymin\n psfcat['iymax'][i] = bbox.iymax \n psfcat = Table(psfcat)\n # Remake the empirical EPSF \n cube = starcube(psfcat,image,npix=psf.npix,fillvalue=np.nan)\n epsf,nbadstar,rms = mkempirical(cube,order=psf.order,coords=coords,shape=psf._shape)\n newpsf = models.PSFEmpirical(epsf,imshape=image.shape,order=psf.order)\n if verbose:\n print('Median RMS: '+str(np.median(pf.starrms)))\n print('dt = %.2f sec' % (time.time()-t0))\n return newpsf, None, None, psfcat, pf\n \n pf = PSFFitter(psf,image,cat,fitradius=fitradius,verbose=False) #verbose)\n xdata = np.arange(pf.ntotpix)\n initpar = psf.params.copy()\n method = str(method).lower()\n \n # Curve_fit\n if method=='curve_fit': \n # Perform the fitting\n bestpar,cov = curve_fit(pf.model,xdata,pf.imflatten,\n sigma=pf.errflatten,p0=initpar,jac=pf.jac)\n perror = np.sqrt(np.diag(cov))\n \n # All other fitting methods\n else:\n # Iterate\n count = 0\n percdiff = 1e10\n bestpar = initpar.copy()\n\n dchisq = -1\n oldchisq = 1e30\n bounds = psf.bounds\n maxsteps = psf._steps\n while (countminpercdiff and dchisq<0):\n # Get the Jacobian and model\n m,jac = pf.jac(xdata,*bestpar,retmodel=True)\n chisq = np.sum((pf.imflatten-m)**2/pf.errflatten**2)\n dy = pf.imflatten-m\n # Weights\n wt = 1/pf.errflatten**2\n # Solve Jacobian\n dbeta = lsq.jac_solve(jac,dy,method=method,weight=wt)\n\n # Perform line search\n alpha,new_dbeta = pf.linesearch(xdata,bestpar,dbeta,m,jac)\n \n if verbose:\n print(' pars = '+str(bestpar))\n print(' dbeta = '+str(dbeta))\n\n # Update the parameters\n oldpar = bestpar.copy()\n #bestpar = psf.newpars(bestpar,dbeta,bounds,maxsteps)\n bestpar = psf.newpars(bestpar,new_dbeta,bounds,maxsteps) \n diff = np.abs(bestpar-oldpar)\n denom = np.abs(oldpar.copy())\n denom[denom==0] = 1.0 # deal with zeros\n percdiff = np.max(diff/denom*100)\n dchisq = chisq-oldchisq\n percdiffchisq = dchisq/oldchisq*100\n oldchisq = chisq\n count += 1\n \n if verbose:\n print(' '+str(count+1)+' '+str(bestpar)+' '+str(percdiff)+' '+str(chisq))\n \n # Make the best model\n bestmodel = pf.model(xdata,*bestpar)\n \n # Estimate uncertainties\n if method != 'curve_fit':\n # Calculate covariance matrix\n cov = lsq.jac_covariance(jac,dy,wt=wt)\n perror = np.sqrt(np.diag(cov))\n \n pars = bestpar\n if verbose:\n print('Best-fitting parameters: '+str(pars))\n print('Errors: '+str(perror))\n print('Median RMS: '+str(np.median(pf.starrms)))\n\n # create the best-fitting PSF\n newpsf = psf.copy()\n newpsf._params = pars \n\n # Output best-fitting values for the PSF stars as well\n dt = np.dtype([('id',int),('amp',float),('x',float),('y',float),('npix',int),('rms',float),\n ('chisq',float),('ixmin',int),('ixmax',int),('iymin',int),('iymax',int)])\n psfcat = np.zeros(len(cat),dtype=dt)\n if 'id' in cat.colnames:\n psfcat['id'] = cat['id']\n else:\n psfcat['id'] = np.arange(len(cat))+1\n psfcat['amp'] = pf.staramp\n psfcat['x'] = pf.starxcen\n psfcat['y'] = pf.starycen\n psfcat['chisq'] = pf.starchisq\n psfcat['rms'] = pf.starrms\n psfcat['npix'] = pf.starnpix \n for i in range(len(cat)):\n bbox = pf.bboxdata[i]\n psfcat['ixmin'][i] = bbox.ixmin\n psfcat['ixmax'][i] = bbox.ixmax\n psfcat['iymin'][i] = bbox.iymin\n psfcat['iymax'][i] = bbox.iymax \n psfcat = Table(psfcat)\n \n if verbose:\n print('dt = %.2f sec' % (time.time()-t0))\n \n # Make the star models\n #starmodels = pf.starmodel(pars=pars)\n \n return newpsf, pars, perror, psfcat, pf\n\n \ndef getpsf(psf,image,cat,fitradius=None,lookup=False,lorder=0,method='qr',subnei=False,\n allcat=None,maxiter=10,minpercdiff=1.0,reject=False,maxrejiter=3,verbose=False):\n \"\"\"\n Fit PSF model to stars in an image with outlier rejection of badly-fit stars.\n\n Parameters\n ----------\n psf : PSF object\n PSF object with initial parameters to use.\n image : CCDData object\n Image to use to fit PSF model to stars.\n cat : table\n Catalog with initial amp/x/y values for the stars to use to fit the PSF.\n fitradius : float, table\n The fitting radius. If none is input then the initial PSF FWHM will be used.\n lookup : boolean, optional\n Use an empirical lookup table. Default is False.\n lorder : int, optional\n The order of the spatial variations (0=constant, 1=linear). Default is 0.\n method : str, optional\n Method to use for solving the non-linear least squares problem: \"qr\",\n \"svd\", \"cholesky\", and \"curve_fit\". Default is \"qr\".\n subnei : boolean, optional\n Subtract stars neighboring the PSF stars. Default is False.\n allcat : table, optional\n Catalog of all objects in the image. This is needed for bad PSF star\n rejection.\n maxiter : int, optional\n Maximum number of iterations to allow. Only for methods \"qr\", \"svd\", and \"cholesky\".\n Default is 10.\n minpercdiff : float, optional\n Minimum percent change in the parameters to allow until the solution is\n considered converged and the iteration loop is stopped. Only for methods\n \"qr\" and \"svd\". Default is 1.0.\n reject : boolean, optional\n Reject PSF stars with high RMS values. Default is False.\n maxrejiter : int, boolean\n Maximum number of PSF star rejection iterations. Default is 3.\n verbose : boolean, optional\n Verbose output.\n\n Returns\n -------\n newpsf : PSF object\n New PSF object with the best-fit model parameters.\n pars : numpy array\n Array of best-fit model parameters\n perror : numpy array\n Uncertainties in \"pars\".\n psfcat : table\n Table of best-fitting amp/xcen/ycen values for the PSF stars.\n\n Example\n -------\n\n newpsf,pars,perror,psfcat = getpsf(psf,image,cat)\n\n \"\"\"\n\n t0 = time.time()\n print = utils.getprintfunc() # Get print function to be used locally, allows for easy logging \n\n # Fitting radius\n if fitradius is None:\n if type(psf)==models.PSFPenny:\n fitradius = psf.fwhm()*1.5\n else:\n fitradius = psf.fwhm()\n \n # subnei but no allcat input\n if subnei and allcat is None:\n raise ValueError('allcat is needed for PSF neighbor star subtraction')\n \n if 'id' not in cat.colnames:\n cat['id'] = np.arange(len(cat))+1\n psfcat = cat.copy()\n\n # Initializing output PSF star catalog\n dt = np.dtype([('id',int),('amp',float),('x',float),('y',float),('npix',int),('rms',float),\n ('chisq',float),('ixmin',int),('ixmax',int),('iymin',int),('iymax',int),('reject',int)])\n outcat = np.zeros(len(cat),dtype=dt)\n outcat = Table(outcat)\n for n in ['id','x','y']:\n outcat[n] = cat[n]\n \n # Remove stars that are too close to the edge\n ny,nx = image.shape\n bd = (psfcat['x'](nx-1-fitradius)) | \\\n (psfcat['y'](ny-1-fitradius))\n nbd = np.sum(bd)\n if nbd > 0:\n if verbose:\n print('Removing '+str(nbd)+' stars near the edge')\n psfcat = psfcat[~bd]\n\n # Generate an empirical image of the stars\n # and fit a model to it to get initial estimates\n if type(psf)!=models.PSFEmpirical:\n cube = starcube(psfcat,image,npix=psf.npix,fillvalue=np.nan)\n epsf,nbadstar,rms = mkempirical(cube,order=0)\n epsfim = CCDData(epsf,error=epsf.copy()*0+1,mask=~np.isfinite(epsf))\n pars,perror,mparams = psf.fit(epsfim,pars=[1.0,psf.npix/2,psf.npix//2],allpars=True)\n initpar = mparams.copy()\n curpsf = psf.copy()\n curpsf.params = initpar\n if verbose:\n print('Initial estimate from empirical PSF fit = '+str(mparams))\n else:\n curpsf = psf.copy()\n initpar = psf.params.copy()\n \n # Outlier rejection iterations\n nrejiter = 0\n flag = 0\n nrejstar = 100\n fitrad = fitradius\n useimage = image.copy()\n while (flag==0):\n if verbose:\n print('--- Iteration '+str(nrejiter+1)+' ---') \n\n # Update the fitting radius\n if nrejiter>0:\n fitrad = curpsf.fwhm()\n if verbose:\n print(' Fitting radius = %5.3f' % (fitrad))\n \n # Reject outliers\n if reject and nrejiter>0:\n medrms = np.median(pcat['rms'])\n sigrms = dln.mad(pcat['rms'].data)\n gd, = np.where(pcat['rms'] < medrms+3*sigrms)\n nrejstar = len(psfcat)-len(gd)\n if verbose:\n print(' RMS = %6.4f +/- %6.4f' % (medrms,sigrms))\n print(' Threshold RMS = '+str(medrms+3*sigrms))\n print(' Rejecting '+str(nrejstar)+' stars')\n if nrejstar>0:\n psfcat = psfcat[gd]\n\n # Subtract neighbors\n if nrejiter>0 and subnei:\n if verbose:\n print('Subtracting neighbors')\n # Find the neighbors in allcat\n # Fit the neighbors and PSF stars\n # Subtract neighbors from the image\n useimage = image.copy() # start with original image\n useimage = subtractnei(useimage,allcat,cat,curpsf)\n \n # Fitting the PSF to the stars\n #-----------------------------\n newpsf,pars,perror,pcat,pf = fitpsf(curpsf,useimage,psfcat,fitradius=fitrad,method=method,\n maxiter=maxiter,minpercdiff=minpercdiff,verbose=verbose)\n\n # Add information into the output catalog\n ind1,ind2 = dln.match(outcat['id'],pcat['id'])\n outcat['reject'] = 1\n for n in pcat.columns:\n outcat[n][ind1] = pcat[n][ind2]\n outcat['reject'][ind1] = 0\n\n # Compare PSF parameters\n if type(newpsf)!=models.PSFEmpirical:\n pardiff = newpsf.params-curpsf.params\n else:\n pardiff = newpsf._data-curpsf._data\n sumpardiff = np.sum(np.abs(pardiff))\n curpsf = newpsf.copy()\n \n # Stopping criteria\n if reject is False or sumpardiff<0.05 or nrejiter>=maxrejiter or nrejstar==0: flag=1\n if subnei is True and nrejiter==0: flag=0 # iterate at least once with neighbor subtraction\n \n nrejiter += 1\n \n # Generate an empirical look-up table of corrections\n if lookup:\n if verbose:\n print('Making empirical lookup table with order='+str(lorder))\n\n pf.mklookup(lorder)\n # Fit the stars again and get new RMS values\n xdata = np.arange(pf.ntotpix)\n out = pf.model(xdata,*pf.psf.params)\n newpsf = pf.psf.copy()\n # Update information in the output catalog\n ind1,ind2 = dln.match(outcat['id'],pcat['id'])\n outcat['reject'] = 1\n outcat['reject'][ind1] = 0\n outcat['amp'][ind1] = pf.staramp[ind2]\n outcat['x'][ind1] = pf.starxcen[ind2]\n outcat['y'][ind1] = pf.starycen[ind2]\n outcat['rms'][ind1] = pf.starrms[ind2]\n outcat['chisq'][ind1] = pf.starchisq[ind2] \n if verbose:\n print('Median RMS: '+str(np.median(pf.starrms))) \n \n if verbose:\n print('dt = %.2f sec' % (time.time()-t0))\n \n return newpsf, pars, perror, outcat\n", "meta": {"hexsha": "3c5b80bfc3215635f5fb424dda6c4b1430dbb6b9", "size": 42427, "ext": "py", "lang": "Python", "max_stars_repo_path": "prometheus/getpsf.py", "max_stars_repo_name": "dnidever/prometheus", "max_stars_repo_head_hexsha": "153865ece023b93d51b481106d09ef929e431417", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prometheus/getpsf.py", "max_issues_repo_name": "dnidever/prometheus", "max_issues_repo_head_hexsha": "153865ece023b93d51b481106d09ef929e431417", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prometheus/getpsf.py", "max_forks_repo_name": "dnidever/prometheus", "max_forks_repo_head_hexsha": "153865ece023b93d51b481106d09ef929e431417", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8609904431, "max_line_length": 132, "alphanum_fraction": 0.5512763099, "include": true, "reason": "import numpy,from scipy,import astropy,from astropy", "num_tokens": 11695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.2598256322295121, "lm_q1q2_score": 0.13599802308417222}} {"text": "\"\"\"\nThis module contains the TreeGrower class.\n\nTreeGrowee builds a regression tree fitting a Newton-Raphson step, based on\nthe gradients and hessians of the training data.\n\"\"\"\nfrom heapq import heappush, heappop\nimport numpy as np\nfrom numba import njit, prange\nfrom time import time\n\nfrom .splitting import (SplittingContext, split_indices, find_node_split, update_prediction_values)\nfrom .predictor import TreePredictor, PREDICTOR_RECORD_DTYPE\n\nfrom pygbm.options import OptionSet\n\n\nclass TreeNode:\n \"\"\"Tree Node class used in TreeGrower.\n\n This isn't used for prediction purposes, only for training (see\n TreePredictor).\n\n Parameters\n ----------\n depth : int\n The depth of the node, i.e. its distance from the root\n samples_indices : array of int\n The indices of the samples at the node\n sum_gradients : float\n The sum of the gradients of the samples at the node\n sum_hessians : float\n The sum of the hessians of the samples at the node\n parent : TreeNode or None, optional(default=None)\n The parent of the node. None for root.\n\n Attributes\n ----------\n depth : int\n The depth of the node, i.e. its distance from the root\n samples_indices : array of int\n The indices of the samples at the node\n sum_g_hf, sum_gx_hfx, sum_h, sum_hx, sum_hx2 : float\n Difference sums for samples at the node\n parent : TreeNode or None, optional(default=None)\n The parent of the node. None for root.\n split_info : SplitInfo or None\n The result of the split evaluation\n left_child : TreeNode or None\n The left child of the node. None for leaves.\n right_child : TreeNode or None\n The right child of the node. None for leaves.\n value : float or None\n The value of the leaf, as computed in finalize_leaf(). None for\n non-leaf nodes\n find_split_time : float\n The total time spent computing the histogram and finding the best\n split at the node.\n construction_speed : float\n The Number of samples at the node divided find_split_time.\n apply_split_time : float\n The total time spent actually splitting the node, e.g. splitting\n samples_indices into left and right child.\n hist_subtraction : bool\n Wheter the subtraction method was used for computing the histograms.\n \"\"\"\n\n split_info = None\n left_child = None\n right_child = None\n value = None\n left_coefficient=None\n right_coefficient=None\n histograms = None\n sibling = None\n parent = None\n find_split_time = 0.\n construction_speed = 0.\n apply_split_time = 0.\n hist_subtraction = False\n\n def __init__(self, depth, sample_indices, sum_g_hf, sum_gx_hfx, sum_h, sum_hx, sum_hx2, parent=None):\n self.depth = depth\n self.sample_indices = sample_indices\n self.n_samples = sample_indices.shape[0]\n self.sum_g_hf = sum_g_hf\n self.sum_gx_hfx = sum_gx_hfx\n self.sum_h = sum_h\n self.sum_hx = sum_hx\n self.sum_hx2 = sum_hx2\n self.parent = parent\n\n def __repr__(self):\n # To help with debugging\n out = f\"TreeNode: depth={self.depth}, \"\n out += f\"samples={len(self.sample_indices)}\"\n if self.split_info is not None:\n out += f\", feature_idx={self.split_info.feature_idx}\"\n out += f\", bin_idx={self.split_info.bin_idx}\"\n return out\n\n def __lt__(self, other_node):\n \"\"\"Comparison for priority queue.\n\n Nodes with high gain are higher priority than nodes with low gain.\n\n heapq.heappush only need the '<' operator.\n heapq.heappop take the smallest item first (smaller is higher\n priority).\n\n Parameters\n -----------\n other_node : TreeNode\n The node to compare with.\n \"\"\"\n if self.split_info is None or other_node.split_info is None:\n raise ValueError(\"Cannot compare nodes with split_info\")\n return self.split_info.gain > other_node.split_info.gain\n\n\nclass TreeGrower:\n \"\"\"Tree grower class used to build a tree.\n\n The tree is fitted to predict the values of a Newton-Raphson step. The\n splits are considered in a best-first fashion, and the quality of a\n split is defined in splitting._split_gain.\n\n Parameters\n ----------\n X_binned : array-like of int, shape=(n_samples, n_features)\n The binned input samples. Must be Fortran-aligned.\n gradients : array-like, shape=(n_samples,)\n The gradients of each training sample. Those are the gradients of the\n loss w.r.t the predictions, evaluated at iteration ``i - 1``.\n hessians : array-like, shape=(n_samples,)\n The hessians of each training sample. Those are the hessians of the\n loss w.r.t the predictions, evaluated at iteration ``i - 1``.\n max_leaf_nodes : int or None, optional(default=None)\n The maximum number of leaves for each tree. If None, there is no\n maximum limit.\n max_depth : int or None, optional(default=None)\n The maximum depth of each tree. The depth of a tree is the number of\n nodes to go from the root to the deepest leaf.\n min_samples_leaf : int, optional(default=20)\n The minimum number of samples per leaf.\n min_gain_to_split : float, optional(default=0.)\n The minimum gain needed to split a node. Splits with lower gain will\n be ignored.\n max_bins : int, optional(default=256)\n The maximum number of bins. Used to define the shape of the\n histograms.\n n_bins_per_feature : array-like of int or int, optional(default=None)\n The actual number of bins needed for each feature, which is lower or\n equal to ``max_bins``. If it's an int, all features are considered to\n have the same number of bins. If None, all features are considered to\n have ``max_bins`` bins.\n l2_regularization : float, optional(default=0)\n The L2 regularization parameter.\n min_det_to_split : float, optional(default=1e-3)\n The minimum sum of hessians needed in each node. Splits that result in\n at least one child having a sum of hessians less than\n min_determinant_to_split are discarded.\n shrinkage : float, optional(default=1)\n The shrinkage parameter to apply to the leaves values, also known as\n learning rate.\n \"\"\"\n def __init__(self, dataset, gradients, hessians, options: OptionSet):\n\n self.max_leaf_nodes = options['max_leaf_nodes']\n self.max_depth = options['max_depth']\n self.min_samples_leaf = options['min_samples_leaf']\n self.min_gain_to_split = options['min_gain_to_split']\n self.max_bins = options['max_bins']\n self.n_bins_per_feature = dataset.n_bins_per_feature\n self.numerical_thresholds = dataset.numerical_thresholds\n self.w_l2_reg = options['w_l2_reg']\n self.b_l2_reg = options['b_l2_reg']\n self.min_hessian_to_split = options['min_hessian_to_split']\n self.shrinkage = options['learning_rate']\n\n self._validate_parameters(dataset.X_binned, dataset.X, self.max_leaf_nodes, self.max_depth,\n self.min_samples_leaf, self.min_gain_to_split,\n self.w_l2_reg, self.b_l2_reg, self.min_hessian_to_split)\n\n if self.n_bins_per_feature is None:\n self.n_bins_per_feature = self.max_bins\n\n if isinstance(self.n_bins_per_feature, int):\n self.n_bins_per_feature = np.array(\n [self.n_bins_per_feature] * dataset.X_binned.shape[1],\n dtype=np.uint32)\n\n self.splitting_context = SplittingContext(\n dataset.X_binned, dataset.X, self.max_bins, self.n_bins_per_feature, gradients,\n hessians, self.w_l2_reg, self.b_l2_reg, self.min_hessian_to_split,\n self.min_samples_leaf, self.min_gain_to_split)\n self.X_binned = dataset.X_binned\n self.splittable_nodes = []\n self.finalized_leaves = []\n self.total_find_split_time = 0. # time spent finding the best splits\n self.total_apply_split_time = 0. # time spent splitting nodes\n self._initialize_root()\n self.n_nodes = 1\n\n def _validate_parameters(self, X_binned, X, max_leaf_nodes, max_depth,\n min_samples_leaf, min_gain_to_split,\n w_l2_reg, b_l2_reg, min_hessian_to_split):\n \"\"\"Validate parameters passed to __init__.\n\n Also validate parameters passed to SplittingContext because we cannot\n raise exceptions in a jitclass.\n \"\"\"\n if X_binned.dtype != np.uint8:\n raise NotImplementedError(\n \"Explicit feature binning required for now\")\n if not X_binned.flags.f_contiguous:\n raise ValueError(\n \"X_binned should be passed as Fortran contiguous \"\n \"array for maximum efficiency.\")\n if not X.flags.f_contiguous:\n raise ValueError(\n \"X should be passed as Fortran contiguous \"\n \"array for maximum efficiency.\")\n if max_leaf_nodes is not None and max_leaf_nodes < 1:\n raise ValueError(f'max_leaf_nodes={max_leaf_nodes} should not be'\n f' smaller than 1')\n if max_depth is not None and max_depth < 1:\n raise ValueError(f'max_depth={max_depth} should not be'\n f' smaller than 1')\n if min_samples_leaf < 1:\n raise ValueError(f'min_samples_leaf={min_samples_leaf} should '\n f'not be smaller than 1')\n if min_gain_to_split < 0:\n raise ValueError(f'min_gain_to_split={min_gain_to_split} '\n f'must be positive.')\n if w_l2_reg < 0 or b_l2_reg < 0:\n raise ValueError(f'l2_regularization=w:{w_l2_reg},b:{b_l2_reg} must be '\n f'positive.')\n if min_hessian_to_split < 0:\n raise ValueError(f'min_hessian_to_split={min_hessian_to_split} '\n f'must be positive.')\n\n def grow(self):\n \"\"\"Grow the tree, from root to leaves.\"\"\"\n while self.can_split_further():\n self.split_next()\n\n def _initialize_root(self):\n \"\"\"Initialize root node and finalize it if needed.\"\"\"\n n_samples = self.X_binned.shape[0]\n depth = 0\n self.root = TreeNode(\n depth=depth,\n sample_indices=self.splitting_context.partition.view(),\n sum_g_hf=self.splitting_context.gradients.sum(),\n sum_h=self.splitting_context.hessians.sum(),\n sum_gx_hfx=0,\n sum_hx=0,\n sum_hx2=0\n )\n if (self.max_leaf_nodes is not None and self.max_leaf_nodes == 1):\n self._finalize_leaf(self.root)\n return\n if self.root.n_samples < 2 * self.min_samples_leaf:\n # Do not even bother computing any splitting statistics.\n self._finalize_leaf(self.root)\n return\n\n self._compute_root_spittability()\n\n def _compute_root_spittability(self):\n \"\"\"Compute histograms and best possible split of a root node\n \"\"\"\n node = self.root\n tic = time()\n split_info, histograms = find_node_split(\n self.splitting_context, node.sample_indices)\n\n toc = time()\n node.find_split_time = toc - tic\n self.total_find_split_time += node.find_split_time\n node.construction_speed = node.n_samples / node.find_split_time\n node.split_info = split_info\n node.histograms = histograms\n\n if node.split_info.gain <= 0: # no valid split\n# import pdb; pdb.set_trace()\n # Note: this condition is reached if either all the leaves are\n # pure (best gain = 0), or if no split would satisfy the\n # constraints, (min_hessians_to_split, min_gain_to_split,\n # min_samples_leaf)\n self._finalize_leaf(node)\n\n else:\n heappush(self.splittable_nodes, node)\n\n def _compute_sibling_splittability(self, left_child_node, right_child_node):\n if left_child_node.n_samples > right_child_node.n_samples:\n min_child_node, max_child_node = right_child_node, left_child_node\n else:\n min_child_node, max_child_node = left_child_node, right_child_node\n\n if max_child_node.n_samples < 2 * self.min_samples_leaf:\n self._finalize_leaf(max_child_node)\n self._finalize_leaf(min_child_node)\n return left_child_node, right_child_node\n\n tic = time()\n split_info, histograms = find_node_split(\n self.splitting_context, min_child_node.sample_indices)\n toc = time()\n min_child_node.find_split_time = toc - tic\n self.total_find_split_time += min_child_node.find_split_time\n min_child_node.construction_speed = min_child_node.n_samples / min_child_node.find_split_time\n min_child_node.split_info = split_info\n min_child_node.histograms = histograms\n\n tic = time()\n split_info, histograms = find_node_split(\n self.splitting_context, max_child_node.sample_indices)\n toc = time()\n max_child_node.find_split_time = toc - tic\n self.total_find_split_time += max_child_node.find_split_time\n max_child_node.construction_speed = max_child_node.n_samples / max_child_node.find_split_time\n max_child_node.split_info = split_info\n max_child_node.histograms = histograms\n\n if max_child_node.split_info.gain <= 0: # no valid split\n # Note: this condition is reached if either all the leaves are\n # pure (best gain = 0), or if no split would satisfy the\n # constraints, (min_hessians_to_split, min_gain_to_split,\n # min_samples_leaf)\n self._finalize_leaf(max_child_node)\n\n else:\n heappush(self.splittable_nodes, max_child_node)\n\n if min_child_node.split_info.gain <= 0: # no valid split\n # Note: this condition is reached if either all the leaves are\n # pure (best gain = 0), or if no split would satisfy the\n # constraints, (min_hessians_to_split, min_gain_to_split,\n # min_samples_leaf)\n self._finalize_leaf(min_child_node)\n\n else:\n heappush(self.splittable_nodes, min_child_node)\n\n return left_child_node, right_child_node\n\n def split_next(self):\n \"\"\"Split the node with highest potential gain.\n\n Returns\n -------\n left : TreeNode\n The resulting left child.\n right : TreeNode\n The resulting right child.\n \"\"\"\n if len(self.splittable_nodes) == 0:\n raise StopIteration(\"No more splittable nodes\")\n\n # Consider the node with the highest loss reduction (a.k.a. gain)\n node = heappop(self.splittable_nodes)\n\n tic = time()\n (sample_indices_left, sample_indices_right) = split_indices(\n self.splitting_context, node.split_info, node.sample_indices)\n toc = time()\n node.apply_split_time = toc - tic\n self.total_apply_split_time += node.apply_split_time\n\n depth = node.depth + 1\n n_leaf_nodes = len(self.finalized_leaves) + len(self.splittable_nodes)\n n_leaf_nodes += 2\n\n left_child_node = TreeNode(depth,\n sample_indices_left,\n node.split_info.left_g_hf,\n node.split_info.left_gx_hfx,\n node.split_info.left_h,\n node.split_info.left_hx,\n node.split_info.left_hx2,\n parent=node)\n right_child_node = TreeNode(depth,\n sample_indices_right,\n node.split_info.right_g_hf,\n node.split_info.right_gx_hfx,\n node.split_info.right_h,\n node.split_info.right_hx,\n node.split_info.right_hx2,\n parent=node)\n left_child_node.sibling = right_child_node\n right_child_node.sibling = left_child_node\n node.right_child = right_child_node\n node.left_child = left_child_node\n self.n_nodes += 2\n\n node.left_coefficient = self._compute_linear_coefficient(left_child_node)\n node.right_coefficient = self._compute_linear_coefficient(right_child_node)\n\n update_prediction_values(\n self.splitting_context, sample_indices_left,\n node.left_coefficient, node.split_info.feature_idx\n )\n update_prediction_values(\n self.splitting_context, sample_indices_right,\n node.right_coefficient, node.split_info.feature_idx\n )\n\n if (self.max_leaf_nodes is not None\n and n_leaf_nodes == self.max_leaf_nodes):\n self._finalize_leaf(left_child_node)\n self._finalize_leaf(right_child_node)\n self._finalize_splittable_nodes()\n return left_child_node, right_child_node\n\n if self.max_depth is not None and depth == self.max_depth:\n self._finalize_leaf(left_child_node)\n self._finalize_leaf(right_child_node)\n return left_child_node, right_child_node\n\n self._compute_sibling_splittability(left_child_node, right_child_node)\n\n return left_child_node, right_child_node\n\n def can_split_further(self):\n \"\"\"Return True if there are still nodes to split.\"\"\"\n return len(self.splittable_nodes) >= 1\n\n def _compute_linear_coefficient(self, node):\n\n sum_hx2_reg = node.sum_hx2 + self.splitting_context.w_l2_reg\n sum_h_reg = node.sum_h + self.splitting_context.b_l2_reg\n coefficient = (node.sum_hx * node.sum_g_hf - sum_h_reg * node.sum_gx_hfx) / \\\n (sum_hx2_reg * sum_h_reg - node.sum_hx ** 2)\n\n return coefficient\n\n def _finalize_leaf(self, node):\n if node.parent is None:\n self._finalize_leaf_plain(node)\n else:\n self._finalize_leaf_linear(node)\n\n def _finalize_leaf_linear(self, node):\n sum_hx2_reg = node.sum_hx2 + self.splitting_context.w_l2_reg\n sum_h_reg = node.sum_h + self.splitting_context.b_l2_reg\n node.value = self.shrinkage * (node.sum_hx * node.sum_gx_hfx - sum_hx2_reg * node.sum_g_hf) / (\n sum_hx2_reg * sum_h_reg - node.sum_hx**2)\n self.finalized_leaves.append(node)\n\n def _finalize_leaf_plain(self, node):\n \"\"\"Compute the prediction value that minimizes the objective function.\n\n This sets the node.value attribute (node is a leaf iff node.value is\n not None).\n\n See Equation 5 of:\n XGBoost: A Scalable Tree Boosting System, T. Chen, C. Guestrin, 2016\n https://arxiv.org/abs/1603.02754\n \"\"\"\n node.value = -self.shrinkage * node.sum_g_hf / (\n node.sum_h + self.splitting_context.b_l2_reg)\n self.finalized_leaves.append(node)\n\n def _finalize_splittable_nodes(self):\n \"\"\"Transform all splittable nodes into leaves.\n\n Used when some constraint is met e.g. maximum number of leaves or\n maximum depth.\"\"\"\n while len(self.splittable_nodes) > 0:\n node = self.splittable_nodes.pop()\n self._finalize_leaf(node)\n\n def make_predictor(self):\n \"\"\"Make a TreePredictor object out of the current tree.\n\n Parameters\n ----------\n numerical_thresholds : array-like of floats, optional (default=None)\n The actual thresholds values of each bin, expected to be in sorted\n increasing order. None if the training data was pre-binned.\n\n Returns\n -------\n A TreePredictor object.\n \"\"\"\n predictor_nodes = np.zeros(self.n_nodes, dtype=PREDICTOR_RECORD_DTYPE)\n self._fill_predictor_node_array(\n predictor_nodes, self.root,\n numerical_thresholds=self.numerical_thresholds\n )\n return TreePredictor(nodes=predictor_nodes)\n\n def _fill_predictor_node_array(self, predictor_nodes, grower_node,\n numerical_thresholds=None, next_free_idx=0):\n \"\"\"Helper used in make_predictor to set the TreePredictor fields.\"\"\"\n node = predictor_nodes[next_free_idx]\n node['count'] = grower_node.n_samples\n node['depth'] = grower_node.depth\n if grower_node.split_info is not None:\n node['gain'] = grower_node.split_info.gain\n else:\n node['gain'] = -1\n\n if grower_node.value is not None:\n # Leaf node\n node['is_leaf'] = True\n node['value'] = grower_node.value\n return next_free_idx + 1\n else:\n # Decision node\n split_info = grower_node.split_info\n feature_idx, bin_idx = split_info.feature_idx, split_info.bin_idx\n node['feature_idx'] = feature_idx\n node['bin_threshold'] = bin_idx\n if numerical_thresholds is not None:\n node['threshold'] = numerical_thresholds[feature_idx][bin_idx]\n node['left_coefficient'] = grower_node.left_coefficient * self.shrinkage\n node['right_coefficient'] = grower_node.right_coefficient * self.shrinkage\n next_free_idx += 1\n\n node['left'] = next_free_idx\n next_free_idx = self._fill_predictor_node_array(\n predictor_nodes, grower_node.left_child,\n numerical_thresholds=numerical_thresholds,\n next_free_idx=next_free_idx)\n\n node['right'] = next_free_idx\n return self._fill_predictor_node_array(\n predictor_nodes, grower_node.right_child,\n numerical_thresholds=numerical_thresholds,\n next_free_idx=next_free_idx)\n\n def update_raw_predictions(self, raw_predictions):\n # prepare leaves_data so that _update_raw_predictions can be\n # @njitted\n leaves_data = [(l.value, l.sample_indices)\n for l in self.finalized_leaves]\n prediction_value = self.splitting_context.prediction_value * self.shrinkage\n _update_raw_predictions(leaves_data, raw_predictions, prediction_value)\n\n\n@njit(parallel=True)\ndef _update_raw_predictions(leaves_data, raw_predictions, prediction_value):\n \"\"\"Update raw_predictions by reading the predictions of the ith tree\n directly form the leaves.\n\n Can only be used for predicting the training data. raw_predictions\n contains the sum of the tree values from iteration 0 to i - 1. This adds\n the predictions of the ith tree to raw_predictions.\n\n Parameters\n ----------\n leaves_data: list of tuples (leaf.value, leaf.sample_indices)\n The leaves data used to update raw_predictions.\n raw_predictions : array-like, shape=(n_samples,)\n The raw predictions for the training data.\n prediction_value:array-like, shape=(n_samples,)\n The accumulated linear values\n \"\"\"\n for leaf_idx in prange(len(leaves_data)):\n leaf_value, sample_indices = leaves_data[leaf_idx]\n for sample_idx in sample_indices:\n raw_predictions[sample_idx] += leaf_value\n n_samples = raw_predictions.shape[0]\n for i in prange(n_samples):\n raw_predictions[i] += prediction_value[i]\n", "meta": {"hexsha": "86bc5b6da26d70c8bce65d5d83d2a937b0c10a92", "size": 23667, "ext": "py", "lang": "Python", "max_stars_repo_path": "pygbm/pwl/grower.py", "max_stars_repo_name": "Goorman/pygbm", "max_stars_repo_head_hexsha": "456c374318c033c502d1bd663decbd2ff4e0c055", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pygbm/pwl/grower.py", "max_issues_repo_name": "Goorman/pygbm", "max_issues_repo_head_hexsha": "456c374318c033c502d1bd663decbd2ff4e0c055", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pygbm/pwl/grower.py", "max_forks_repo_name": "Goorman/pygbm", "max_forks_repo_head_hexsha": "456c374318c033c502d1bd663decbd2ff4e0c055", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.5210526316, "max_line_length": 105, "alphanum_fraction": 0.6431740398, "include": true, "reason": "import numpy,from numba", "num_tokens": 5205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.24508501313237172, "lm_q1q2_score": 0.13589240118633858}} {"text": "# -*- coding: utf-8 -*-\n\"\"\"\nDeprecated Colour Models Transformations\n========================================\n\nDefines various deprecated colour models transformations:\n\n- :func:`colour.RGB_to_HSV`\n- :func:`colour.HSV_to_RGB`\n- :func:`colour.RGB_to_HSL`\n- :func:`colour.HSL_to_RGB`\n- :func:`colour.RGB_to_CMY`\n- :func:`colour.CMY_to_RGB`\n- :func:`colour.CMY_to_CMYK`\n- :func:`colour.CMYK_to_CMY`\n\nThese colour models are stated as deprecated because they trade off perceptual\nrelevance for computation speed. They should not be used in the colour science\ndomain although they are useful for image analysis and provide end user\nsoftware colour selection tools.\n\nThey are provided for convenience and completeness.\n\nWarning\n-------\nDon't use that! Seriously...\n\nReferences\n----------\n- :cite:`EasyRGBh` : EasyRGB. (n.d.). RGB > CMY. Retrieved May 18, 2014,\n from http://www.easyrgb.com/index.php?X=MATH&H=11#text11\n- :cite:`EasyRGBi` : EasyRGB. (n.d.). CMY > RGB. Retrieved May 18, 2014,\n from http://www.easyrgb.com/index.php?X=MATH&H=12#text12\n- :cite:`EasyRGBj` : EasyRGB. (n.d.). RGB > HSV. Retrieved May 18, 2014,\n from http://www.easyrgb.com/index.php?X=MATH&H=20#text20\n- :cite:`EasyRGBk` : EasyRGB. (n.d.). HSL > RGB. Retrieved May 18, 2014,\n from http://www.easyrgb.com/index.php?X=MATH&H=19#text19\n- :cite:`EasyRGBl` : EasyRGB. (n.d.). RGB > HSL. Retrieved May 18, 2014,\n from http://www.easyrgb.com/index.php?X=MATH&H=18#text18\n- :cite:`EasyRGBm` : EasyRGB. (n.d.). CMYK > CMY. Retrieved May 18, 2014,\n from http://www.easyrgb.com/index.php?X=MATH&H=14#text14\n- :cite:`EasyRGBn` : EasyRGB. (n.d.). HSV > RGB. Retrieved May 18, 2014,\n from http://www.easyrgb.com/index.php?X=MATH&H=21#text21\n- :cite:`EasyRGBo` : EasyRGB. (n.d.). CMY > CMYK. Retrieved May 18, 2014,\n from http://www.easyrgb.com/index.php?X=MATH&H=13#text13\n- :cite:`Smith1978b` : Smith, A. R. (1978). Color gamut transform pairs. In\n Proceedings of the 5th annual conference on Computer graphics and\n interactive techniques - SIGGRAPH '78 (pp. 12-19). New York, New York,\n USA: ACM Press. doi:10.1145/800248.807361\n- :cite:`Wikipedia2003` : Wikipedia. (2003). HSL and HSV. Retrieved\n September 10, 2014, from http://en.wikipedia.org/wiki/HSL_and_HSV\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport numpy as np\n\nfrom colour.utilities import (as_float_array, from_range_1, to_domain_1,\n tsplit, tstack)\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013-2019 - Colour Developers'\n__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-developers@colour-science.org'\n__status__ = 'Production'\n\n__all__ = [\n 'RGB_to_HSV', 'HSV_to_RGB', 'RGB_to_HSL', 'HSL_to_RGB', 'RGB_to_CMY',\n 'CMY_to_RGB', 'CMY_to_CMYK', 'CMYK_to_CMY'\n]\n\n\ndef RGB_to_HSV(RGB):\n \"\"\"\n Converts from *RGB* colourspace to *HSV* colourspace.\n\n Parameters\n ----------\n RGB : array_like\n *RGB* colourspace array.\n\n Returns\n -------\n ndarray\n *HSV* array.\n\n Notes\n -----\n\n +------------+-----------------------+---------------+\n | **Domain** | **Scale - Reference** | **Scale - 1** |\n +============+=======================+===============+\n | ``RGB`` | [0, 1] | [0, 1] |\n +------------+-----------------------+---------------+\n\n +------------+-----------------------+---------------+\n | **Range** | **Scale - Reference** | **Scale - 1** |\n +============+=======================+===============+\n | ``HSV`` | [0, 1] | [0, 1] |\n +------------+-----------------------+---------------+\n\n References\n ----------\n :cite:`EasyRGBj`, :cite:`Smith1978b`, :cite:`Wikipedia2003`\n\n Examples\n --------\n >>> RGB = np.array([0.45620519, 0.03081071, 0.04091952])\n >>> RGB_to_HSV(RGB) # doctest: +ELLIPSIS\n array([ 0.9960394..., 0.9324630..., 0.4562051...])\n \"\"\"\n\n RGB = to_domain_1(RGB)\n\n maximum = np.amax(RGB, -1)\n delta = np.ptp(RGB, -1)\n\n V = maximum\n\n R, G, B = tsplit(RGB)\n\n S = as_float_array(delta / maximum)\n S[np.asarray(delta == 0)] = 0\n\n delta_R = (((maximum - R) / 6) + (delta / 2)) / delta\n delta_G = (((maximum - G) / 6) + (delta / 2)) / delta\n delta_B = (((maximum - B) / 6) + (delta / 2)) / delta\n\n H = delta_B - delta_G\n H = np.where(G == maximum, (1 / 3) + delta_R - delta_B, H)\n H = np.where(B == maximum, (2 / 3) + delta_G - delta_R, H)\n H[np.asarray(H < 0)] += 1\n H[np.asarray(H > 1)] -= 1\n H[np.asarray(delta == 0)] = 0\n\n HSV = tstack([H, S, V])\n\n return from_range_1(HSV)\n\n\ndef HSV_to_RGB(HSV):\n \"\"\"\n Converts from *HSV* colourspace to *RGB* colourspace.\n\n Parameters\n ----------\n HSV : array_like\n *HSV* colourspace array.\n\n Returns\n -------\n ndarray\n *RGB* colourspace array.\n\n Notes\n -----\n\n +------------+-----------------------+---------------+\n | **Domain** | **Scale - Reference** | **Scale - 1** |\n +============+=======================+===============+\n | ``HSV`` | [0, 1] | [0, 1] |\n +------------+-----------------------+---------------+\n\n +------------+-----------------------+---------------+\n | **Range** | **Scale - Reference** | **Scale - 1** |\n +============+=======================+===============+\n | ``RGB`` | [0, 1] | [0, 1] |\n +------------+-----------------------+---------------+\n\n References\n ----------\n :cite:`EasyRGBn`, :cite:`Smith1978b`, :cite:`Wikipedia2003`\n\n Examples\n --------\n >>> HSV = np.array([0.99603944, 0.93246304, 0.45620519])\n >>> HSV_to_RGB(HSV) # doctest: +ELLIPSIS\n array([ 0.4562051..., 0.0308107..., 0.0409195...])\n \"\"\"\n\n H, S, V = tsplit(to_domain_1(HSV))\n\n h = as_float_array(H * 6)\n h[np.asarray(h == 6)] = 0\n\n i = np.floor(h)\n j = V * (1 - S)\n k = V * (1 - S * (h - i))\n l = V * (1 - S * (1 - (h - i))) # noqa\n\n i = tstack([i, i, i]).astype(np.uint8)\n\n RGB = np.choose(\n i, [\n tstack([V, l, j]),\n tstack([k, V, j]),\n tstack([j, V, l]),\n tstack([j, k, V]),\n tstack([l, j, V]),\n tstack([V, j, k]),\n ],\n mode='clip')\n\n return from_range_1(RGB)\n\n\ndef RGB_to_HSL(RGB):\n \"\"\"\n Converts from *RGB* colourspace to *HSL* colourspace.\n\n Parameters\n ----------\n RGB : array_like\n *RGB* colourspace array.\n\n Returns\n -------\n ndarray\n *HSL* array.\n\n Notes\n -----\n\n +------------+-----------------------+---------------+\n | **Domain** | **Scale - Reference** | **Scale - 1** |\n +============+=======================+===============+\n | ``RGB`` | [0, 1] | [0, 1] |\n +------------+-----------------------+---------------+\n\n +------------+-----------------------+---------------+\n | **Range** | **Scale - Reference** | **Scale - 1** |\n +============+=======================+===============+\n | ``HSL`` | [0, 1] | [0, 1] |\n +------------+-----------------------+---------------+\n\n References\n ----------\n :cite:`EasyRGBl`, :cite:`Smith1978b`, :cite:`Wikipedia2003`\n\n Examples\n --------\n >>> RGB = np.array([0.45620519, 0.03081071, 0.04091952])\n >>> RGB_to_HSL(RGB) # doctest: +ELLIPSIS\n array([ 0.9960394..., 0.8734714..., 0.2435079...])\n \"\"\"\n\n RGB = to_domain_1(RGB)\n\n minimum = np.amin(RGB, -1)\n maximum = np.amax(RGB, -1)\n delta = np.ptp(RGB, -1)\n\n R, G, B = tsplit(RGB)\n\n L = (maximum + minimum) / 2\n\n S = np.where(\n L < 0.5,\n delta / (maximum + minimum),\n delta / (2 - maximum - minimum),\n )\n S[np.asarray(delta == 0)] = 0\n\n delta_R = (((maximum - R) / 6) + (delta / 2)) / delta\n delta_G = (((maximum - G) / 6) + (delta / 2)) / delta\n delta_B = (((maximum - B) / 6) + (delta / 2)) / delta\n\n H = delta_B - delta_G\n H = np.where(G == maximum, (1 / 3) + delta_R - delta_B, H)\n H = np.where(B == maximum, (2 / 3) + delta_G - delta_R, H)\n H[np.asarray(H < 0)] += 1\n H[np.asarray(H > 1)] -= 1\n H[np.asarray(delta == 0)] = 0\n\n HSL = tstack([H, S, L])\n\n return from_range_1(HSL)\n\n\ndef HSL_to_RGB(HSL):\n \"\"\"\n Converts from *HSL* colourspace to *RGB* colourspace.\n\n Parameters\n ----------\n HSL : array_like\n *HSL* colourspace array.\n\n Returns\n -------\n ndarray\n *RGB* colourspace array.\n\n Notes\n -----\n\n +------------+-----------------------+---------------+\n | **Domain** | **Scale - Reference** | **Scale - 1** |\n +============+=======================+===============+\n | ``HSL`` | [0, 1] | [0, 1] |\n +------------+-----------------------+---------------+\n\n +------------+-----------------------+---------------+\n | **Range** | **Scale - Reference** | **Scale - 1** |\n +============+=======================+===============+\n | ``RGB`` | [0, 1] | [0, 1] |\n +------------+-----------------------+---------------+\n\n References\n ----------\n :cite:`EasyRGBk`, :cite:`Smith1978b`, :cite:`Wikipedia2003`\n\n Examples\n --------\n >>> HSL = np.array([0.99603944, 0.87347144, 0.24350795])\n >>> HSL_to_RGB(HSL) # doctest: +ELLIPSIS\n array([ 0.4562051..., 0.0308107..., 0.0409195...])\n \"\"\"\n\n H, S, L = tsplit(to_domain_1(HSL))\n\n def H_to_RGB(vi, vj, vH):\n \"\"\"\n Converts *hue* value to *RGB* colourspace.\n \"\"\"\n\n vH = as_float_array(vH)\n\n vH[np.asarray(vH < 0)] += 1\n vH[np.asarray(vH > 1)] -= 1\n\n v = np.full(vi.shape, np.nan)\n\n v = np.where(\n np.logical_and(6 * vH < 1, np.isnan(v)),\n vi + (vj - vi) * 6 * vH,\n v,\n )\n v = np.where(np.logical_and(2 * vH < 1, np.isnan(v)), vj, v)\n v = np.where(\n np.logical_and(3 * vH < 2, np.isnan(v)),\n vi + (vj - vi) * ((2 / 3) - vH) * 6,\n v,\n )\n v = np.where(np.isnan(v), vi, v)\n\n return v\n\n j = np.where(L < 0.5, L * (1 + S), (L + S) - (S * L))\n i = 2 * L - j\n\n R = H_to_RGB(i, j, H + (1 / 3))\n G = H_to_RGB(i, j, H)\n B = H_to_RGB(i, j, H - (1 / 3))\n\n R = np.where(S == 1, L, R)\n G = np.where(S == 1, L, G)\n B = np.where(S == 1, L, B)\n\n RGB = tstack([R, G, B])\n\n return from_range_1(RGB)\n\n\ndef RGB_to_CMY(RGB):\n \"\"\"\n Converts from *RGB* colourspace to *CMY* colourspace.\n\n Parameters\n ----------\n RGB : array_like\n *RGB* colourspace array.\n\n Returns\n -------\n ndarray\n *CMY* array.\n\n Notes\n -----\n\n +------------+-----------------------+---------------+\n | **Domain** | **Scale - Reference** | **Scale - 1** |\n +============+=======================+===============+\n | ``RGB`` | [0, 1] | [0, 1] |\n +------------+-----------------------+---------------+\n\n +------------+-----------------------+---------------+\n | **Range** | **Scale - Reference** | **Scale - 1** |\n +============+=======================+===============+\n | ``CMY`` | [0, 1] | [0, 1] |\n +------------+-----------------------+---------------+\n\n References\n ----------\n :cite:`EasyRGBh`\n\n Examples\n --------\n >>> RGB = np.array([0.45620519, 0.03081071, 0.04091952])\n >>> RGB_to_CMY(RGB) # doctest: +ELLIPSIS\n array([ 0.5437948..., 0.9691892..., 0.9590804...])\n \"\"\"\n\n CMY = 1 - to_domain_1(RGB)\n\n return from_range_1(CMY)\n\n\ndef CMY_to_RGB(CMY):\n \"\"\"\n Converts from *CMY* colourspace to *CMY* colourspace.\n\n Parameters\n ----------\n CMY : array_like\n *CMY* colourspace array.\n\n Returns\n -------\n ndarray\n *RGB* colourspace array.\n\n Notes\n -----\n\n +------------+-----------------------+---------------+\n | **Domain** | **Scale - Reference** | **Scale - 1** |\n +============+=======================+===============+\n | ``CMY`` | [0, 1] | [0, 1] |\n +------------+-----------------------+---------------+\n\n +------------+-----------------------+---------------+\n | **Range** | **Scale - Reference** | **Scale - 1** |\n +============+=======================+===============+\n | ``RGB`` | [0, 1] | [0, 1] |\n +------------+-----------------------+---------------+\n\n References\n ----------\n :cite:`EasyRGBi`\n\n Examples\n --------\n >>> CMY = np.array([0.54379481, 0.96918929, 0.95908048])\n >>> CMY_to_RGB(CMY) # doctest: +ELLIPSIS\n array([ 0.4562051..., 0.0308107..., 0.0409195...])\n \"\"\"\n\n RGB = 1 - to_domain_1(CMY)\n\n return from_range_1(RGB)\n\n\ndef CMY_to_CMYK(CMY):\n \"\"\"\n Converts from *CMY* colourspace to *CMYK* colourspace.\n\n Parameters\n ----------\n CMY : array_like\n *CMY* colourspace array.\n\n Returns\n -------\n ndarray\n *CMYK* array.\n\n Notes\n -----\n\n +------------+-----------------------+---------------+\n | **Domain** | **Scale - Reference** | **Scale - 1** |\n +============+=======================+===============+\n | ``CMY`` | [0, 1] | [0, 1] |\n +------------+-----------------------+---------------+\n\n +------------+-----------------------+---------------+\n | **Range** | **Scale - Reference** | **Scale - 1** |\n +============+=======================+===============+\n | ``CMYK`` | [0, 1] | [0, 1] |\n +------------+-----------------------+---------------+\n\n References\n ----------\n :cite:`EasyRGBo`\n\n Examples\n --------\n >>> CMY = np.array([0.54379481, 0.96918929, 0.95908048])\n >>> CMY_to_CMYK(CMY) # doctest: +ELLIPSIS\n array([ 0. , 0.9324630..., 0.9103045..., 0.5437948...])\n \"\"\"\n\n C, M, Y = tsplit(to_domain_1(CMY))\n\n K = np.ones(C.shape)\n K = np.where(C < K, C, K)\n K = np.where(M < K, M, K)\n K = np.where(Y < K, Y, K)\n\n C = as_float_array((C - K) / (1 - K))\n M = as_float_array((M - K) / (1 - K))\n Y = as_float_array((Y - K) / (1 - K))\n\n C[np.asarray(K == 1)] = 0\n M[np.asarray(K == 1)] = 0\n Y[np.asarray(K == 1)] = 0\n\n CMYK = tstack([C, M, Y, K])\n\n return from_range_1(CMYK)\n\n\ndef CMYK_to_CMY(CMYK):\n \"\"\"\n Converts from *CMYK* colourspace to *CMY* colourspace.\n\n Parameters\n ----------\n CMYK : array_like\n *CMYK* colourspace array.\n\n Returns\n -------\n ndarray\n *CMY* array.\n\n Notes\n -----\n\n +------------+-----------------------+---------------+\n | **Domain** | **Scale - Reference** | **Scale - 1** |\n +============+=======================+===============+\n | ``CMYK`` | [0, 1] | [0, 1] |\n +------------+-----------------------+---------------+\n\n +------------+-----------------------+---------------+\n | **Range** | **Scale - Reference** | **Scale - 1** |\n +============+=======================+===============+\n | ``CMY`` | [0, 1] | [0, 1] |\n +------------+-----------------------+---------------+\n\n References\n ----------\n :cite:`EasyRGBm`\n\n Examples\n --------\n >>> CMYK = np.array([0.50000000, 0.00000000, 0.74400000, 0.01960784])\n >>> CMYK_to_CMY(CMYK) # doctest: +ELLIPSIS\n array([ 0.5098039..., 0.0196078..., 0.7490196...])\n \"\"\"\n\n C, M, Y, K = tsplit(to_domain_1(CMYK))\n\n CMY = tstack([C * (1 - K) + K, M * (1 - K) + K, Y * (1 - K) + K])\n\n return from_range_1(CMY)\n", "meta": {"hexsha": "768bfcfbb49a4f20e505b57ed6f014dfc844d80d", "size": 15717, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/models/rgb/deprecated.py", "max_stars_repo_name": "MaxSchambach/colour", "max_stars_repo_head_hexsha": "3f3685d616fda4be58cec20bc1e16194805d7e2d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "colour/models/rgb/deprecated.py", "max_issues_repo_name": "MaxSchambach/colour", "max_issues_repo_head_hexsha": "3f3685d616fda4be58cec20bc1e16194805d7e2d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colour/models/rgb/deprecated.py", "max_forks_repo_name": "MaxSchambach/colour", "max_forks_repo_head_hexsha": "3f3685d616fda4be58cec20bc1e16194805d7e2d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0160427807, "max_line_length": 78, "alphanum_fraction": 0.4091111535, "include": true, "reason": "import numpy", "num_tokens": 4857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.24508500761839527, "lm_q1q2_score": 0.13589239452029328}} {"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\nimport logging\nfrom functools import lru_cache\nimport numpy as np\nimport astropy.units as u\nfrom astropy.utils import lazyproperty\nfrom astropy.coordinates.angle_utilities import angular_separation\nfrom regions import CircleSkyRegion\nfrom gammapy.maps import Map\nfrom gammapy.modeling.models import (\n TemplateNPredModel,\n PointSpatialModel,\n)\n\nPSF_CONTAINMENT = 0.999\nCUTOUT_MARGIN = 0.1 * u.deg\n\nlog = logging.getLogger(__name__)\n\n\nclass MapEvaluator:\n \"\"\"Sky model evaluation on maps.\n\n This evaluates a sky model on a 3D map and convolves with the IRFs,\n and returns a map of the predicted counts.\n Note that background counts are not added.\n\n For now, we only make it work for 3D WCS maps with an energy axis.\n No HPX, no other axes, those can be added later here or via new\n separate model evaluator classes.\n\n Parameters\n ----------\n model : `~gammapy.modeling.models.SkyModel`\n Sky model\n exposure : `~gammapy.maps.Map`\n Exposure map\n psf : `~gammapy.irf.PSFKernel`\n PSF kernel\n edisp : `~gammapy.irf.EDispKernel`\n Energy dispersion\n mask : `~gammapy.maps.Map`\n Mask to apply to the likelihood for fitting.\n gti : `~gammapy.data.GTI`\n GTI of the observation or union of GTI if it is a stacked observation\n evaluation_mode : {\"local\", \"global\"}\n Model evaluation mode.\n The \"local\" mode evaluates the model components on smaller grids to save computation time.\n This mode is recommended for local optimization algorithms.\n The \"global\" evaluation mode evaluates the model components on the full map.\n This mode is recommended for global optimization algorithms.\n use_cache : bool\n Use npred caching.\n \"\"\"\n\n def __init__(\n self,\n model=None,\n exposure=None,\n psf=None,\n edisp=None,\n gti=None,\n mask=None,\n evaluation_mode=\"local\",\n use_cache=True,\n ):\n\n self.model = model\n self.exposure = exposure\n self.psf = psf\n self.edisp = edisp\n self.mask = mask\n self.gti = gti\n self.use_cache = use_cache\n self._init_position = None\n self.contributes = True\n self.psf_containment = None\n\n if evaluation_mode not in {\"local\", \"global\"}:\n raise ValueError(f\"Invalid evaluation_mode: {evaluation_mode!r}\")\n\n self.evaluation_mode = evaluation_mode\n\n # TODO: this is preliminary solution until we have further unified the model handling\n if (\n isinstance(self.model, TemplateNPredModel)\n or self.model.spatial_model is None\n or self.model.evaluation_radius is None\n ):\n self.evaluation_mode = \"global\"\n\n # define cached computations\n self._compute_npred = lru_cache()(self._compute_npred)\n self._compute_flux_spatial = lru_cache()(self._compute_flux_spatial)\n self._cached_parameter_values = None\n self._cached_parameter_values_previous = None\n self._cached_parameter_values_spatial = None\n self._cached_position = (0, 0)\n self._computation_cache = None\n self._neval = 0 # for debugging\n self._renorm = 1\n self._spatial_oversampling_factor = 1\n if self.exposure is not None:\n if not self.geom.is_region or self.geom.region is not None:\n self.update_spatial_oversampling_factor(self.geom)\n\n # workaround for the lru_cache pickle issue\n # see e.g. https://github.com/cloudpipe/cloudpickle/issues/178\n def __getstate__(self):\n state = self.__dict__.copy()\n for key, value in state.items():\n func = getattr(value, \"__wrapped__\", None)\n if func is not None:\n state[key] = func\n\n return state\n\n def __setstate__(self, state):\n for key, value in state.items():\n if key in [\n \"_compute_npred\",\n \"_compute_flux_spatial\",\n ]:\n state[key] = lru_cache()(value)\n\n self.__dict__ = state\n\n @property\n def geom(self):\n \"\"\"True energy map geometry (`~gammapy.maps.Geom`)\"\"\"\n return self.exposure.geom\n\n @property\n def needs_update(self):\n \"\"\"Check whether the model component has drifted away from its support.\"\"\"\n # TODO: simplify and clean up\n if isinstance(self.model, TemplateNPredModel):\n return False\n elif self.exposure is None:\n return True\n elif self.geom.is_region:\n return False\n elif self.evaluation_mode == \"global\" or self.model.evaluation_radius is None:\n return False\n elif not self.parameters_spatial_changed(reset=False):\n return False\n else:\n return self.irf_position_changed\n\n @property\n def psf_width(self):\n \"\"\"Width of the PSF\"\"\"\n if self.psf is not None:\n psf_width = np.max(self.psf.psf_kernel_map.geom.width)\n else:\n psf_width = 0 * u.deg\n return psf_width\n\n def use_psf_containment(self, geom):\n \"\"\"Use psf containment for point sources and circular regions\"\"\"\n if not geom.is_region:\n return False\n\n is_point_model = isinstance(self.model.spatial_model, PointSpatialModel)\n is_circle_region = isinstance(geom.region, CircleSkyRegion)\n return is_point_model & is_circle_region\n\n @property\n def cutout_width(self):\n \"\"\"Cutout width for the model component\"\"\"\n return self.psf_width + 2 * (self.model.evaluation_radius + CUTOUT_MARGIN)\n\n def update(self, exposure, psf, edisp, geom, mask):\n \"\"\"Update MapEvaluator, based on the current position of the model component.\n\n Parameters\n ----------\n exposure : `~gammapy.maps.Map`\n Exposure map.\n psf : `gammapy.irf.PSFMap`\n PSF map.\n edisp : `gammapy.irf.EDispMap`\n Edisp map.\n geom : `WcsGeom`\n Counts geom\n mask : `~gammapy.maps.Map`\n Mask to apply to the likelihood for fitting.\n \"\"\"\n # TODO: simplify and clean up\n log.debug(\"Updating model evaluator\")\n\n # lookup edisp\n if edisp:\n energy_axis = geom.axes[\"energy\"]\n self.edisp = edisp.get_edisp_kernel(\n self.model.position, energy_axis=energy_axis\n )\n\n # lookup psf\n if psf and self.model.spatial_model:\n if self.apply_psf_after_edisp:\n geom = geom.as_energy_true\n else:\n geom = exposure.geom\n\n if self.use_psf_containment(geom=geom):\n energy_true = geom.axes[\"energy_true\"].center.reshape((-1, 1, 1))\n self.psf_containment = psf.containment(\n energy_true=energy_true, rad=geom.region.radius\n )\n else:\n if geom.is_region or geom.is_hpx:\n geom = geom.to_wcs_geom()\n\n self.psf = psf.get_psf_kernel(\n position=self.model.position, geom=geom, containment=PSF_CONTAINMENT\n )\n\n if self.evaluation_mode == \"local\":\n self.contributes = self.model.contributes(mask=mask, margin=self.psf_width)\n\n if self.contributes:\n self.exposure = exposure.cutout(\n position=self.model.position, width=self.cutout_width, odd_npix=True\n )\n else:\n self.exposure = exposure\n\n if self.contributes:\n if not self.geom.is_region or self.geom.region is not None:\n self.update_spatial_oversampling_factor(self.geom)\n\n self._compute_npred.cache_clear()\n self._compute_flux_spatial.cache_clear()\n self._computation_cache = None\n self._cached_parameter_previous = None\n\n def update_spatial_oversampling_factor(self, geom):\n \"\"\"Update spatial oversampling_factor for model evaluation\"\"\"\n res_scale = self.model.evaluation_bin_size_min\n\n res_scale = res_scale.to_value(\"deg\") if res_scale is not None else 0\n\n if geom.is_region or geom.is_hpx:\n geom = geom.to_wcs_geom()\n if res_scale != 0:\n factor = int(np.ceil(np.max(geom.pixel_scales.deg) / res_scale))\n self._spatial_oversampling_factor = factor\n\n def compute_dnde(self):\n \"\"\"Compute model differential flux at map pixel centers.\n\n Returns\n -------\n model_map : `~gammapy.maps.Map`\n Sky cube with data filled with evaluated model values.\n Units: ``cm-2 s-1 TeV-1 deg-2``\n \"\"\"\n return self.model.evaluate_geom(self.geom, self.gti)\n\n def compute_flux(self, *arg):\n \"\"\"Compute flux\"\"\"\n return self.model.integrate_geom(self.geom, self.gti)\n\n def compute_flux_psf_convolved(self, *arg):\n \"\"\"Compute psf convolved and temporal model corrected flux.\"\"\"\n value = self.compute_flux_spectral()\n\n if self.model.spatial_model:\n if self.psf_containment is not None:\n value = value * self.psf_containment\n else:\n value = value * self.compute_flux_spatial()\n\n if self.model.temporal_model:\n value *= self.compute_temporal_norm()\n\n return Map.from_geom(geom=self.geom, data=value.value, unit=value.unit)\n\n def compute_flux_spatial(self):\n \"\"\"Compute spatial flux using caching\"\"\"\n if self.parameters_spatial_changed() or not self.use_cache:\n self._compute_flux_spatial.cache_clear()\n return self._compute_flux_spatial()\n\n def _compute_flux_spatial(self):\n \"\"\"Compute spatial flux\n\n Returns\n ----------\n value: `~astropy.units.Quantity`\n Psf-corrected, integrated flux over a given region.\n \"\"\"\n if self.geom.is_region:\n # We don't estimate spatial contributions if no psf are defined\n if self.geom.region is None or self.psf is None:\n return 1\n\n wcs_geom = self.geom.to_wcs_geom(width_min=self.cutout_width).to_image()\n\n if self.psf and self.model.apply_irf[\"psf\"]:\n values = self._compute_flux_spatial_geom(wcs_geom)\n else:\n values = self.model.spatial_model.integrate_geom(\n wcs_geom, oversampling_factor=1\n )\n axes = [self.geom.axes[\"energy_true\"].squash()]\n values = values.to_cube(axes=axes)\n\n weights = wcs_geom.region_weights(regions=[self.geom.region])\n value = (values.quantity * weights).sum(axis=(1, 2), keepdims=True)\n else:\n value = self._compute_flux_spatial_geom(self.geom)\n\n return value\n\n def _compute_flux_spatial_geom(self, geom):\n \"\"\"Compute spatial flux oversampling geom if necessary\"\"\"\n if not self.model.spatial_model.is_energy_dependent:\n geom = geom.to_image()\n value = self.model.spatial_model.integrate_geom(geom)\n\n if self.psf and self.model.apply_irf[\"psf\"]:\n value = self.apply_psf(value)\n\n return value\n\n def compute_flux_spectral(self):\n \"\"\"Compute spectral flux\"\"\"\n energy = self.geom.axes[\"energy_true\"].edges\n value = self.model.spectral_model.integral(\n energy[:-1],\n energy[1:],\n )\n if self.geom.is_hpx:\n return value.reshape((-1, 1))\n else:\n return value.reshape((-1, 1, 1))\n\n def compute_temporal_norm(self):\n \"\"\"Compute temporal norm\"\"\"\n integral = self.model.temporal_model.integral(\n self.gti.time_start, self.gti.time_stop\n )\n return np.sum(integral)\n\n def apply_exposure(self, flux):\n \"\"\"Compute npred cube\n\n For now just divide flux cube by exposure\n \"\"\"\n npred = (flux.quantity * self.exposure.quantity).to_value(\"\")\n return Map.from_geom(self.geom, data=npred, unit=\"\")\n\n def apply_psf(self, npred):\n \"\"\"Convolve npred cube with PSF\"\"\"\n tmp = npred.convolve(self.psf)\n tmp.data[tmp.data < 0.0] = 0\n return tmp\n\n def apply_edisp(self, npred):\n \"\"\"Convolve map data with energy dispersion.\n\n Parameters\n ----------\n npred : `~gammapy.maps.Map`\n Predicted counts in true energy bins\n\n Returns\n -------\n npred_reco : `~gammapy.maps.Map`\n Predicted counts in reco energy bins\n \"\"\"\n return npred.apply_edisp(self.edisp)\n\n def _compute_npred(self):\n \"\"\"Compute npred\"\"\"\n if isinstance(self.model, TemplateNPredModel):\n npred = self.model.evaluate()\n else:\n if not self.parameter_norm_only_changed:\n for method in self.methods_sequence:\n values = method(self._computation_cache)\n self._computation_cache = values\n npred = self._computation_cache\n else:\n npred = self._computation_cache * self.renorm()\n return npred\n\n @property\n def apply_psf_after_edisp(self):\n \"\"\" \"\"\"\n if not isinstance(self.model, TemplateNPredModel):\n return self.model.apply_irf.get(\"psf_after_edisp\")\n\n def compute_npred(self):\n \"\"\"Evaluate model predicted counts.\n\n Returns\n -------\n npred : `~gammapy.maps.Map`\n Predicted counts on the map (in reco energy bins)\n \"\"\"\n if self.parameters_changed or not self.use_cache:\n self._compute_npred.cache_clear()\n\n return self._compute_npred()\n\n @property\n def parameters_changed(self):\n \"\"\"Parameters changed\"\"\"\n values = self.model.parameters.value\n\n # TODO: possibly allow for a tolerance here?\n changed = ~np.all(self._cached_parameter_values == values)\n\n if changed:\n self._cached_parameter_values = values\n\n return changed\n\n @property\n def parameter_norm_only_changed(self):\n \"\"\"Only norm parameter changed\"\"\"\n norm_only_changed = False\n idx = self._norm_idx\n values = self.model.parameters.value\n if idx and self._computation_cache is not None:\n changed = self._cached_parameter_values_previous == values\n norm_only_changed = sum(changed) == 1 and changed[idx]\n\n if not norm_only_changed:\n self._cached_parameter_values_previous = values\n return norm_only_changed\n\n def parameters_spatial_changed(self, reset=True):\n \"\"\"Parameters changed\n\n Parameters\n ----------\n reset : bool\n Reset cached values\n\n Returns\n -------\n changed : bool\n Whether spatial parameters changed.\n \"\"\"\n values = self.model.spatial_model.parameters.value\n\n # TODO: possibly allow for a tolerance here?\n changed = ~np.all(self._cached_parameter_values_spatial == values)\n\n if changed and reset:\n self._cached_parameter_values_spatial = values\n\n return changed\n\n @property\n def irf_position_changed(self):\n \"\"\"Position for IRF changed\"\"\"\n\n # Here we do not use SkyCoord.separation to improve performance\n # (it avoids equivalence comparisons for frame and units)\n lon_cached, lat_cached = self._cached_position\n lon, lat = self.model.position_lonlat\n\n separation = angular_separation(lon, lat, lon_cached, lat_cached)\n changed = separation > (self.model.evaluation_radius + CUTOUT_MARGIN).to_value(\n u.rad\n )\n\n if changed:\n self._cached_position = lon, lat\n\n return changed\n\n @lazyproperty\n def _norm_idx(self):\n \"\"\"norm index\"\"\"\n names = self.model.parameters.names\n ind = [idx for idx, name in enumerate(names) if name in [\"norm\", \"amplitude\"]]\n if len(ind) == 1:\n return ind[0]\n else:\n return None\n\n def renorm(self):\n value = self.model.parameters.value[self._norm_idx]\n value_cached = self._cached_parameter_values_previous[self._norm_idx]\n return value / value_cached\n\n @lazyproperty\n def methods_sequence(self):\n \"\"\"order to apply irf\"\"\"\n\n if self.apply_psf_after_edisp:\n methods = [\n self.compute_flux,\n self.apply_exposure,\n self.apply_edisp,\n self.apply_psf,\n ]\n if not self.psf or not self.model.apply_irf[\"psf\"]:\n methods.remove(self.apply_psf)\n else:\n methods = [\n self.compute_flux_psf_convolved,\n self.apply_exposure,\n self.apply_edisp,\n ]\n if not self.model.apply_irf[\"exposure\"]:\n methods.remove(self.apply_exposure)\n if not self.model.apply_irf[\"edisp\"]:\n methods.remove(self.apply_edisp)\n return methods\n", "meta": {"hexsha": "02fa6bd3f1e5664eb670e3e95fa369d5bf38df5b", "size": 17186, "ext": "py", "lang": "Python", "max_stars_repo_path": "gammapy/datasets/evaluator.py", "max_stars_repo_name": "gammapy/gammapy", "max_stars_repo_head_hexsha": "021df28fe5b9423127e58e85b797b8ff3069baea", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 155, "max_stars_repo_stars_event_min_datetime": "2015-02-25T12:38:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T17:54:30.000Z", "max_issues_repo_path": "gammapy/datasets/evaluator.py", "max_issues_repo_name": "gammapy/gammapy", "max_issues_repo_head_hexsha": "021df28fe5b9423127e58e85b797b8ff3069baea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3131, "max_issues_repo_issues_event_min_datetime": "2015-01-06T15:36:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T17:30:57.000Z", "max_forks_repo_path": "gammapy/datasets/evaluator.py", "max_forks_repo_name": "gammapy/gammapy", "max_forks_repo_head_hexsha": "021df28fe5b9423127e58e85b797b8ff3069baea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 158, "max_forks_repo_forks_event_min_datetime": "2015-03-16T20:36:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T16:05:37.000Z", "avg_line_length": 33.2417794971, "max_line_length": 98, "alphanum_fraction": 0.6074130106, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 3722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.26894141551050293, "lm_q1q2_score": 0.13552123878656783}} {"text": "import os\nimport json\nimport numpy as np\nimport pandas as pd\n\nfrom pathlib import Path\n\nfrom .half_sarcomere import half_sarcomere as hs\nfrom .heart_rate import heart_rate as hr\nfrom .baroreflex import baroreflex as br\nfrom .growth import growth as gr\nfrom .vad import vad as va\n\nfrom protocol import protocol as prot\nfrom sim_options import sim_options as sim_opt\n\nclass single_ventricle_circulation():\n \"\"\"Class for a single ventricle circulation\"\"\"\n\n # Import functions from additional files\n from .calculate_properties import \\\n return_wall_thickness, \\\n return_lv_circumference, \\\n return_internal_radius_for_chamber_volume, \\\n return_lv_pressure, \\\n return_stroke_work\n\n from .write_data import \\\n write_complete_data_to_sim_data, \\\n write_complete_data_to_envelope_data, \\\n write_envelope_data_to_sim_data, \\\n write_output_files, \\\n write_sim_results_to_file,\\\n run_output_handler\n\n def __init__(self, model_json_file_string, thread_id=[]):\n\n # Check for file\n if (model_json_file_string == []):\n print('No model file specified. Cannot create model')\n return\n\n # Set thread id\n self.thread_id = thread_id\n\n # Status\n print('Initialising single_ventricle_circulation from %s on thread_id %i'\n % (model_json_file_string, self.thread_id))\n\n # Load the model as a dict\n with open(model_json_file_string, 'r') as f:\n sc_model = json.load(f)\n\n # Create a model dict for things that do not change during a simulation\n self.model = dict()\n # And a data dict for things that might\n self.data = dict()\n\n # Initialize the circulation object using data from the json file\n circ_model = sc_model[\"circulation\"]\n\n # Store the number of compartments\n self.model['no_of_compartments'] = len(circ_model['compartments'])\n\n # Initialise the time\n self.data['time'] = 0\n\n # Store blood volume\n self.data['blood_volume'] = circ_model['blood_volume']\n\n vessels_list = []\n for comp in circ_model['compartments']:\n if not (comp['name'] == 'ventricle'):\n n = comp['name']\n vessels_list.append(comp['name'])\n for t in ['resistance', 'compliance', 'slack_volume',\n 'inertance']:\n n = ('%s_%s') % (comp['name'], t)\n self.data[n] = comp[t]\n else:\n # Ventricle\n self.data['ventricle_resistance'] = comp['resistance']\n self.data['ventricle_slack_volume'] = comp['slack_volume']\n self.data['ventricle_wall_volume'] = comp['wall_volume']\n self.model['ventricle_wall_density'] = comp['wall_density']\n self.model['ventricle_inertance'] = comp['inertance']\n\n # Build the compliance, inertance, and resistance arrays\n self.data['compliance'] = []\n for v in vessels_list:\n c = self.data[('%s_compliance' % v)]\n self.data['compliance'].append(c)\n # Add in 0 for ventricular compliance\n self.data['compliance'].append(0)\n # Convert to numpy array\n self.data['compliance'] = np.array(self.data['compliance'])\n\n self.data['inertance'] = []\n for v in vessels_list:\n i = self.data[('%s_inertance' % v)]\n self.data['inertance'].append(i)\n # Add in 0 for ventricular inertance\n self.data['inertance'].append(0)\n # Convert to numpy array\n self.data['inertance'] = np.array(self.data['inertance'])\n\n self.data['resistance'] = []\n vessels_list.append('ventricle')\n self.model['compartment_list'] = vessels_list\n for v in self.model['compartment_list']:\n r = self.data[('%s_resistance' % v)]\n self.data['resistance'].append(r)\n self.data['resistance'] = np.array(self.data['resistance'])\n\n # Add in conductances for valves\n self.data['mitral_insufficiency_conductance'] = 0\n self.data['aortic_insufficiency_conductance'] = 0\n\n # Create a heart-rate object\n self.hr = hr.heart_rate(sc_model['heart_rate'])\n\n # Pull off the half_sarcomere parameters and make a half-sarcomere\n self.hs = hs.half_sarcomere(sc_model['half_sarcomere'], self)\n\n # Deduce the hsl where force is zero and set the hsl to that length\n self.hs.data['slack_hsl'] = \\\n self.hs.myof.return_hs_length_for_stress(0.0)\n delta_hsl = self.hs.data['slack_hsl'] - self.hs.data['hs_length']\n self.hs.update_simulation(0.0, delta_hsl, 0.0)\n\n # Deduce the slack circumference of the ventricle and deduce\n # the number of sarcomeres by dividing the slack_hsl\n self.data['ventricle_circumference'] = \\\n self.return_lv_circumference(self.data['ventricle_slack_volume'])\n self.data['n_hs'] = 1e9*self.data['ventricle_circumference'] / \\\n self.hs.data['slack_hsl']\n\n # Create and fill arrays for the volume, slack_volume and pressure\n self.data['v'] = np.zeros(self.model['no_of_compartments'])\n self.data['s'] = np.zeros(self.model['no_of_compartments'])\n # Put most of the blood in the veins\n for i, c in enumerate(self.model['compartment_list']):\n n = ('%s_slack_volume' % c)\n self.data['s'][i] = self.data[n]\n self.data['v'][i] = self.data[n]\n self.data['total_slack_volume'] = sum(self.data['s'])\n\n # Excess blood goes in veins\n self.data['v'][-2] = self.data['v'][-2] + \\\n (self.data['blood_volume'] - self.data['total_slack_volume'])\n\n # Set the thick wall multiplier\n # 0 for thin_wall, 1 for thick_wall\n self.thick_wall_multiplier = 0\n if (sc_model['half_sarcomere']['myofilaments']['implementation']['thick_wall_approximation']):\n self.thick_wall_multiplier = 1\n\n self.data['p'] = np.zeros(self.model['no_of_compartments'])\n for i in np.arange(0, self.model['no_of_compartments']-1):\n self.data['p'][i] = (self.data['v'][i] - self.data['s'][i]) / \\\n self.data['compliance'][i]\n self.data['p'][-1] = self.return_lv_pressure(self.data['v'][-1])\n\n # Allocate space for pressure, volume and slack_volume\n for i, v in enumerate(self.model['compartment_list']):\n self.data['pressure_%s' % v] = self.data['p'][i]\n self.data['volume_%s' % v] = self.data['v'][i]\n self.data['slack_volume_%s' % v] = self.data['s'][i]\n\n # Add in the wall thickness\n self.data['ventricle_wall_thickness'] = self.return_wall_thickness(\n self.data['volume_ventricle'])\n\n # Allocate space for flows\n self.data['f'] = np.zeros(self.model['no_of_compartments'])\n if (self.model['no_of_compartments'] == 7):\n self.model['flow_list'] = \\\n ['flow_ventricle_to_aorta',\n 'flow_aorta_to_arteries',\n 'flow_arteries_to_arterioles',\n 'flow_arterioles_to_capillaries',\n 'flow_capillaries_to_venules',\n 'flow_venules_to_veins',\n 'flow_veins_to_ventricle',\n 'flow_VAD']\n for f in self.model['flow_list']:\n self.data[f] = 0\n else:\n print('Initialisation: Flows need to be rebuilt for model')\n exit(1)\n\n # Set the heart rate\n self.data['heart_rate'] = self.hr.return_heart_rate()\n\n # If requried, create the baroreceptor\n self.data['baro_active'] = 0\n if ('baroreflex' in sc_model):\n self.br = br.baroreflex(sc_model['baroreflex'],\n self,\n self.data['pressure_arteries'])\n else:\n self.br = []\n\n # Create the growth modules\n self.data['growth_active'] = 0\n self.data['growth_dn'] = 0\n self.data['growth_dm'] = 0\n\n if ('growth' in sc_model):\n self.gr = gr.growth(sc_model['growth'], self)\n else:\n self.gr = []\n\n # Add functional fields\n self.data['stroke_volume'] = 0\n self.data['ejection_fraction'] = 0\n self.data['stroke_work'] = 0\n self.data['stroke_cost'] = 0\n self.data['efficiency'] = 0\n self.data['mean_arterial_pressure'] = 0\n\n # Set the last index for heart_beat initiation\n self.last_heart_beat_time = -1\n\n # If required create a VAD\n if ('VAD' in sc_model):\n self.va = va.VAD(sc_model['VAD'], self)\n else:\n self.va = []\n \n # Save space for some filenames\n self.sim_results_file_string = []\n self.output_handerl_file_string = []\n\n # Create a sim_options object\n self.so = []\n\n def create_data_structure(self, no_of_data_points):\n \"\"\" returns a data frame from the data dicts of each component \"\"\"\n\n sim_data = pd.DataFrame()\n z = np.zeros(no_of_data_points)\n\n # Prune some fields from the self_data\n sk = []\n for k in self.data.keys():\n if (k not in ['p','v','s','compliance','resistance',\n 'inertance','f']):\n sk.append(k)\n\n data_fields = sk + \\\n list(self.hr.data.keys()) + \\\n list(self.hs.data.keys()) + \\\n list(self.hs.memb.data.keys()) + \\\n list(self.hs.myof.data.keys())\n if hasattr(self.hs, 'ener'):\n data_fields = data_fields + \\\n list(self.hs.ener.data.keys())\n data_fields = data_fields + ['write_mode']\n\n # Add in fields from optional modules\n if (self.br != []):\n data_fields = data_fields + list(self.br.data.keys())\n if (self.gr != [] ):\n data_fields = data_fields + list(self.gr.data.keys())\n if (self.va != []):\n data_fields = data_fields + list(self.va.data.keys())\n\n for f in data_fields:\n s = pd.Series(data=z, name=f)\n sim_data = pd.concat([sim_data, s], axis=1)\n\n return sim_data\n\n def run_simulation(self,\n protocol_file_string=[],\n output_handler_file_string=[],\n sim_options_file_string=[],\n sim_results_file_string=[]):\n \"\"\" Run the simulation \"\"\"\n\n # Load the protocol\n if (protocol_file_string == []):\n print(\"No protocol_file_string. Exiting\")\n return\n self.prot = prot.protocol(protocol_file_string)\n\n # Check for sim_options\n if (sim_options_file_string):\n self.so = sim_opt.sim_options(sim_options_file_string,\n self.prot.data['time_step'],\n self)\n else:\n self.so = []\n\n # Determine the number of data points in the output file\n # If burst mode has been set in the sim_options, we need to create\n # two data structures - one for the main data, and the other that\n # can be used to calculate the min and max values in a given time\n # envelope\n # Otherwise, we just need one structure with a row for every\n # time-point in the simulation\n if ('n_burst_points' in self.so.data):\n self.sim_data = \\\n self.create_data_structure(self.so.data['n_burst_points'])\n self.envelope_data = \\\n self.create_data_structure(self.so.data['n_envelope_points'])\n else:\n self.sim_data = \\\n self.create_data_structure(self.prot.data['no_of_time_steps'])\n\n # Update the file handles\n self.sim_results_file_string = sim_results_file_string\n self.output_handler_file_string = output_handler_file_string\n\n # Step through the simulation\n time_step = self.prot.data['time_step']\n self.t_counter = 0\n self.write_counter = 0\n self.envelope_counter = 0\n for i in np.arange(self.prot.data['no_of_time_steps']):\n # Iplmement a step\n self.implement_time_step(time_step)\n # Check whether we should dump the output\n if ('periodic_save_interval_s' in self.so.data):\n if ((i > 0) and \n (np.mod(self.data['time'],\n self.so.data['periodic_save_interval_s'])\n < time_step) and\n (i < (self.prot.data['no_of_time_steps']-1))):\n # Write sim data to file and run the output handler\n self.write_output_files() \n\n # Tidy up by writing sim data to file and running the output handler\n self.write_output_files()\n\n\n def return_system_values(self, time_interval=3):\n d = dict()\n if (self.data['time'] > time_interval):\n self.temp_data = \\\n self.sim_data[self.sim_data['time'].between(\n self.data['time']-time_interval, self.data['time'])]\n d['volume_ventricle_max'] = \\\n self.temp_data['volume_ventricle'].max()\n d['stroke_volume'] = d['volume_ventricle_max'] - \\\n self.temp_data['volume_ventricle'].min()\n d['ejection_fraction'] = self.temp_data['ejection_fraction'].mean()\n d['heart_rate'] = self.data['heart_rate']\n d['cardiac_output'] = d['stroke_volume'] * d['heart_rate']\n d['hs_length_max'] = self.temp_data['hs_length'].max()\n d['fractional_shortening'] = \\\n (d['hs_length_max'] - self.temp_data['hs_length'].min()) / \\\n d['hs_length_max']\n d['cpt_int_pas_stress_mean'] = self.temp_data['cpt_int_pas_stress'].mean()\n d['cpt_cb_stress_mean'] = self.temp_data['cpt_cb_stress'].mean()\n d['efficiency'] = self.data['efficiency']\n d['pressure_artery_max'] = \\\n self.temp_data['pressure_arteries'].max()\n d['pressure_artery_min'] = \\\n self.temp_data['pressure_arteries'].min()\n d['pressure_veins_mean'] = \\\n self.temp_data['pressure_veins'].mean()\n d['volume_veins_proportion'] = \\\n self.temp_data['volume_veins'].mean() / \\\n self.data['blood_volume']\n d['n_hs'] = self.data['n_hs']\n d['dn'] = self.data['growth_dn']\n d['ventricle_wall_volume'] = self.data['ventricle_wall_volume']\n d['dm'] = self.data['growth_dm']\n\n if ('ener_intracell_ATP_conc' in self.temp_data):\n d['ener_intracell_ATP_conc'] = \\\n self.temp_data['ener_intracell_ATP_conc'].mean()\n\n if ('baro_B_a' in self.temp_data):\n d['baro_B_a'] = self.temp_data['baro_B_a'].mean()\n if ('baro_B_b' in self.temp_data):\n d['baro_B_b'] = self.temp_data['baro_B_b'].mean()\n if ('baro_B_c_heart_rate_t_quiescent_period' in self.temp_data):\n d['baro_B_c_heart_rate'] = self.temp_data['baro_B_c_heart_rate_t_quiescent_period'].mean()\n\n return d\n\n def implement_time_step(self, time_step):\n \"\"\" Implements time step \"\"\"\n self.data['time'] = self.data['time'] + time_step\n\n # Display progress\n if (self.t_counter % 1000 == 0):\n print('Thread_id[%i]: Sim time (s): %.0f %.0f%% complete' %\n (self.thread_id, self.data['time'],\n 100*self.t_counter/self.prot.data['no_of_time_steps']))\n system_values = self.return_system_values()\n print(json.dumps(system_values, indent=4))\n\n # Check for baroreflex and implement\n if (self.br):\n self.data['baro_active'] = 0\n for b in self.prot.baro_activations:\n if ((self.t_counter >= b.data['t_start_ind']) and\n (self.t_counter < b.data['t_stop_ind'])):\n self.data['baro_active'] = 1\n\n self.br.implement_time_step(self.data['pressure_arteries'],\n time_step,\n reflex_active=\n self.data['baro_active'])\n\n # Check and implement perturbations\n for p in self.prot.perturbations:\n\n if((self.t_counter >= p.data['t_start_ind']) and\n (self.t_counter < p.data['t_stop_ind'])):\n if (p.data['level'] == 'myofilaments'):\n self.hs.myof.data[p.data['variable']] += \\\n p.data['increment']\n elif (p.data['level'] == 'VAD'):\n self.va.data[p.data['variable']] += \\\n p.data['increment']\n elif (p.data['level'] == 'circulation'):\n self.data[p.data['variable']] += \\\n p.data['increment']\n elif (p.data['level'] == 'baroreflex'):\n self.br.data[p.data['variable']] += \\\n p.data['increment']\n elif (p.data['level'] == 'growth'):\n self.gr.data[p.data['variable']] += \\\n p.data['growth']\n\n self.check_baroreflex_perturbations(p)\n\n # Rebuild system arrays\n self.rebuild_from_perturbations()\n\n # Check for growth module and implement\n if (self.gr):\n self.data['growth_active'] = 0\n for g in self.prot.growth_activations:\n if ((self.t_counter >= g.data['t_start_ind']) and\n (self.t_counter < g.data['t_stop_ind'])):\n self.data['growth_active'] = 1\n\n self.gr.implement_time_step(time_step,\n growth_active=\n self.data['growth_active'])\n\n # Run the hr module\n (activation, new_beat) = self.hr.implement_time_step(time_step)\n\n # Advance half_sarcomere forward in time\n # First update the kinetic steps\n self.hs.update_simulation(time_step, 0, activation)\n\n # Now evolve volumes\n self.data['v'] = self.evolve_volumes(time_step, self.data['v'])\n\n # Apply the length change to the half-sarcomere\n new_circumference = self.return_lv_circumference(\n self.data['v'][-1])\n delta_circumference = new_circumference - \\\n self.data['ventricle_circumference']\n delta_hsl = ((1e9*delta_circumference) -\n (self.hs.data['hs_length'] * self.data['growth_dn'])) / \\\n self.data['n_hs']\n\n # Update model\n self.data['ventricle_circumference'] = new_circumference\n self.data['ventricle_wall_volume'] = \\\n self.data['ventricle_wall_volume'] + \\\n self.data['growth_dm'] + \\\n (self.data['ventricle_wall_volume'] *\n self.data['growth_dn'] / self.data['n_hs'])\n self.data['n_hs'] = self.data['n_hs'] + self.data['growth_dn']\n\n # Update the half-sarcomere with the new length\n self.hs.update_simulation(0, delta_hsl, 0)\n\n # Update the pressures\n for i in range(self.model['no_of_compartments']-1):\n self.data['p'][i] = (self.data['v'][i] - self.data['s'][i]) / \\\n self.data['compliance'][i]\n self.data['p'][-1] = self.return_lv_pressure(self.data['v'][-1])\n\n # Update the objects' data\n self.update_data(time_step, new_beat)\n self.hs.update_data(new_beat)\n\n # Now that ventricular volume is calculated, update the wall thickness\n self.data['ventricle_wall_thickness'] = self.return_wall_thickness(\n self.data['volume_ventricle'])\n\n # Now update the sim_data if appropriate\n # This requires checking if we are in burst mode and if so,\n # what write mode we are in\n save_mode = 1\n burst_mode = 'complete'\n if ('n_burst_points' in self.so.data):\n # Work out what we want to write to file\n (save_mode, burst_mode) = \\\n self.so.return_save_status(self.data['time'])\n # Update the envelope data\n self.write_complete_data_to_envelope_data(self.envelope_counter)\n\n if (save_mode == 1):\n # Write full data to sim_data\n self.write_complete_data_to_sim_data(self.write_counter)\n if (save_mode == 2):\n # Write envelope data to sim_data\n self.write_envelope_data_to_sim_data(self.write_counter)\n\n # Dump cb distributions if required\n if self.so:\n if ('cb_dump_file_string' in self.so.data):\n if ((self.t_counter >=\n self.so.data['cb_dump_t_start_ind']) and\n (self.t_counter <\n self.so.data['cb_dump_t_stop_ind'])):\n self.so.append_cb_distribution(self.data['time'])\n\n # Update the last heart beat time if required\n if (new_beat > 0):\n self.last_heart_beat_time = self.data['time']\n\n # Update the t counter for the next step\n self.t_counter = self.t_counter + 1\n\n def check_baroreflex_perturbations(self, p):\n \"\"\" Checks whether a parameter under reflex control has been\n externally perturned and adjusts values accordingly \"\"\"\n\n for bc in self.br.controls:\n if (bc.data['variable'] == p.data['variable']):\n bc.data['basal_value'] = bc.data['basal_value'] + \\\n p.data['increment']\n bc.data['para_value'] == bc.data['para_factor'] * \\\n bc.data['basal_value']\n bc.data['symp_value'] == bc.data['symp_factor'] * \\\n bc.data['basal_value']\n\n def return_min_max(self, data_frame):\n \"\"\" returns list of min and max values from a data frame \"\"\"\n min_value = data_frame.min()\n max_value = data_frame.max()\n\n return min_value, max_value\n\n def rebuild_from_perturbations(self):\n \"\"\" builds system arrays that could change during simulation \"\"\"\n\n for i, v in enumerate(self.model['compartment_list']):\n r = self.data[('%s_resistance' % v)]\n self.data['resistance'][i] = r\n\n for i, v in enumerate(self.model['compartment_list']):\n if (i < (self.model['no_of_compartments']-1)):\n c = self.data[('%s_compliance' % v)]\n self.data['compliance'][i] = c\n\n def update_data(self, time_step, new_beat):\n \"\"\" Update data after a time step \"\"\"\n\n # Update data for the heart-rate\n self.data['heart_rate'] = self.hr.return_heart_rate()\n\n self.data['f'] = self.return_flows(self.data['v'], time_step)\n for i, f in enumerate(self.model['flow_list']):\n self.data[f] = self.data['f'][i]\n\n for i, v in enumerate(self.model['compartment_list']):\n self.data['pressure_%s' % v] = self.data['p'][i]\n self.data['volume_%s' % v] = self.data['v'][i]\n \n if (hasattr(self.hs, 'ener')):\n self.data['ener_ATPase_to_myo'] = \\\n self.hs.ener.data['ener_flux_ATP_consumed'] / \\\n (0.001 * self.data['ventricle_wall_volume'] *\n (1.0 - self.hs.myof.data['prop_fibrosis']) * \n self.hs.myof.data['prop_myofilaments'])\n\n # If it is new beat, calculate cycle metrics\n if ((new_beat > 0) and (self.last_heart_beat_time > 0)):\n # Prune data to last cycle\n \n # Deduce the fields that are needed\n cycle_fields = ['time', 'pressure_ventricle',\n 'pressure_arteries', 'volume_ventricle']\n if hasattr(self.hs, 'ener'):\n cycle_fields = cycle_fields + ['ener_flux_ATP_consumed']\n\n d_cycle = self.sim_data[cycle_fields]\n \n d_cycle = d_cycle[d_cycle['time'].between(\n self.last_heart_beat_time, self.data['time'])]\n \n self.data['stroke_volume'] = d_cycle['volume_ventricle'].max() - \\\n d_cycle['volume_ventricle'].min()\n \n self.data['ejection_fraction'] = self.data['stroke_volume'] / \\\n d_cycle['volume_ventricle'].max()\n \n self.data['stroke_work'] = self.return_stroke_work(d_cycle)\n\n self.data['mean_arterial_pressure'] = \\\n d_cycle['pressure_arteries'].mean()\n \n if hasattr(self.hs, 'ener'):\n self.data['stroke_cost'] = \\\n -d_cycle['ener_flux_ATP_consumed'].sum() * time_step * \\\n self.hs.myof.implementation['delta_G_ATP']\n \n if (self.data['stroke_cost'] > 0):\n self.data['efficiency'] = self.data['stroke_work'] / \\\n self.data['stroke_cost']\n else:\n self.data['efficiency'] = np.nan\n \n \n\n def return_flows(self, v, time_step):\n \"\"\" return flows between compartments \"\"\"\n\n # Calculate pressure in each compartment\n p = np.zeros(self.model['no_of_compartments'])\n for i in np.arange(len(p)-1):\n p[i] = (v[i]-self.data['s'][i]) / self.data['compliance'][i]\n p[-1] = self.return_lv_pressure(v[-1])\n\n # Add 1 for VAD\n f = np.zeros(self.model['no_of_compartments']+1)\n r = self.data['resistance']\n inert = self.data['inertance']\n last_f = self.data['f']\n \n for i in np.arange(len(p)):\n f[i] = (1.0 / (r[i] + inert[i]/time_step)) * \\\n (p[i-1] - p[i] + (inert[i] * last_f[i] / time_step))\n\n # Check for VAD\n if (self.va):\n f[-1] = self.va.data['max_flow'] +\\\n (p[-1] - p[0]) * self.va.data['pump_slope']\n\n # Add in the valves\n # Aortic\n if (p[-1] <= p[0]):\n f[0] = (p[-1] - p[0]) * \\\n self.data['aortic_insufficiency_conductance']\n # Mitral\n if (p[-1] >= p[-2]):\n f[-2] = (p[-2]-p[-1]) * \\\n self.data['mitral_insufficiency_conductance']\n\n return f\n\n def evolve_volumes(self, time_step, initial_v):\n \"\"\" Evolves volumes for a time-step \"\"\"\n from scipy.integrate import solve_ivp\n\n def derivs(t, v):\n dv = np.zeros(self.model['no_of_compartments'])\n flows = self.return_flows(v, time_step)\n for i in np.arange(self.model['no_of_compartments']):\n if (i == (self.model['no_of_compartments']-1)):\n dv[i] = flows[i] - flows[0] + flows[-1]\n else:\n dv[i] = flows[i] - flows[i+1]\n return dv\n\n sol = solve_ivp(derivs, [0, time_step], initial_v)\n\n # Tidy up negative values\n y = sol.y[:, -1]\n y[np.nonzero(y < 0)] = 0\n # Rest goes in veins\n y[-2] = y[-2] + (self.data['blood_volume'] - np.sum(y))\n return y\n", "meta": {"hexsha": "4aa64bbdef430367bdb2664fb870e2b4790ea4b0", "size": 27412, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python_code/single_ventricle_circulation/single_ventricle_circulation.py", "max_stars_repo_name": "Campbell-Muscle-Lab/PyMyoVent", "max_stars_repo_head_hexsha": "317cca915ed2df6720fc81c40a4e7c74acbc8cbf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-26T18:59:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T18:59:44.000Z", "max_issues_repo_path": "Python_code/single_ventricle_circulation/single_ventricle_circulation.py", "max_issues_repo_name": "Campbell-Muscle-Lab/PyMyoVent", "max_issues_repo_head_hexsha": "317cca915ed2df6720fc81c40a4e7c74acbc8cbf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python_code/single_ventricle_circulation/single_ventricle_circulation.py", "max_forks_repo_name": "Campbell-Muscle-Lab/PyMyoVent", "max_forks_repo_head_hexsha": "317cca915ed2df6720fc81c40a4e7c74acbc8cbf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4306784661, "max_line_length": 106, "alphanum_fraction": 0.5546475996, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.25091277568224823, "lm_q1q2_score": 0.13523777594890457}} {"text": "#\n# Copyright (C) 2017-2018 European Synchrotron Radiation Facility, Grenoble, France\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# .\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n# .\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\"\"\"CSR rebinning engine implemented in pure python (with bits of scipy !) \n\"\"\"\n\n__author__ = \"Jerome Kieffer\"\n__contact__ = \"Jerome.Kieffer@ESRF.eu\"\n__license__ = \"MIT\"\n__copyright__ = \"European Synchrotron Radiation Facility, Grenoble, France\"\n__date__ = \"19/01/2021\"\n__status__ = \"development\"\n\nimport logging\nlogger = logging.getLogger(__name__)\nimport numpy\nfrom scipy.sparse import csr_matrix\nfrom .preproc import preproc as preproc_np\ntry:\n from ..ext.preproc import preproc as preproc_cy\nexcept ImportError as err:\n logger.warning(\"ImportError pyFAI.ext.preproc %s\", err)\n preproc = preproc_np\nelse:\n preproc = preproc_cy\n\nfrom ..containers import Integrate1dtpl, Integrate2dtpl\n\n\nclass CSRIntegrator(object):\n\n def __init__(self,\n image_size,\n lut=None,\n empty=0.0):\n \"\"\"Constructor of the abstract class\n \n :param size: input image size\n :param lut: tuple of 3 arrays with data, indices and indptr,\n index of the start of line in the CSR matrix\n :param empty: value for empty pixels\n \"\"\"\n self.size = image_size\n self.empty = empty\n self.bins = None\n self._csr = None\n self._csr2 = None # Used for propagating variance\n self.lut_size = 0 # actually nnz\n self.data = None\n self.indices = None\n self.indptr = None\n if lut is not None:\n assert len(lut) == 3\n self.set_matrix(*lut)\n\n def set_matrix(self, data, indices, indptr):\n \"\"\"Actually set the CSR sparse matrix content\n \n :param data: the non zero values NZV\n :param indices: the column number of the NZV\n :param indptr: the index of the start of line\"\"\"\n self.data = data\n self.indices = indices\n self.indptr = indptr\n self.lut_size = len(indices)\n self.bins = len(indptr) - 1\n self._csr = csr_matrix((data, indices, indptr), shape=(self.bins, self.size))\n self._csr2 = csr_matrix((data * data, indices, indptr), shape=(self.bins, self.size)) # contains the coef squared, used for variance propagation\n\n def integrate(self,\n signal,\n variance=None,\n dummy=None,\n delta_dummy=None,\n dark=None,\n flat=None,\n solidangle=None,\n polarization=None,\n absorption=None,\n normalization_factor=1.0,\n ):\n \"\"\"Actually perform the CSR matrix multiplication after preprocessing.\n \n :param signal: array of the right size with the signal in it.\n :param variance: Variance associated with the signal\n :param dummy: values which have to be discarded (dynamic mask)\n :param delta_dummy: precision for dummy values\n :param dark: noise to be subtracted from signal\n :param flat: flat-field normalization array\n :param flat: solidangle normalization array\n :param polarization: :solidangle normalization array\n :param absorption: :absorption normalization array\n :param normalization_factor: scale all normalization with this scalar\n :return: the preprocessed data integrated as array nbins x 4 which contains:\n regrouped signal, variance, normalization and pixel count \n\n Nota: all normalizations are grouped in the preprocessing step.\n \"\"\"\n shape = signal.shape\n prep = preproc(signal,\n dark=dark,\n flat=flat,\n solidangle=solidangle,\n polarization=polarization,\n absorption=absorption,\n mask=None,\n dummy=dummy,\n delta_dummy=delta_dummy,\n normalization_factor=normalization_factor,\n empty=self.empty,\n split_result=4,\n variance=variance,\n dtype=numpy.float32)\n prep.shape = numpy.prod(shape), -1\n # logger.warning(\"prep.shape %s lut_size %s, image_size %s, bins %s\", prep.shape, self.lut_size, self.size, self.bins)\n res = numpy.empty((numpy.prod(self.bins), 4), dtype=numpy.float32)\n # logger.warning(self._csr.shape)\n res[:, 0] = self._csr.dot(prep[:, 0])\n if variance is not None:\n res[:, 1] = self._csr2.dot(prep[:, 1])\n res[:, 2] = self._csr.dot(prep[:, 2])\n res[:, 3] = self._csr.dot(prep[:, 3])\n return res\n\n\nclass CsrIntegrator1d(CSRIntegrator):\n\n def __init__(self,\n image_size,\n lut=None,\n empty=0.0,\n unit=None,\n bin_centers=None,\n ):\n \"\"\"Constructor of the abstract class for 1D integration\n \n :param image_size: size of the image \n :param lut: (data, indices, indptr) of the CSR matrix\n :param empty: value for empty pixels\n :param unit: the kind of radial units\n :param bin_center: position of the bin center\n \n Nota: bins are deduced from bin_centers \n\n\n TODO: \n ~/workspace-400/pyFAI/build/lib.linux-x86_64-3.7/pyFAI/azimuthalIntegrator.py in sigma_clip_ng(self, data, npt, correctSolidAngle, polarization_factor, variance, error_model, dark, flat, method, unit, thres, max_iter, dummy, delta_dummy, mask, normalization_factor, metadata, safe, **kwargs)\n 3508 elif (mask is None) and (integr.check_mask):\n 3509 reset = \"no mask but CSR has mask\"\n-> 3510 elif (mask is not None) and (integr.mask_checksum != mask_crc):\n 3511 reset = \"mask changed\"\n 3512 # if (radial_range is None) and (integr.pos0Range is not None):\n\nAttributeError: 'CsrIntegrator1d' object has no attribute 'mask_checksum'\n\n \"\"\"\n self.bin_centers = bin_centers\n CSRIntegrator.__init__(self, image_size, lut, empty)\n self.pos0_range = self.pos1_range = self._geometry = None\n self.unit = unit\n\n def set_geometry(self, geometry):\n from pyFAI.geometry import Geometry\n assert numpy.prod(geometry.detector.shape) == self.size\n assert isinstance(geometry, Geometry)\n self._geometry = geometry\n\n def set_matrix(self, data, indices, indptr):\n \"\"\"Actually set the CSR sparse matrix content\n \n :param data: the non zero values NZV\n :param indices: the column number of the NZV\n :param indptr: the index of the start of line\"\"\"\n\n CSRIntegrator.set_matrix(self, data, indices, indptr)\n assert len(self.bin_centers) == self.bins\n\n def integrate(self,\n signal,\n variance=None,\n dummy=None,\n delta_dummy=None,\n dark=None,\n flat=None,\n solidangle=None,\n polarization=None,\n absorption=None,\n normalization_factor=1.0,\n ):\n \"\"\"Actually perform the 1D integration \n \n :param signal: array of the right size with the signal in it.\n :param variance: Variance associated with the signal\n :param dummy: values which have to be discarded (dynamic mask)\n :param delta_dummy: precision for dummy values\n :param dark: noise to be subtracted from signal\n :param flat: flat-field normalization array\n :param flat: solidangle normalization array\n :param polarization: :solidangle normalization array\n :param absorption: :absorption normalization array\n :param normalization_factor: scale all normalization with this scalar\n :return: Integrate1dResult or Integrate1dWithErrorResult object depending on variance \n \n \"\"\"\n if variance is None:\n do_variance = False\n else:\n do_variance = True\n trans = CSRIntegrator.integrate(self, signal, variance, dummy, delta_dummy,\n dark, flat, solidangle, polarization,\n absorption, normalization_factor)\n signal = trans[:, 0]\n variance = trans[:, 1]\n normalization = trans[:, 2]\n count = trans[..., -1] # should be 3\n mask = (normalization == 0)\n with numpy.errstate(divide='ignore', invalid='ignore'):\n intensity = signal / normalization\n intensity[mask] = self.empty\n if do_variance:\n error = numpy.sqrt(variance) / normalization\n error[mask] = self.empty\n else:\n variance = error = None\n return Integrate1dtpl(self.bin_centers,\n intensity, error,\n signal, variance, normalization, count)\n\n integrate_ng = integrate\n\n def sigma_clip(self, data, dark=None, dummy=None, delta_dummy=None,\n variance=None, dark_variance=None,\n flat=None, solidangle=None, polarization=None, absorption=None,\n safe=True, error_model=None,\n normalization_factor=1.0,\n cutoff=4.0, cycle=5):\n \"\"\"\n Perform a sigma-clipping iterative filter within each along each row. \n see the doc of scipy.stats.sigmaclip for more descriptions.\n \n If the error model is \"azimuthal\": the variance is the variance within a bin,\n which is refined at each iteration, can be costly !\n \n Else, the error is propagated according to:\n\n .. math::\n\n signal = (raw - dark)\n variance = variance + dark_variance\n normalization = normalization_factor*(flat * solidangle * polarization * absortoption)\n count = number of pixel contributing\n\n Integration is performed using the CSR representation of the look-up table on all\n arrays: signal, variance, normalization and count\n\n :param dark: array of same shape as data for pre-processing\n :param dummy: value for invalid data\n :param delta_dummy: precesion for dummy assessement\n :param variance: array of same shape as data for pre-processing\n :param dark_variance: array of same shape as data for pre-processing\n :param flat: array of same shape as data for pre-processing\n :param solidangle: array of same shape as data for pre-processing\n :param polarization: array of same shape as data for pre-processing\n :param safe: if True (default) compares arrays on GPU according to their checksum, unless, use the buffer location is used\n :param normalization_factor: divide raw signal by this value\n :param cutoff: discard all points with |value - avg| > cutoff * sigma. 3-4 is quite common \n :param cycle: perform at maximum this number of cycles. 5 is common.\n :return: namedtuple with \"position intensity error signal variance normalization count\"\n \"\"\"\n shape = data.shape\n error_model = error_model.lower() if error_model else \"\"\n\n if self._geometry is None:\n raise RuntimeError(\"Set geometry first\")\n\n prep = preproc(data,\n dark=dark,\n flat=flat,\n solidangle=solidangle,\n polarization=polarization,\n absorption=absorption,\n mask=None,\n dummy=dummy,\n delta_dummy=delta_dummy,\n normalization_factor=normalization_factor,\n empty=self.empty,\n split_result=4,\n variance=variance,\n dtype=numpy.float32,\n poissonian=error_model.startswith(\"pois\"))\n prep_flat = prep.reshape((numpy.prod(shape), 4))\n res = self._csr.dot(prep_flat)\n print(cycle)\n for _ in range(cycle):\n msk = res[:, 2] == 0\n avg = res[:, 0] / res[:, 2]\n std = numpy.sqrt(res[:, 1] / res[:, 2])\n avg[msk] = 0\n std[msk] = 0\n\n avg2d = self._geometry.calcfrom1d(self.bin_centers, avg, shape=shape,\n dim1_unit=self.unit, correctSolidAngle=False, dummy=0.0)\n std2d = self._geometry.calcfrom1d(self.bin_centers, std, shape=shape,\n dim1_unit=self.unit, correctSolidAngle=False, dummy=0.0)\n cnt = abs(prep[..., 0] / prep[..., 2] - avg2d) / std2d\n msk2d = numpy.logical_and(numpy.logical_not(numpy.isfinite(cnt)), cnt > cutoff)\n prep[msk2d,:] = 0\n res = self._csr.dot(prep_flat)\n msk = res[:, 2] == 0\n avg = res[:, 0] / res[:, 2]\n std = numpy.sqrt(res[:, 1] / res[:, 2])\n avg[msk] = 0\n std[msk] = 0\n\n return Integrate1dtpl(self.bin_centers, avg, std, res[:, 0], res[:, 1], res[:, 2], res[:, 3])\n\n\nclass CsrIntegrator2d(CSRIntegrator):\n\n def __init__(self,\n image_size,\n lut=None,\n empty=0.0,\n bin_centers0=None,\n bin_centers1=None):\n \"\"\"Constructor of the abstract class for 2D integration\n \n :param size: input image size\n :param lut: tuple of 3 arrays with data, indices and indptr,\n index of the start of line in the CSR matrix\n :param empty: value for empty pixels\n :param bin_center: position of the bin center\n\n Nota: bins are deduced from bin_centers0, bin_centers1 \n \n \"\"\"\n self.bin_centers0 = bin_centers0\n self.bin_centers1 = bin_centers1\n CSRIntegrator.__init__(self, image_size, lut, empty)\n\n def set_matrix(self, data, indices, indptr):\n \"\"\"Actually set the CSR sparse matrix content\n \n :param data: the non zero values NZV\n :param indices: the column number of the NZV\n :param indptr: the index of the start of line\"\"\"\n\n CSRIntegrator.set_matrix(self, data, indices, indptr)\n assert len(self.bin_centers0) * len(self.bin_centers1) == len(indptr) - 1\n self.bins = (len(self.bin_centers0), len(self.bin_centers1))\n\n def integrate(self,\n signal,\n variance=None,\n dummy=None,\n delta_dummy=None,\n dark=None,\n flat=None,\n solidangle=None,\n polarization=None,\n absorption=None,\n normalization_factor=1.0):\n \"\"\"Actually perform the 2D integration \n \n :param signal: array of the right size with the signal in it.\n :param variance: Variance associated with the signal\n :param dummy: values which have to be discarded (dynamic mask)\n :param delta_dummy: precision for dummy values\n :param dark: noise to be subtracted from signal\n :param flat: flat-field normalization array\n :param flat: solidangle normalization array\n :param polarization: :solidangle normalization array\n :param absorption: :absorption normalization array\n :param normalization_factor: scale all normalization with this scalar\n :return: Integrate2dtpl namedtuple: \"radial azimuthal intensity error signal variance normalization count\"\n \n \"\"\"\n if variance is None:\n do_variance = False\n else:\n do_variance = True\n trans = CSRIntegrator.integrate(self, signal, variance, dummy, delta_dummy,\n dark, flat, solidangle, polarization,\n absorption, normalization_factor)\n trans.shape = self.bins + (-1,)\n\n signal = trans[..., 0]\n variance = trans[..., 1]\n normalization = trans[..., 2]\n count = trans[..., -1] # should be 3\n mask = (normalization == 0)\n with numpy.errstate(divide='ignore', invalid='ignore'):\n intensity = signal / normalization\n intensity[mask] = self.empty\n if do_variance:\n error = numpy.sqrt(variance) / normalization\n error[mask] = self.empty\n else:\n variance = error = None\n return Integrate2dtpl(self.bin_centers0, self.bin_centers1,\n intensity, error,\n signal, variance, normalization, count)\n\n", "meta": {"hexsha": "b9c359fccdffe9690175aec61b1ce2cbc1581dd7", "size": 17911, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyFAI/engines/CSR_engine.py", "max_stars_repo_name": "loichuder/pyFAI", "max_stars_repo_head_hexsha": "8b1d8dd522c4d2d9ac919b9869eb8c314b18e271", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyFAI/engines/CSR_engine.py", "max_issues_repo_name": "loichuder/pyFAI", "max_issues_repo_head_hexsha": "8b1d8dd522c4d2d9ac919b9869eb8c314b18e271", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyFAI/engines/CSR_engine.py", "max_forks_repo_name": "loichuder/pyFAI", "max_forks_repo_head_hexsha": "8b1d8dd522c4d2d9ac919b9869eb8c314b18e271", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.4431279621, "max_line_length": 299, "alphanum_fraction": 0.5911451064, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.24220562872535945, "lm_q1q2_score": 0.13522994425737087}} {"text": "#! /usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\n ***\n UVW\n ***\n\"\"\"\n\n\n__author__ = 'Alan Loh'\n__copyright__ = 'Copyright 2020, nenupy'\n__credits__ = ['Alan Loh']\n__maintainer__ = 'Alan'\n__email__ = 'alan.loh@obspm.fr'\n__status__ = 'Production'\n__all__ = [\n 'UVW'\n]\n\n\nimport numpy as np\nfrom astropy.coordinates import SkyCoord\nimport astropy.units as u\nfrom astropy.time import Time\nfrom pyproj import Transformer\n\nfrom nenupy.instru import ma_info\nfrom nenupy.astro import (\n lst,\n lha,\n toFK5,\n eq_zenith,\n wavelength\n)\n\nimport logging\nlog = logging.getLogger(__name__)\n\n\n# ============================================================= #\n# ---------------------------- UVW ---------------------------- #\n# ============================================================= #\nclass UVW(object):\n \"\"\"\n \"\"\"\n\n def __init__(self, times, mas, freqs=None):\n self.bsl_xyz = None\n self.times = times\n self.freqs = freqs\n self.mas = mas\n\n\n # --------------------------------------------------------- #\n # --------------------- Getter/Setter --------------------- #\n @property\n def mas(self):\n return self._mas\n @mas.setter\n def mas(self, m):\n if not isinstance(m, np.ndarray):\n raise TypeError(\n 'mas should be a numpy array.'\n )\n ma_pos = np.array([a.tolist() for a in ma_info['pos']])\n available_mas = np.arange(ma_pos.shape[0])\n antpos = ma_pos[np.isin(available_mas, m)]\n # RGF93 to ITRF97\n # See http://epsg.io/?q=itrf97 to find correct EPSG\n t = Transformer.from_crs(\n crs_from='EPSG:2154', # RGF93\n crs_to='EPSG:4896'# ITRF2005\n )\n antpos[:, 0], antpos[:, 1], antpos[:, 2] = t.transform(\n xx=antpos[:, 0],\n yy=antpos[:, 1],\n zz=antpos[:, 2]\n )\n\n xyz = antpos[..., None]\n xyz = xyz[:, :, 0][:, None]\n # xyz = xyz - xyz.transpose(1, 0, 2)\n xyz = xyz.transpose(1, 0, 2) - xyz\n # self.bsl = xyz[np.triu_indices(m.size)]\n self.bsl = xyz[np.tril_indices(m.size)]\n self._mas = m\n return\n\n\n @property\n def times(self):\n \"\"\" Times at which the UVW must be computed.\n\n :setter: Times\n \n :getter: Times\n \n :type: :class:`~astropy.time.Time`\n \"\"\"\n return self._times\n @times.setter\n def times(self, t):\n if not isinstance(t, Time):\n raise TypeError(\n 'times must be a Time instance.'\n )\n self._times = t\n return \n\n\n @property\n def freqs(self):\n return self._freqs\n @freqs.setter\n def freqs(self, f):\n if f is None:\n self._freqs = None\n else:\n if not isinstance(f, u.Quantity):\n f *= u.MHz\n if f.isscalar:\n f = np.array([f.value]) * u.MHz\n self._freqs = f\n return\n\n\n @property\n def uvw(self):\n \"\"\" UVW in meters.\n\n :getter: (times, baselines, UVW)\n \n :type: :class:`~numpy.ndarray`\n \"\"\"\n if not hasattr(self, '_uvw'):\n raise Exception(\n 'Run .compute() first.'\n )\n return self._uvw\n\n\n @property\n def uvw_wave(self):\n \"\"\" UVW in lambdas.\n\n :getter: (times, freqs, baselines, UVW)\n \n :type: :class:`~numpy.ndarray`\n \"\"\"\n if not hasattr(self, '_uvw'):\n raise Exception(\n 'Run .compute() first.'\n )\n if self.freqs is None:\n raise ValueError(\n 'No frequency input, fill self.freqs.'\n )\n lamb = wavelength(self.freqs).value\n na = np.newaxis\n return self._uvw[:, na, :, :]/lamb[na, :, na, na]\n\n\n # --------------------------------------------------------- #\n # ------------------------ Methods ------------------------ #\n def compute(self, phase_center=None):\n r\"\"\" Compute the UVW at a given ``phase_center`` for all\n the :attr:`~nenupy.crosslet.uvw.UVW.times` and baselines\n formed by :attr:`~nenupy.crosslet.uvw.UVW.mas`.\n\n :param phase_center: Observation phase center. If\n ``None``, local zenith is considered as phase\n center for all :attr:`~nenupy.crosslet.uvw.UVW.times`.\n :type phase_center: :class:`~astropy.coordinates.SkyCoord`\n\n UVW are computed such as:\n\n .. math::\n \\pmatrix{\n u \\\\\n v \\\\\n w\n } =\n \\pmatrix{\n \\sin(h) & \\cos(h) & 0\\\\\n -\\sin(\\delta) \\cos(h) & \\sin(\\delta) \\sin(h) & \\cos(\\delta)\\\\\n \\cos(\\delta)\\cos(h) & -\\cos(\\delta) \\sin(h) & \\sin(\\delta)\n }\n \\pmatrix{\n \\Delta x\\\\\n \\Delta y\\\\\n \\Delta z\n }\n\n :math:`u`, :math:`v`, :math:`w` are in meters. :math:`h`\n is the hour angle (see :func:`~nenupy.astro.astro.lha`)\n at which the phase center is observed, :math:`\\delta`\n is the phase center's declination, :math:`(\\Delta x,\n \\Delta y, \\Delta z)` are the baselines projections\n with the convention of :math:`x` to the South, :math:`y`\n to the East and :math:`z` to :math:`\\delta = 90` deg.\n\n Result of the computation are stored as a :class:`~numpy.ndarray`\n in :attr:`~nenupy.crosslet.uvw.UVW.uvw` whose shape is\n (times, cross-correlations, 3), 3 being :math:`(u, v, w)`.\n \"\"\"\n # Phase center\n if phase_center is None:\n log.info(\n 'UVW phase centered at local zenith.'\n )\n phase_center = eq_zenith(self.times)\n else:\n if not isinstance(phase_center, SkyCoord):\n raise TypeError(\n 'phase_center should be a SkyCoord object'\n )\n if phase_center.isscalar:\n ones = np.ones(self.times.size)\n ra_tab = ones * phase_center.ra\n dec_tab = ones * phase_center.dec\n phase_center = SkyCoord(ra_tab, dec_tab)\n else:\n if phase_center.size != self.times.size:\n raise ValueError(\n 'Size of phase_center != times'\n )\n log.info(\n 'UVW phase centered at RA={}, Dec={}'.format(\n phase_center.ra[0].deg,\n phase_center.dec[0].deg\n )\n )\n # Hour angles\n lstTime = lst(\n time=self.times,\n kind='apparent'\n )\n phase_center = toFK5(\n skycoord=phase_center,\n time=self.times\n )\n ha = lha(\n lst=lstTime,\n skycoord=phase_center\n )\n\n # Transformations\n self._uvw = np.zeros(\n (\n self.times.size,\n self.bsl.shape[0],\n 3\n )\n )\n xyz = np.array(self.bsl).T\n # rot = np.radians(-90) # x to the south, y to the east\n # rotation = np.array(\n # [\n # [ np.cos(rot), np.sin(rot), 0],\n # [-np.sin(rot), np.cos(rot), 0],\n # [ 0, 0, 1]\n # ]\n # )\n for i in range(self.times.size):\n sr = np.sin(ha[i].rad)\n cr = np.cos(ha[i].rad)\n sd = np.sin(phase_center.dec[i].rad)\n cd = np.cos(phase_center.dec[i].rad)\n rot_uvw = np.array([\n [ sr, cr, 0],\n [-sd*cr, sd*sr, cd],\n [ cd*cr, -cd*sr, sd]\n ])\n # self.uvw[i, ...] = - np.dot(\n # np.dot(rot_uvw, xyz).T,\n # rotation\n # )\n self._uvw[i, ...] = - np.dot(rot_uvw, xyz).T\n return\n\n\n @classmethod\n def from_tvdata(cls, tvdata):\n \"\"\"\n \"\"\"\n from nenupy.crosslet import TV_Data\n if not isinstance(tvdata, TV_Data):\n raise TypeError(\n 'tvdata must be a TV_Data instance'\n )\n uvw = cls(\n times=tvdata.times,\n freqs=tvdata.freqs,\n mas=tvdata.mas\n )\n uvw.compute()\n return uvw\n\n\n @classmethod\n def from_xstdata(cls, xstdata):\n \"\"\"\n \"\"\"\n from nenupy.crosslet import XST_Data\n if isinstance(xstdata, XST_Data):\n pass\n elif isinstance(xstdata, str):\n xstdata = XST_Data(xstdata)\n else:\n raise TypeError(\n 'xstdata must be a XST_Data instance or XST file.'\n )\n uvw = cls(\n times=xstdata.times,\n freqs=xstdata.freqs,\n mas=xstdata.mas\n )\n uvw.compute()\n return uvw\n\n\n # def rephase(self, ra, dec):\n # \"\"\"\n # \"\"\"\n # self._uvw\n # --------------------------------------------------------- #\n # ----------------------- Internal ------------------------ #\n\n# ============================================================= #\n\n", "meta": {"hexsha": "673c4dfb0445f434ca0c575edb0e7af71589a9bb", "size": 9450, "ext": "py", "lang": "Python", "max_stars_repo_path": "nenupy/crosslet/uvw.py", "max_stars_repo_name": "lucilecoutouly/nenupy", "max_stars_repo_head_hexsha": "8bfcab9558087f0696080d750293d9b8edc30665", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nenupy/crosslet/uvw.py", "max_issues_repo_name": "lucilecoutouly/nenupy", "max_issues_repo_head_hexsha": "8bfcab9558087f0696080d750293d9b8edc30665", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nenupy/crosslet/uvw.py", "max_forks_repo_name": "lucilecoutouly/nenupy", "max_forks_repo_head_hexsha": "8bfcab9558087f0696080d750293d9b8edc30665", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3783783784, "max_line_length": 81, "alphanum_fraction": 0.4375661376, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 2247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.2422056341953392, "lm_q1q2_score": 0.13522994375137692}} {"text": "\nfrom __future__ import absolute_import\nfrom ._hydrodiskstars import c_hydrodiskstars\nfrom . import data\n\n\nclass hydrodiskstars:\n\n\tr\"\"\"\n\tA stellar migration scheme informed by the ``h277`` simulation, a zoom-in\n\thydrodynamic simulation of a Milky Way like galaxy ran from cosmological\n\tinitial conditions (a part of the ``g14`` simulation suite, Christensen et\n\tal 2012 [1]_).\n\n\t**Signature**: vice.toolkit.hydrodisk.hydrodiskstars(radial_bins, N = 1e5,\n\tmode = \"diffusion\")\n\n\t.. versionadded:: 1.2.0\n\n\t.. warning:: Simulations which adopt this model that run for longer than\n\t\t13.2 Gyr are not supported. Stellar populations in the built-in\n\t\thydrodynamical simulation data span 13.2 Gyr of ages; simulations on\n\t\tlonger timescales are highly likely to produce a\n\t\t``segmentation fault``.\n\n\tParameters\n\t----------\n\tradial_bins : array-like [elements must be positive real numbers]\n\t\tThe bins in galactocentric radius in kpc describing the disk model.\n\t\tThis must extend from 0 to at least 20. Need not be sorted in any\n\t\tway. Will be stored as an attribute.\n\tN : int [default : 1e5]\n\t\tAn approximate number of star particles from the hydrodynamical\n\t\tsimulation to include in the sample of candidate analogs. Their data\n\t\tare not stored in a single file, but split across random subsamples to\n\t\tdecrease computational overhead when the full sample is not required.\n\t\tIn practice, this number should be slightly larger than the number of\n\t\t(relevant) stellar populations simulated by a multizone model.\n\n\t\t.. note:: There are 3,102,519 star particles available for this\n\t\t\tobject. Any more stellar populations than this would oversample\n\t\t\tthese data.\n\n\tmode : str [case-insensitive] or ``None`` [default : \"diffusion\"]\n\t\tThe attribute 'mode', initialized via keyword argument.\n\n\tAttributes\n\t----------\n\tradial_bins : list\n\t\tThe bins in galactocentric radius in kpc describing the disk model.\n\tanalog_data : dataframe\n\t\tThe raw star particle data from the hydrodynamical simulation.\n\tanalog_index : int\n\t\tThe index of the star particle acting as the current analog. -1 if the\n\t\tanalog has not yet been set (see note below under `Calling`_).\n\tmode : str or ``None``\n\t\tThe mode of stellar migration, describing the approximation of how\n\t\tstars move from birth to final radii. Either \"diffusion\", \"sudden\", or\n\t\t\"linear\". See property docstring for more details.\n\n\t\t.. note:: Only subclasses may set this attribute ``None``, in which\n\t\t\tcase it is assumed that a custom migration approximation is\n\t\t\temployed by an overridden ``__call__`` function. In this case,\n\t\t\tif this attribute is not set to ``None``, multizone simulations\n\t\t\twill *still* use the approximation denoted by this property.\n\n\tCalling\n\t-------\n\tAs all stellar migration prescriptions must, this object can be called\n\twith three parameters, in the following order:\n\n\t\tzone : int\n\t\t\tThe zone index of formation of the stellar population. Must be\n\t\t\tnon-negative.\n\t\ttform : float\n\t\t\tThe time of formation of the stellar population in Gyr.\n\t\ttime : float\n\t\t\tThe simulation time in Gyr (i.e. not the age of the star particle).\n\n\t.. note:: The search for analog star particles is ran when the formation\n\t\ttime and simulation time are equal. Therefore, calling this object\n\t\twith the second and third parameters equal resets the star particle\n\t\tacting as the analog, and the data for the corresponding star particle\n\t\tcan then be accessed via the attribute ``analog_index``.\n\n\tFunctions\n\t---------\n\tdecomp_filter : [instancemethod]\n\t\tFilter the star particles based on their kinematic decomposition.\n\n\tRaises\n\t------\n\t* ValueError\n\t\t- Minimum radius does not equal zero\n\t\t- Maximum radius < 20\n\t* ScienceWarning\n\t\t- This object is called with a time larger than 13.2 Gyr\n\t\t- The number of analog star particles requested is larger than the\n\t\t number available from the hydrodynamical simulation (3,102,519)\n\n\tNotes\n\t-----\n\tThis object requires VICE's supplementary data sample, available in its\n\tGitHub repository at ./vice/toolkit/hydrodisk/data. The first time a\n\t``hydrodiskstars`` object is constructed, VICE will download\n\tthe additional data automatically. If this process fails, it may be due to\n\tnot having administrator's privileges on your system; in this event, users\n\tshould speak with their administrator, who would then be able to download\n\ttheir data by running the following on their system:\n\n\t>>> import vice\n\t>>> vice.toolkit.hydrodisk.data.download()\n\n\tThis migration scheme works by assigning each stellar population in the\n\tsimulation an analog star particle from the hydrodynamical simulation. The\n\tanalog is randomly drawn from a sample of star particles which formed at\n\ta similar radius and time, and the stellar population then assumes the\n\tchange in orbital radius of its analog.\n\n\tVICE first searches for analogs in the ``h277`` data for star particles\n\twhich formed at a radius of :math:`R \\pm` 250 pc and at a time of\n\t:math:`T \\pm` 250 Myr. If no analogs are found that satisfy this\n\trequirement, the search is widened to :math:`R \\pm` 500 pc and\n\t:math:`T \\pm` 500 Myr. If still no analog is found, then the time\n\trestriction of :math:`T \\pm` 500 Myr is maintained, and VICE finds the star\n\tparticle with the smallest difference in birth radius, assigning it as the\n\tanalog. These values parameterizing this search algorithm are declared in\n\t``vice/src/toolkit/hydrodiskstars.h`` in the VICE source tree. For further\n\tdetails, see \"Milky Way-Like Galaxies\" under VICE's science documentation.\n\n\tThis object can be subclassed to implement a customized migration\n\tapproximation by overriding the ``__call__`` function. However, in this\n\tcase, users must also set the attribute ``mode`` to ``None``. If this\n\trequirement is not satisfied, multizone simulations will **still** use the\n\tapproximation denoted by the ``mode`` attribute, **not** their overridden\n\t``__call__`` function.\n\n\tThe ``h277`` galaxy had a weak and transient bar, but does not have one at\n\tthe present day. This is one notable difference between it and the Milky\n\tWay.\n\n\tExample Code\n\t------------\n\t>>> from vice.toolkit.hydrodisk import hydrodiskstars\n\t>>> import numpy as np\n\t>>> example = hydrodiskstars(np.linspace(0, 20, 81), N = 5e5)\n\t>>> example.radial_bins\n\t[0.0,\n\t 0.25,\n\t 0.5,\n\t ...\n\t 19.5,\n\t 19.75,\n\t 20.0]\n\t>>> example.analog_data.keys()\n\t['id', 'tform', 'rform', 'rfinal', 'zfinal', 'vrad', 'vphi', 'vz']\n\t>>> example.analog_index\n\t-1\n\t>>> example(5, 7.2, 7.2)\n\t5\n\t>>> example.analog_index\n\t200672\n\t>>> example.analog_data[\"vrad\"][example.analog_index]\n\t5.6577\n\t>>> example.mode\n\t\"diffusion\"\n\n\t.. [1] Christensen et al. (2012), MNRAS, 425, 3058\n\t\"\"\"\n\n\tdef __init__(self, rad_bins, N = 1e5, mode = \"diffusion\"):\n\t\tif not data._h277_exists():\n\t\t\tprint(\"VICE supplementary data required, downloading now.\")\n\t\t\tprint(\"You will not need to repeat this process.\")\n\t\t\tdata.download()\n\t\telse: pass\n\t\tself.__c_version = c_hydrodiskstars(rad_bins, N = N, mode = mode)\n\n\tdef __call__(self, zone, tform, time):\n\t\treturn self.__c_version.__call__(zone, tform, time)\n\n\tdef __enter__(self):\n\t\t# Opens a with statement\n\t\treturn self\n\n\tdef __exit__(self, exc_type, exc_value, exc_tb):\n\t\t# Raises all exceptions inside a with statement\n\t\treturn exc_value is None\n\n\tdef __object_address(self):\n\t\tr\"\"\"\n\t\tReturns the memory address of the HYDRODISKSTARS object in C. For\n\t\tinternal usage only; usage of this function by the user is strongly\n\t\tdiscouraged.\n\t\t\"\"\"\n\t\treturn self.__c_version.object_address()\n\n\t@property\n\tdef radial_bins(self):\n\t\tr\"\"\"\n\t\tType : list [elements are positive real numbers]\n\n\t\tThe bins in galactocentric radius in kpc describing the disk model.\n\t\tMust extend from 0 to at least 20 kpc. Need not be sorted in any way\n\t\twhen assigned.\n\n\t\tExample Code\n\t\t------------\n\t\t>>> from vice.toolkit.hydrodisk import hydrodiskstars\n\t\t>>> import numpy as np\n\t\t>>> example = hydrodiskstars([0, 5, 10, 15, 20])\n\t\t>>> example.radial_bins\n\t\t[0, 5, 10, 15, 20]\n\t\t>>> example.radial_bins = list(range(31))\n\t\t>>> example.radial_bins\n\t\t[0,\n\t\t 1,\n\t\t 2,\n\t\t ...\n\t\t 17,\n\t\t 18,\n\t\t 19,\n\t\t 20]\n\t\t\"\"\"\n\t\treturn self.__c_version.radial_bins\n\n\t@radial_bins.setter\n\tdef radial_bins(self, value):\n\t\tself.__c_version.radial_bins = value\n\n\t@property\n\tdef analog_data(self):\n\t\tr\"\"\"\n\t\tType : dataframe\n\n\t\tThe star particle data from the hydrodynamical simulation. The\n\t\tfollowing keys map to the following data:\n\n\t\t\t- id: \tThe IDs of each star particle\n\t\t\t- tform: \tThe time the star particle formed in Gyr\n\t\t\t- rform: \tThe radius the star particle formed at in kpc\n\t\t\t- rfinal: \tThe radius the star particle ended up at in kpc\n\t\t\t- zform: \tThe disk midplane distance in kpc at the time of\n\t\t\t formation.\n\t\t\t- zfinal: \tThe disk midplane distance in kpc at the end of the\n\t\t\t simulation\n\t\t\t- vrad: The radial velocity of the star particle at the end of\n\t\t\t the simulation in km/sec\n\t\t\t- vphi: The azimuthal velocity of the star particle at the end\n\t\t\t of the simulation in km/sec\n\t\t\t- vz: \t\tThe velocity perpendicular to the disk midplane at the\n\t\t\t end of the simulation in km/sec\n\t\t\t- decomp: \tAn integer denoting which kinematic subclass the star\n\t\t\t particle belongs to (1: thin disk, 2: thick disk, 3: bulge,\n\t\t\t 4: pseudobulge, 5: halo).\n\n\t\tExample Code\n\t\t------------\n\t\t>>> from vice.toolkit.hydrodisk import hydrodiskstars\n\t\t>>> import numpy as np\n\t\t>>> example = hydrodiskstars(np.linspace(0, 20, 81))\n\t\t>>> example.analog_data.keys()\n\t\t['id', 'tform', 'rform', 'rfinal', 'zfinal', 'vrad', 'vphi', 'vz']\n\t\t>>> example.analog_data[\"rfinal\"][:10]\n\t\t[2.0804,\n\t\t 14.9953,\n\t\t 2.2718,\n\t\t 15.1236,\n\t\t 2.3763,\n\t\t 0.9242,\n\t\t 9.0908,\n\t\t 0.1749,\n\t\t 8.415,\n\t\t 20.1452]\n\t\t\"\"\"\n\t\treturn self.__c_version.analog_data\n\n\t@property\n\tdef analog_index(self):\n\t\tr\"\"\"\n\t\tType : int\n\n\t\tThe index of the analog in the hydrodynamical simulation star particle\n\t\tdata. -1 if it has not yet been assigned.\n\n\t\t.. note:: Calling this object at a given zone with the formation time\n\t\t\tand the simulation time equal resets the star particle acting as\n\t\t\tthe analog.\n\n\t\tExample Code\n\t\t------------\n\t\t>>> from vice.toolkit.hydrodisk import hydrodiskstars\n\t\t>>> import numpy as np\n\t\t>>> example = hydrodiskstars(np.linspace(0, 20, 81))\n\t\t>>> example.analog_index\n\t\t-1 # no analog yet\n\t\t>>> example(2, 1, 1) # final two arguments equal resets analog\n\t\t15745\n\t\t>>> example(10, 4, 4)\n\t\t10\n\t\t>>> example.analog_index\n\t\t101206\n\t\t>>> example.analog_data[\"rfinal\"][example.analog_index]\n\t\t2.6411\n\t\t>>> example.analog_data[\"vrad\"][example.analog_data]\n\t\t92.2085\n\t\t\"\"\"\n\t\treturn self.__c_version.analog_index\n\n\t@property\n\tdef mode(self):\n\t\tr\"\"\"\n\t\tType : str [case-insensitive] or ``None``\n\n\t\tDefault : \"diffusion\"\n\n\t\tRecognized Values\n\t\t-----------------\n\t\tThe following is a breakdown of how stellar populations migrate in\n\t\tmultizone simulations under each approximation.\n\n\t\t- \"diffusion\"\n\t\t\tThe orbital radius at times between birth and 13.2 Gyr are assigned\n\t\t\tvia a sqrt(time) dependence, the mean displacement if stars\n\t\t\tmigrated according to a random walk. Stellar populations spiral\n\t\t\tinward or outward with a smooth time dependence in this model.\n\t\t- \"linear\"\n\t\t\tOrbital radii at times between birth and 13.2 Gyr are assigned via\n\t\t\tlinear interpolation. Stellar populations therefore spiral\n\t\t\tuniformly inward or outward from birth to final radii, with orbital\n\t\t\tradius changing more slowly for young stars than in the diffusion\n\t\t\tmodel, but more quickly for old stars.\n\t\t- \"sudden\"\n\t\t\tThe time of migration is randomly drawn from a uniform distribution\n\t\t\tbetween when a stellar population is born and 13.2 Gyr. At times\n\t\t\tprior to this, it is at its radius of birth; at subsequent times,\n\t\t\tit is at its final radius. Stellar populations therefore spend no\n\t\t\ttime at intermediate radii.\n\t\t- ``None``\n\t\t\tOnly supported for subclasses of the hydrodiskstars object, this\n\t\t\tshould be used when the user intends to override the built-in\n\t\t\tmigration assumptions and implement a different one. In these\n\t\t\tcases, the ``__call__`` method should be overridden in addition to\n\t\t\tthis attribute being set to ``None``.\n\n\t\t.. note:: The \"post-processing\" model from Johnson et al. (2021) [1]_\n\t\t\tcorresponds to setting the attribute ``simple = True`` in the\n\t\t\t``milkyway`` object, inherited from the base class ``multizone``.\n\n\t\tExample Code\n\t\t------------\n\t\t>>> from vice.toolkit.hydrodisk import hydrodiskstars\n\t\t>>> import numpy as np\n\t\t>>> example = hydrodiskstars(np.linspace(0, 20, 81))\n\t\t>>> example.mode\n\t\t'diffusion'\n\t\t>>> example.mode = \"sudden\"\n\t\t>>> example.mode = \"linear\"\n\n\t\t.. [1] Johnson et al. (2021), 2103.09838\n\t\t\"\"\"\n\t\treturn self.__c_version.mode\n\n\t@mode.setter\n\tdef mode(self, value):\n\t\tif value is None:\n\t\t\tif type(self) != hydrodiskstars:\n\t\t\t\tself.__c_version.mode = None\n\t\t\telse:\n\t\t\t\traise ValueError(\"\"\"None-Type value for attribute 'mode' only \\\nsupported for subclasses of hydrodiskstars object.\"\"\")\n\t\telse:\n\t\t\tself.__c_version.mode = value\n\n\n\tdef decomp_filter(self, values):\n\t\tr\"\"\"\n\t\tFilter the star particles from the hydrodynamic simulation based on\n\t\tthe kinematic decomposition.\n\n\t\tParameters\n\t\t----------\n\t\tvalues : ``list`` [elements of type ``int``]\n\t\t\tThe integer values of the \"decomp\" column in the ``analog_data``\n\t\t\tattribute to base the filter on. Those with a decomposition tag\n\t\t\tequal to one of the values in this list will pass the filter and\n\t\t\tremain in the sample.\n\n\t\t\t.. note:: The integer values mean that an individual star particle\n\t\t\t\thas kinematics associated with the following sub-populations:\n\t\t\t\t\n\t\t\t\t\t- 1: thin disk\n\t\t\t\t\t- 2: thick disk\n\t\t\t\t\t- 3: bulge\n\t\t\t\t\t- 4: pseudobulge\n\t\t\t\t\t- 5: halo\n\n\t\tExample Code\n\t\t------------\n\t\t>>> from vice.toolkit.hydrodisk import hydrodiskstars\n\t\t>>> import numpy as np\n\t\t>>> example = hydrodiskstars(np.linspace(0, 20, 81))\n\t\t>>> len(example.analog_data['id'])\n\t\t102857\n\t\t>>> example.decomp_filter([1, 2]) # disk stars only\n\t\t>>> len(example.analog_data['id'])\n\t\t57915\n\t\t>>> all([i in [1, 2] for i in example.analog_data['decomp']])\n\t\tTrue\n\t\t>>> example = hydrodiskstars(np.linspace(0, 20, 81))\n\t\t>>> len(example.analog_data['id'])\n\t\t102857\n\t\t>>> example.decomp_filter([3, 4]) # bulge stars only\n\t\t>>> len(example.analog_data['id'])\n\t\t44942\n\t\t>>> all([i in [3, 4] for i in example.analog_data['decomp']])\n\t\tTrue\n\t\t\"\"\"\n\t\tself.__c_version.decomp_filter(values)\n\n", "meta": {"hexsha": "97d6938b8f6d40198f1e15207df02ba8308b20ff", "size": 14289, "ext": "py", "lang": "Python", "max_stars_repo_path": "vice/toolkit/hydrodisk/hydrodiskstars.py", "max_stars_repo_name": "rcooke-ast/VICE", "max_stars_repo_head_hexsha": "762911eb4192c7206ce2ae36b645d120ed889cb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2018-09-26T21:02:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T18:07:03.000Z", "max_issues_repo_path": "vice/toolkit/hydrodisk/hydrodiskstars.py", "max_issues_repo_name": "rcooke-ast/VICE", "max_issues_repo_head_hexsha": "762911eb4192c7206ce2ae36b645d120ed889cb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-05-03T13:08:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-17T20:11:37.000Z", "max_forks_repo_path": "vice/toolkit/hydrodisk/hydrodiskstars.py", "max_forks_repo_name": "rcooke-ast/VICE", "max_forks_repo_head_hexsha": "762911eb4192c7206ce2ae36b645d120ed889cb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-05-10T19:26:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-10T08:13:42.000Z", "avg_line_length": 33.9406175772, "max_line_length": 76, "alphanum_fraction": 0.7119462524, "include": true, "reason": "import numpy", "num_tokens": 3951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.23091975234373585, "lm_q1q2_score": 0.13511141362464416}} {"text": "\nfrom __future__ import division\nimport os\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nfrom torch.nn.functional import upsample,normalize\nfrom ...nn import PAM_Module\nfrom ...nn import CAM_Module\nfrom .base import BaseNet\nfrom torch.nn.parallel.scatter_gather import gather\n\n\n__all__ = ['DANet', 'get_danet']\ndef random_rectangle_mask_gene(img_size, batch_size, num_rect, device, max_size_factor):\n\n msk = torch.ones((batch_size, 1, img_size[0], img_size[1]), device=device).float()\n\n for batch_idx in range(batch_size):\n for i in range(num_rect):\n pos = np.random.rand(2)\n size = np.maximum(np.random.rand(2), 0.1/max_size_factor) * max_size_factor\n\n h_start = int(pos[0] * img_size[0])\n w_start = int(pos[1] * img_size[1])\n h = np.minimum(int(size[0] * img_size[0]), img_size[0]-h_start)\n w = np.minimum(int(size[1] * img_size[1]), img_size[1]-w_start)\n\n msk[batch_idx, :, h_start:h_start+h, w_start:w_start+w] = 0.\n\n return msk\n\n\n#maxpooling as inpainting module\ndef MaxpoolingAsInpainting(x, x_fore_augment):\n #print(x.detach().cpu().numpy().shape)\n #print(str(4))\n x_fore_augments = gather(x_fore_augment, 0, dim=0)\n pred = torch.max(x_fore_augment[0], 1)[1].unsqueeze(1)\n\n #print(str(5))\n #print(x_fore_augment[0].detach().cpu().numpy().shape)\n\n x_fore_pool = F.interpolate(pred.float(), size=x.size()[2:4]).detach().clone()\n fore_msk = (x_fore_pool > 0.5).float().detach().clone()\n fore_msk = F.max_pool2d((fore_msk).detach().clone(), kernel_size=3, stride=1, padding=1)\n bkgd_msk_prev = (1.-fore_msk).detach().clone()\n bkgd_msk = bkgd_msk_prev.detach().clone()\n x_new = x.detach().clone() * bkgd_msk.detach()[0].clone()\n x_patch = x.detach().clone() * 0.\n\n while torch.mean(1.-bkgd_msk).item() > 0.0001 and torch.min(torch.mean(bkgd_msk, dim=(1, 2, 3))) > 0.:\n x_new =0.5* F.max_pool2d((x_new).detach().clone(), kernel_size=3, stride=1, padding=1)+ 0.5*F.avg_pool2d((x_new).detach().clone(), kernel_size=3, stride=1, padding=1)\n bkgd_msk = F.max_pool2d((bkgd_msk_prev).detach().clone(),kernel_size=3, stride=1, padding=1)\n x_patch = (x_patch + (bkgd_msk-bkgd_msk_prev)*x_new).detach().clone()\n bkgd_msk_prev = bkgd_msk.detach().clone()\n\n return x_patch,pred\n\n\n\nclass PSPModule(nn.Module):\n def __init__(self, features, out_features=1024, sizes=(1, 2, 3, 6)):\n super().__init__()\n self.stages = []\n self.stages = nn.ModuleList([self._make_stage(features, size) for size in sizes])\n self.bottleneck = nn.Conv2d(features * (len(sizes) + 1), out_features, kernel_size=1)\n self.relu = nn.ReLU()\n\n def _make_stage(self, features, size):\n prior = nn.AdaptiveAvgPool2d(output_size=(size, size))\n conv = nn.Conv2d(features, features, kernel_size=1, bias=False)\n return nn.Sequential(prior, conv)\n\n def forward(self, feats):\n h, w = feats.size(2), feats.size(3)\n priors = [F.interpolate(input=stage(feats), size=(h, w), mode='bilinear', align_corners=False) for stage in self.stages] + [feats]\n bottle = self.bottleneck(torch.cat(priors, 1))\n return self.relu(bottle)\n\nclass PSPUpsample(nn.Module):\n def __init__(self, in_channels, out_channels):\n super().__init__()\n self.conv = nn.Sequential(\n nn.Conv2d(in_channels, out_channels, 3, padding=1),\n nn.BatchNorm2d(out_channels),\n nn.PReLU()\n )\n\n def forward(self, x):\n h, w = 2 * x.size(2), 2 * x.size(3)\n p = F.interpolate(input=x, size=(h, w), mode='bilinear', align_corners=False)\n return self.conv(p)\n\n\nclass PSPNet(nn.Module):\n def __init__(self, n_classes, sizes, psp_size, backend,pretrained):\n super().__init__()\n self.feats = backend\n self.psp = PSPModule(psp_size, 1024, sizes)\n self.drop_1 = nn.Dropout2d(p=0.3)\n\n self.up_1 = PSPUpsample(1024, 256)\n self.up_2 = PSPUpsample(256, 64)\n self.up_3 = PSPUpsample(64, 64)\n\n self.drop_2 = nn.Dropout2d(p=0.15)\n self.final = nn.Sequential(\n nn.Conv2d(64, n_classes, kernel_size=1),\n )\n\n def forward(self, x, training, device, gt_fore, use_gt_fore):\n\n f = self.feats\n p = self.psp(f)\n p = self.drop_1(p)\n\n p = self.up_1(p)\n p = self.drop_2(p)\n\n p = self.up_2(p)\n p = self.drop_2(p)\n\n p = self.up_3(p)\n p = self.drop_2(p)\n\n return self.final(p)\n\nclass Upsample(nn.Module):\n def __init__(self, in_channels, out_channels):\n super().__init__()\n self.conv = nn.Sequential(\n nn.Conv2d(in_channels, out_channels, 3, padding=1),\n nn.BatchNorm2d(out_channels),\n nn.PReLU()\n )\n\n def forward(self, x):\n h, w = 2 * x.size(2), 2 * x.size(3)\n p = F.interpolate(input=x, size=(h, w), mode='bilinear', align_corners=False)\n return self.conv(p)\n\n\ndef load_weights_sequential(target, source_state):\n model_to_load= {k: v for k, v in source_state.items() if k in target.state_dict().keys()}\n target.load_state_dict(model_to_load, strict=False)\n\n\ndef conv3x3(in_planes, out_planes, stride=1, dilation=1):\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=dilation, dilation=dilation, bias=False)\n\n\nclass DANet(BaseNet):\n r\"\"\"Fully Convolutional Networks for Semantic Segmentation\n\n Parameters\n ----------\n nclass : int\n Number of categories for the training dataset.\n backbone : string\n Pre-trained dilated backbone network type (default:'resnet50'; 'resnet50',\n 'resnet101' or 'resnet152').\n norm_layer : object\n Normalization layer used in backbone network (default: :class:`mxnet.gluon.nn.BatchNorm`;\n\n\n Reference:\n\n Long, Jonathan, Evan Shelhamer, and Trevor Darrell. \"Fully convolutional networks\n for semantic segmentation.\" *CVPR*, 2015\n\n \"\"\"\n def __init__(self, nclass, backbone, aux=False, se_loss=False, norm_layer=nn.BatchNorm2d, **kwargs):\n super(DANet, self).__init__(nclass, backbone, aux, se_loss, norm_layer=norm_layer, **kwargs)\n #print(str(10))\n inter_channels=512\n self.head = DANetHead(2048, nclass, norm_layer)\n self.conv511 = nn.Sequential(nn.Conv2d(inter_channels, inter_channels, 3, padding=1, bias=False),\n norm_layer(inter_channels),\n nn.ReLU())\n\n\n #self.conv6 = nn.Sequential(nn.Dropout2d(0.1, False), nn.Conv2d(inter_channels, out_channels, 1))\n #self.conv10 = nn.Sequential(nn.Dropout2d(0.1, False), nn.Conv2d(512, 2, 1))\n\n self.convforeout = nn.Sequential(\n #nn.Conv2d(1024, 512, 3, padding=1, bias=False),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n nn.Conv2d(512, 512, 3, padding=1, bias=False),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n Upsample(512, 256),\n Upsample(256, 128),\n nn.Conv2d(128, 1, 1, bias=False)\n )\n\n self.convforeout2 = nn.Sequential(\n #nn.Conv2d(64, 512, 3, padding=1, bias=False),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n nn.Conv2d(512, 512, 3, padding=1, bias=False),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n Upsample(512, 256),\n Upsample(256, 128),\n nn.Conv2d(128, 1, 1, bias=False)\n )\n self.convforeout3 = nn.Sequential(\n #nn.Conv2d(64, 512, 3, padding=1, bias=False),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n nn.Conv2d(512, 512, 3, padding=1, bias=False),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n Upsample(512, 256),\n Upsample(256, 128),\n nn.Conv2d(128, 1, 1, bias=False)\n )\n\n\n def forward(self, x):\n #print(str(0))\n imsize = x.size()[2:]\n _, _, c3, c4 = self.base_forward(x)\n #print(str(100))\n x = self.head(c4)\n x = list(x)\n\n #x[0] = upsample(x[0], imsize, **self._up_kwargs)\n x[0]=self.conv511(x[0])\n x[1] = upsample(x[1], imsize, **self._up_kwargs)\n x[2] = upsample(x[2], imsize, **self._up_kwargs)\n x[3] = upsample(x[3], imsize, **self._up_kwargs)\n #2.maxpooling as inpainting\n final_featuremap,x_fore_augment=MaxpoolingAsInpainting(x[0],[x[1],x[2],x[3]])\n\n\n\n\n x1 = final_featuremap * (F.interpolate(x_fore_augment.float(), size=x[0].size()[2:4]) > 0.5).float() +\\\n x[0] * (F.interpolate(x_fore_augment.float(), size=x[0].size()[2:4]) < 0.5).float()\n\n #=output=self.conv10(x1)\n\n x_fore_pred = self.convforeout(x1+x[0])\n x_fore_pred = torch.sigmoid(x_fore_pred)\n output = F.interpolate(x_fore_pred, scale_factor=2)\n\n #output = upsample(output, imsize, **self._up_kwargs)\n\n outputs = [output]\n outputs.append(x[1])\n outputs.append(x[2])\n outputs.append(x[3])\n outputs.append(F.interpolate(torch.sigmoid(self.convforeout2(x[0])),scale_factor=2))\n outputs.append(F.interpolate(torch.sigmoid(self.convforeout3(x1)),scale_factor=2))\n #print(\"output length is:\"+str(len(outputs))+\"\\n\")\n return tuple(outputs)\n\nclass DANetHead(nn.Module):\n def __init__(self, in_channels, out_channels, norm_layer):\n super(DANetHead, self).__init__()\n inter_channels = in_channels // 4\n self.conv5a = nn.Sequential(nn.Conv2d(in_channels, inter_channels, 3, padding=1, bias=False),\n norm_layer(inter_channels),\n nn.ReLU())\n\n self.conv5c = nn.Sequential(nn.Conv2d(in_channels, inter_channels, 3, padding=1, bias=False),\n norm_layer(inter_channels),\n nn.ReLU())\n\n self.sa = PAM_Module(inter_channels)\n\n self.sc = CAM_Module(inter_channels)\n self.conv51 = nn.Sequential(nn.Conv2d(inter_channels, inter_channels, 3, padding=1, bias=False),\n norm_layer(inter_channels),\n nn.ReLU())\n self.conv52 = nn.Sequential(nn.Conv2d(inter_channels, inter_channels, 3, padding=1, bias=False),\n norm_layer(inter_channels),\n nn.ReLU())\n\n self.conv6 = nn.Sequential(nn.Dropout2d(0.1, False), nn.Conv2d(inter_channels, out_channels, 1))\n self.conv7 = nn.Sequential(nn.Dropout2d(0.1, False), nn.Conv2d(inter_channels, out_channels, 1))\n\n self.conv8 = nn.Sequential(nn.Dropout2d(0.1, False), nn.Conv2d(inter_channels, out_channels, 1))\n self.conv9 = nn.Sequential(nn.Dropout2d(0.1, False), nn.Conv2d(inter_channels, 2, 1))\n\n #self.layer3 = self._make_layer(block, 256, layers[2], stride=1, dilation=2)\n #self.layer4 = self._make_layer(block, 512, layers[3], stride=1, dilation=4)\n\n\n def _make_layer(self, block, planes, blocks, stride=1, dilation=1):\n downsample = None\n\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = [block(self.inplanes, planes, stride, downsample)]\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes, dilation=dilation))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n #print(str(2))\n feat1 = self.conv5a(x)\n\n\n\n #the foreground branch\n sa_feat = self.sa(feat1)\n sa_conv = self.conv51(sa_feat)\n sa_output = self.conv6(sa_conv)\n\n feat2 = self.conv5c(x)\n sc_feat = self.sc(feat2)\n sc_conv = self.conv52(sc_feat)\n sc_output = self.conv7(sc_conv)\n\n feat_sum = sa_conv+sc_conv\n\n sasc_output = self.conv8(feat_sum)\n #print(str(3))\n #the road branch\n #1. intermediate feature map extraction\n sa_feat2=self.sa(feat1)\n #print(str(1))\n\n #x_3 = self.layer3(x)\n #x = self.layer4(x_3)\n #final=PSPNet(x,, psp_size=1024, pretrained=False, n_classes=3)\n #use pspnet maybe?\n return (sa_feat2, sasc_output, sa_output, sc_output)\n\ndef get_danet(dataset='pascal_voc', backbone='resnet50', pretrained=False,\n root='~/.encoding/models', **kwargs):\n r\"\"\"DANet model from the paper `\"Dual Attention Network for Scene Segmentation\"\n `\n \"\"\"\n acronyms = {\n 'pascal_voc': 'voc',\n 'pascal_aug': 'voc',\n 'pcontext': 'pcontext',\n 'ade20k': 'ade',\n 'cityscapes': 'cityscapes',\n }\n # infer number of classes\n from ...datasets import datasets, VOCSegmentation, VOCAugSegmentation, ADE20KSegmentation\n model = DANet(20, backbone=backbone, root=root, **kwargs)\n if pretrained:\n from .model_store import get_model_file\n model.load_state_dict(torch.load(\n get_model_file('fcn_%s_%s'%(backbone, acronyms[dataset]), root=root)),\n strict=False)\n return model\n", "meta": {"hexsha": "45ac5d337c855c4bd5c44d856e0a604cc5744b98", "size": 13553, "ext": "py", "lang": "Python", "max_stars_repo_path": "experiments/segmentation/encoding/models/sseg/danet.py", "max_stars_repo_name": "coolgrasshopper/amodal_road_segmentation", "max_stars_repo_head_hexsha": "462209242973815055f085ada99772af32082f5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-03T02:05:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-03T02:05:41.000Z", "max_issues_repo_path": "experiments/segmentation/encoding/models/sseg/danet.py", "max_issues_repo_name": "coolgrasshopper/amodal_road_segmentation", "max_issues_repo_head_hexsha": "462209242973815055f085ada99772af32082f5c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "experiments/segmentation/encoding/models/sseg/danet.py", "max_forks_repo_name": "coolgrasshopper/amodal_road_segmentation", "max_forks_repo_head_hexsha": "462209242973815055f085ada99772af32082f5c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2335164835, "max_line_length": 174, "alphanum_fraction": 0.6051058806, "include": true, "reason": "import numpy", "num_tokens": 3715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.25386100132422423, "lm_q1q2_score": 0.13485334720556091}} {"text": "import numpy\nimport simtk.unit\nimport simtk.openmm as mm\n\nprint('OpenMM version: ', mm.version.full_version)\nfrom openmmtools.constants import kB\n\n\nclass CustomizableGHMC(mm.CustomIntegrator):\n \"\"\"Customizable GHMC: proposal can contain mix of deterministic and stochastic steps.\n If the provided `splitting` is deterministic, then we add the stochastic velocity update to the beginning of the splitting.\n\n The class of allowable splittings is the same as for the LangevinSplittingIntegrator\n \"\"\"\n\n def __init__(self,\n splitting=\"V R V\",\n temperature=298.0 * simtk.unit.kelvin,\n collision_rate=91.0 / simtk.unit.picoseconds,\n timestep=1.0 * simtk.unit.femtoseconds,\n constraint_tolerance=1e-4,\n ):\n \"\"\"\n Parameters\n ----------\n splitting : string\n Sequence of R, V substeps to be executed each timestep.\n Forces are only used in V-step. Handle multiple force groups by appending the force group index\n to V-steps, e.g. \"V0\" will only use forces from force group 0. \"V\" will perform a step using all forces.\n\n temperature : numpy.unit.Quantity compatible with kelvin, default: 298.0*simtk.unit.kelvin\n Temperature of heat bath\n\n collision_rate : numpy.unit.Quantity compatible with 1/picoseconds, default: 91.0/simtk.unit.picoseconds\n Collision rate\n\n timestep : numpy.unit.Quantity compatible with femtoseconds, default: 1.0*simtk.unit.femtoseconds\n Integration timestep\n\n constraint_tolerance : float\n Numerical tolerance for solving constraints\n \"\"\"\n\n # Compute constants\n kT = kB * temperature\n gamma = collision_rate\n kinetic_energy = \"0.5 * m * v * v\"\n\n # Convert splitting string into a list of all-caps strings\n splitting = splitting.upper().split()\n\n # Count how many times each step appears, so we know how big each R/V/O substep will be\n n_R = sum([letter == \"R\" for letter in splitting])\n n_V = sum([letter == \"V\" for letter in splitting])\n n_O = sum([letter == \"O\" for letter in splitting])\n\n # If the splitting is deterministic, add a velocity-randomization step to the beginning\n # of the procedure\n if n_O == 0:\n splitting = [\"O\"] + splitting\n\n # Check if the splitting string asks for multi-time-stepping.\n # If so, each force group should be integrated for a total length equal to dt\n if len(set([step for step in splitting if step[0] == \"V\"])) > 1:\n mts = True\n fgs = set([step[1:] for step in splitting if step[0] == \"V\"])\n n_Vs = dict()\n for fg in fgs:\n n_Vs[fg] = sum([step[1:] == fg for step in splitting])\n else:\n mts = False\n\n # Do a couple sanity checks on the splitting string\n # Make sure we contain at least one of R, V, O steps\n assert (\"R\" in splitting)\n assert (\"V\" in [s[0] for s in splitting])\n assert (\"O\" in splitting)\n\n # Make sure it contains no invalid characters\n assert (set(splitting).issubset(set(\"RVO\").union(set([\"V{}\".format(i) for i in range(32)]))))\n\n # If the splitting string contains both \"V\" and a force-group-specific V0,V1,etc.,\n # then raise an error\n if mts and (n_V > 0):\n raise (ValueError(\"Splitting string includes an evaluation of all forces and \"\n \"evaluation of subsets of forces.\"))\n\n # Define substep functions\n def R_step():\n # update positions (and velocities, if there are constraints)\n self.addComputePerDof(\"x\", \"x + ((dt / {}) * v)\".format(n_R))\n self.addComputePerDof(\"x1\", \"x\") # save pre-constraint positions in x1\n self.addConstrainPositions() # x is now constrained\n self.addComputePerDof(\"v\", \"v + ((x - x1) / (dt / {}))\".format(n_R))\n self.addConstrainVelocities()\n\n def V_step(fg):\n \"\"\"Deterministic velocity update, using only forces from force-group fg.\n Parameters\n ----------\n fg : string\n Force group to use in this substep.\n \"\" means all forces, \"0\" means force-group 0, etc.\n \"\"\"\n # update velocities\n if mts:\n self.addComputePerDof(\"v\", \"v + ((dt / {}) * f{} / m)\".format(n_Vs[fg], fg))\n else:\n self.addComputePerDof(\"v\", \"v + (dt / {}) * f / m\".format(n_V))\n self.addConstrainVelocities()\n\n def O_step():\n # measure heat\n self.addComputeSum(\"old_ke\", kinetic_energy)\n\n # update velocities\n self.addComputePerDof(\"v\", \"(a * v) + (b * sqrt(kT / m) * gaussian)\")\n self.addConstrainVelocities()\n\n # measure heat\n self.addComputeSum(\"new_ke\", kinetic_energy)\n self.addComputeGlobal(\"heat\", \"heat + (new_ke - old_ke)\")\n\n def substep_function(step_string):\n if step_string == \"R\":\n R_step()\n elif step_string[0] == \"V\":\n V_step(step_string[1:])\n\n def compute_total_energy(name=\"e_old\"):\n self.addComputeSum(\"ke\", kinetic_energy)\n self.addComputeGlobal(name, \"ke + energy\")\n\n # Create a new CustomIntegrator\n super(CustomizableGHMC, self).__init__(timestep)\n\n # Initialize\n self.addGlobalVariable(\"kT\", kT)\n\n # Velocity mixing parameter: current velocity component\n h = timestep\n self.addGlobalVariable(\"a\", numpy.exp(-gamma * h))\n\n # Velocity mixing parameter: random velocity component\n self.addGlobalVariable(\"b\", numpy.sqrt(1 - numpy.exp(- 2 * gamma * h)))\n\n # Positions before application of position constraints\n self.addPerDofVariable(\"x1\", 0)\n\n # Set constraint tolerance\n self.setConstraintTolerance(constraint_tolerance)\n\n # Add bookkeeping variables\n self.addGlobalVariable(\"ke_old\", 0)\n self.addGlobalVariable(\"ke_new\", 0)\n self.addGlobalVariable(\"heat\", 0)\n self.addGlobalVariable(\"shadow_work\", 0)\n self.addGlobalVariable(\"e_old\", 0)\n self.addGlobalVariable(\"e_new\", 0)\n self.addGlobalVariable(\"acc_ratio\", 0)\n self.addGlobalVariable(\"accept\", 0)\n self.addGlobalVariable(\"naccept\", 0)\n self.addGlobalVariable(\"ntrials\", 0)\n self.addPerDofVariable(\"xold\", 0)\n self.addPerDofVariable(\"vold\", 0)\n\n # Compute energy of current state\n self.addUpdateContextState()\n self.addComputePerDof(\"xold\", \"x\")\n self.addComputePerDof(\"vold\", \"v\")\n compute_total_energy(\"e_old\")\n\n # Reset \"heat\" to zero\n self.addComputeGlobal(\"heat\", \"0\")\n\n # Integrate / generate proposal\n for i, step in enumerate(splitting):\n substep_function(step)\n\n # Compute M-H ratio in terms of energy change during the deterministic steps\n compute_total_energy(\"e_new\")\n self.addComputeGlobal(\"shadow_work\", \"(e_new - e_old) - heat\")\n self.addComputeGlobal(\"acc_ratio\", \"exp(- shadow_work / kT)\")\n\n # Accept / reject : flip momenta upon rejection\n self.addComputeGlobal(\"accept\", \"step(acc_ratio - uniform)\")\n self.beginIfBlock(\"accept != 1\")\n self.addComputePerDof(\"x\", \"xold\")\n self.addComputePerDof(\"v\", \"-vold\")\n self.endBlock()\n\n # Update acceptance statistics\n self.addComputeGlobal(\"naccept\", \"naccept + accept\")\n self.addComputeGlobal(\"ntrials\", \"ntrials + 1\")\n", "meta": {"hexsha": "d7350c839cd9b4797346df98ca458e3439f27707", "size": 7757, "ext": "py", "lang": "Python", "max_stars_repo_path": "benchmark/integrators/ghmc.py", "max_stars_repo_name": "choderalab/integrator-benchmark", "max_stars_repo_head_hexsha": "bb307e6ebf476b652e62e41ae49730f530732da3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-02-22T09:08:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T21:21:35.000Z", "max_issues_repo_path": "benchmark/integrators/ghmc.py", "max_issues_repo_name": "choderalab/integrator-benchmark", "max_issues_repo_head_hexsha": "bb307e6ebf476b652e62e41ae49730f530732da3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2017-04-15T21:34:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-22T13:56:40.000Z", "max_forks_repo_path": "benchmark/integrators/ghmc.py", "max_forks_repo_name": "choderalab/integrator-benchmark", "max_forks_repo_head_hexsha": "bb307e6ebf476b652e62e41ae49730f530732da3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-12-06T05:43:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-01T01:00:24.000Z", "avg_line_length": 39.7794871795, "max_line_length": 127, "alphanum_fraction": 0.5995874694, "include": true, "reason": "import numpy", "num_tokens": 1835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.24798742068237772, "lm_q1q2_score": 0.1346232690452604}} {"text": "from __future__ import division, print_function, absolute_import\nimport numpy as np\nimport pandas as pd\nimport os\nfrom copy import copy\n\ndatabasepath = os.path.join(os.path.dirname(__file__), 'database')\ndatabasepath += '/saftgamma_database.xlsx'\n\nfile = pd.ExcelFile(databasepath, engine='openpyxl')\ndf_groups = pd.read_excel(file, 'groups', index_col='groups')\ndf_mie_kl = pd.read_excel(file, 'unlikemie_kl')\ndf_asso_kl = pd.read_excel(file, 'unlikeasso_kl')\ndf_secondorder = pd.read_excel(file, 'secondmie')\ndf_secondasso = pd.read_excel(file, 'secondasso')\n\n\nclass GCdatabase(object):\n '''\n SAFT-Gamma-Mie group contribution database Object\n\n This object have implemeted methods to modify the database published\n groups and interactions parameters for SAFT-Gamma-Mie EoS.\n\n The included parameters are obtained from J. Chem. Eng. Data 2020,\n 65, 12, 5862–5890. https://doi.org/10.1021/acs.jced.0c00746\n\n Parameters\n ----------\n df_groups: DataFrame\n DataFrame that includes group information\n df_mie_kl: DataFrame\n DataFrame that includes unlike Mie parameters\n df_asso_kl: DataFrame\n DataFrame that includes unlike association Parameters\n df_secondorder: DataFrame\n Dataframe that includes second order modification to Mie interactions\n df_scondasso: DataFrame\n Dataframe that includes second order modification to association\n interactions\n\n Attributes\n ----------\n group_list: List of groups on the database\n df_groups: DataFrame that includes group information\n df_mie_kl: DataFrame that includes unlike Mie parameters\n df_asso_kl: DataFrame that includes unlike association Parameters\n df_secondorder: Dataframe that includes second order modification\n to Mie interactions\n df_scondasso: Dataframe that includes second order modification to\n association interactions\n\n Methods\n -------\n add_group: method to add a new group\n new_interaction_mie: method to set unlike Mie interactions\n new_interaction_asso: method to add association parameters\n get_interactions: method to get the interactions between two groups\n restore_database: method to restore the database to its initial value\n '''\n def __init__(self, df_groups=df_groups, df_mie_kl=df_mie_kl,\n df_asso_kl=df_asso_kl, df_secondorder=df_secondorder,\n df_secondasso=df_secondasso):\n\n self.df_groups = df_groups\n self.df_mie_kl = df_mie_kl\n self.df_asso_kl = df_asso_kl\n self.df_secondorder = df_secondorder\n self.df_secondasso = df_secondasso\n\n self.df_groups_backup = copy(df_groups)\n self.df_mie_kl_backup = copy(df_mie_kl)\n self.df_asso_kl_backup = copy(df_asso_kl)\n self.df_secondorder_backup = copy(df_secondorder)\n self.df_secondasso_backup = copy(df_secondasso)\n\n self.group_list = list(self.df_groups.index)\n\n def add_group(self, name, vk=1., Sk=1., sigma=0., eps=0., lr=12., la=6.,\n nH=0, ne1=0, ne2=0, charge=0., sigma_born=0., mw=0.,\n overwrite=False):\n \"\"\"\n add_group method\n\n Method that adds a new group to the database\n\n Parameters\n ----------\n name: string\n name of the group\n vk: float\n number os sites used by the group\n Sk: float\n shape factor of the group\n sigma: float\n lenght scale of the group, used in Mie potential [Amstrong]\n eps: float\n energy scale of the group, used in Mie potential [K]\n lr: float\n repulsive exponent of the group, used in Mie potential\n la: float\n attractive exponent of the group, used in Mie potential\n nH: int\n number of Hidrogen associative sites\n ne1: int\n number of e1 associative sites\n ne2: int\n number of e2 associative sites\n charge: int\n charge of the group (electron charge) [Adim.]\n sigma_born: float\n diameter used in Born contribution [Amstrong]\n mw: float\n molar weight of the group [g/mol]\n overwrite: bool, optional\n whether to overwrite or not current parameters of the database\n \"\"\"\n Nst = np.count_nonzero([nH, ne1, ne2])\n group_included = name in self.group_list\n\n if group_included and not overwrite:\n raise Exception('group {} already included in database, set'.format(name) +\n ' overwrite=True to overwrite the current parameters')\n elif group_included and overwrite:\n new_parameters = np.array([vk, Sk, sigma, eps, lr, la, Nst, nH,\n ne1, ne2, charge, sigma_born, mw])\n self.df_groups.loc[name] = new_parameters\n else:\n new_group = {'groups': name, 'vk*': vk, 'Sk': Sk,\n 'sigma_kk': sigma, 'eps_kk': eps,\n 'lr_kk': lr, 'la_kk': la, 'Nst_kk': Nst, 'nH_kk': nH,\n 'ne1_kk': ne1, 'ne2_kk': ne2, 'charge_kk': charge,\n 'sigma_born_kk': sigma_born, 'mw_kk': mw}\n groups_aux = self.df_groups.reset_index()\n groups_new = groups_aux.append(new_group, ignore_index=True)\n groups_new.set_index('groups', inplace=True)\n self.df_groups = groups_new\n self.group_list = list(self.df_groups.index)\n\n def new_interaction_mie(self, group_k, group_l, eps_kl=0., lr_kl='CR',\n overwrite=False):\n \"\"\"\n new_interaction_mie method\n\n Method that adds the unlike mie interactions between group k and\n group l\n\n Parameters\n ----------\n group_k: string\n name of the group k\n group_l: string\n name of the group l\n eps_kl: float\n unlike energy scale between the groups, used in Mie potential [K]\n lr_kl: float\n unlike repulsive exponent between the groups, used in Mie potential\n overwrite: bool, optional\n whether to overwrite or not current parameters of the database\n \"\"\"\n bool_kk = self.df_mie_kl.group_k == group_k\n bool_ll = self.df_mie_kl.group_l == group_l\n bool_kl = self.df_mie_kl.group_k == group_l\n bool_lk = self.df_mie_kl.group_l == group_k\n\n index1 = self.df_mie_kl.index[bool_kk & bool_ll]\n len1 = index1.shape[0]\n\n index2 = self.df_mie_kl.index[bool_kl & bool_lk]\n len2 = index2.shape[0]\n\n if len1 == 1:\n index = index1\n n = len1\n elif len2 == 1:\n index = index2\n n = len2\n else:\n n = 0\n already_in = n > 0\n if already_in and not overwrite:\n raise Exception('Interaction parameters between group {} '.format(group_k) +\n ' and group {}'.format(group_l) + ' are already in the database' +\n ' set overwrite=True to overwrite the current parameters')\n\n elif already_in and overwrite:\n self.df_mie_kl.iloc[index, [2, 3]] = [eps_kl, lr_kl]\n else:\n new_interaction = {'group_k': group_k, 'group_l': group_l,\n 'eps_kl': eps_kl, 'lr_kl': lr_kl}\n df_mie_new = self.df_mie_kl.append(new_interaction, ignore_index=True)\n self.df_mie_kl = df_mie_new\n\n def new_interaction_asso(self, group_k, group_l, site_k, site_l,\n epsAB_kl=0., kAB_kl=0, overwrite=False):\n \"\"\"\n new_interaction_mie method\n\n Method that adds the unlike mie interactions between group k and\n group l\n\n Parameters\n ----------\n group_k: string\n name of the group k\n group_l: string\n name of the group l\n site_k: string\n name of the site k, available optiones are 'H', 'e1' and 'e2'\n site_l: string\n name of the site l, available optiones are 'H', 'e1' and 'e2'\n epsAB_kl: float\n unlike association energy between the the groups [K]\n kAB_kl: float\n unlike association volume between the groups [Amstrong^3]\n overwrite: bool, optional\n whether to overwrite or not current parameters of the database\n \"\"\"\n bool_kk = self.df_asso_kl.group_k == group_k\n bool_ll = self.df_asso_kl.group_l == group_l\n bool_kl = self.df_asso_kl.group_k == group_l\n bool_lk = self.df_asso_kl.group_l == group_k\n boolsite_kk = self.df_asso_kl.iloc[:, 1] == site_k\n boolsite_ll = self.df_asso_kl.iloc[:, 3] == site_l\n\n index1 = self.df_asso_kl.index[bool_kk & bool_ll & boolsite_kk & boolsite_ll]\n len1 = index1.shape[0]\n\n index2 = self.df_asso_kl.index[bool_kl & bool_lk & boolsite_kk & boolsite_ll]\n len2 = index2.shape[0]\n\n if len1 == 1:\n index = index1\n n = len1\n elif len2 == 1:\n index = index2\n n = len2\n else:\n n = 0\n\n already_in = n > 0\n if already_in and not overwrite:\n raise Exception('Interaction parameters between site{} of'.format(site_k) +\n ' of group {} '.format(group_k) + 'and site {}'.format(site_l) +\n ' of group {}'.format(group_l) + 'are already in the database' +\n ' set overwrite=True to overwrite the current parameters')\n\n elif already_in and overwrite:\n self.df_asso_kl.iloc[index, [4, 5]] = [epsAB_kl, kAB_kl]\n else:\n new_interaction = {'group_k': group_k,\n 'site\\xa0a\\xa0of group\\xa0k': site_k,\n 'group_l': group_l,\n 'site\\xa0b\\xa0of group\\xa0l': site_l,\n 'epsAB_kl': epsAB_kl, 'KAB_kl': kAB_kl}\n df_asso_new = self.df_asso_kl.append(new_interaction, ignore_index=True)\n self.df_asso_kl = df_asso_new\n\n def get_interactions(self, group_k, group_l):\n \"\"\"\n get_interactions method\n\n Method that outputs the available interactions between group k and\n group l\n\n Parameters\n ----------\n group_k: string\n name of the group k\n group_l: string\n name of the group l\n\n Returns\n -------\n df_group : DataFrame\n parameters of each group\n df_mie : DataFrame\n unlike Mie Parameters\n df_asso : DataFrame\n unlike association parameters\n \"\"\"\n df_group = self.df_groups.loc[[group_l, group_k]]\n\n bool_kk = self.df_mie_kl.group_k == group_k\n bool_ll = self.df_mie_kl.group_l == group_l\n bool_kl = self.df_mie_kl.group_k == group_l\n bool_lk = self.df_mie_kl.group_l == group_k\n\n df1 = self.df_mie_kl[bool_kk & bool_ll]\n len1 = df1.shape[0]\n\n df2 = self.df_mie_kl[bool_kl & bool_lk]\n len2 = df2.shape[0]\n\n if len1 == 1:\n df_mie = df1\n elif len2 == 1:\n df_mie = df2\n else:\n df_mie = 'There are no custom interaction parameters set for group {}'.format(group_k)\n df_mie += 'and group {}'.format(group_l)\n\n bool_kk = self.df_asso_kl.group_k == group_k\n bool_ll = self.df_asso_kl.group_l == group_l\n bool_kl = self.df_asso_kl.group_k == group_l\n bool_lk = self.df_asso_kl.group_l == group_k\n\n df1 = self.df_asso_kl[bool_kk & bool_ll]\n len1 = df1.shape[0]\n\n df2 = self.df_asso_kl[bool_kl & bool_lk]\n len2 = df2.shape[0]\n\n if len1 >= 1:\n df_asso = df1\n elif len2 >= 1:\n df_asso = df2\n else:\n df_asso = 'There are no association parameters set for group {}'.format(group_k)\n df_asso += ' and group {}'.format(group_l)\n\n return df_group, df_mie, df_asso\n\n def restore_database(self):\n \"\"\"\n restore_database method\n\n Method that restores the database of its initial state.\n This method will erase any custom groups or interactions\n set up by the user.\n \"\"\"\n self.df_groups = copy(self.df_groups_backup)\n self.df_mie_kl = copy(self.df_mie_kl_backup)\n self.df_asso_kl = copy(self.df_asso_kl_backup)\n self.df_secondorder = copy(self.df_secondorder_backup)\n self.df_secondasso = copy(self.df_secondasso_backup)\n\n self.group_list = list(self.df_groups.index)\n\n\ndatabase = GCdatabase()\n", "meta": {"hexsha": "7087064d02d82685e860d05f502049bb68a3d175", "size": 12708, "ext": "py", "lang": "Python", "max_stars_repo_path": "sgtpy/database.py", "max_stars_repo_name": "MatKie/SGTPy", "max_stars_repo_head_hexsha": "8e98d92fedd2b07d834e547e5154ec8f70d80728", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2020-12-27T17:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-19T06:28:28.000Z", "max_issues_repo_path": "sgtpy/database.py", "max_issues_repo_name": "MatKie/SGTPy", "max_issues_repo_head_hexsha": "8e98d92fedd2b07d834e547e5154ec8f70d80728", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-05-15T14:27:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-19T15:42:24.000Z", "max_forks_repo_path": "sgtpy/database.py", "max_forks_repo_name": "MatKie/SGTPy", "max_forks_repo_head_hexsha": "8e98d92fedd2b07d834e547e5154ec8f70d80728", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-02-21T01:33:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T15:11:08.000Z", "avg_line_length": 37.1578947368, "max_line_length": 98, "alphanum_fraction": 0.6011174064, "include": true, "reason": "import numpy", "num_tokens": 3131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.26284183737131667, "lm_q1q2_score": 0.13450053259385455}} {"text": "#!/usr/bin/env python\n#\n# Author: Qiming Sun \n#\n\nimport time\nimport ctypes\nimport tempfile\nimport numpy\nimport h5py\nimport pyscf.lib as lib\nfrom pyscf.lib import logger\nimport pyscf.ao2mo\nfrom pyscf.cc import _ccsd\n\n# t2,l2 as ijab\n\ndef kernel(mycc, eris, t1=None, t2=None, l1=None, l2=None,\n max_cycle=50, tol=1e-8, verbose=logger.INFO):\n cput0 = (time.clock(), time.time())\n if isinstance(verbose, logger.Logger):\n log = verbose\n else:\n log = logger.Logger(mycc.stdout, verbose)\n\n if t1 is None: t1 = mycc.t1\n if t2 is None: t2 = mycc.t2\n if l1 is None: l1 = t1\n if l2 is None: l2 = t2\n\n nocc, nvir = t1.shape\n saved = make_intermediates(mycc, t1, t2, eris)\n\n if mycc.diis:\n adiis = lib.diis.DIIS(mycc, mycc.diis_file)\n adiis.space = mycc.diis_space\n else:\n adiis = lambda t1,t2,*args: (t1, t2)\n cput0 = log.timer('CCSD lambda initialization', *cput0)\n\n conv = False\n for istep in range(max_cycle):\n l1new, l2new = update_amps(mycc, t1, t2, l1, l2, eris, saved)\n normt = numpy.linalg.norm(l1new-l1) + numpy.linalg.norm(l2new-l2)\n l1, l2 = l1new, l2new\n l1new = l2new = None\n if mycc.diis:\n l1, l2 = mycc.diis(l1, l2, istep, normt, 0, adiis)\n log.info('cycle = %d norm(lambda1,lambda2) = %.6g', istep+1, normt)\n cput0 = log.timer('CCSD iter', *cput0)\n if normt < tol:\n conv = True\n break\n return conv, l1, l2\n\n\n# l2, t2 as ijab\ndef make_intermediates(mycc, t1, t2, eris):\n log = logger.Logger(mycc.stdout, mycc.verbose)\n nocc, nvir = t1.shape\n nov = nocc * nvir\n foo = eris.fock[:nocc,:nocc]\n fov = eris.fock[:nocc,nocc:]\n fvv = eris.fock[nocc:,nocc:]\n\n class _Saved(object):\n pass\n saved = _Saved()\n\n# As we don't have l2 in memory, hold tau temporarily in memory\n w1 = fvv - numpy.einsum('ja,jb->ba', fov, t1)\n w2 = foo + numpy.einsum('ib,jb->ij', fov, t1)\n w3 = _cp(numpy.einsum('kc,jkbc->bj', fov, t2) * 2 + fov.T)\n w3 -= numpy.einsum('kc,kjbc->bj', fov, t2)\n w3 += reduce(numpy.dot, (t1.T, fov, t1.T))\n w4 = fov.copy()\n\n eris_ovvv = _cp(eris.ovvv)\n eris_ovvv = lib.unpack_tril(eris_ovvv.reshape(nov,-1))\n eris_ovvv = eris_ovvv.reshape(nocc,nvir,nvir,nvir)\n\n wovvv = numpy.empty((nocc,nvir,nvir,nvir))\n t2tmp = numpy.empty((nocc,nvir,nocc,nvir))\n for i in range(nocc):\n wovvv[i] = eris_ovvv[i].transpose(1,0,2) * 2\n t2tmp[i] = t2[i].transpose(2,0,1)\n #:wovvv += numpy.einsum('jabd,kjdc->kabc', eris_ovvv, t2) * -1.5\n tmp = lib.dot(t2tmp.reshape(nov,-1), wovvv.reshape(-1,nvir**2),\n -1.5/2).reshape(-1,nvir,nvir,nvir)\n g2ovvv = tmp\n for i in range(nocc):\n wovvv[i] -= eris_ovvv[i].transpose(1,2,0)\n wovvv[i] += tmp[i].transpose(1,2,0)\n g2ovvv[i] = eris_ovvv[i]*2\n g2ovvv[i] -= eris_ovvv[i].transpose(1,2,0)\n tmp = t2tmp = None\n\n w1 += numpy.einsum('jcba,jc->ba', eris_ovvv, t1*2)\n w1 -= numpy.einsum('jabc,jc->ba', eris_ovvv, t1)\n #:w3 += numpy.einsum('kdcb,kjdc->bj', eris_ovvv, theta)\n theta = numpy.empty(t2.shape)\n for i in range(nocc):\n theta[i] = t2[i] * 2\n theta[i] -= t2[i].transpose(0,2,1)\n lib.dot(eris_ovvv[i].reshape(-1,nvir).T,\n _cp(theta[i].reshape(nocc,-1)).T, 1, w3, 1)\n\n theta = _cp(theta.transpose(0,2,1,3))\n #:vkbca = numpy.einsum('jdca,kbjd->kbca', g2ovvv, theta)\n vkbca = lib.dot(_cp(theta.reshape(nov,-1)),\n g2ovvv.reshape(-1,nvir*nvir)).reshape(-1,nvir,nvir,nvir)\n for i in range(nocc):\n wovvv[i] += vkbca[i].transpose(2,0,1)\n wovvv[i] -= vkbca[i].transpose(2,1,0) * .5\n vkabc = None\n\n #:wOVov = numpy.einsum('jbcd,kd->jbkc', eris_ovvv, t1)\n #:wOvOv = numpy.einsum('jdcb,kd->jbkc', eris_ovvv, -t1)\n wOVov = lib.dot(eris_ovvv.reshape(-1,nvir),\n t1.T).reshape(-1,nvir,nvir,nocc).transpose(0,1,3,2).copy()\n for i in range(nocc):\n g2ovvv[i] = eris_ovvv[i].transpose(1,2,0) * 2\n wOvOv = lib.dot(g2ovvv.reshape(-1,nvir),\n -t1.T, .5).reshape(-1,nvir,nvir,nocc).transpose(0,1,3,2).copy()\n for i in range(nocc):\n g2ovvv[i] -= eris_ovvv[i].transpose(1,0,2)\n eris_ovov = _cp(_cp(eris.ovov).transpose(0,2,1,3))\n tau = _ccsd.make_tau(t2, t1, t1)\n #:wooov[:,j0:j1] = numpy.einsum('icbd,jkbd->ijkc', g2ovvv, tau)\n #:woooo[:,:,j0:j1] = numpy.einsum('icjd,klcd->ijkl', eris_ovov, tau)\n tmp = lib.dot(g2ovvv.reshape(-1,nvir**2), tau.reshape(-1,nvir**2).T)\n wooov = _cp(tmp.reshape(-1,nvir,nocc,nocc).transpose(0,2,3,1))\n woooo = lib.dot(eris_ovov.reshape(-1,nvir**2),\n tau.reshape(-1,nvir**2).T).reshape(-1,nocc,nocc,nocc)\n eris_ovov = eris_ovvv = g2ovvv = tau = tmp = None\n\n eris_ooov = _cp(eris.ooov)\n eris_ovoo = _cp(eris.ovoo)\n #:woooo += numpy.einsum('icjl,kc->ijkl', eris_ovoo, t1)\n #:wOVov += numpy.einsum('jblk,lc->jbkc', eris_ovoo, -t1)\n for i in range(nocc):\n woooo[i] += lib.dot(t1, eris_ovoo[i].reshape(nvir,-1)).reshape((nocc,)*3).transpose(1,0,2)\n lib.dot(eris_ovoo.reshape(-1,nocc), t1, -1, wOVov.reshape(-1,nvir), 1)\n #:wooov -= numpy.einsum('ibjl,lkcb->ijkc', eris_ovoo*1.5, t2)\n t2tmp = numpy.empty((nocc,nvir,nocc,nvir))\n for i in range(nocc):\n t2tmp[i] = t2[i].transpose(2,0,1)\n tmp_ooov = _cp(-eris_ooov.transpose(2,0,1,3)).reshape(-1,nov)\n lib.dot(tmp_ooov, t2tmp.reshape(nov,-1), 1.5, wooov.reshape(-1,nov), 1)\n t2tmp = None\n\n g2ooov, tmp_ooov = tmp_ooov.reshape(nocc,nocc,nocc,nvir), None\n g2ooov += eris_ooov * 2\n #:vikjc = numpy.einsum('iklb,jlcb->ikjc', g2ooov, theta)\n vikjc = lib.dot(g2ooov.reshape(-1,nov), theta.reshape(-1,nov).T)\n vikjc = vikjc.reshape(nocc,nocc,nocc,nvir)\n wooov += vikjc.transpose(0,2,1,3)\n wooov -= vikjc*.5\n g2ooov = vikjc = eris_ovoo = None\n\n w2 += numpy.einsum('ijkb,kb->ij', eris_ooov, t1) * 2\n w2 -= numpy.einsum('kjib,kb->ij', eris_ooov, t1)\n #:w3 -= numpy.einsum('kjlc,klbc->bj', eris_ooov, theta)\n for i in range(nocc):\n lib.dot(_cp(theta[i].transpose(1,2,0)).reshape(-1,nvir).T,\n eris_ooov[i].reshape(nocc,-1).T, -1, w3, 1)\n #:woooo += numpy.einsum('ikjc,lc->ijkl', eris_ooov, t1)\n #:wOvOv += numpy.einsum('jklb,lc->jbkc', eris_ooov, t1)\n woooo += lib.dot(eris_ooov.reshape(-1,nvir),\n t1.T).reshape((-1,nocc,nocc,nocc)).transpose(0,2,1,3)\n for i in range(nocc):\n lib.dot(_cp(eris_ooov[i].transpose(2,0,1)).reshape(-1,nocc),\n t1, 1, wOvOv[i].reshape(-1,nvir), 1)\n wooov[i] += eris_ooov[i].transpose(1,0,2)*2\n wooov[i] -= eris_ooov[i]\n eris_ooov = theta = None\n\n eris_ovov = _cp(eris.ovov)\n g2ovov = numpy.empty((nocc,nocc,nvir,nvir))\n for i in range(nocc):\n g2ovov[i] = eris_ovov[i].transpose(1,0,2)*2\n g2ovov[i] -= eris_ovov[i].transpose(1,2,0)\n tmpw4 = numpy.einsum('klcd,ld->kc', g2ovov, t1)\n #:w1 -= numpy.einsum('kcja,kjcb->ba', g2ovov, t2)\n w1 -= lib.dot(t2.reshape(-1,nvir).T, g2ovov.reshape(-1,nvir))\n w1 -= numpy.einsum('ja,jb->ba', tmpw4, t1)\n #:w2 += numpy.einsum('ibkc,jkbc->ij', g2ovov, t2)\n w2 += lib.dot(g2ovov.reshape(nocc,-1), t2.reshape(nocc,-1).T)\n w2 += numpy.einsum('ib,jb->ij', tmpw4, t1)\n w3 += reduce(numpy.dot, (t1.T, tmpw4, t1.T))\n w4 += tmpw4\n vOVov = eris_ovov.copy()\n #:vOVov += numpy.einsum('jbld,klcd->jbkc', g2ovov, t2)\n #:vOVov -= numpy.einsum('jbld,kldc->jbkc', eris_ovov, t2)\n lib.dot(_cp(g2ovov.transpose(0,2,1,3)).reshape(-1,nov),\n _cp(t2.transpose(0,2,1,3).reshape(nov,-1).T), 1,\n vOVov.reshape(nov,-1), 1)\n lib.dot(eris_ovov.reshape(-1,nov),\n _cp(t2.transpose(0,3,1,2).reshape(nov,-1).T), -1,\n vOVov.reshape(nov,-1), 1)\n g2ovov = None\n\n #:tmp = numpy.einsum('jbld,kd->ljbk', eris_ovov, t1)\n #:wOVov -= numpy.einsum('ljbk,lc->jbkc', tmp, t1)\n #:tmp = numpy.einsum('jdlb,kd->ljbk', eris_ovov, t1)\n #:wOvOv += numpy.einsum('ljbk,lc->jbkc', tmp, t1)\n tmp = numpy.empty((nocc,nvir,nocc))\n for j in range(nocc):\n lib.dot(_cp(eris_ovov[j].transpose(1,0,2)).reshape(-1,nvir),\n t1.T, 1, tmp.reshape(-1,nocc))\n lib.dot(tmp.reshape(nocc,-1).T, t1, -1, wOVov[j].reshape(-1,nvir), 1)\n lib.dot(eris_ovov[j].reshape(nvir,-1).T, t1.T, 1,\n tmp.reshape(-1,nocc))\n lib.dot(tmp.reshape(nocc,-1).T, t1, 1, wOvOv[j].reshape(-1,nvir), 1)\n tmp = None\n\n #:vOvOv = numpy.einsum('jdlb,kldc->jbkc', eris_ovov, t2)\n ovovtmp = _cp(eris_ovov.transpose(0,3,2,1).reshape(-1,nov))\n vOvOv = numpy.empty((nocc,nvir,nocc,nvir))\n for j in range(nocc):\n lib.dot(t2[j].reshape(-1,nvir).T, ovovtmp.T, 1,\n vOvOv[j].reshape(nvir,-1))\n vOvOv[j] -= eris.oovv[j].transpose(2,0,1)\n ovovtmp = eris_ovov = None\n vOvOv = lib.transpose(vOvOv.reshape(nov,-1)).reshape(nocc,nvir,nocc,nvir)\n wOVov += vOVov\n wOvOv += vOvOv\n saved.wOVov = wOVov\n saved.wOvOv = wOvOv\n ovovtmp = wOVov = wOvOv = eris_ovov = None\n\n ov2 = vOVov*2 + vOvOv\n w3 += numpy.einsum('kcjb,kc->bj', ov2, t1)\n #:wooov += numpy.einsum('ibjc,kb->ijkc', ov2, t1)\n #:wovvv -= numpy.einsum('jakb,jc->kabc', ov2, t1)\n for i in range(nocc):\n wooov[i] += lib.dot(t1, ov2[i].reshape(nvir,-1)).reshape(nocc,nocc,nvir).transpose(1,0,2)\n lib.dot(_cp(ov2.transpose(0,2,1,3).reshape(nocc,-1)).T,\n t1, -1, wovvv.reshape(-1,nvir), 1)\n ov2 = None\n ov1 = vOvOv*2 + vOVov\n #:wooov -= numpy.einsum('ibkc,jb->ijkc', ov1, t1)\n #:wovvv += numpy.einsum('jakc,jb->kabc', ov1, t1)\n for i in range(nocc):\n lib.dot(t1, ov1[i].reshape(nvir,-1), -1, wooov[i].reshape(nocc,-1), 1)\n wovvv += lib.dot(_cp(ov1.reshape(nocc,-1)).T,\n t1).reshape(nvir,-1,nvir,nvir).transpose(1,0,3,2)\n ov1 = None\n\n woooo += _cp(eris.oooo).transpose(0,2,1,3)\n saved.woooo = woooo\n saved.wooov = wooov\n woooo = wooov = None\n\n w3 += numpy.einsum('bc,jc->bj', w1, t1)\n w3 -= numpy.einsum('kj,kb->bj', w2, t1)\n\n eris_ooov = _cp(eris.ooov)\n g2ooov = eris_ooov * 2\n g2ooov -= eris_ooov.transpose(2,0,1,3)\n #:tmp = numpy.einsum('kjla,jb->kabl', g2ooov, t1)\n #:wovvv = numpy.einsum('kabl,lc->kabc', tmp, t1)\n #:wovvv += numpy.einsum('kjla,jlbc->kabc', g2ooov, t2)\n tmp = lib.dot(g2ooov.reshape(nocc,-1).T, t1).reshape(-1,nocc,nvir,nvir).transpose(0,2,3,1)\n lib.dot(_cp(tmp.reshape(-1,nocc)), t1, 1, wovvv.reshape(-1,nvir), 1)\n tmp = None\n lib.dot(_cp(g2ooov.transpose(0,2,1,3).reshape(nocc**2,-1)).T,\n t2.reshape(nocc**2,-1), 1, wovvv.reshape(nov,-1), 1)\n g2ooov = eris_ooov = vOVov = vOvOv = None\n\n saved.wovvv = wovvv\n saved.w1 = w1\n saved.w2 = w2\n saved.w3 = w3\n saved.w4 = w4\n return saved\n\n\n# update L1, L2\ndef update_amps(mycc, t1, t2, l1, l2, eris=None, saved=None):\n if saved is None:\n saved = make_intermediates(mycc, t1, t2, eris)\n time1 = time0 = time.clock(), time.time()\n log = logger.Logger(mycc.stdout, mycc.verbose)\n nocc, nvir = t1.shape\n nov = nocc * nvir\n foo = eris.fock[:nocc,:nocc]\n fov = eris.fock[:nocc,nocc:]\n fvv = eris.fock[:nocc,:nocc]\n\n #:mba = numpy.einsum('klca,klcb->ba', l2, t2*2-t2.transpose(0,1,3,2))\n #:mij = numpy.einsum('ikcd,jkcd->ij', l2, t2*2-t2.transpose(0,1,3,2))\n #:theta = t2*2 - t2.transpose(0,1,3,2)\n theta = _ccsd.make_0132(t2, t2, 2, -1)\n mba = lib.dot(theta.reshape(-1,nvir).T, l2.reshape(-1,nvir))\n mij = lib.dot(l2.reshape(nocc,-1), theta.reshape(nocc,-1).T)\n theta = None\n mba1 = numpy.einsum('jc,jb->bc', l1, t1) + mba\n mij1 = numpy.einsum('kb,jb->kj', l1, t1) + mij\n mia1 =(t1 + numpy.einsum('kc,jkbc->jb', l1, t2) * 2\n - numpy.einsum('kc,jkcb->jb', l1, t2)\n - reduce(numpy.dot, (t1, l1.T, t1))\n - numpy.einsum('bd,jd->jb', mba, t1)\n - numpy.einsum('lj,lb->jb', mij, t1))\n\n tmp = mycc.add_wvvVV(numpy.zeros_like(l1), l2, eris)\n l2new = numpy.empty((nocc,nocc,nvir,nvir))\n ij = 0\n for i in range(nocc):\n for j in range(i):\n tmp1 = tmp[ij] * .5 # *.5 because of l2+l2.transpose(1,0,3,2) later\n l2new[i,j] = tmp1\n l2new[j,i] = tmp1.T\n ij += 1\n l2new[i,i] = tmp[ij] * .5\n ij += 1\n l1new =(numpy.einsum('ijab,jb->ia', l2new, t1) * 4\n - numpy.einsum('jiab,jb->ia', l2new, t1) * 2)\n tmp = tmp1 = None\n\n l1new += eris.fock[:nocc,nocc:]\n l1new += numpy.einsum('ib,ba->ia', l1, saved.w1)\n l1new -= numpy.einsum('ja,ij->ia', l1, saved.w2)\n l1new -= numpy.einsum('ik,ka->ia', mij, saved.w4)\n l1new -= numpy.einsum('ca,ic->ia', mba, saved.w4)\n l1new += numpy.einsum('ijab,bj->ia', l2, saved.w3) * 2\n l1new -= numpy.einsum('ijba,bj->ia', l2, saved.w3)\n\n l2new += numpy.einsum('ia,jb->ijab', l1, saved.w4)\n #:l2new += numpy.einsum('jibc,ca->jiba', l2, saved.w1)\n #:l2new -= numpy.einsum('kiba,jk->jiba', l2, saved.w2)\n lib.dot(l2.reshape(-1,nvir), saved.w1, 1, l2new.reshape(-1,nvir), 1)\n lib.dot(saved.w2, l2.reshape(nocc,-1),-1, l2new.reshape(nocc,-1), 1)\n\n eris_ooov = _cp(eris.ooov)\n l1new -= numpy.einsum('jkia,kj->ia', eris_ooov, mij1) * 2\n l1new += numpy.einsum('ikja,kj->ia', eris_ooov, mij1)\n #:l2new -= numpy.einsum('ka,kijb->jiba', l1, eris_ooov)\n lib.dot(_cp(eris_ooov.transpose(0,2,1,3).reshape(nocc,-1)).T,\n l1, -1, l2new.reshape(-1,nvir), 1)\n eris_ooov = None\n\n tau = _ccsd.make_tau(t2, t1, t1)\n #:l2tau = numpy.einsum('ijcd,klcd->ijkl', l2, tau)\n l2tau = lib.dot(l2.reshape(nocc**2,-1),\n tau.reshape(nocc**2,-1).T).reshape((nocc,)*4)\n tau = None\n l2t1 = numpy.einsum('ijcd,kc->ijkd', l2, t1)\n\n eris_ovvv = _cp(eris.ovvv)\n eris_ovvv = lib.unpack_tril(eris_ovvv.reshape(nov,-1))\n eris_ovvv = eris_ovvv.reshape(nocc,nvir,nvir,nvir)\n\n l1new += numpy.einsum('iabc,bc->ia', eris_ovvv, mba1) * 2\n l1new -= numpy.einsum('ibca,bc->ia', eris_ovvv, mba1)\n #:l2new += numpy.einsum('ic,jbac->jiba', l1, eris_ovvv)\n tmp = lib.dot(l1, eris_ovvv.reshape(-1,nvir).T).reshape(nocc,-1,nvir,nvir)\n for i in range(nocc):\n l2new[i] += tmp[i].transpose(0,2,1)\n #:m4 = numpy.einsum('ijkd,kadb->ijab', l2t1, eris_ovvv)\n m4 = tmp\n lib.dot(_cp(l2t1.reshape(nocc*nocc,-1)),\n _cp(eris_ovvv.transpose(0,2,1,3).reshape(-1,nvir**2)),\n 1, m4.reshape(nocc*nocc,-1))\n l2new -= m4\n l1new -= numpy.einsum('ijab,jb->ia', m4, t1) * 2\n l1new -= numpy.einsum('ijab,ia->jb', m4, t1) * 2\n l1new += numpy.einsum('jiab,jb->ia', m4, t1)\n l1new += numpy.einsum('jiab,ia->jb', m4, t1)\n eris_ovvv = tmp = None\n\n eris_ovov = _cp(eris.ovov)\n l1new += numpy.einsum('jb,iajb->ia', l1, eris_ovov) * 2\n #:l2new -= numpy.einsum('jbic,ca->jiba', eris_ovov, mba1)\n #:l2new -= numpy.einsum('kajb,ik->ijab', eris_ovov, mij1)\n tmp = lib.dot(eris_ovov.reshape(-1,nvir), mba1).reshape(nocc,nvir,nocc,nvir)\n lib.dot(mij1, eris_ovov.reshape(nocc,-1), 1, tmp.reshape(nocc,-1), 1)\n tmp_oovv = numpy.empty((nocc,nocc,nvir,nvir))\n for i in range(nocc):\n tmp_oovv[i] = eris_ovov[i].transpose(1,0,2) * .5\n l2new[i] += tmp_oovv[i]\n l2new[i] -= tmp[i].transpose(1,0,2)\n tmp = None\n l1new += numpy.einsum('iajb,jb->ia', eris_ovov, mia1) * 2\n l1new -= numpy.einsum('ibja,jb->ia', eris_ovov, mia1)\n #:m4 = numpy.einsum('kalb,ijkl->ijab', eris_ovov, l2tau)\n lib.dot(l2tau.reshape(nocc*nocc,-1), tmp_oovv.reshape(-1,nvir**2),\n 1, m4.reshape(nocc**2,-1))\n l2new += m4\n l1new += numpy.einsum('ijab,jb->ia', m4, t1) * 4\n l1new -= numpy.einsum('ijba,jb->ia', m4, t1) * 2\n eris_ovov = m4 = tmp_oovv = None\n\n eris_oovv = _cp(eris.oovv)\n l1new -= numpy.einsum('jb,ijba->ia', l1, eris_oovv)\n eris_oovv = None\n\n saved_wooov = _cp(saved.wooov)\n #:l1new -= numpy.einsum('jkca,ijkc->ia', l2, saved_wooov)\n l1new -= lib.dot(saved_wooov.reshape(nocc,-1), l2.reshape(-1,nvir))\n saved_wovvv = _cp(saved.wovvv)\n #:l1new += numpy.einsum('kibc,kabc->ia', l2, saved_wovvv)\n for j in range(nocc):\n l1new += lib.dot(l2[j].reshape(nocc,-1),\n saved_wovvv[j].reshape(nvir,-1).T)\n saved_wooov = saved_wovvv = None\n\n saved_wOvOv = _cp(saved.wOvOv)\n tmp_ovov = _cp(saved.wOVov) * 2\n tmp_ovov += saved_wOvOv\n #:tmp = l2.transpose(0,2,1,3) - l2.transpose(0,3,1,2)*.5\n #:l2new += numpy.einsum('kcia,kcjb->jiba', tmp, tmp_ovov)\n tmp = numpy.empty((nocc,nvir,nocc,nvir))\n for i in range(nocc):\n tmp[i] = l2[i].transpose(2,0,1)*-.5\n tmp[i] += l2[i].transpose(1,0,2)\n tmp = lib.dot(tmp_ovov.reshape(-1,nov),\n tmp.reshape(nov,-1)).reshape(-1,nvir,nocc,nvir)\n #:tmp = numpy.einsum('jkca,ibkc->ijab', l2, saved_wOvOv)\n for i in range(nocc):\n l2new[i] += tmp[i].transpose(1,0,2)\n tmp_ovov[i] = l2[i].transpose(2,0,1)\n lib.dot(saved_wOvOv.reshape(-1,nov), tmp_ovov.reshape(nov,-1),\n 1, tmp.reshape(nov,-1))\n for i in range(nocc):\n l2new[i] += tmp[i].transpose(1,2,0)\n l2new[i] += tmp[i].transpose(1,0,2) * .5\n saved_wOvOv = tmp = tmp_ovov = None\n\n saved_woooo = _cp(saved.woooo)\n #:m3 = numpy.einsum('klab,ijkl->ijab', l2, saved_woooo)\n m3 = lib.dot(saved_woooo.reshape(-1,nocc**2),\n l2.reshape(nocc**2,-1), .5).reshape(-1,nocc,nvir,nvir)\n l2new += m3\n l1new += numpy.einsum('ijab,jb->ia', m3, t1) * 4\n l1new -= numpy.einsum('ijba,jb->ia', m3, t1) * 2\n saved_woooo = m3 = None\n\n mo_e = eris.fock.diagonal()\n eia = lib.direct_sum('i-j->ij', mo_e[:nocc], mo_e[nocc:])\n l1new /= eia\n l1new += l1\n\n# l2new = l2new + l2new.transpose(1,0,3,2)\n# l2new /= lib.direct_sum('ia+jb->ijab', eia, eia)\n# l2new += l2\n ij = 0\n for i in range(nocc):\n for j in range(i):\n dab = lib.direct_sum('a+b->ab', eia[i], eia[j])\n tmp = (l2new[i,j]+l2new[j,i].T) / dab + l2[i,j]\n l2new[i,j] = tmp\n l2new[j,i] = tmp.T\n ij += 1\n dab = lib.direct_sum('a+b->ab', eia[i], eia[i])\n l2new[i,i] = (l2new[i,i]+l2new[i,i].T)/dab + l2[i,i]\n ij += 1\n\n time0 = log.timer_debug1('update l1 l2', *time0)\n return l1new, l2new\n\ndef _cp(a):\n return numpy.array(a, copy=False, order='C')\n\n\nif __name__ == '__main__':\n from pyscf import gto\n from pyscf import scf\n from pyscf.cc import ccsd\n from pyscf import ao2mo\n\n mol = gto.M()\n mf = scf.RHF(mol)\n\n mcc = ccsd.CCSD(mf)\n\n numpy.random.seed(12)\n nocc = 5\n nmo = 12\n nvir = nmo - nocc\n eri0 = numpy.random.random((nmo,nmo,nmo,nmo))\n eri0 = ao2mo.restore(1, ao2mo.restore(8, eri0, nmo), nmo)\n fock0 = numpy.random.random((nmo,nmo))\n fock0 = fock0 + fock0.T + numpy.diag(range(nmo))*2\n t1 = numpy.random.random((nocc,nvir))\n t2 = numpy.random.random((nocc,nocc,nvir,nvir))\n t2 = t2 + t2.transpose(1,0,3,2)\n l1 = numpy.random.random((nocc,nvir))\n l2 = numpy.random.random((nocc,nocc,nvir,nvir))\n l2 = l2 + l2.transpose(1,0,3,2)\n\n eris = lambda:None\n eris.oooo = eri0[:nocc,:nocc,:nocc,:nocc].copy()\n eris.ooov = eri0[:nocc,:nocc,:nocc,nocc:].copy()\n eris.ovoo = eri0[:nocc,nocc:,:nocc,:nocc].copy()\n eris.oovv = eri0[:nocc,:nocc,nocc:,nocc:].copy()\n eris.ovov = eri0[:nocc,nocc:,:nocc,nocc:].copy()\n idx = numpy.tril_indices(nvir)\n eris.ovvv = eri0[:nocc,nocc:,nocc:,nocc:][:,:,idx[0],idx[1]].copy()\n eris.vvvv = pyscf.ao2mo.restore(4,eri0[nocc:,nocc:,nocc:,nocc:],nvir)\n eris.fock = fock0\n\n saved = make_intermediates(mcc, t1, t2, eris)\n l1new, l2new = update_amps(mcc, t1, t2, l1, l2, eris, saved)\n print(abs(l1new).sum()-38172.7896467303)\n print(numpy.dot(l1new.flatten(), numpy.arange(35)) - 739312.005491083)\n print(numpy.dot(l1new.flatten(), numpy.sin(numpy.arange(35)))-7019.50937051188)\n print(numpy.dot(numpy.sin(l1new.flatten()), numpy.arange(35))-69.6652346635955)\n\n print(abs(l2new).sum()-72035.4931071527)\n print(abs(l2new-l2new.transpose(1,0,3,2)).sum())\n print(numpy.dot(l2new.flatten(), numpy.arange(35**2)) - 48427109.5409886)\n print(numpy.dot(l2new.flatten(), numpy.sin(numpy.arange(35**2)))-137.758016736487)\n print(numpy.dot(numpy.sin(l2new.flatten()), numpy.arange(35**2))-507.656936701192)\n\n\n mol = gto.Mole()\n mol.verbose = 0\n mol.atom = [\n [8 , (0. , 0. , 0.)],\n [1 , (0. , -0.757 , 0.587)],\n [1 , (0. , 0.757 , 0.587)]]\n\n mol.basis = 'cc-pvdz'\n mol.build()\n rhf = scf.RHF(mol)\n rhf.conv_tol = 1e-16\n rhf.scf()\n\n mcc = ccsd.CCSD(rhf)\n mcc.conv_tol = 1e-12\n ecc, t1, t2 = mcc.kernel()\n\n nmo = rhf.mo_energy.size\n fock0 = numpy.diag(rhf.mo_energy)\n nocc = mol.nelectron // 2\n nvir = nmo - nocc\n\n eris = mcc.ao2mo()\n conv, l1, l2 = kernel(mcc, eris, t1, t2, tol=1e-8)\n print(numpy.linalg.norm(l1)-0.0132626841292)\n print(numpy.linalg.norm(l2)-0.212575609057)\n\n import ccsd_rdm\n dm1 = ccsd_rdm.make_rdm1(mcc, t1, t2, l1, l2)\n dm2 = ccsd_rdm.make_rdm2(mcc, t1, t2, l1, l2)\n h1 = reduce(numpy.dot, (rhf.mo_coeff.T, rhf.get_hcore(), rhf.mo_coeff))\n eri = pyscf.ao2mo.full(rhf._eri, rhf.mo_coeff)\n eri = pyscf.ao2mo.restore(1, eri, nmo).reshape((nmo,)*4)\n e1 = numpy.einsum('pq,pq', h1, dm1)\n e2 = numpy.einsum('pqrs,pqrs', eri, dm2) * .5\n print e1+e2+mol.energy_nuc() - rhf.e_tot - ecc\n", "meta": {"hexsha": "82d9d4035ec915bdb7d605d958efbee18c383ae1", "size": 21563, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/cc/ccsd_lambda_incore.py", "max_stars_repo_name": "KMCzajkowski/pyscf", "max_stars_repo_head_hexsha": "e8af41d910cc0d3963655120c0b689590ad978e7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyscf/cc/ccsd_lambda_incore.py", "max_issues_repo_name": "KMCzajkowski/pyscf", "max_issues_repo_head_hexsha": "e8af41d910cc0d3963655120c0b689590ad978e7", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyscf/cc/ccsd_lambda_incore.py", "max_forks_repo_name": "KMCzajkowski/pyscf", "max_forks_repo_head_hexsha": "e8af41d910cc0d3963655120c0b689590ad978e7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-12-06T03:10:50.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-06T03:10:50.000Z", "avg_line_length": 38.9927667269, "max_line_length": 98, "alphanum_fraction": 0.5873486992, "include": true, "reason": "import numpy", "num_tokens": 8734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.25683199707586785, "lm_q1q2_score": 0.13342969864045096}} {"text": "import collections\nimport functools\nimport numpy as np\nimport scipy.signal as signal\nfrom pathlib import Path\ntry:\n import backstaff.units as units\n import backstaff.plotting as plotting\n import backstaff.field_lines as field_lines\n import backstaff.beam_heating as beam_heating\nexcept ModuleNotFoundError:\n import units\n import plotting\n import field_lines\n import beam_heating\n\n\nclass ElectronBeamSwarm(field_lines.FieldLineSet3):\n\n VALUE_DESCRIPTIONS = {\n 'x': r'$x$ [Mm]',\n 'y': r'$y$ [Mm]',\n 'z': 'Height [Mm]',\n 'z0': 'Initial height [Mm]',\n 's': r'$s$ [Mm]',\n 'sz0': r'$s(z=0) - s$ [Mm]',\n 'initial_pitch_angle_cosine': r'$\\mu_0$',\n 'collisional_pitch_angle_cosine': r'$\\mu$',\n 'adiabatic_pitch_angle_cosine': r'$\\mu$',\n 'initial_pitch_angle': r'$\\beta_0$ [deg]',\n 'electric_field_angle_cosine': 'Electric field angle cosine',\n 'total_power': 'Total power [erg/s]',\n 'total_power_density': r'Total power density [erg/s/cm$^3$]',\n 'total_energy_density': r'Total energy density [erg/cm$^3$]',\n 'lower_cutoff_energy': r'$E_\\mathrm{{c}}$ [keV]',\n 'acceleration_volume': r'Acceleration site volume [cm$^3$]',\n 'estimated_depletion_distance': r'$\\tilde{{s}}_\\mathrm{{dep}}$ [Mm]',\n 'total_propagation_distance': r'$s_\\mathrm{{dep}}$ [Mm]',\n 'residual_factor': r'$r$',\n 'acceleration_height': 'Acceleration site height [Mm]',\n 'depletion_height': 'Depletion height [Mm]',\n 'beam_electron_fraction': 'Beam electrons relative to total electrons',\n 'return_current_speed_fraction': 'Speed relative to speed of light',\n 'estimated_electron_density': r'Electron density [electrons/cm$^3$]',\n 'deposited_power': 'Deposited power [erg/s]',\n 'deposited_power_per_dist':\n r'$\\mathrm{{d}}\\mathcal{{E}}/\\mathrm{{d}}s$ [erg/s/cm]',\n 'deposited_power_density': r'$Q$ [erg/s/cm$^3$]',\n 'power_change': 'Power change [erg/s]',\n 'power_density_change': r'Power density change [erg/s/cm$^3$]',\n 'beam_flux': r'Energy flux [erg/s/cm$^2$]',\n 'conduction_flux': r'Energy flux [erg/s/cm$^2$]',\n 'remaining_power': 'Remaining power [erg/s]',\n 'relative_cumulative_power':\n r'$\\mathcal{{E}}/P_\\mathrm{{beam}}$ [$\\%$]',\n 'r': r'$\\rho$ [g/cm$^3$]',\n 'tg': r'$T$ [K]',\n 'nel': r'$n_\\mathrm{{e}}$ [electrons/cm$^3$]',\n 'krec': r'$K$ [Bifrost units]',\n 'qspitz': r'Power density change [erg/s/cm$^3$]',\n 'r0': r'$\\rho$ [g/cm$^3$]',\n 'tg0': r'$T$ [K]',\n 'p': r'$P$ [dyn/cm$^2$]',\n 'b': r'$|B|$ [G]',\n 'beta': r'$\\beta$',\n 'ux': r'$u_x$ [cm/s]',\n 'uy': r'$u_y$ [cm/s]',\n 'uz': r'$u_z$ [cm/s]',\n 'us': r'$u_s$ [cm/s]',\n 'uhor': r'$u_\\mathrm{h}$ [cm/s]',\n }\n\n VALUE_UNIT_CONVERTERS = {\n 'r': lambda f: f*units.U_R,\n 'qspitz': lambda f: f*(units.U_E/units.U_T),\n 'qjoule': lambda f: f*(units.U_E/units.U_T),\n 'dedt': lambda f: f*(units.U_E/units.U_T),\n 'r0': lambda f: f*units.U_R,\n 'z': lambda f: -f,\n 'z0': lambda f: -f,\n 'bx': lambda f: f*units.U_B,\n 'by': lambda f: f*units.U_B,\n 'bz': lambda f: f*units.U_B,\n 'b': lambda f: f*units.U_B,\n 'p': lambda f: f*units.U_E,\n 'ux': lambda f: f*units.U_U,\n 'uy': lambda f: f*units.U_U,\n 'uz': lambda f: f*units.U_U,\n 'us': lambda f: f*units.U_U,\n 'uhor': lambda f: f*units.U_U,\n }\n\n @staticmethod\n def from_file(file_path,\n acceleration_data_type=None,\n params={},\n derived_quantities=[],\n verbose=False):\n import backstaff.reading as reading\n file_path = Path(file_path)\n extension = file_path.suffix\n if extension == '.pickle':\n electron_beam_swarm = reading.read_electron_beam_swarm_from_combined_pickles(\n file_path,\n acceleration_data_type=acceleration_data_type,\n params=params,\n derived_quantities=derived_quantities,\n verbose=verbose)\n elif extension == '.fl':\n electron_beam_swarm = reading.read_electron_beam_swarm_from_custom_binary_file(\n file_path,\n acceleration_data_type=acceleration_data_type,\n params=params,\n derived_quantities=derived_quantities,\n verbose=verbose)\n else:\n raise ValueError(\n 'Invalid file extension {} for electron beam data.'.format(\n extension))\n\n return electron_beam_swarm\n\n @staticmethod\n def dummy(domain_bounds):\n return ElectronBeamSwarm(domain_bounds, 0, {}, {}, {}, {}, {})\n\n def __init__(self,\n domain_bounds,\n number_of_beams,\n fixed_scalar_values,\n fixed_vector_values,\n varying_scalar_values,\n varying_vector_values,\n acceleration_data,\n params={},\n derived_quantities=[],\n verbose=False):\n assert isinstance(acceleration_data, dict)\n self.number_of_beams = number_of_beams\n self.acceleration_data = acceleration_data\n super().__init__(domain_bounds,\n number_of_beams,\n fixed_scalar_values,\n fixed_vector_values,\n varying_scalar_values,\n varying_vector_values,\n params=params,\n derived_quantities=derived_quantities,\n verbose=verbose)\n\n if self.verbose:\n print('Acceleration data:\\n {}'.format('\\n '.join(\n self.acceleration_data.keys())))\n\n def get_subset(self,\n only_quantities=None,\n included_field_lines_finder=None,\n **kwargs):\n return super().get_subset(\n self.acceleration_data,\n only_quantities=only_quantities,\n included_field_lines_finder=included_field_lines_finder,\n **kwargs)\n\n def get_number_of_beams(self):\n return self.number_of_beams\n\n def compute_number_of_sites(self):\n return np.unique(np.stack(\n (self.fixed_scalar_values['x0'], self.fixed_scalar_values['y0'],\n self.fixed_scalar_values['z0']),\n axis=1),\n axis=0).shape[0]\n\n def get_acceleration_data(self, acceleration_data_type):\n return self.acceleration_data[acceleration_data_type]\n\n def get_acceleration_sites(self):\n return self.get_acceleration_data('acceleration_sites')\n\n def _derive_quantities(self, derived_quantities):\n\n super()._derive_quantities(derived_quantities)\n\n if 'initial_pitch_angle' in derived_quantities:\n self.fixed_scalar_values['initial_pitch_angle'] = np.arccos(\n self.get_fixed_scalar_values(\n 'initial_pitch_angle_cosine'))*180.0/np.pi\n\n if 'total_power_density' in derived_quantities:\n self.fixed_scalar_values[\n 'total_power_density'] = self.get_fixed_scalar_values(\n 'total_power')/self.get_fixed_scalar_values(\n 'acceleration_volume')\n\n if 'total_energy_density' in derived_quantities:\n self._obtain_total_energy_densities()\n\n if 'non_thermal_energy_per_thermal_electron' in derived_quantities:\n self.fixed_scalar_values[\n 'non_thermal_energy_per_thermal_electron'] = self._obtain_total_energy_densities(\n )/self.get_fixed_scalar_values(\n 'nel0' if self.has_fixed_scalar_values('nel0') else 'nel')\n\n if 'mean_electron_energy' in derived_quantities:\n self._obtain_mean_electron_energies()\n\n if 'acceleration_height' in derived_quantities:\n self.fixed_scalar_values['acceleration_height'] = np.asfarray(\n [-z[0] for z in self.get_varying_scalar_values('z')])\n\n if 'depletion_height' in derived_quantities:\n self.fixed_scalar_values['depletion_height'] = np.asfarray(\n [-z[-1] for z in self.get_varying_scalar_values('z')])\n\n if 'acceleration_site_electron_density' in derived_quantities:\n self._obtain_acceleration_site_electron_densities()\n\n if 'beam_electron_fraction' in derived_quantities:\n self._obtain_beam_electron_fractions()\n\n if 'return_current_speed_fraction' in derived_quantities:\n mean_electron_energies = self._obtain_mean_electron_energies(\n )*units.KEV_TO_ERG\n mean_electron_speed_fractions = np.sqrt(\n 1.0 - 1.0/(1.0 + mean_electron_energies/units.MC2_ELECTRON)**2)\n beam_electron_fractions = self._obtain_beam_electron_fractions()\n self.fixed_scalar_values[\n 'return_current_speed_fraction'] = beam_electron_fractions*mean_electron_speed_fractions\n\n if 'acceleration_current' in derived_quantities:\n self._obtain_acceleration_currents()\n\n if 'acceleration_induced_magnetic_field' in derived_quantities:\n self._obtain_acceleration_induced_magnetic_fields()\n\n if 'acceleration_ambient_magnetic_field' in derived_quantities:\n self._obtain_acceleration_ambient_magnetic_field()\n\n if 'relative_acceleration_induced_magnetic_field' in derived_quantities:\n B_induced = self._obtain_acceleration_induced_magnetic_fields()\n B = self._obtain_acceleration_ambient_magnetic_field()\n self.fixed_scalar_values[\n 'relative_acceleration_induced_magnetic_field'] = B_induced/B\n\n if 'acceleration_induced_electric_field' in derived_quantities:\n self._obtain_acceleration_induced_electric_fields()\n\n if 'parallel_electric_field' in derived_quantities:\n self._obtain_parallel_electric_fields()\n\n if 'relative_acceleration_induced_electric_field' in derived_quantities:\n E_induced = self._obtain_acceleration_induced_electric_fields()\n E = np.abs(self._obtain_parallel_electric_fields())\n self.fixed_scalar_values[\n 'relative_acceleration_induced_electric_field'] = E_induced/E\n\n if 'return_current_heating_ratio' in derived_quantities:\n self._obtain_return_current_heating_ratio()\n\n if 'estimated_electron_density' in derived_quantities:\n assert self.has_varying_scalar_values('r')\n self.varying_scalar_values['estimated_electron_density'] = [\n self.varying_scalar_values['r'][i]*units.U_R*\n units.MASS_DENSITY_TO_ELECTRON_DENSITY\n for i in range(self.get_number_of_beams())\n ]\n\n if 'deposited_power_per_dist' in derived_quantities:\n scale = 1.0/(self.get_param('dense_step_length')*units.U_L)\n self.varying_scalar_values['deposited_power_per_dist'] = [\n arr*scale\n for arr in self.varying_scalar_values['deposited_power']\n ]\n\n if 'power_change' in derived_quantities:\n self.varying_scalar_values['power_change'] = [\n arr.copy()\n for arr in self.varying_scalar_values['deposited_power']\n ]\n for i in range(self.get_number_of_beams()):\n self.varying_scalar_values['power_change'][i][\n 0] -= self.fixed_scalar_values['total_power'][i]\n\n if 'power_density_change' in derived_quantities:\n self.varying_scalar_values['power_density_change'] = [\n arr.copy() for arr in\n self.varying_scalar_values['deposited_power_density']\n ]\n for i in range(self.get_number_of_beams()):\n self.varying_scalar_values['power_density_change'][i][\n 0] -= self.get_fixed_scalar_values(\n 'total_power')[i]/self.get_fixed_scalar_values(\n 'acceleration_volume')[i]\n\n if 'padded_total_power_density' in derived_quantities:\n self.varying_scalar_values['padded_total_power_density'] = [\n np.zeros_like(arr) for arr in self.varying_scalar_values['x']\n ]\n for i in range(self.get_number_of_beams()):\n self.varying_scalar_values['padded_total_power_density'][i][\n 0] += self.get_fixed_scalar_values(\n 'total_power')[i]/self.get_fixed_scalar_values(\n 'acceleration_volume')[i]\n\n if 'beam_flux' in derived_quantities:\n self.varying_scalar_values['beam_flux'] = [\n arr.copy() for arr in\n self.varying_scalar_values['deposited_power_density']\n ]\n for i in range(self.get_number_of_beams()):\n self.varying_scalar_values['beam_flux'][i][\n 0] -= self.get_fixed_scalar_values(\n 'total_power')[i]/self.get_fixed_scalar_values(\n 'acceleration_volume')[i]\n self.varying_scalar_values['beam_flux'][i] *= self.get_param(\n 'dense_step_length')*units.U_L\n\n if 'conduction_flux' in derived_quantities:\n self.varying_scalar_values['conduction_flux'] = [\n arr.copy() for arr in self.varying_scalar_values['qspitz']\n ]\n for i in range(self.get_number_of_beams()):\n self.varying_scalar_values['conduction_flux'][\n i] *= self.get_param(\n 'dense_step_length')*units.U_L*units.U_E/units.U_T\n\n if 'cumulative_power' in derived_quantities:\n self.varying_scalar_values['cumulative_power'] = [\n np.cumsum(self.varying_scalar_values['deposited_power'][i])\n for i in range(self.get_number_of_beams())\n ]\n\n if 'relative_cumulative_power' in derived_quantities:\n self.varying_scalar_values['relative_cumulative_power'] = [\n 100*\n np.cumsum(self.varying_scalar_values['deposited_power'][i])/\n self.fixed_scalar_values['total_power'][i]\n for i in range(self.get_number_of_beams())\n ]\n\n if 'remaining_power' in derived_quantities:\n self.varying_scalar_values['remaining_power'] = [\n self.fixed_scalar_values['total_power'][i] -\n np.cumsum(self.varying_scalar_values['deposited_power'][i])\n for i in range(self.get_number_of_beams())\n ]\n\n if 'pitch_angle_intersection_energy' in derived_quantities:\n assert self.has_param('power_law_delta')\n delta = self.get_param('power_law_delta')\n self.varying_scalar_values['pitch_angle_intersection_energy'] = [\n Ec/np.sqrt(\n (1.0 -\n (np.sqrt(np.maximum(0.0, 1.0 - b*\n (1.0 - mu0**2)/b[0]))/mu0)**3)/\n r**(-2/delta))\n for Ec, mu0, b, r in zip(\n self.get_fixed_scalar_values('lower_cutoff_energy'),\n self.get_fixed_scalar_values('initial_pitch_angle_cosine'),\n self.get_varying_scalar_values('b'),\n self.get_varying_scalar_values('residual_factor'))\n ]\n\n # if 'collisional_pitch_angle_cosine' in derived_quantities:\n # assert self.has_param('power_law_delta')\n # delta = self.get_param('power_law_delta')\n # self.varying_scalar_values['collisional_pitch_angle_cosine'] = [\n # mu0*np.cbrt(np.maximum(0.0, 1.0 - r**(-2/delta)))\n # for mu0, r in zip(\n # self.get_fixed_scalar_values('initial_pitch_angle_cosine'),\n # self.get_varying_scalar_values('residual_factor'))\n # ]\n\n if 'adiabatic_pitch_angle_cosine' in derived_quantities:\n self.varying_scalar_values['adiabatic_pitch_angle_cosine'] = [\n np.sqrt(np.maximum(0.0, 1.0 - b*(1.0 - mu0**2)/b[0]))\n for mu0, b in zip(\n self.get_fixed_scalar_values('initial_pitch_angle_cosine'),\n self.get_varying_scalar_values('b'))\n ]\n\n def _obtain_mean_electron_energies(self):\n if not self.has_fixed_scalar_values('mean_electron_energy'):\n assert self.has_param('power_law_delta')\n delta = self.get_param('power_law_delta')\n self.fixed_scalar_values['mean_electron_energy'] = (\n (delta - 0.5)/(delta - 1.5)\n )*self.get_fixed_scalar_values('lower_cutoff_energy')\n\n return self.get_fixed_scalar_values('mean_electron_energy')\n\n def _obtain_mean_electron_speeds(self):\n if not self.has_fixed_scalar_values('mean_electron_speed'):\n assert self.has_param('power_law_delta')\n delta = self.get_param('power_law_delta')\n self.fixed_scalar_values['mean_electron_speed'] = (\n (delta - 0.5)/(delta - 1))*np.sqrt(\n 2*self.get_fixed_scalar_values('lower_cutoff_energy')*\n units.KEV_TO_ERG/units.M_ELECTRON) # [cm/s]\n\n return self.get_fixed_scalar_values('mean_electron_speed')\n\n def _obtain_acceleration_site_electron_densities(self):\n if not self.has_fixed_scalar_values(\n 'acceleration_site_electron_density'):\n assert self.has_fixed_scalar_values(\n 'r0') or self.has_fixed_scalar_values('r')\n self.fixed_scalar_values[\n 'acceleration_site_electron_density'] = self.get_fixed_scalar_values(\n 'r0' if self.has_fixed_scalar_values('r0') else 'r'\n )*units.U_R*units.MASS_DENSITY_TO_ELECTRON_DENSITY\n\n return self.get_fixed_scalar_values(\n 'acceleration_site_electron_density')\n\n def _obtain_beam_electron_fractions(self):\n if not self.has_fixed_scalar_values('beam_electron_fraction'):\n assert self.has_param('particle_energy_fraction')\n assert self.has_fixed_scalar_values(\n 'bx') and self.has_fixed_scalar_values(\n 'by') and self.has_fixed_scalar_values('bz')\n assert self.has_fixed_scalar_values(\n 'ix') and self.has_fixed_scalar_values(\n 'iy') and self.has_fixed_scalar_values('iz')\n\n bx = self.get_fixed_scalar_values('bx')*units.U_B\n by = self.get_fixed_scalar_values('by')*units.U_B\n bz = self.get_fixed_scalar_values('bz')*units.U_B\n ix = self.get_fixed_scalar_values('ix')\n iy = self.get_fixed_scalar_values('iy')\n iz = self.get_fixed_scalar_values('iz')\n free_energy = (bx*bx + by*by + bz*bz - (bx*ix + by*iy + bz*iz)**2/\n (ix*ix + iy*iy + iz*iz))/(8.0*np.pi)\n mean_electron_energies = self._obtain_mean_electron_energies(\n )*units.KEV_TO_ERG\n electron_densities = self._obtain_acceleration_site_electron_densities(\n )\n self.fixed_scalar_values[\n 'beam_electron_fraction'] = self.get_param(\n 'particle_energy_fraction')*free_energy/(\n mean_electron_energies*electron_densities)\n\n return self.get_fixed_scalar_values('beam_electron_fraction')\n\n def _obtain_total_energy_densities(self):\n if not self.has_fixed_scalar_values('total_energy_density'):\n assert self.has_param('acceleration_duration')\n self.fixed_scalar_values[\n 'total_energy_density'] = self.get_fixed_scalar_values(\n 'total_power')*self.get_param(\n 'acceleration_duration')/self.get_fixed_scalar_values(\n 'acceleration_volume')\n\n return self.get_fixed_scalar_values('total_energy_density')\n\n def _obtain_acceleration_currents(self):\n if not self.has_fixed_scalar_values('acceleration_current'):\n u_acc = self._obtain_total_energy_densities()\n E_mean = self._obtain_mean_electron_energies()*units.KEV_TO_ERG\n v_mean = self._obtain_mean_electron_speeds()\n self.fixed_scalar_values[\n 'acceleration_current'] = units.Q_ELECTRON*u_acc*v_mean/E_mean\n\n return self.get_fixed_scalar_values('acceleration_current')\n\n def _obtain_acceleration_induced_magnetic_fields(self):\n if not self.has_fixed_scalar_values(\n 'acceleration_induced_magnetic_field'):\n j = self._obtain_acceleration_currents()\n L = np.cbrt(self.get_fixed_scalar_values('acceleration_volume'))\n self.fixed_scalar_values[\n 'acceleration_induced_magnetic_field'] = np.pi*j*L/units.CLIGHT\n\n return self.get_fixed_scalar_values(\n 'acceleration_induced_magnetic_field')\n\n def _obtain_resistivities(self):\n if not self.has_fixed_scalar_values('resistivity'):\n nel = self.get_fixed_scalar_values('nel0')\n tg = self.get_fixed_scalar_values('tg0')\n r = self.get_fixed_scalar_values('r0')*units.U_R\n x = beam_heating.compute_equilibrium_hydrogen_ionization_fraction(\n tg, nel)\n nH = beam_heating.compute_total_hydrogen_density(r)\n\n self.fixed_scalar_values['resistivity'] = (\n 7.26e-9*x/tg**(3/2))*np.log(\n 3*np.sqrt((units.KBOLTZMANN*tg)**3/(np.pi*nH))/\n (2*units.Q_ELECTRON**3)) + 7.6e-18*(1 - x)*np.sqrt(tg)/x\n\n return self.get_fixed_scalar_values('resistivity')\n\n def _obtain_acceleration_induced_electric_fields(self):\n if not self.has_fixed_scalar_values(\n 'acceleration_induced_electric_field'):\n j = self._obtain_acceleration_currents()\n eta = self._obtain_resistivities()\n self.fixed_scalar_values[\n 'acceleration_induced_electric_field'] = eta*j*units.STATV_TO_V*1e2\n\n return self.get_fixed_scalar_values(\n 'acceleration_induced_electric_field')\n\n def _obtain_parallel_electric_fields(self):\n if not self.has_fixed_scalar_values('parallel_electric_field'):\n bx = self.get_fixed_scalar_values('bx0')*units.U_B\n by = self.get_fixed_scalar_values('by0')*units.U_B\n bz = self.get_fixed_scalar_values('bz0')*units.U_B\n ex = self.get_fixed_scalar_values('ex0')*units.U_EL\n ey = self.get_fixed_scalar_values('ey0')*units.U_EL\n ez = self.get_fixed_scalar_values('ez0')*units.U_EL\n\n self.fixed_scalar_values['parallel_electric_field'] = (\n bx*ex + by*ey + bz*ez)/np.sqrt(bx**2 + by**2 + bz**2)\n\n return self.get_fixed_scalar_values('parallel_electric_field')\n\n def _obtain_return_current_heating_ratio(self):\n if not self.has_fixed_scalar_values('return_current_heating_ratio'):\n E_mean = self._obtain_mean_electron_energies() # [keV]\n mu = self.get_fixed_scalar_values('initial_pitch_angle_cosine')\n\n nel = self.get_fixed_scalar_values('nel0')\n tg = self.get_fixed_scalar_values('tg0')\n r = self.get_fixed_scalar_values('r0')*units.U_R\n x = beam_heating.compute_equilibrium_hydrogen_ionization_fraction(\n tg, nel)\n r = self.get_fixed_scalar_values('r0')*units.U_R\n nH = beam_heating.compute_total_hydrogen_density(r) # [1/cm^3]\n\n electron_coulomb_logarithm = beam_heating.compute_electron_coulomb_logarithm(\n nel, E_mean)\n neutral_hydrogen_coulomb_logarithm = beam_heating.compute_neutral_hydrogen_coulomb_logarithm(\n E_mean)\n gamma = beam_heating.compute_effective_coulomb_logarithm(\n x,\n electron_coulomb_logarithm,\n neutral_hydrogen_coulomb_logarithm,\n )\n\n E = self._obtain_acceleration_induced_electric_fields()/(\n units.STATV_TO_V*1e2) # [statV/cm]\n e = units.Q_ELECTRON # [statC]\n\n self.fixed_scalar_values['return_current_heating_ratio'] = (\n E*e/nH)/(2*np.pi*e**4*gamma/(mu*E_mean*units.KEV_TO_ERG))\n\n return self.get_fixed_scalar_values('return_current_heating_ratio')\n\n def _obtain_acceleration_ambient_magnetic_field(self):\n if not self.has_fixed_scalar_values(\n 'acceleration_ambient_magnetic_field'):\n bx = self.get_fixed_scalar_values('bx0')\n by = self.get_fixed_scalar_values('by0')\n bz = self.get_fixed_scalar_values('bz0')\n\n B = np.sqrt(bx**2 + by**2 + bz**2)*units.U_B\n\n self.fixed_scalar_values['acceleration_ambient_magnetic_field'] = B\n\n return self.get_fixed_scalar_values(\n 'acceleration_ambient_magnetic_field')\n\n\nclass AccelerationSites(field_lines.FieldLineSet3):\n\n VALUE_DESCRIPTIONS = ElectronBeamSwarm.VALUE_DESCRIPTIONS\n VALUE_UNIT_CONVERTERS = ElectronBeamSwarm.VALUE_UNIT_CONVERTERS\n\n def __init__(self,\n domain_bounds,\n number_of_sites,\n fixed_scalar_values,\n fixed_vector_values,\n varying_scalar_values,\n varying_vector_values,\n params={},\n derived_quantities=[],\n verbose=False):\n self.number_of_sites = number_of_sites\n super().__init__(domain_bounds,\n number_of_sites,\n fixed_scalar_values,\n fixed_vector_values,\n varying_scalar_values,\n varying_vector_values,\n params=params,\n derived_quantities=derived_quantities,\n verbose=verbose)\n\n def get_number_of_sites(self):\n return self.number_of_sites\n\n\ndef find_beams_starting_in_coords(x_coords,\n y_coords,\n z_coords,\n propagation_senses,\n fixed_scalar_values,\n max_propagation_sense_diff=1e-6,\n max_distance=1e-5):\n return [\n i for i, (x, y, z, s) in enumerate(\n zip(fixed_scalar_values['x0'], fixed_scalar_values['y0'],\n fixed_scalar_values['z0'],\n fixed_scalar_values['propagation_sense']))\n if np.any(\n np.logical_and(\n (x - x_coords)**2 + (y - y_coords)**2 +\n (z - z_coords)**2 <= max_distance**2,\n np.abs(s - propagation_senses) < max_propagation_sense_diff))\n ]\n\n\ndef find_beams_propagating_longer_than_distance(min_distance,\n fixed_scalar_values):\n return list(\n np.nonzero(\n fixed_scalar_values['total_propagation_distance'] > min_distance)\n [0])\n\n\ndef find_beams_in_temperature_height_region(height_lims, tg_lims,\n varying_scalar_values):\n return [\n i for i, (z, tg) in enumerate(\n zip(varying_scalar_values['z'], varying_scalar_values['tg']))\n if np.any((z > -height_lims[1])*(z < -height_lims[0])*\n (tg > tg_lims[0])*(tg < tg_lims[1]))\n ]\n\n\ndef find_peak_deposition_point(varying_scalar_values, field_line_idx):\n deposited_power = varying_scalar_values['deposited_power'][field_line_idx]\n indices, _ = signal.find_peaks(deposited_power/np.mean(deposited_power),\n prominence=2)\n return slice(np.max(indices) if indices.size > 0 else -1, None, None)\n\n\ndef plot_electron_beams(*args, **kwargs):\n return field_lines.plot_field_lines(*args, **kwargs)\n\n\ndef plot_electron_beam_properties(*args, **kwargs):\n return field_lines.plot_field_line_properties(*args, **kwargs)\n\n\ndef plot_beam_value_histogram(*args, **kwargs):\n return field_lines.plot_field_line_value_histogram(*args, **kwargs)\n\n\ndef plot_beam_value_histogram_difference(*args, **kwargs):\n return field_lines.plot_field_line_value_histogram_difference(\n *args, **kwargs)\n\n\ndef plot_beam_value_2d_histogram(*args, **kwargs):\n return field_lines.plot_field_line_value_2d_histogram(*args, **kwargs)\n\n\ndef plot_beam_value_2d_histogram_difference(*args, **kwargs):\n return field_lines.plot_field_line_value_2d_histogram_difference(\n *args, **kwargs)\n\n\ndef plot_beam_value_2d_histogram_comparison(*args, **kwargs):\n return field_lines.plot_field_line_value_2d_histogram_comparison(\n *args, **kwargs)\n", "meta": {"hexsha": "072970b93423ba47b79735cc5c26824c05038aef", "size": 29230, "ext": "py", "lang": "Python", "max_stars_repo_path": "backstaff/electron_beams.py", "max_stars_repo_name": "lars-frogner/Backstaff", "max_stars_repo_head_hexsha": "8f500c6044d5b9fb546e2494fdac9ab6430ee4f5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "backstaff/electron_beams.py", "max_issues_repo_name": "lars-frogner/Backstaff", "max_issues_repo_head_hexsha": "8f500c6044d5b9fb546e2494fdac9ab6430ee4f5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "backstaff/electron_beams.py", "max_forks_repo_name": "lars-frogner/Backstaff", "max_forks_repo_head_hexsha": "8f500c6044d5b9fb546e2494fdac9ab6430ee4f5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.6268656716, "max_line_length": 105, "alphanum_fraction": 0.6118371536, "include": true, "reason": "import numpy,import scipy", "num_tokens": 6609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737564, "lm_q2_score": 0.2509127812837603, "lm_q1q2_score": 0.1332872213172127}} {"text": "\"\"\" General framework for parallel tempering MCMC. \"\"\"\r\nimport copy\r\nfrom logging import Logger\r\nimport math\r\nimport numpy as np\r\nimport os\r\nimport random\r\nimport time\r\nfrom typing import List\r\n\r\nfrom rdkit import Chem\r\nfrom rdkit.Chem import AllChem, rdForceFieldHelpers\r\nfrom rdkit.Chem.Lipinski import RotatableBondSmarts\r\n# noinspection PyPackageRequirements\r\nfrom tap import Tap\r\nfrom tqdm import tqdm\r\n\r\nfrom conformation.rdkit_hmc import calc_energy_grad, hmc_step\r\n\r\n\r\nclass Args(Tap):\r\n \"\"\"\r\n System arguments.\r\n \"\"\"\r\n bin_path: str # Path to RDKit binary file containing molecule\r\n max_attempts: int = 10000 # Max number of embedding attempts\r\n num_minimization_iters: int = 0 # Number of minimization steps\r\n temperatures: List[float] = [300, 500] # Temperature ladder, with the first being the target temperature\r\n epsilon: float = 1 # Leapfrog step size in femtoseconds\r\n L: int = 10 # Number of leapfrog steps\r\n num_steps: int = 1 # Number of parallel tempering steps\r\n swap_prob: float = 0.2 # Probability of performing a swap operation on a given step\r\n subsample_frequency: int = 1 # Frequency at which configurations are saved from MH steps\r\n log_frequency: int = 100 # Log frequency\r\n save_dir: str # Path to directory containing output files\r\n\r\n\r\ndef parallel_tempering(args: Args, logger: Logger) -> None:\r\n \"\"\"\r\n Parallel tempering scheme.\r\n :param args: System arguments.\r\n :param logger: System logger.\r\n :return: None.\r\n \"\"\"\r\n # Set up logger\r\n debug, info = logger.debug, logger.info\r\n\r\n # Define constants\r\n k_b = 3.297e-24 # Boltzmann constant in cal/K\r\n avogadro = 6.022e23\r\n args.epsilon *= 1e-15 # Convert to femtoseconds\r\n\r\n # Load molecule\r\n # noinspection PyUnresolvedReferences\r\n mol = Chem.Mol(open(args.bin_path, \"rb\").read())\r\n mol.RemoveAllConformers()\r\n\r\n debug(f'Starting search...')\r\n\r\n # Generate initial conformations\r\n # Here, we consider the variables of interest, q, to effectively be the atomic coordinates\r\n initial_q = copy.deepcopy(mol)\r\n num_atoms = initial_q.GetNumAtoms()\r\n AllChem.EmbedMultipleConfs(initial_q, maxAttempts=args.max_attempts, numConfs=len(args.temperatures), numThreads=0)\r\n AllChem.MMFFOptimizeMoleculeConfs(initial_q, maxIters=args.num_minimization_iters, numThreads=0)\r\n current_q_list = []\r\n for i in range(len(args.temperatures)):\r\n current_q = copy.deepcopy(mol)\r\n c = initial_q.GetConformers()[i]\r\n c.SetId(0)\r\n current_q.AddConformer(c)\r\n current_q_list.append(current_q)\r\n\r\n # Compute force field information\r\n mmff_p = rdForceFieldHelpers.MMFFGetMoleculeProperties(initial_q)\r\n force_field = rdForceFieldHelpers.MMFFGetMoleculeForceField(initial_q, mmff_p)\r\n\r\n # Masses in kg\r\n mass = np.array([mol.GetAtomWithIdx(i).GetMass() / (1000. * avogadro) for i in range(num_atoms)])\r\n\r\n # Add the first conformation to the list\r\n energy, _ = calc_energy_grad(current_q_list[0].GetConformer().GetPositions(), force_field)\r\n all_conformation_molecules = [current_q_list[0]]\r\n\r\n debug(f'Running HMC steps...')\r\n start_time = time.time()\r\n num_internal_accepted = [0]*len(args.temperatures)\r\n num_swap_accepted = [0]*(len(args.temperatures) - 1)\r\n num_swap_attempted = [0]*(len(args.temperatures) - 1)\r\n total_num_swap_accepted = 0\r\n total_swap_attempted = 0\r\n for step in tqdm(range(args.num_steps)):\r\n alpha = random.uniform(0, 1)\r\n if alpha > args.swap_prob:\r\n results = []\r\n for i in range(len(args.temperatures)):\r\n accepted, current_q, current_energy = hmc_step(current_q_list[i], force_field, args.temperatures[i],\r\n k_b, avogadro, mass, num_atoms, args.epsilon, args.L)\r\n results.append([accepted, current_q, current_energy])\r\n\r\n for i in range(len(args.temperatures)):\r\n accepted, current_q, current_energy = results[i]\r\n\r\n if accepted:\r\n current_q_list[i] = current_q # Necessary because Python is pass by object reference!\r\n num_internal_accepted[i] += 1\r\n\r\n if i == 0:\r\n if step % args.subsample_frequency == 0:\r\n all_conformation_molecules.append(current_q)\r\n\r\n elif len(args.temperatures) > 1:\r\n swap_index = random.randint(0, len(args.temperatures) - 2)\r\n energy_k0, _ = calc_energy_grad(current_q_list[swap_index].GetConformer().GetPositions(), force_field)\r\n energy_k0 *= (1000.0 * 4.184 / avogadro)\r\n energy_k1, _ = calc_energy_grad(current_q_list[swap_index + 1].GetConformer().GetPositions(), force_field)\r\n energy_k1 *= (1000.0 * 4.184 / avogadro)\r\n delta_beta = (1./(k_b * args.temperatures[swap_index] * 4.184) -\r\n 1./(k_b * args.temperatures[swap_index + 1] * 4.184))\r\n delta_energy = energy_k0 - energy_k1\r\n delta = delta_beta * delta_energy\r\n\r\n prob_ratio = math.exp(-delta)\r\n mu = random.uniform(0, 1)\r\n if swap_index == 0:\r\n energy, _ = calc_energy_grad(current_q_list[0].GetConformer().GetPositions(), force_field)\r\n if mu <= prob_ratio:\r\n tmp = copy.deepcopy(current_q_list[swap_index])\r\n current_q_list[swap_index] = copy.deepcopy(current_q_list[swap_index + 1])\r\n current_q_list[swap_index + 1] = tmp\r\n num_swap_accepted[swap_index] += 1\r\n total_num_swap_accepted += 1\r\n if swap_index == 0:\r\n if step % args.subsample_frequency == 0:\r\n all_conformation_molecules.append(current_q_list[0])\r\n num_swap_attempted[swap_index] += 1\r\n total_swap_attempted += 1\r\n\r\n if step % args.log_frequency == 0:\r\n for i in range(len(args.temperatures)):\r\n debug(f'% Moves accepted for temperature {args.temperatures[i]}: '\r\n f'{float(num_internal_accepted[i]) / float(step + 1) * 100.0}')\r\n\r\n for i in range(len(args.temperatures) - 1):\r\n if num_swap_attempted[i] == 0:\r\n debug(f'% Moves accepted for swap at base temperature {args.temperatures[i]}: NA')\r\n else:\r\n debug(f'% Moves accepted for swap at base temperature {args.temperatures[i]}: '\r\n f'{float(num_swap_accepted[i]) / num_swap_attempted[i] * 100.0}')\r\n\r\n debug(f'# Swap moves attempted: {total_swap_attempted}')\r\n if total_swap_attempted == 0:\r\n debug(f'% Moves accepted for swap: {0.0}')\r\n debug(f'% Moves accepted for swap: NA')\r\n else:\r\n debug(f'% Moves accepted for swap: '\r\n f'{float(total_num_swap_accepted) / float(total_swap_attempted) * 100.0}')\r\n end_time = time.time()\r\n debug(f'Total Time (s): {end_time - start_time}')\r\n for i in range(len(args.temperatures)):\r\n debug(f'% Moves accepted for temperature {args.temperatures[i]}: '\r\n f'{float(num_internal_accepted[i]) / float(args.num_steps) * 100.0}')\r\n debug(f'# Swap moves attempted: {total_swap_attempted}')\r\n if total_swap_attempted > 0:\r\n debug(f'% Moves accepted for swap: {float(total_num_swap_accepted) / float(total_swap_attempted) * 100.0}')\r\n\r\n # Discover the rotatable bonds\r\n rotatable_bonds = mol.GetSubstructMatches(RotatableBondSmarts)\r\n debug(f'Num rotatable bonds: {len(rotatable_bonds)}')\r\n\r\n # Save all sub sampled conformations in molecule object\r\n # noinspection PyUnresolvedReferences\r\n all_mol = Chem.Mol(open(args.bin_path, \"rb\").read())\r\n all_mol.RemoveAllConformers()\r\n for i in range(len(all_conformation_molecules)):\r\n c = all_conformation_molecules[i].GetConformer()\r\n c.SetId(i)\r\n all_mol.AddConformer(c)\r\n\r\n # Save molecule to binary file\r\n bin_str = all_mol.ToBinary()\r\n with open(os.path.join(args.save_dir, \"conformations.bin\"), \"wb\") as b:\r\n b.write(bin_str)\r\n", "meta": {"hexsha": "49024046215e16fc4e017823991c8e1bb37fb5b4", "size": 8264, "ext": "py", "lang": "Python", "max_stars_repo_path": "conformation/parallel_tempering.py", "max_stars_repo_name": "ks8/conformation", "max_stars_repo_head_hexsha": "f470849d5b7b90dc5a65bab8a536de1d57c1021a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "conformation/parallel_tempering.py", "max_issues_repo_name": "ks8/conformation", "max_issues_repo_head_hexsha": "f470849d5b7b90dc5a65bab8a536de1d57c1021a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conformation/parallel_tempering.py", "max_forks_repo_name": "ks8/conformation", "max_forks_repo_head_hexsha": "f470849d5b7b90dc5a65bab8a536de1d57c1021a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.9130434783, "max_line_length": 120, "alphanum_fraction": 0.6317763795, "include": true, "reason": "import numpy", "num_tokens": 1998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.25982564942392716, "lm_q1q2_score": 0.13295709913826675}} {"text": "# Copyright (c) 2012-2015 The GPy authors (see AUTHORS.txt)\n# Licensed under the BSD 3-clause license (see LICENSE.txt)\n\nimport numpy as np\nfrom scipy import stats,special\nimport scipy as sp\nfrom . import link_functions\nfrom ..util.misc import chain_1, chain_2, chain_3, blockify_dhess_dtheta, blockify_third, blockify_hessian, safe_exp\nfrom scipy.integrate import quad\nimport warnings\nfrom ..core.parameterization import Parameterized\n\nclass Likelihood(Parameterized):\n \"\"\"\n Likelihood base class, used to defing p(y|f).\n\n All instances use _inverse_ link functions, which can be swapped out. It is\n expected that inheriting classes define a default inverse link function\n\n To use this class, inherit and define missing functionality.\n\n Inheriting classes *must* implement:\n pdf_link : a bound method which turns the output of the link function into the pdf\n logpdf_link : the logarithm of the above\n\n To enable use with EP, inheriting classes *must* define:\n TODO: a suitable derivative function for any parameters of the class\n It is also desirable to define:\n moments_match_ep : a function to compute the EP moments If this isn't defined, the moments will be computed using 1D quadrature.\n\n To enable use with Laplace approximation, inheriting classes *must* define:\n Some derivative functions *AS TODO*\n\n For exact Gaussian inference, define *JH TODO*\n\n \"\"\"\n def __init__(self, gp_link, name):\n super(Likelihood, self).__init__(name)\n assert isinstance(gp_link,link_functions.GPTransformation), \"gp_link is not a valid GPTransformation.\"\n self.gp_link = gp_link\n self.log_concave = False\n self.not_block_really = False\n\n def request_num_latent_functions(self, Y):\n \"\"\"\n The likelihood should infer how many latent functions are needed for the likelihood\n\n Default is the number of outputs\n \"\"\"\n return Y.shape[1]\n\n def exact_inference_gradients(self, dL_dKdiag,Y_metadata=None):\n return np.zeros(self.size)\n\n def update_gradients(self, partial):\n if self.size > 0:\n raise NotImplementedError('Must be implemented for likelihoods with parameters to be optimized')\n\n def _preprocess_values(self,Y):\n \"\"\"\n In case it is needed, this function assess the output values or makes any pertinent transformation on them.\n\n :param Y: observed output\n :type Y: Nx1 numpy.darray\n\n \"\"\"\n return Y\n\n def conditional_mean(self, gp):\n \"\"\"\n The mean of the random variable conditioned on one value of the GP\n \"\"\"\n raise NotImplementedError\n\n def conditional_variance(self, gp):\n \"\"\"\n The variance of the random variable conditioned on one value of the GP\n \"\"\"\n raise NotImplementedError\n\n def log_predictive_density(self, y_test, mu_star, var_star, Y_metadata=None):\n \"\"\"\n Calculation of the log predictive density\n\n .. math:\n p(y_{*}|D) = p(y_{*}|f_{*})p(f_{*}|\\mu_{*}\\\\sigma^{2}_{*})\n\n :param y_test: test observations (y_{*})\n :type y_test: (Nx1) array\n :param mu_star: predictive mean of gaussian p(f_{*}|mu_{*}, var_{*})\n :type mu_star: (Nx1) array\n :param var_star: predictive variance of gaussian p(f_{*}|mu_{*}, var_{*})\n :type var_star: (Nx1) array\n \"\"\"\n assert y_test.shape==mu_star.shape\n assert y_test.shape==var_star.shape\n assert y_test.shape[1] == 1\n\n flat_y_test = y_test.flatten()\n flat_mu_star = mu_star.flatten()\n flat_var_star = var_star.flatten()\n\n if Y_metadata is not None:\n #Need to zip individual elements of Y_metadata aswell\n Y_metadata_flat = {}\n if Y_metadata is not None:\n for key, val in Y_metadata.items():\n Y_metadata_flat[key] = np.atleast_1d(val).reshape(-1,1)\n\n zipped_values = []\n\n for i in range(y_test.shape[0]):\n y_m = {}\n for key, val in Y_metadata_flat.items():\n if np.isscalar(val) or val.shape[0] == 1:\n y_m[key] = val\n else:\n #Won't broadcast yet\n y_m[key] = val[i]\n zipped_values.append((flat_y_test[i], flat_mu_star[i], flat_var_star[i], y_m))\n else:\n #Otherwise just pass along None's\n zipped_values = zip(flat_y_test, flat_mu_star, flat_var_star, [None]*y_test.shape[0])\n\n def integral_generator(yi, mi, vi, yi_m):\n \"\"\"Generate a function which can be integrated\n to give p(Y*|Y) = int p(Y*|f*)p(f*|Y) df*\"\"\"\n def f(fi_star):\n #exponent = np.exp(-(1./(2*vi))*np.square(mi-fi_star))\n #from GPy.util.misc import safe_exp\n #exponent = safe_exp(exponent)\n #res = safe_exp(self.logpdf(fi_star, yi, yi_m))*exponent\n\n #More stable in the log space\n res = np.exp(self.logpdf(fi_star, yi, yi_m)\n - 0.5*np.log(2*np.pi*vi)\n - 0.5*np.square(fi_star-mi)/vi)\n if not np.isfinite(res):\n import ipdb; ipdb.set_trace() # XXX BREAKPOINT\n return res\n\n return f\n\n p_ystar, _ = zip(*[quad(integral_generator(yi, mi, vi, yi_m), -np.inf, np.inf)\n for yi, mi, vi, yi_m in zipped_values])\n p_ystar = np.array(p_ystar).reshape(*y_test.shape)\n return np.log(p_ystar)\n\n def log_predictive_density_sampling(self, y_test, mu_star, var_star, Y_metadata=None, num_samples=1000):\n \"\"\"\n Calculation of the log predictive density via sampling\n\n .. math:\n log p(y_{*}|D) = log 1/num_samples prod^{S}_{s=1} p(y_{*}|f_{*s})\n f_{*s} ~ p(f_{*}|\\mu_{*}\\\\sigma^{2}_{*})\n\n :param y_test: test observations (y_{*})\n :type y_test: (Nx1) array\n :param mu_star: predictive mean of gaussian p(f_{*}|mu_{*}, var_{*})\n :type mu_star: (Nx1) array\n :param var_star: predictive variance of gaussian p(f_{*}|mu_{*}, var_{*})\n :type var_star: (Nx1) array\n :param num_samples: num samples of p(f_{*}|mu_{*}, var_{*}) to take\n :type num_samples: int\n \"\"\"\n assert y_test.shape==mu_star.shape\n assert y_test.shape==var_star.shape\n assert y_test.shape[1] == 1\n\n #Take samples of p(f*|y)\n #fi_samples = np.random.randn(num_samples)*np.sqrt(var_star) + mu_star\n fi_samples = np.random.normal(mu_star, np.sqrt(var_star), size=(mu_star.shape[0], num_samples))\n\n from scipy.misc import logsumexp\n log_p_ystar = -np.log(num_samples) + logsumexp(self.logpdf(fi_samples, y_test, Y_metadata=Y_metadata), axis=1)\n log_p_ystar = np.array(log_p_ystar).reshape(*y_test.shape)\n return log_p_ystar\n\n def moments_match_ep(self,obs,tau,v,Y_metadata_i=None):\n \"\"\"\n Calculation of moments using quadrature\n\n :param obs: observed output\n :param tau: cavity distribution 1st natural parameter (precision)\n :param v: cavity distribution 2nd natural paramenter (mu*precision)\n \"\"\"\n #Compute first integral for zeroth moment.\n #NOTE constant np.sqrt(2*pi/tau) added at the end of the function\n mu = v/tau\n sigma2 = 1./tau\n #Lets do these for now based on the same idea as Gaussian quadrature\n # i.e. multiply anything by close to zero, and its zero.\n f_min = mu - 20*np.sqrt(sigma2)\n f_max = mu + 20*np.sqrt(sigma2)\n\n def int_1(f):\n return self.pdf(f, obs, Y_metadata=Y_metadata_i)*np.exp(-0.5*tau*np.square(mu-f))\n z_scaled, accuracy = quad(int_1, f_min, f_max)\n\n #Compute second integral for first moment\n def int_2(f):\n return f*self.pdf(f, obs, Y_metadata=Y_metadata_i)*np.exp(-0.5*tau*np.square(mu-f))\n mean, accuracy = quad(int_2, f_min, f_max)\n mean /= z_scaled\n\n #Compute integral for variance\n def int_3(f):\n return (f**2)*self.pdf(f, obs, Y_metadata=Y_metadata_i)*np.exp(-0.5*tau*np.square(mu-f))\n Ef2, accuracy = quad(int_3, f_min, f_max)\n Ef2 /= z_scaled\n variance = Ef2 - mean**2\n\n #Add constant to the zeroth moment\n #NOTE: this constant is not needed in the other moments because it cancells out.\n z = z_scaled/np.sqrt(2*np.pi/tau)\n\n return z, mean, variance\n\n #only compute gh points if required\n __gh_points = None\n def _gh_points(self, T=20):\n if self.__gh_points is None:\n self.__gh_points = np.polynomial.hermite.hermgauss(T)\n return self.__gh_points\n\n def variational_expectations(self, Y, m, v, gh_points=None, Y_metadata=None):\n \"\"\"\n Use Gauss-Hermite Quadrature to compute\n\n E_p(f) [ log p(y|f) ]\n d/dm E_p(f) [ log p(y|f) ]\n d/dv E_p(f) [ log p(y|f) ]\n\n where p(f) is a Gaussian with mean m and variance v. The shapes of Y, m and v should match.\n\n if no gh_points are passed, we construct them using defualt options\n \"\"\"\n\n if gh_points is None:\n gh_x, gh_w = self._gh_points()\n else:\n gh_x, gh_w = gh_points\n\n shape = m.shape\n m,v,Y = m.flatten(), v.flatten(), Y.flatten()\n\n #make a grid of points\n X = gh_x[None,:]*np.sqrt(2.*v[:,None]) + m[:,None]\n\n #evaluate the likelhood for the grid. First ax indexes the data (and mu, var) and the second indexes the grid.\n # broadcast needs to be handled carefully.\n logp = self.logpdf(X,Y[:,None], Y_metadata=Y_metadata)\n dlogp_dx = self.dlogpdf_df(X, Y[:,None], Y_metadata=Y_metadata)\n d2logp_dx2 = self.d2logpdf_df2(X, Y[:,None], Y_metadata=Y_metadata)\n\n #clipping for numerical stability\n #logp = np.clip(logp,-1e9,1e9)\n #dlogp_dx = np.clip(dlogp_dx,-1e9,1e9)\n #d2logp_dx2 = np.clip(d2logp_dx2,-1e9,1e9)\n\n #average over the gird to get derivatives of the Gaussian's parameters\n #division by pi comes from fact that for each quadrature we need to scale by 1/sqrt(pi)\n F = np.dot(logp, gh_w)/np.sqrt(np.pi)\n dF_dm = np.dot(dlogp_dx, gh_w)/np.sqrt(np.pi)\n dF_dv = np.dot(d2logp_dx2, gh_w)/np.sqrt(np.pi)\n dF_dv /= 2.\n\n if np.any(np.isnan(dF_dv)) or np.any(np.isinf(dF_dv)):\n stop\n if np.any(np.isnan(dF_dm)) or np.any(np.isinf(dF_dm)):\n stop\n\n if self.size:\n dF_dtheta = self.dlogpdf_dtheta(X, Y[:,None], Y_metadata=Y_metadata) # Ntheta x (orig size) x N_{quad_points}\n dF_dtheta = np.dot(dF_dtheta, gh_w)/np.sqrt(np.pi)\n dF_dtheta = dF_dtheta.reshape(self.size, shape[0], shape[1])\n else:\n dF_dtheta = None # Not yet implemented\n return F.reshape(*shape), dF_dm.reshape(*shape), dF_dv.reshape(*shape), dF_dtheta\n\n def predictive_mean(self, mu, variance, Y_metadata=None):\n \"\"\"\n Quadrature calculation of the predictive mean: E(Y_star|Y) = E( E(Y_star|f_star, Y) )\n\n :param mu: mean of posterior\n :param sigma: standard deviation of posterior\n\n \"\"\"\n #conditional_mean: the edpected value of y given some f, under this likelihood\n fmin = -np.inf\n fmax = np.inf\n def int_mean(f,m,v):\n exponent = -(0.5/v)*np.square(f - m)\n #If exponent is under -30 then exp(exponent) will be very small, so don't exp it!)\n #If p is zero then conditional_mean will overflow\n assert v.all() > 0\n p = safe_exp(exponent)\n\n #If p is zero then conditional_variance will overflow\n if p < 1e-10:\n return 0.\n else:\n return self.conditional_mean(f)*p\n scaled_mean = [quad(int_mean, fmin, fmax,args=(mj,s2j))[0] for mj,s2j in zip(mu,variance)]\n mean = np.array(scaled_mean)[:,None] / np.sqrt(2*np.pi*(variance))\n return mean\n\n def predictive_variance(self, mu,variance, predictive_mean=None, Y_metadata=None):\n \"\"\"\n Approximation to the predictive variance: V(Y_star)\n\n The following variance decomposition is used:\n V(Y_star) = E( V(Y_star|f_star)**2 ) + V( E(Y_star|f_star) )**2\n\n :param mu: mean of posterior\n :param sigma: standard deviation of posterior\n :predictive_mean: output's predictive mean, if None _predictive_mean function will be called.\n\n \"\"\"\n #sigma2 = sigma**2\n normalizer = np.sqrt(2*np.pi*variance)\n\n fmin_v = -np.inf\n fmin_m = np.inf\n fmin = -np.inf\n fmax = np.inf\n\n from ..util.misc import safe_exp\n # E( V(Y_star|f_star) )\n def int_var(f,m,v):\n exponent = -(0.5/v)*np.square(f - m)\n p = safe_exp(exponent)\n #If p is zero then conditional_variance will overflow\n if p < 1e-10:\n return 0.\n else:\n return self.conditional_variance(f)*p\n scaled_exp_variance = [quad(int_var, fmin_v, fmax,args=(mj,s2j))[0] for mj,s2j in zip(mu,variance)]\n exp_var = np.array(scaled_exp_variance)[:,None] / normalizer\n\n #V( E(Y_star|f_star) ) = E( E(Y_star|f_star)**2 ) - E( E(Y_star|f_star) )**2\n\n #E( E(Y_star|f_star) )**2\n if predictive_mean is None:\n predictive_mean = self.predictive_mean(mu,variance)\n predictive_mean_sq = predictive_mean**2\n\n #E( E(Y_star|f_star)**2 )\n def int_pred_mean_sq(f,m,v,predictive_mean_sq):\n exponent = -(0.5/v)*np.square(f - m)\n p = np.exp(exponent)\n #If p is zero then conditional_mean**2 will overflow\n if p < 1e-10:\n return 0.\n else:\n return self.conditional_mean(f)**2*p\n\n scaled_exp_exp2 = [quad(int_pred_mean_sq, fmin_m, fmax,args=(mj,s2j,pm2j))[0] for mj,s2j,pm2j in zip(mu,variance,predictive_mean_sq)]\n exp_exp2 = np.array(scaled_exp_exp2)[:,None] / normalizer\n\n var_exp = exp_exp2 - predictive_mean_sq\n\n # V(Y_star) = E[ V(Y_star|f_star) ] + V[ E(Y_star|f_star) ]\n # V(Y_star) = E[ V(Y_star|f_star) ] + E(Y_star**2|f_star) - E[Y_star|f_star]**2\n return exp_var + var_exp\n\n def pdf_link(self, inv_link_f, y, Y_metadata=None):\n raise NotImplementedError\n\n def logpdf_link(self, inv_link_f, y, Y_metadata=None):\n raise NotImplementedError\n\n def dlogpdf_dlink(self, inv_link_f, y, Y_metadata=None):\n raise NotImplementedError\n\n def d2logpdf_dlink2(self, inv_link_f, y, Y_metadata=None):\n raise NotImplementedError\n\n def d3logpdf_dlink3(self, inv_link_f, y, Y_metadata=None):\n raise NotImplementedError\n\n def dlogpdf_link_dtheta(self, inv_link_f, y, Y_metadata=None):\n raise NotImplementedError\n\n def dlogpdf_dlink_dtheta(self, inv_link_f, y, Y_metadata=None):\n raise NotImplementedError\n\n def d2logpdf_dlink2_dtheta(self, inv_link_f, y, Y_metadata=None):\n raise NotImplementedError\n\n def pdf(self, f, y, Y_metadata=None):\n \"\"\"\n Evaluates the link function link(f) then computes the likelihood (pdf) using it\n\n .. math:\n p(y|\\\\lambda(f))\n\n :param f: latent variables f\n :type f: Nx1 array\n :param y: data\n :type y: Nx1 array\n :param Y_metadata: Y_metadata which is not used in student t distribution - not used\n :returns: likelihood evaluated for this point\n :rtype: float\n \"\"\"\n if isinstance(self.gp_link, link_functions.Identity):\n return self.pdf_link(f, y, Y_metadata=Y_metadata)\n else:\n inv_link_f = self.gp_link.transf(f)\n return self.pdf_link(inv_link_f, y, Y_metadata=Y_metadata)\n\n def logpdf_sum(self, f, y, Y_metadata=None):\n \"\"\"\n Convenience function that can overridden for functions where this could\n be computed more efficiently\n \"\"\"\n return np.sum(self.logpdf(f, y, Y_metadata=Y_metadata))\n\n def logpdf(self, f, y, Y_metadata=None):\n \"\"\"\n Evaluates the link function link(f) then computes the log likelihood (log pdf) using it\n\n .. math:\n \\\\log p(y|\\\\lambda(f))\n\n :param f: latent variables f\n :type f: Nx1 array\n :param y: data\n :type y: Nx1 array\n :param Y_metadata: Y_metadata which is not used in student t distribution - not used\n :returns: log likelihood evaluated for this point\n :rtype: float\n \"\"\"\n if isinstance(self.gp_link, link_functions.Identity):\n return self.logpdf_link(f, y, Y_metadata=Y_metadata)\n else:\n inv_link_f = self.gp_link.transf(f)\n return self.logpdf_link(inv_link_f, y, Y_metadata=Y_metadata)\n\n def dlogpdf_df(self, f, y, Y_metadata=None):\n \"\"\"\n Evaluates the link function link(f) then computes the derivative of log likelihood using it\n Uses the Faa di Bruno's formula for the chain rule\n\n .. math::\n \\\\frac{d\\\\log p(y|\\\\lambda(f))}{df} = \\\\frac{d\\\\log p(y|\\\\lambda(f))}{d\\\\lambda(f)}\\\\frac{d\\\\lambda(f)}{df}\n\n :param f: latent variables f\n :type f: Nx1 array\n :param y: data\n :type y: Nx1 array\n :param Y_metadata: Y_metadata which is not used in student t distribution - not used\n :returns: derivative of log likelihood evaluated for this point\n :rtype: 1xN array\n \"\"\"\n if isinstance(self.gp_link, link_functions.Identity):\n return self.dlogpdf_dlink(f, y, Y_metadata=Y_metadata)\n else:\n inv_link_f = self.gp_link.transf(f)\n dlogpdf_dlink = self.dlogpdf_dlink(inv_link_f, y, Y_metadata=Y_metadata)\n dlink_df = self.gp_link.dtransf_df(f)\n return chain_1(dlogpdf_dlink, dlink_df)\n\n @blockify_hessian\n def d2logpdf_df2(self, f, y, Y_metadata=None):\n \"\"\"\n Evaluates the link function link(f) then computes the second derivative of log likelihood using it\n Uses the Faa di Bruno's formula for the chain rule\n\n .. math::\n \\\\frac{d^{2}\\\\log p(y|\\\\lambda(f))}{df^{2}} = \\\\frac{d^{2}\\\\log p(y|\\\\lambda(f))}{d^{2}\\\\lambda(f)}\\\\left(\\\\frac{d\\\\lambda(f)}{df}\\\\right)^{2} + \\\\frac{d\\\\log p(y|\\\\lambda(f))}{d\\\\lambda(f)}\\\\frac{d^{2}\\\\lambda(f)}{df^{2}}\n\n :param f: latent variables f\n :type f: Nx1 array\n :param y: data\n :type y: Nx1 array\n :param Y_metadata: Y_metadata which is not used in student t distribution - not used\n :returns: second derivative of log likelihood evaluated for this point (diagonal only)\n :rtype: 1xN array\n \"\"\"\n if isinstance(self.gp_link, link_functions.Identity):\n d2logpdf_df2 = self.d2logpdf_dlink2(f, y, Y_metadata=Y_metadata)\n else:\n inv_link_f = self.gp_link.transf(f)\n d2logpdf_dlink2 = self.d2logpdf_dlink2(inv_link_f, y, Y_metadata=Y_metadata)\n dlink_df = self.gp_link.dtransf_df(f)\n dlogpdf_dlink = self.dlogpdf_dlink(inv_link_f, y, Y_metadata=Y_metadata)\n d2link_df2 = self.gp_link.d2transf_df2(f)\n d2logpdf_df2 = chain_2(d2logpdf_dlink2, dlink_df, dlogpdf_dlink, d2link_df2)\n return d2logpdf_df2\n\n @blockify_third\n def d3logpdf_df3(self, f, y, Y_metadata=None):\n \"\"\"\n Evaluates the link function link(f) then computes the third derivative of log likelihood using it\n Uses the Faa di Bruno's formula for the chain rule\n\n .. math::\n \\\\frac{d^{3}\\\\log p(y|\\\\lambda(f))}{df^{3}} = \\\\frac{d^{3}\\\\log p(y|\\\\lambda(f)}{d\\\\lambda(f)^{3}}\\\\left(\\\\frac{d\\\\lambda(f)}{df}\\\\right)^{3} + 3\\\\frac{d^{2}\\\\log p(y|\\\\lambda(f)}{d\\\\lambda(f)^{2}}\\\\frac{d\\\\lambda(f)}{df}\\\\frac{d^{2}\\\\lambda(f)}{df^{2}} + \\\\frac{d\\\\log p(y|\\\\lambda(f)}{d\\\\lambda(f)}\\\\frac{d^{3}\\\\lambda(f)}{df^{3}}\n\n :param f: latent variables f\n :type f: Nx1 array\n :param y: data\n :type y: Nx1 array\n :param Y_metadata: Y_metadata which is not used in student t distribution - not used\n :returns: third derivative of log likelihood evaluated for this point\n :rtype: float\n \"\"\"\n if isinstance(self.gp_link, link_functions.Identity):\n d3logpdf_df3 = self.d3logpdf_dlink3(f, y, Y_metadata=Y_metadata)\n else:\n inv_link_f = self.gp_link.transf(f)\n d3logpdf_dlink3 = self.d3logpdf_dlink3(inv_link_f, y, Y_metadata=Y_metadata)\n dlink_df = self.gp_link.dtransf_df(f)\n d2logpdf_dlink2 = self.d2logpdf_dlink2(inv_link_f, y, Y_metadata=Y_metadata)\n d2link_df2 = self.gp_link.d2transf_df2(f)\n dlogpdf_dlink = self.dlogpdf_dlink(inv_link_f, y, Y_metadata=Y_metadata)\n d3link_df3 = self.gp_link.d3transf_df3(f)\n d3logpdf_df3 = chain_3(d3logpdf_dlink3, dlink_df, d2logpdf_dlink2, d2link_df2, dlogpdf_dlink, d3link_df3)\n return d3logpdf_df3\n\n\n def dlogpdf_dtheta(self, f, y, Y_metadata=None):\n \"\"\"\n TODO: Doc strings\n \"\"\"\n if self.size > 0:\n if self.not_block_really:\n raise NotImplementedError(\"Need to make a decorator for this!\")\n if isinstance(self.gp_link, link_functions.Identity):\n return self.dlogpdf_link_dtheta(f, y, Y_metadata=Y_metadata)\n else:\n inv_link_f = self.gp_link.transf(f)\n return self.dlogpdf_link_dtheta(inv_link_f, y, Y_metadata=Y_metadata)\n else:\n # There are no parameters so return an empty array for derivatives\n return np.zeros((0, f.shape[0], f.shape[1]))\n\n def dlogpdf_df_dtheta(self, f, y, Y_metadata=None):\n \"\"\"\n TODO: Doc strings\n \"\"\"\n if self.size > 0:\n if self.not_block_really:\n raise NotImplementedError(\"Need to make a decorator for this!\")\n if isinstance(self.gp_link, link_functions.Identity):\n return self.dlogpdf_dlink_dtheta(f, y, Y_metadata=Y_metadata)\n else:\n inv_link_f = self.gp_link.transf(f)\n dlink_df = self.gp_link.dtransf_df(f)\n dlogpdf_dlink_dtheta = self.dlogpdf_dlink_dtheta(inv_link_f, y, Y_metadata=Y_metadata)\n\n dlogpdf_df_dtheta = np.zeros((self.size, f.shape[0], f.shape[1]))\n #Chain each parameter of hte likelihood seperately\n for p in range(self.size):\n dlogpdf_df_dtheta[p, :, :] = chain_1(dlogpdf_dlink_dtheta[p,:,:], dlink_df)\n return dlogpdf_df_dtheta\n #return chain_1(dlogpdf_dlink_dtheta, dlink_df)\n else:\n # There are no parameters so return an empty array for derivatives\n return np.zeros((0, f.shape[0], f.shape[1]))\n\n def d2logpdf_df2_dtheta(self, f, y, Y_metadata=None):\n \"\"\"\n TODO: Doc strings\n \"\"\"\n if self.size > 0:\n if self.not_block_really:\n raise NotImplementedError(\"Need to make a decorator for this!\")\n if isinstance(self.gp_link, link_functions.Identity):\n return self.d2logpdf_dlink2_dtheta(f, y, Y_metadata=Y_metadata)\n else:\n inv_link_f = self.gp_link.transf(f)\n dlink_df = self.gp_link.dtransf_df(f)\n d2link_df2 = self.gp_link.d2transf_df2(f)\n d2logpdf_dlink2_dtheta = self.d2logpdf_dlink2_dtheta(inv_link_f, y, Y_metadata=Y_metadata)\n dlogpdf_dlink_dtheta = self.dlogpdf_dlink_dtheta(inv_link_f, y, Y_metadata=Y_metadata)\n\n d2logpdf_df2_dtheta = np.zeros((self.size, f.shape[0], f.shape[1]))\n #Chain each parameter of hte likelihood seperately\n for p in range(self.size):\n d2logpdf_df2_dtheta[p, :, :] = chain_2(d2logpdf_dlink2_dtheta[p,:,:], dlink_df, dlogpdf_dlink_dtheta[p,:,:], d2link_df2)\n return d2logpdf_df2_dtheta\n #return chain_2(d2logpdf_dlink2_dtheta, dlink_df, dlogpdf_dlink_dtheta, d2link_df2)\n else:\n # There are no parameters so return an empty array for derivatives\n return np.zeros((0, f.shape[0], f.shape[1]))\n\n def _laplace_gradients(self, f, y, Y_metadata=None):\n dlogpdf_dtheta = self.dlogpdf_dtheta(f, y, Y_metadata=Y_metadata)\n dlogpdf_df_dtheta = self.dlogpdf_df_dtheta(f, y, Y_metadata=Y_metadata)\n d2logpdf_df2_dtheta = self.d2logpdf_df2_dtheta(f, y, Y_metadata=Y_metadata)\n\n #Parameters are stacked vertically. Must be listed in same order as 'get_param_names'\n # ensure we have gradients for every parameter we want to optimize\n assert dlogpdf_dtheta.shape[0] == self.size #num_param array x f, d\n assert dlogpdf_df_dtheta.shape[0] == self.size #num_param x f x d x matrix or just num_param x f\n assert d2logpdf_df2_dtheta.shape[0] == self.size #num_param x f matrix or num_param x f x d x matrix, num_param x f x f or num_param x f x f x d\n\n return dlogpdf_dtheta, dlogpdf_df_dtheta, d2logpdf_df2_dtheta\n\n def predictive_values(self, mu, var, full_cov=False, Y_metadata=None):\n \"\"\"\n Compute mean, variance of the predictive distibution.\n\n :param mu: mean of the latent variable, f, of posterior\n :param var: variance of the latent variable, f, of posterior\n :param full_cov: whether to use the full covariance or just the diagonal\n :type full_cov: Boolean\n \"\"\"\n try:\n pred_mean = self.predictive_mean(mu, var, Y_metadata=Y_metadata)\n pred_var = self.predictive_variance(mu, var, pred_mean, Y_metadata=Y_metadata)\n except NotImplementedError:\n print(\"Finding predictive mean and variance via sampling rather than quadrature\")\n Nf_samp = 300\n Ny_samp = 1\n s = np.random.randn(mu.shape[0], Nf_samp)*np.sqrt(var) + mu\n ss_y = self.samples(s, Y_metadata, samples=Ny_samp)\n pred_mean = np.mean(ss_y, axis=1)[:, None]\n pred_var = np.var(ss_y, axis=1)[:, None]\n\n return pred_mean, pred_var\n\n def predictive_quantiles(self, mu, var, quantiles, Y_metadata=None):\n #compute the quantiles by sampling!!!\n Nf_samp = 300\n Ny_samp = 1\n s = np.random.randn(mu.shape[0], Nf_samp)*np.sqrt(var) + mu\n ss_y = self.samples(s, Y_metadata)#, samples=Ny_samp)\n #ss_y = ss_y.reshape(mu.shape[0], mu.shape[1], Nf_samp*Ny_samp)\n\n pred_quantiles = [np.percentile(ss_y, q, axis=1)[:,None] for q in quantiles]\n return pred_quantiles\n\n def samples(self, gp, Y_metadata=None, samples=1):\n \"\"\"\n Returns a set of samples of observations based on a given value of the latent variable.\n\n :param gp: latent variable\n :param samples: number of samples to take for each f location\n \"\"\"\n raise NotImplementedError(\"\"\"May be possible to use MCMC with user-tuning, see\n MCMC_pdf_samples in likelihood.py and write samples function\n using this, beware this is a simple implementation\n of Metropolis and will not work well for all likelihoods\"\"\")\n\n def MCMC_pdf_samples(self, fNew, num_samples=1000, starting_loc=None, stepsize=0.1, burn_in=1000, Y_metadata=None):\n \"\"\"\n Simple implementation of Metropolis sampling algorithm\n\n Will run a parallel chain for each input dimension (treats each f independently)\n Thus assumes f*_1 independant of f*_2 etc.\n\n :param num_samples: Number of samples to take\n :param fNew: f at which to sample around\n :param starting_loc: Starting locations of the independant chains (usually will be conditional_mean of likelihood), often link_f\n :param stepsize: Stepsize for the normal proposal distribution (will need modifying)\n :param burnin: number of samples to use for burnin (will need modifying)\n :param Y_metadata: Y_metadata for pdf\n \"\"\"\n print(\"Warning, using MCMC for sampling y*, needs to be tuned!\")\n if starting_loc is None:\n starting_loc = fNew\n from functools import partial\n logpdf = partial(self.logpdf, f=fNew, Y_metadata=Y_metadata)\n pdf = lambda y_star: np.exp(logpdf(y=y_star[:, None]))\n #Should be the link function of f is a good starting point\n #(i.e. the point before you corrupt it with the likelihood)\n par_chains = starting_loc.shape[0]\n chain_values = np.zeros((par_chains, num_samples))\n chain_values[:, 0][:,None] = starting_loc\n #Use same stepsize for all par_chains\n stepsize = np.ones(par_chains)*stepsize\n accepted = np.zeros((par_chains, num_samples+burn_in))\n accept_ratio = np.zeros(num_samples+burn_in)\n #Whilst burning in, only need to keep the previous lot\n burnin_cache = np.zeros(par_chains)\n burnin_cache[:] = starting_loc.flatten()\n burning_in = True\n for i in xrange(burn_in+num_samples):\n next_ind = i-burn_in\n if burning_in:\n old_y = burnin_cache\n else:\n old_y = chain_values[:,next_ind-1]\n\n old_lik = pdf(old_y)\n #Propose new y from Gaussian proposal\n new_y = np.random.normal(loc=old_y, scale=stepsize)\n new_lik = pdf(new_y)\n #Accept using Metropolis (not hastings) acceptance\n #Always accepts if new_lik > old_lik\n accept_probability = np.minimum(1, new_lik/old_lik)\n u = np.random.uniform(0,1,par_chains)\n #print \"Accept prob: \", accept_probability\n accepts = u < accept_probability\n if burning_in:\n burnin_cache[accepts] = new_y[accepts]\n burnin_cache[~accepts] = old_y[~accepts]\n if i == burn_in:\n burning_in = False\n chain_values[:,0] = burnin_cache\n else:\n #If it was accepted then new_y becomes the latest sample\n chain_values[accepts, next_ind] = new_y[accepts]\n #Otherwise use old y as the sample\n chain_values[~accepts, next_ind] = old_y[~accepts]\n\n accepted[~accepts, i] = 0\n accepted[accepts, i] = 1\n accept_ratio[i] = np.sum(accepted[:,i])/float(par_chains)\n\n #Show progress\n if i % int((burn_in+num_samples)*0.1) == 0:\n print(\"{}% of samples taken ({})\".format((i/int((burn_in+num_samples)*0.1)*10), i))\n print(\"Last run accept ratio: \", accept_ratio[i])\n\n print(\"Average accept ratio: \", np.mean(accept_ratio))\n return chain_values\n", "meta": {"hexsha": "78f72d9d3be6454c9ba4eec6a0857cde16530c2d", "size": 31108, "ext": "py", "lang": "Python", "max_stars_repo_path": "gaussian_processes/GPy_1_0_5/likelihoods/likelihood.py", "max_stars_repo_name": "highlandenergy/no-covid-19-climate-silver-lining-in-the-us-power-sector", "max_stars_repo_head_hexsha": "1568db61f4cfd5d1aa3ffc65ce594ad8fe5e3893", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gaussian_processes/GPy_1_0_5/likelihoods/likelihood.py", "max_issues_repo_name": "highlandenergy/no-covid-19-climate-silver-lining-in-the-us-power-sector", "max_issues_repo_head_hexsha": "1568db61f4cfd5d1aa3ffc65ce594ad8fe5e3893", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gaussian_processes/GPy_1_0_5/likelihoods/likelihood.py", "max_forks_repo_name": "highlandenergy/no-covid-19-climate-silver-lining-in-the-us-power-sector", "max_forks_repo_head_hexsha": "1568db61f4cfd5d1aa3ffc65ce594ad8fe5e3893", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.145631068, "max_line_length": 344, "alphanum_fraction": 0.6141185547, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 8070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.2598256322295121, "lm_q1q2_score": 0.1329570903395991}} {"text": "#!/usr/bin/env python\n\"\"\"\nCopyright (c) 2002-2009 William H. Green and the CanTherm Team\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\n\nimport sys\nimport readGeomFc\nimport pdb\nimport math\nfrom numpy import *\nfrom scipy import *\n\nclass CanTherm:\n CalcType = ''\n ReacType = ''\n Temp = []\n MoleculeList = []\n Entropy = []\n Thermal = []\n Cp = []\n scale = 0.0\n #CBSQB3 E for H, N, O, C, P\n atomE = {'H':-0.499818 , 'N':-54.520543 , 'O':-74.987624 , 'C':-37.785385 , 'P':-340.817186}\n #expt H contains H + TC + SOC (spin orbital correction)\n atomH = {'H':50.62 , 'N':111.49 , 'O':58.163 , 'C':169.8147 }\n #BAC for C-H C-C C=C C.TB.C O-H C-O C=O\n bondC = [-0.11, -0.3, -0.08, -0.64, 0.02, 0.33, 0.55]\n\n\n\ndef main():\n data = CanTherm()\n inputFile = open(sys.argv[1],'r') \n readGeomFc.readInputFile(inputFile,data)\n \n mol = data.MoleculeList[0]\n symm = mol.extSymm\n Mass = mol.Mass\n geom = mol.geom\n\n print \"NearProlateP\"\n print \"NElecStatesD\"\n print \"1\"\n print \"ElecStatesL\"\n print mol.nelec,\" , 0.0D0\"\n print \"NModesD\"\n print len(mol.Freq), \" ,0.99\"\n print \"ModesL\"\n for i in range(len(mol.Freq)/3+1):\n for j in range(3):\n if 3*i+j 0 and lines[stop-1].strip() == \"\":\n stop -= 1\n ilines = iter(lines[:stop])\n # read XCFG header\n for line in ilines:\n p_nl += 1\n stripped_line = line.strip()\n # blank lines and lines starting with # are ignored\n if stripped_line == \"\" or line[0] == '#':\n continue\n elif xcfg_Number_of_particles is None:\n if line.find(\"Number of particles =\") != 0:\n emsg = (\"%d: first line must \" +\n \"contain 'Number of particles ='\") % p_nl\n raise StructureFormatError(emsg)\n xcfg_Number_of_particles = int(line[21:].split(None, 1)[0])\n p_natoms = xcfg_Number_of_particles\n elif line.find(\"A =\") == 0:\n xcfg_A = float(line[3:].split(None, 1)[0])\n elif line.find(\"H0(\") == 0:\n i, j = ( int(line[3])-1 , int(line[5])-1 )\n xcfg_H0[i,j] = float(line[10:].split(None, 1)[0])\n xcfg_H0_set[i,j] = True\n elif line.find(\".NO_VELOCITY.\") == 0:\n xcfg_NO_VELOCITY = True\n elif line.find(\"entry_count =\") == 0:\n xcfg_entry_count = int(line[13:].split(None, 1)[0])\n elif p_auxiliary_re.match(line):\n m = p_auxiliary_re.match(line)\n idx = int(m.group(1))\n p_auxiliary[idx] = line[m.end():].split(None, 1)[0]\n else:\n break\n # check header for consistency\n if numpy.any(xcfg_H0_set == False):\n emsg = \"H0 tensor is not properly defined\"\n raise StructureFormatError(emsg)\n p_auxnum = len(p_auxiliary) and max(p_auxiliary.keys())+1\n for i in range(p_auxnum):\n if not i in p_auxiliary:\n p_auxiliary[i] = \"aux%d\" % i\n sorted_aux_keys = p_auxiliary.keys()\n sorted_aux_keys.sort()\n if p_auxnum != 0:\n stru.xcfg = {\n 'auxiliaries' : [ p_auxiliary[k]\n for k in sorted_aux_keys ]\n }\n if 6-3*xcfg_NO_VELOCITY+len(p_auxiliary) != xcfg_entry_count:\n emsg = (\"%d: auxiliary fields \" +\n \"not consistent with entry_count\") % p_nl\n raise StructureFormatError(emsg)\n # define proper lattice\n stru.lattice.setLatBase(xcfg_H0)\n # build p_assign_atom function to assign entries to proper fields\n p_exprs = [ \"a.xyz[0]=fields[0]\",\n \"a.xyz[1]=fields[1]\",\n \"a.xyz[2]=fields[2]\" ]\n if not xcfg_NO_VELOCITY:\n p_exprs += [ \"a.v=numpy.zeros(3, dtype=float)\",\n \"a.v[0]=fields[3]\",\n \"a.v[1]=fields[4]\",\n \"a.v[2]=fields[5]\" ]\n for idx in sorted_aux_keys:\n prop = p_auxiliary[idx]\n col = idx + 6 - 3*xcfg_NO_VELOCITY\n if prop == \"Uiso\":\n p_exprs.append(\"a.U[0,0]=a.U[1,1]=a.U[2,2]=\" +\n \"fields[%d]\" % col)\n elif re.match(r\"^U\\d\\d$\", prop) \\\n and 1<=int(prop[1])<=3 and 1<=int(prop[2])<=3 :\n i, j = int(prop[1])-1, int(prop[2])-1\n if i==j:\n p_exprs.append(\"a.U[%i,%i]=fields[%d]\" % (i, j, col) )\n else:\n p_exprs.append(\"a.U[%i,%i]=a.U[%i,%i]=fields[%d]\" % \\\n (i, j, j, i, col) )\n else:\n p_exprs.append( \"a.__dict__[%r]=fields[%d]\" % \\\n (prop, col) )\n p_assign_expr = \"pass; \" + \"; \".join(p_exprs[3:])\n exec \"def p_assign_atom(a, fields) : %s\" % p_assign_expr\n # here we are inside data\n p_element = None\n p_nl -= 1\n for line in lines[p_nl:stop]:\n p_nl += 1\n words = line.split()\n # ignore atom mass\n if len(words) == 1 and isfloat(words[0]):\n continue\n # parse element allowing empty symbol\n elif len(words) <= 1:\n w = line.strip()\n p_element = w[:1].upper() + w[1:].lower()\n elif len(words) == xcfg_entry_count and p_element is not None:\n fields = [ float(w) for w in words ]\n stru.addNewAtom(p_element, fields[:3])\n a = stru.getLastAtom()\n a.xyz *= xcfg_A\n p_assign_atom(a, fields)\n else:\n emsg = \"%d: invalid record\" % p_nl\n raise StructureFormatError(emsg)\n if len(stru) != p_natoms:\n emsg = \"expected %d atoms, read %d\" % (p_natoms, len(stru))\n raise StructureFormatError(emsg)\n except (ValueError, IndexError):\n emsg = \"%d: file is not in XCFG format\" % p_nl\n exc_type, exc_value, exc_traceback = sys.exc_info()\n raise StructureFormatError, emsg, exc_traceback\n return stru\n # End of parseLines\n\n def toLines(self, stru):\n \"\"\"Convert Structure stru to a list of lines in XCFG atomeye format.\n\n Return list of strings.\n \"\"\"\n if len(stru) == 0:\n emsg = \"cannot convert empty structure to XCFG format\"\n raise StructureFormatError(emsg)\n lines = []\n lines.append( \"Number of particles = %i\" % len(stru) )\n # figure out length unit A\n allxyz = numpy.array([a.xyz for a in stru])\n lo_xyz = allxyz.min(axis=0)\n hi_xyz = allxyz.max(axis=0)\n max_range_xyz = (hi_xyz-lo_xyz).max()\n if numpy.allclose(stru.lattice.abcABG(), (1, 1, 1, 90, 90, 90)):\n max_range_xyz += self.cluster_boundary\n # range of CFG coordinates must be less than 1\n p_A = numpy.ceil(max_range_xyz + 1.0e-13)\n # atomeye draws rubbish when boxsize is less than 3.5\n hi_ucvect = max([numpy.sqrt(numpy.dot(v,v)) for v in stru.lattice.base])\n if hi_ucvect*p_A < 3.5:\n p_A = numpy.ceil(3.5 / hi_ucvect)\n lines.append( \"A = %.8g Angstrom\" % p_A )\n # how much do we need to shift the coordinates?\n p_dxyz = numpy.zeros(3, dtype=float)\n for i in range(3):\n if lo_xyz[i]/p_A < 0.0 or hi_xyz[i]/p_A >= 1.0 \\\n or (lo_xyz[i] == hi_xyz[i] and lo_xyz[i] == 0.0) :\n p_dxyz[i] = 0.5 - (hi_xyz[i]+lo_xyz[i])/2.0/p_A\n # H0 tensor\n for i in range(3):\n for j in range(3):\n lines.append( \"H0(%i,%i) = %.8g A\" % \\\n (i+1, j+1, stru.lattice.base[i,j]) )\n # get out for empty structure\n if len(stru) == 0: return lines\n a_first = stru[0]\n p_NO_VELOCITY = \"v\" not in a_first.__dict__\n if p_NO_VELOCITY:\n lines.append(\".NO_VELOCITY.\")\n # build a p_auxiliaries list of (aux_name,atom_expression) tuples\n # if stru came from xcfg file, it would store original auxiliaries in\n # xcfg dictionary\n try:\n p_auxiliaries = [ (aux, \"a.\"+aux)\n for aux in stru.xcfg['auxiliaries'] ]\n except AttributeError:\n p_auxiliaries = []\n # add occupancy if any atom has nonunit occupancy\n for a in stru:\n if a.occupancy != 1.0:\n p_auxiliaries.append( ('occupancy', 'a.occupancy') )\n break\n # add temperature factor with as many terms as needed\n # check whether all temperature factors are zero or isotropic\n p_allUzero = True\n p_allUiso = True\n for a in stru:\n if p_allUzero and numpy.any(a.U != 0.0):\n p_allUzero = False\n if not numpy.all(a.U == a.U[0,0]*numpy.identity(3)):\n p_allUiso = False\n # here p_allUzero must be false\n break\n if p_allUzero:\n pass\n elif p_allUiso:\n p_auxiliaries.append( ('Uiso', 'a.U[0,0]') )\n else:\n p_auxiliaries.extend([ ('U11', 'a.U[0,0]'),\n ('U22', 'a.U[1,1]'),\n ('U33', 'a.U[2,2]') ])\n # check if there are off-diagonal elements\n allU = numpy.array([a.U for a in stru])\n if numpy.any(allU[:,0,1] != 0.0):\n p_auxiliaries.append( ('U12', 'a.U[0,1]') )\n if numpy.any(allU[:,0,2] != 0.0):\n p_auxiliaries.append( ('U13', 'a.U[0,2]') )\n if numpy.any(allU[:,1,2] != 0.0):\n p_auxiliaries.append( ('U23', 'a.U[1,2]') )\n # count entries\n p_entry_count = 6 - 3*p_NO_VELOCITY + len(p_auxiliaries)\n lines.append(\"entry_count = %d\" % p_entry_count)\n # add auxiliaries\n for i in range(len(p_auxiliaries)):\n lines.append(\"auxiliary[%d] = %s [au]\" % (i, p_auxiliaries[i][0]))\n # now define p_entry_line function for representing atom properties\n p_exprs = [ \"def p_entry_line(a, p_A, p_dxyz):\",\n \" fields = list( a.xyz/p_A+p_dxyz )\" ]\n if not p_NO_VELOCITY:\n p_exprs.append( \\\n \" fields += [ a.v[0], a.v[1], a.v[2] ]\" )\n p_exprs += [\" fields += [ \" +\n \",\".join([e for p,e in p_auxiliaries]) + \" ]\",\n \" line = ' '.join([ '%.8g' % x for x in fields ])\",\n \" return line\" ]\n exec \"\\n\".join(p_exprs)\n # we are ready to output atoms:\n lines.append(\"\")\n p_element = None\n for a in stru:\n if a.element != p_element:\n p_element = a.element\n lines.append(\"%.4f\" % AtomicMass.get(p_element, 0.0))\n lines.append(p_element)\n lines.append(p_entry_line(a, p_A, p_dxyz))\n return lines\n # End of toLines\n\n# End of class P_xcfg\n\n# Routines\n\ndef getParser():\n return P_xcfg()\n\n# End of file\n", "meta": {"hexsha": "41057fa017de974f3f124a735eb2d81cf8428779", "size": 17922, "ext": "py", "lang": "Python", "max_stars_repo_path": "diffpy/Structure/Parsers/P_xcfg.py", "max_stars_repo_name": "mmckerns/diffpy.Structure", "max_stars_repo_head_hexsha": "62551146e29ce4a8988d92779b34d0748f8c74f9", "max_stars_repo_licenses": ["Artistic-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "diffpy/Structure/Parsers/P_xcfg.py", "max_issues_repo_name": "mmckerns/diffpy.Structure", "max_issues_repo_head_hexsha": "62551146e29ce4a8988d92779b34d0748f8c74f9", "max_issues_repo_licenses": ["Artistic-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "diffpy/Structure/Parsers/P_xcfg.py", "max_forks_repo_name": "mmckerns/diffpy.Structure", "max_forks_repo_head_hexsha": "62551146e29ce4a8988d92779b34d0748f8c74f9", "max_forks_repo_licenses": ["Artistic-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9784172662, "max_line_length": 80, "alphanum_fraction": 0.5011717442, "include": true, "reason": "import numpy", "num_tokens": 5755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.21469141911224196, "lm_q1q2_score": 0.13284685245796254}} {"text": "\"\"\"\nModule containing a useable interface for the data output of Budapest-Florida code\nin Python.\n\n# Current features\n\n- History class providing support for fort.18 files\n- Model class providing support for fort.95 files\n- LimmitCycle class providing support for fort.19 files\n- bpfDataRead function provides easy initialization in given directory\n\nCreated by: Gábor B. Kovács 2021\n\"\"\"\nfrom astropy.constants import cgs\nfrom math import pi\nimport numpy as np\nimport astropy.constants as constants\nfrom astropy import units\n#import calcion\n#from . import calcion\n\nclass BaseData:\n \"\"\"\n Base class for the three most common Bupest-Florida Code output, such as\n - fort.95 which contains the static starting model profile\n - fort.19 which contains the profiles for two full periods\n - fort.18 which contains the photosphere data, for the entire run\n \"\"\"\n def __init__(self, data=None, col_names=None):\n self.datablock=data\n self.column_names=col_names\n\n def data(self,key):\n if key in self.datablock:\n return self.datablock[key]\n else:\n raise KeyError('There is no'+str(key)+'data member.')\n \n def insertColumn(self,data,columnnames):\n if isinstance(data,dict):\n #print('dict')\n self.datablock.update(data)\n else:\n #print(type(data))\n self.datablock.update(dict(zip(columnnames,data)))\n self.column_names += columnnames\n return self\n\n def __getattr__(self,key):\n return self.data(key)\n \n\nclass History(BaseData):\n \"\"\"\n This class provides standard interface for working with fort.18 files.\n Column names:\n - time: Elapsed time from hydro start in days\n - vel_rad: Radial velocity in the photosphere\n - L_phot: Photosphere luminosity\n - radius: Radius of surface (One zone below nzn.)\n - L_surf: Luminosity of the surface zone\n \"\"\"\n columnnames=('time','vel_rad','L_phot','radius','L_surf') \n def __init__(self,path):\n data,colnames=self.read_data(path)\n super().__init__(data,colnames)\n \n\n def read_data(self,path):\n datafile=open(path)\n dataLines=datafile.readlines()\n#This should be static!\n columns=[]\n for i in range(0,len(dataLines[0].split())):\n columns.append([float(x.split()[i]) for x in dataLines])\n columns[i]=np.array(columns[i])\n datafile.close()\n return dict(zip(self.columnnames,columns)), self.columnnames\n\n \nclass Model(BaseData):\n \"\"\"\n Class providing interface for working with fort.95 files.\n \"\"\"\n columnnames=('zone','radius','pressure','spec_vol','energy','temperature','turbulent_energy',\n 'dm','L_c','p_turb','L_r','sk','L_turb','s','cs','fcsl','st','cla','taup','taud','opacity',\n 'edt','cp')\n def __init__(self,path):\n data,colnames=self.read_data(path)\n super().__init__(data,colnames)\n \n def read_data(self,path):\n datafile=open(path)\n dataLines=datafile.readlines()\n columns=[]\n for i in range(0,len(dataLines[0].split())-1):\n columns.append([float(x.split()[i].replace('D','E')) for x in dataLines])\n columns[i]=np.array(columns[i])\n datafile.close()\n return dict(zip(self.columnnames,columns)), self.columnnames\n\n\nclass DataPoint(BaseData):\n \"\"\"\n Helper class for fort.19 data access, holds one record of fort.19 data.\n Fields are:\n phase - phase of pulsation\n zone - zone number of mass cell\n velocity - velocity of mass cell\n L_r - radiative luminosity\n radius - radius at mass cell\n temperature - temperature of the cell\n dm - size of the cell\n opacity - opacity in the cell\n energy - internal energy\n e_t - turbulent energy\n entropy - specific entropy\n F_t - turbulent luminosity\n F_c - convective luminosity\n pressure - gas pressure in cell\n p_t - turbulent pressure\n p_eddy - viscous pressure of the cell\n mass - mass (Langrangian) coordinate of the cell.\n \"\"\"\n columnnames=('phase','zone','velocity','L_r','radius','temperature','dm','opacity','energy','e_t','entropy',\n 'F_t','F_c','pressure','p_t','p_eddy','mass')\n\n def __init__(self,Line : str):\n #TODO: d D e E csere!\n\n data=dict(zip(DataPoint.columnnames,[float(x.translate({\"d\": \"e\",\"D\" : \"e\"})) for x in Line.split()]))\n #for x in Line.split(): print(float(x))\n super().__init__(data,DataPoint.columnnames)\n\n @classmethod\n def createDataPointList(cls, Template = None):\n return dict(zip(Template.column_names, [ list() for i in enumerate(Template.column_names)]))\n \n @classmethod\n def fillDataPointList(cls,datapoints : list):\n if not all(isinstance(x,cls) for x in datapoints):\n raise TypeError(\"datapoints should be a list of DataPoint\")\n template = datapoints[0]\n datapoint_list=cls.createDataPointList(template)\n for point in datapoints:\n for key in template.column_names:\n data = point.data(key)\n datapoint_list[key].append(data)\n for key in datapoint_list:\n datapoint_list[key]=np.array(datapoint_list[key])\n return datapoint_list\n\n\nclass RawProfiles:\n \"\"\"\n Container holding DataPoints extracted from fort.19\n \"\"\"\n def __init__(self, filename):\n self.datablock=None\n self.num_time_series=0\n self.num_profiles=0\n self.read_file(filename)\n self.CalcSpecVol()\n\n def read_file(self,filename):\n infile=open(filename)\n lines = infile.readlines()\n self.datablock = [DataPoint(line) for line in lines]\n self.num_time_series = int(self.datablock[-1].zone)\n self.num_profiles = int(self.datablock[-1].phase)\n infile.close()\n\n def __getitem__(self,key) -> DataPoint:\n return self.datablock[key]\n\n def __iter__(self):\n return iter(self.datablock)\n\n def CalcSpecVol(self):\n for i in range(len(self.datablock)):\n #print(i)\n r = self.datablock[i].radius\n if self.datablock[i].zone == 1:\n volume = 4 * r ** 3 * pi / 3\n spec_vol = volume / self.datablock[i].mass\n else:\n r_nm1 = self.datablock[i-1].radius\n volume = 4* pi /3 * ( r**3 - r_nm1 ** 3)\n if self.datablock[i].dm != 0:\n spec_vol = volume / self.datablock[i].dm\n else:\n spec_vol = volume / self.datablock[i-1].dm\n self.datablock[i].insertColumn([spec_vol],tuple(['spec_vol']))\n\n\n\n\nclass TimeSeries(BaseData):\n \"\"\"\n Holding one zones time series of the limit cycle\n \"\"\"\n def __init__(self,rawprofile_obj : RawProfiles,zone_number):\n if not all([isinstance(rawprofile_obj,RawProfiles),isinstance(zone_number,(int,float))]):\n raise TypeError(\"Wrong arguments\")\n super().__init__(self.createTimeSeries(rawprofile_obj,zone_number),DataPoint.columnnames)\n\n def createTimeSeries(self,rawprofile_obj : RawProfiles, zone_number) -> dict:\n datapoints=rawprofile_obj[zone_number::rawprofile_obj.num_time_series]\n #print(type(datapoints),zone_number,rawprofile_obj.num_time_series,len(rawprofile_obj.datablock))\n data=DataPoint.fillDataPointList(datapoints)\n return data\n\nclass Profiles(BaseData):\n \"\"\"\n Holding a limit cycle profile at given phase number.\n \"\"\"\n def __init__(self,rawprofile_obj : RawProfiles,phase_number):\n super().__init__(self.createProfile(rawprofile_obj,phase_number),DataPoint.columnnames)\n \n def createProfile(self,rawprofile_obj : RawProfiles,phase_number):\n datapoints=[point for point in rawprofile_obj if point.phase == phase_number]\n data=DataPoint.fillDataPointList(datapoints)\n return data\n\nclass LimitCycle:\n \"\"\"\n Class providing user interface for the fort.19 data, both timeseries and profiles extraction, using the same interface.\n For columnnames see DataPoint class.\n \"\"\"\n columnames=DataPoint.columnnames\n def __init__(self,infile_name):\n if isinstance(infile_name,str):\n rawdata=RawProfiles(infile_name)\n elif isinstance(infile_name,RawProfiles):\n rawdata = infile_name\n else:\n raise TypeError(\"Parameter should be either string or RawProfile object.\")\n self.timeSeries=[TimeSeries(rawdata,zone_number) for zone_number in range(1,rawdata.num_time_series+1)]\n self.profiles=[Profiles(rawdata,phase_number) for phase_number in range(1,rawdata.num_profiles+1)]\n self.num_time_series = len(self.timeSeries)\n self.num_profiles=len(self.profiles)\n\n#testing utilities\nif(__name__ == '__main__'):\n from matplotlib import pyplot as plt\n import math\n a_point = DataPoint(\"45\\t136\\t12\\t50\\t5.6\\t2e5\\t4.13e+29\\t125.68\\t1.25e40\\t1.2e38\\t12000\\t1e29\\t12e5\\t1.5e4\\t1e2\\t0.98\\n\")\n fort19_path='/home/gabesz/SPHERLS_playground/bpf_konv/konv-b/fort.19'#'/home/gabesz/Dokumentumok/VS_Code_workspace/calcion/fort.19'\n fort19_data=RawProfiles(fort19_path)\n print(a_point.datablock)\n print(a_point.dm)\n print(fort19_data[15].spec_vol)\n # for cell_obj in fort19_data:\n #print(cell_obj.zone)\n\n #Testing Timeseries:\n #surface:\n surface_element=fort19_data.num_time_series-2\n print(\"érték:\",fort19_data.num_time_series)\n surface_series=TimeSeries(fort19_data,surface_element)\n #print(surface_series.radius)\n mylog=np.vectorize(math.log10)\n #plt.plot(surface_series.phase/77.,surface_series.F_r/constants.L_sun.cgs)\n \n aProfile=Profiles(fort19_data,1)\n\n fort19_handler=LimitCycle(fort19_path)\n\n for phase in range(0):#,len(fort19_handler.profiles)):\n #phase=40\n ts_xdata=fort19_handler.timeSeries[fort19_handler.num_time_series-2].phase\n ts_ydata=fort19_handler.timeSeries[fort19_handler.num_time_series-2].L_r\n xdata=fort19_handler.profiles[phase].zone\n ydata=fort19_handler.profiles[phase].F_c\n #print(xdata,ydata)\n plt.subplot(2,1,1)\n plt.plot(xdata,ydata/constants.L_sun.cgs)\n plt.plot(xdata,fort19_handler.profiles[phase].L_r/constants.L_sun.cgs)\n plt.plot(xdata,fort19_handler.profiles[phase].F_t/constants.L_sun.cgs)\n #plt.plot(aProfile.zone[1:146],mylog(aProfile.temperature[1:146]))\n plt.subplot(2,1,2)\n plt.plot(ts_xdata/77,ts_ydata/constants.L_sun.cgs)\n plt.scatter(ts_xdata[phase]/77,ts_ydata[phase]/constants.L_sun.cgs,color=\"red\")\n plt.show()\n plt.pause(5)\n\n\n #Testing reader\n \n\n #Other tests\n print(len(lim.profiles), lim.num_profiles)\n", "meta": {"hexsha": "1bab2c38d50e3f524d03fcad3e853d2d6aecc21c", "size": 10934, "ext": "py", "lang": "Python", "max_stars_repo_path": "pybpf/tcdata.py", "max_stars_repo_name": "kovacsgb/pybpf", "max_stars_repo_head_hexsha": "d88cdf6e60fad95d1a314a1df4575a834d0fa02e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pybpf/tcdata.py", "max_issues_repo_name": "kovacsgb/pybpf", "max_issues_repo_head_hexsha": "d88cdf6e60fad95d1a314a1df4575a834d0fa02e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pybpf/tcdata.py", "max_forks_repo_name": "kovacsgb/pybpf", "max_forks_repo_head_hexsha": "d88cdf6e60fad95d1a314a1df4575a834d0fa02e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3174061433, "max_line_length": 135, "alphanum_fraction": 0.6520029267, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 2651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.24798743735585302, "lm_q1q2_score": 0.1326976843711654}} {"text": "import sys, os\nimport time\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.utils import data\nfrom parsers import parse_a3m, read_templates\nfrom RoseTTAFoldModel import RoseTTAFoldModule_e2e\nimport util\nfrom collections import namedtuple\nfrom ffindex import *\nfrom kinematics import xyz_to_c6d, c6d_to_bins2, xyz_to_t2d\nfrom trFold import TRFold\n\nscript_dir = '/'.join(os.path.dirname(os.path.realpath(__file__)).split('/')[:-1])\n\nNBIN = [37, 37, 37, 19]\n\nMODEL_PARAM ={\n \"n_module\" : 8,\n \"n_module_str\" : 4,\n \"n_module_ref\" : 4,\n \"n_layer\" : 1,\n \"d_msa\" : 384 ,\n \"d_pair\" : 288,\n \"d_templ\" : 64,\n \"n_head_msa\" : 12,\n \"n_head_pair\" : 8,\n \"n_head_templ\" : 4,\n \"d_hidden\" : 64,\n \"r_ff\" : 4,\n \"n_resblock\" : 1,\n \"p_drop\" : 0.0,\n \"use_templ\" : True,\n \"performer_N_opts\": {\"nb_features\": 64},\n \"performer_L_opts\": {\"nb_features\": 64}\n }\n\nSE3_param = {\n \"num_layers\" : 2,\n \"num_channels\" : 16,\n \"num_degrees\" : 2,\n \"l0_in_features\": 32,\n \"l0_out_features\": 8,\n \"l1_in_features\": 3,\n \"l1_out_features\": 3,\n \"num_edge_features\": 32,\n \"div\": 2,\n \"n_heads\": 4\n }\n\nREF_param = {\n \"num_layers\" : 3,\n \"num_channels\" : 32,\n \"num_degrees\" : 3,\n \"l0_in_features\": 32,\n \"l0_out_features\": 8,\n \"l1_in_features\": 3,\n \"l1_out_features\": 3,\n \"num_edge_features\": 32,\n \"div\": 4,\n \"n_heads\": 4\n }\nMODEL_PARAM['SE3_param'] = SE3_param\nMODEL_PARAM['REF_param'] = REF_param\n\n# params for the folding protocol\nfold_params = {\n \"SG7\" : np.array([[[-2,3,6,7,6,3,-2]]])/21,\n \"SG9\" : np.array([[[-21,14,39,54,59,54,39,14,-21]]])/231,\n \"DCUT\" : 19.5,\n \"ALPHA\" : 1.57,\n \n # TODO: add Cb to the motif\n \"NCAC\" : np.array([[-0.676, -1.294, 0. ],\n [ 0. , 0. , 0. ],\n [ 1.5 , -0.174, 0. ]], dtype=np.float32),\n \"CLASH\" : 2.0,\n \"PCUT\" : 0.5,\n \"DSTEP\" : 0.5,\n \"ASTEP\" : np.deg2rad(10.0),\n \"XYZRAD\" : 7.5,\n \"WANG\" : 0.1,\n \"WCST\" : 0.1\n}\n\nfold_params[\"SG\"] = fold_params[\"SG9\"]\n\nclass Predictor():\n def __init__(self, model_dir=None, use_cpu=False):\n if model_dir == None:\n self.model_dir = \"%s/models\"%(os.path.dirname(os.path.realpath(__file__)))\n else:\n self.model_dir = model_dir\n #\n # define model name\n self.model_name = \"RoseTTAFold\"\n if torch.cuda.is_available() and (not use_cpu):\n self.device = torch.device(\"cuda\")\n else:\n self.device = torch.device(\"cpu\")\n self.active_fn = nn.Softmax(dim=1)\n\n # define model & load model\n self.model = RoseTTAFoldModule_e2e(**MODEL_PARAM).to(self.device)\n\n def load_model(self, model_name, suffix='e2e'):\n chk_fn = \"%s/%s_%s.pt\"%(self.model_dir, model_name, suffix)\n if not os.path.exists(chk_fn):\n return False\n checkpoint = torch.load(chk_fn, map_location=self.device)\n self.model.load_state_dict(checkpoint['model_state_dict'], strict=True)\n return True\n \n def predict(self, a3m_fn, out_prefix, hhr_fn=None, atab_fn=None, window=150, shift=75):\n #模型主要输入是a3m_fn,从中解析出msa。hhr_fn和atab_fn是hhsearch的查询结果,作为辅助输入。hhsearch是一个同源检测工具。\n #同源检测可以理解为,生物进化过程中具有相似功能的蛋白质,其关键区域的氨基酸片段相似,非关键区域的片段可能不同,通过对比\n #高相似度的氨基酸片段来搜索同源蛋白质。原理是从msa分析获得关键区域,再从蛋白质数据库搜索具有相似关键区域的其它蛋白质。\n #从t000_.msa0.a3m加载多序列输入,其中第0个序列是待折叠的序列,多序列是为了聚焦同源基因,其它序列为第0个序列提供辅助信息。\n #msa~[N,L], N是序列个数,L是最长序列长度,元素值0~20,20是PADDING,有效值0~19代表20种氨基酸\n msa = parse_a3m(a3m_fn)\n N, L = msa.shape\n #ffdb: 已知的小分子蛋白质结构,每个蛋白质由一个代号和多个原子表示,如下:\n #代号(entry)=3v0r_A\n #原子列表=<如下> \n # 原子序号 原子 残基 残基序号 X Y Z\n # ATOM 1 N ALA A 1 11.850 12.857 19.449 1.00 82.09 N\n # ATOM 2 CA ALA A 1 10.833 12.912 18.337 1.00 88.45 C\n # ATOM 3 C ALA A 1 11.197 14.110 17.413 1.00 87.11 C\n # ......\n #一个蛋白质由多个氨基酸组成,每个氨基酸由它的残基唯一标识,每个残基由N/CA/C三个固有的原子和其它原子组成\n #可按残基序号将不同残基的原子分组,每个组的开头是N/CA/C三个原子。\n #hhr_fn: 一个多序列的查询结果,通过调用hhsearch工具,以t000_.msa0.ss2.a3m为输入,输入的信息是多序列。\n #本例中查询的对象是T1078 Tsp1,其同源蛋白质一共有433个,查询结果匹配到其中的116个,对其中的每个蛋白读取如下信息:\n # entry=3v0r_A Probab=38.12 Identities=15% Similarity=0.182\n #这一行信息代表3v0r_A和T1078 Tsp1的近似程度\n #atab_fn: hhsearch的另一个输出文件,记录每个匹配到的蛋白质序列中,每个残基的匹配分数,\n # entry=3v0r_A\n # i j score SS probab dssp\n # 3 1 1.73 0.15 0.2682 C\n # 4 2 2.32 0.12 0.3398 C\n # 5 3 0.71 0.10 0.3208 S\n # ......\n #其中i和j与ffdb中的残基序号对应,代表T1078中第i和3v04_A中第j个残基的匹配程度\n #可以理解为,hhr_fn是蛋白质级别的匹配结果,atab_fn是氨基酸对级别的匹配结果(更细化)。\n #read_templates从hhsearch结果中转换出以下数据,只取top_n=10个最相近的蛋白质匹配结果:\n #xyz_t: 维度是[top_n,L,top_k,3],L=138是最长的源蛋白质长度,top_k=3代表取前三个原子(N,CA,C),\n # 因为前3个原子确定了氨基酸在空间中的一个面,从而确定了空间位置和方向,3代表原子的空间坐标\n #t0d: 维度是[top_n,3],3代表(Probab/100,Identities,Similarity)\n #t1d: 维度是[top_n,L,3],记录了每个残基的匹配分数,3代表(score,SS,probab)\n if hhr_fn != None:\n xyz_t, t1d, t0d = read_templates(L, ffdb, hhr_fn, atab_fn, n_templ=10)\n else:\n xyz_t = torch.full((1, L, 3, 3), np.nan).float()\n t1d = torch.zeros((1, L, 3)).float()\n t0d = torch.zeros((1,3)).float()\n #\n msa = torch.tensor(msa).long().view(1, -1, L)\n idx_pdb = torch.arange(L).long().view(1, L)\n #\n # template features\n xyz_t = xyz_t.float().unsqueeze(0)\n t1d = t1d.float().unsqueeze(0)\n t0d = t0d.float().unsqueeze(0)\n #t2d: 维度是[1,top_n,L,L,10],是LxL自相关信息表,10是信息维度,代表distance,sin(omega),sin(theta),sin(phi),\n # cos(omega),cos(theta),cos(pha),Probab/100,Identities,Similarity\n #omega/theta/phi三个角由匹配上的残基的前三个原子(N/CA/C)的位置决定,注意t2d由辅助信息演变过来,本身是稀疏的,\n #没有匹配上的残基所对应的值被设置为0,特别的,若不输入辅助信息,t2d是全零。\n t2d = xyz_to_t2d(xyz_t, t0d)\n could_load = self.load_model(self.model_name, suffix=\"e2e\")\n if not could_load:\n print (\"ERROR: failed to load model\")\n sys.exit()\n self.model.eval()\n with torch.no_grad():\n # 如果蛋白质太长,则以重叠窗口的方式滑动预测每一段\n if L > window*2:\n prob_s = [np.zeros((L,L,NBIN[i]), dtype=np.float32) for i in range(4)]\n count_1d = np.zeros((L,), dtype=np.float32)\n count_2d = np.zeros((L,L), dtype=np.float32)\n node_s = np.zeros((L,MODEL_PARAM['d_msa']), dtype=np.float32)\n #\n grids = np.arange(0, L-window+shift, shift)\n ngrids = grids.shape[0]\n print(\"ngrid: \", ngrids)\n print(\"grids: \", grids)\n print(\"windows: \", window)\n\n for i in range(ngrids):\n for j in range(i, ngrids):\n start_1 = grids[i]\n end_1 = min(grids[i]+window, L)\n start_2 = grids[j]\n end_2 = min(grids[j]+window, L)\n sel = np.zeros((L)).astype(np.bool)\n sel[start_1:end_1] = True\n sel[start_2:end_2] = True\n \n input_msa = msa[:,:,sel]\n mask = torch.sum(input_msa==20, dim=-1) < 0.5*sel.sum() # remove too gappy sequences\n input_msa = input_msa[mask].unsqueeze(0)\n input_msa = input_msa[:,:1000].to(self.device)\n input_idx = idx_pdb[:,sel].to(self.device)\n input_seq = input_msa[:,0].to(self.device)\n #\n # Select template\n input_t1d = t1d[:,:,sel].to(self.device) # (B, T, L, 3)\n input_t2d = t2d[:,:,sel][:,:,:,sel].to(self.device)\n #\n print (\"running crop: %d-%d/%d-%d\"%(start_1, end_1, start_2, end_2), input_msa.shape)\n with torch.cuda.amp.autocast():\n logit_s, node, init_crds, pred_lddt = self.model(input_msa, input_seq, input_idx, t1d=input_t1d, t2d=input_t2d, return_raw=True)\n #\n # Not sure How can we merge init_crds.....\n sub_idx = input_idx[0].cpu()\n sub_idx_2d = np.ix_(sub_idx, sub_idx)\n count_2d[sub_idx_2d] += 1.0\n count_1d[sub_idx] += 1.0\n node_s[sub_idx] += node[0].cpu().numpy()\n for i_logit, logit in enumerate(logit_s):\n prob = self.active_fn(logit.float()) # calculate distogram\n prob = prob.squeeze(0).permute(1,2,0).cpu().numpy()\n prob_s[i_logit][sub_idx_2d] += prob\n del logit_s, node\n #\n # combine all crops\n for i in range(4):\n prob_s[i] = prob_s[i] / count_2d[:,:,None]\n prob_in = np.concatenate(prob_s, axis=-1)\n node_s = node_s / count_1d[:, None]\n #\n # Do iterative refinement using SE(3)-Transformers\n # clear cache memory\n torch.cuda.empty_cache()\n #\n node_s = torch.tensor(node_s).to(self.device).unsqueeze(0)\n seq = msa[:,0].to(self.device)\n idx_pdb = idx_pdb.to(self.device)\n prob_in = torch.tensor(prob_in).to(self.device).unsqueeze(0)\n with torch.cuda.amp.autocast():\n xyz, lddt = self.model(node_s, seq, idx_pdb, prob_s=prob_in, refine_only=True)\n else:\n #仅分析蛋白质没有超过窗口长度的情况\n msa = msa[:,:1000].to(self.device)\n seq = msa[:,0]\n idx_pdb = idx_pdb.to(self.device)\n t1d = t1d[:,:10].to(self.device)\n t2d = t2d[:,:10].to(self.device)\n with torch.cuda.amp.autocast():\n logit_s, _, xyz, lddt = self.model(msa, seq, idx_pdb, t1d=t1d, t2d=t2d)\n prob_s = list()\n for logit in logit_s:\n prob = self.active_fn(logit.float()) # distogram\n prob = prob.reshape(-1, L, L).permute(1,2,0).cpu().numpy()\n prob_s.append(prob)\n \n np.savez_compressed(f\"{out_prefix}.npz\", dist=prob_s[0].astype(np.float16), \\\n omega=prob_s[1].astype(np.float16),\\\n theta=prob_s[2].astype(np.float16),\\\n phi=prob_s[3].astype(np.float16))\n \n self.write_pdb(seq[0], xyz[0], idx_pdb[0], Bfacts=lddt[0], prefix=f\"{out_prefix}_init\")\n \n # run TRFold\n prob_trF = list()\n for prob in prob_s:\n prob = torch.tensor(prob).permute(2,0,1).to(self.device)\n prob += 1e-8\n prob = prob / torch.sum(prob, dim=0)[None]\n prob_trF.append(prob)\n xyz = xyz[0, :, 1]\n TRF = TRFold(prob_trF, fold_params)\n xyz = TRF.fold(xyz, batch=15, lr=0.1, nsteps=200)\n xyz = xyz.detach().cpu().numpy()\n # add O and Cb\n N = xyz[:,0,:]\n CA = xyz[:,1,:]\n C = xyz[:,2,:]\n O = self.extend(np.roll(N, -1, axis=0), CA, C, 1.231, 2.108, -3.142)\n xyz = np.concatenate((xyz, O[:,None,:]), axis=1)\n self.write_pdb(seq[0], xyz, idx_pdb[0], Bfacts=lddt[0], prefix=out_prefix)\n\n def extend(self, a,b,c, L,A,D):\n '''\n input: 3 coords (a,b,c), (L)ength, (A)ngle, and (D)ihedral\n output: 4th coord\n '''\n N = lambda x: x/np.sqrt(np.square(x).sum(-1,keepdims=True) + 1e-8)\n bc = N(b-c)\n n = N(np.cross(b-a, bc))\n m = [bc,np.cross(n,bc),n]\n d = [L*np.cos(A), L*np.sin(A)*np.cos(D), -L*np.sin(A)*np.sin(D)]\n return c + sum([m*d for m,d in zip(m,d)])\n\n def write_pdb(self, seq, atoms, idx, Bfacts=None, prefix=None):\n L = len(seq)\n filename = f\"{prefix}.pdb\"\n ctr = 1\n with open(filename, 'wt') as f:\n if Bfacts == None:\n Bfacts = np.zeros(L)\n else:\n Bfacts = torch.clamp( Bfacts, 0, 1)\n \n for i,s in enumerate(seq):\n if (len(atoms.shape)==2):\n f.write (\"%-6s%5s %4s %3s %s%4d %8.3f%8.3f%8.3f%6.2f%6.2f\\n\"%(\n \"ATOM\", ctr, \" CA \", util.num2aa[s], \n \"A\", idx[i]+1, atoms[i,0], atoms[i,1], atoms[i,2],\n 1.0, Bfacts[i] ) )\n ctr += 1\n\n elif atoms.shape[1]==3:\n for j,atm_j in enumerate((\" N \",\" CA \",\" C \")):\n f.write (\"%-6s%5s %4s %3s %s%4d %8.3f%8.3f%8.3f%6.2f%6.2f\\n\"%(\n \"ATOM\", ctr, atm_j, util.num2aa[s], \n \"A\", idx[i]+1, atoms[i,j,0], atoms[i,j,1], atoms[i,j,2],\n 1.0, Bfacts[i] ) )\n ctr += 1 \n \n elif atoms.shape[1]==4:\n for j,atm_j in enumerate((\" N \",\" CA \",\" C \", \" O \")):\n f.write (\"%-6s%5s %4s %3s %s%4d %8.3f%8.3f%8.3f%6.2f%6.2f\\n\"%(\n \"ATOM\", ctr, atm_j, util.num2aa[s], \n \"A\", idx[i]+1, atoms[i,j,0], atoms[i,j,1], atoms[i,j,2],\n 1.0, Bfacts[i] ) )\n ctr += 1\n\ndef get_args():\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-m\", dest=\"model_dir\", default=\"%s/weights\"%(script_dir),\n help=\"Path to pre-trained network weights [%s/weights]\"%script_dir)\n parser.add_argument(\"-i\", dest=\"a3m_fn\", required=True,\n help=\"Input multiple sequence alignments (in a3m format)\")\n parser.add_argument(\"-o\", dest=\"out_prefix\", required=True,\n help=\"Prefix for output file. The output files will be [out_prefix].npz and [out_prefix].pdb\")\n parser.add_argument(\"--hhr\", default=None,\n help=\"HHsearch output file (hhr file). If not provided, zero matrices will be given as templates\")\n parser.add_argument(\"--atab\", default=None,\n help=\"HHsearch output file (atab file)\")\n parser.add_argument(\"--db\", default=\"%s/pdb100_2021Mar03/pdb100_2021Mar03\"%script_dir,\n help=\"Path to template database [%s/pdb100_2021Mar03]\"%script_dir)\n parser.add_argument(\"--cpu\", dest='use_cpu', default=False, action='store_true')\n\n args = parser.parse_args()\n return args\n\nif __name__ == \"__main__\":\n args = get_args()\n FFDB=args.db\n FFindexDB = namedtuple(\"FFindexDB\", \"index, data\")\n ffdb = FFindexDB(read_index(FFDB+'_pdb.ffindex'),\n read_data(FFDB+'_pdb.ffdata'))\n\n pred = Predictor(model_dir=args.model_dir, use_cpu=args.use_cpu)\n pred.predict(args.a3m_fn, args.out_prefix, args.hhr, args.atab)\n", "meta": {"hexsha": "fbd2ad644bf7f10d4a25be963fb9ec1b843a50aa", "size": 15648, "ext": "py", "lang": "Python", "max_stars_repo_path": "network/predict_e2e.py", "max_stars_repo_name": "mnvai/RoseTTAFold", "max_stars_repo_head_hexsha": "f8944898d6d96849593bc7a3f1b0d7db9dabc6ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "network/predict_e2e.py", "max_issues_repo_name": "mnvai/RoseTTAFold", "max_issues_repo_head_hexsha": "f8944898d6d96849593bc7a3f1b0d7db9dabc6ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "network/predict_e2e.py", "max_forks_repo_name": "mnvai/RoseTTAFold", "max_forks_repo_head_hexsha": "f8944898d6d96849593bc7a3f1b0d7db9dabc6ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.7094972067, "max_line_length": 156, "alphanum_fraction": 0.5065184049, "include": true, "reason": "import numpy", "num_tokens": 5289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.24798742068237775, "lm_q1q2_score": 0.13269768280339836}} {"text": "from __future__ import print_function\nfrom mpi4py import MPI\nfrom pyglib.iface.wanniertb import w90\nimport numpy as np\nimport h5py, glob, scipy, warnings\nfrom pyglib.symm.unitary import get_u_csh2wan_all\nfrom scipy.linalg import block_diag\nfrom scipy.io import FortranFile\nfrom pyglib.estructure.gwannier import mpiget_bndev, \\\n get_wannier_den_matrix_risb\nfrom pyglib.estructure.fermi import get_fermi_weight, get_fermi_level\nfrom pyglib.iface.wannierio import mpiget_wannier_data\n\n\ndef if_gwannier(corbs_list, delta_charge=0., wpath=\"../wannier\",\n lpath=\"../lattice\", wprefix=\"wannier\", lprefix=\"mdl\",\n lrot_list=None, iso=1, ispin=1, ismear=0, delta=0.0258,\n icycle=0):\n cell, _, kpts, include_bands, wfwannier_list, bnd_es = \\\n mpiget_wannier_data(path=wpath)\n # total number of valence electrons\n n_elec = get_total_valence_elec(\"{}/{}_1.out\".format(lpath, lprefix))\n n_elec -= max(0, (include_bands[0]-1)*(3-iso))\n symbols, atomic_positions = wget_symbols_positions(path=wpath,\n wprefix=wprefix)\n # convert to scaled position\n atomic_positions = np.asarray(atomic_positions).dot(\n np.linalg.inv(cell))\n numk = kpts.shape[0]\n # GMPI_x.h5 file\n kvec = set_kvec_para(numk)\n wk = 1./numk\n nbmax = wfwannier_list.shape[3]\n # spin degeneracy\n spin_deg = 3-max(ispin, iso)\n\n comm = MPI.COMM_WORLD\n myrank = comm.Get_rank()\n # wannier basis to complex spherical basis tranformation.\n u_wan2csh = get_wann2csh(nbmax, corbs_list)\n h1e_all = []\n nelectron = 0.\n # input file of dft bare band structure information for cygutz\n with h5py.File('BAREHAM_{}.h5'.format(myrank), 'w') as f:\n for isp in range(wfwannier_list.shape[0]):\n h1e_all.append(np.zeros((nbmax, nbmax), dtype=np.complex))\n for ik in range(kvec[0][2],kvec[0][2]+kvec[0][1]):\n # rescontruct dft hamiltonian matrix\n # in the wannier basis.\n # since it involves a downfolding,\n # some information outside of the frozen energy window\n # will be lost.\n hmat = wfwannier_list[isp][ik].T.conj().dot( \\\n np.diag(bnd_es[isp][ik])).dot(\n wfwannier_list[isp][ik])\n # from wannier basis to correlated orbital-ordered\n # complex spherical harmonics basis,\n # which is the convention used in the cygutz\n # initialization script.\n hmat = u_wan2csh.T.conj().dot(hmat).dot(u_wan2csh)\n # record the onsite one-body part\n h1e_all[isp] += hmat*wk\n # save the downfolded dft hamiltonian\n f['/IKP_{}/ISYM_1/HK0_SPIN1'.format(ik+1)] = hmat.T\n # get the eigen-value and eigen0vectors\n evals, evecs = np.linalg.eigh(hmat)\n # another way to evaluate total valence electrons\n # according to sangkook.\n nelectron += np.count_nonzero(evals < 0.)*(wk*spin_deg)\n # yes, here it is redundant here\n # but for the sake of consistent with wien2k interface.\n # here it implies the downfolding procedure is not necessary.\n f['/IKP_{}/ek0_spin1'.format(ik+1)] = evals\n f['/IKP_{}/T_PSIK0_TO_HK0_BASIS_SPIN{}'.format( \\\n ik+1, isp+1)] = evecs.T\n nelectron = comm.reduce(nelectron, op=MPI.SUM)\n h1e_all = np.asarray(h1e_all)\n h1e_all = comm.reduce(h1e_all, op=MPI.SUM)\n if myrank == 0:\n h1e_list = []\n for isp in range(wfwannier_list.shape[0]):\n h1e_list.append([])\n base = 0\n for corbs in corbs_list:\n norbs = len(corbs)\n h1e_list[isp].append(h1e_all[isp][base:base+norbs, \\\n base:base+norbs])\n base += norbs\n nelectron = int(nelectron+0.5)\n if np.abs(nelectron - n_elec) > 1.e-6:\n warnings.warn(\" wannier valence electrons: {} vs {}!\".format( \\\n nelectron, n_elec))\n n_elec = nelectron\n if icycle <= 1:\n wrt_ginit(symbols, cell, atomic_positions, u_wan2csh,\n lrot_list=lrot_list)\n else:\n update_ginit(u_wan2csh)\n\n ne_list = [[nbmax, 1, nbmax] for k in range(numk)]\n wk_list = [wk for k in range(numk)]\n nelectron = n_elec + delta_charge\n wrt_gparambands(numk, nbmax, ne_list, wk_list, kpts, nelectron,\n h1e_list, iso=iso, ispin=ispin, ismear=ismear, delta=delta)\n\n\ndef get_total_valence_elec(fname):\n comm = MPI.COMM_WORLD\n myrank = comm.Get_rank()\n if myrank == 0:\n with open(fname, \"r\") as f:\n for line in f.readlines():\n if \"valence charge in whole\" in line:\n n_elec = float(line.split()[-1])\n break\n else:\n n_elec = None\n n_elec = comm.bcast(n_elec, root=0)\n return n_elec\n\n\ndef wget_symbols_positions(path=\"./\", wprefix=\"wannier\"):\n with open(path+\"/\"+wprefix+\".win\", \"r\") as f:\n symbols = []\n atomic_positions = []\n read_position = 0\n for line in f.readlines():\n if \"begin\" in line and \"atoms_cart\" in line:\n read_position = 1\n elif \"end\" in line and \"atoms_cart\" in line:\n break\n elif read_position > 0:\n if \"bohr\" in line.lower():\n pref = scipy.constant.physical_constants[ \\\n \"Bohr radius\"]*1.e10\n elif \"ang\" in line.lower():\n pref=1.0\n else:\n line = line.split()\n _symbol = line[0].split(\"_\")[0]\n symbol = _symbol[0:1].upper()\n if len(_symbol) > 1:\n symbol += _symbol[1:].lower()\n # remove possible digit\n for s in symbol:\n if s.isdigit():\n symbol = symbol.replace(s,\"\")\n symbols.append(symbol)\n atomic_positions.append(\n [float(x)*pref for x in line[1:4]])\n return symbols, atomic_positions\n\n\ndef if_gwannier90(corbs_list, delta_charge=0., wpath=\"./\",\n wprefix=\"wannier\", k_grid=None, lrot_list=None,\n iso=1, ispin=1, ismear=0, delta=0.0258,\n icycle=0):\n # read output from wannier90.\n gwannier = w90(wpath, wprefix)\n gmodel = gwannier.model(zero_energy=0.0, min_hopping_norm=1.e-8,\n ignorable_imaginary_part=1.e-8)\n # uniform grid of k-points always contains the origin.\n if k_grid is None:\n k_grid = gwannier.kgrid\n elif isinstance(k_grid, np.int):\n k_grid = np.asarray(gwannier.kgrid)*k_grid\n else:\n assert(len(k_grid)==3), \"Dim(k_grid) is not 3!\"\n\n k_mesh = gmodel.k_uniform_mesh(k_grid)\n numk = k_mesh.shape[0]\n wk = 1./numk\n nbmax = gmodel.get_num_orbitals()\n # spin degeneracy\n spin_deg = 3-max(ispin, iso)\n\n comm = MPI.COMM_WORLD\n myrank = comm.Get_rank()\n\n # GMPI_x.h5 file\n kvec = set_kvec_para(numk)\n # wannier basis to complex spherical basis tranformation.\n u_wan2csh = get_wann2csh(nbmax, corbs_list)\n h1e_list = get_h1e_list_wannier(gwannier, corbs_list)\n nelectron = 0.\n with h5py.File('BAREHAM_{}.h5'.format(myrank), 'w') as f:\n for ik in range(kvec[0][2],kvec[0][2]+kvec[0][1]):\n kpt = k_mesh[ik]\n hmat = gmodel._gen_ham(kpt)\n # from wannier basis to correlated orbital-ordered csh basis.\n hmat = u_wan2csh.T.conj().dot(hmat).dot(u_wan2csh)\n f['/IKP_{}/ISYM_1/HK0_SPIN1'.format(ik+1)] = hmat.T\n evals, evecs = gmodel._sol_ham(hmat, eig_vectors=True)\n nelectron += np.count_nonzero(evals < 0.)*wk*spin_deg\n f['/IKP_{}/ek0_spin1'.format(ik+1)] = evals\n # evec is actually evec.T\n f['/IKP_{}/T_PSIK0_TO_HK0_BASIS_SPIN1'.format(ik+1)] = \\\n evecs.T.conj()\n nelectron = comm.reduce(nelectron, op=MPI.SUM)\n if myrank == 0:\n if icycle <= 1:\n wrt_ginit(gwannier.symbols, gwannier.lat,\n gwannier.atomic_positions, u_wan2csh, lrot_list=lrot_list)\n else:\n update_ginit(u_wan2csh)\n\n ne_list = [[nbmax, 1, nbmax] for k in range(numk)]\n wk_list = [wk for k in range(numk)]\n nelectron = int(nelectron+0.5)+delta_charge\n wrt_gparambands(numk, nbmax, ne_list, wk_list, k_mesh, nelectron,\n h1e_list, iso=iso, ispin=ispin, ismear=ismear, delta=delta)\n\n\ndef set_kvec_para(numk):\n comm = MPI.COMM_WORLD\n ncpu = comm.Get_size()\n nk_per_cpu = numk//ncpu\n if nk_per_cpu*ncpu < numk:\n nk_per_cpu += 1\n myrank = comm.Get_rank()\n kvec = [[]]\n kvec[0].append(myrank)\n k_start = nk_per_cpu*myrank\n kvec[0].append(min(nk_per_cpu, numk-k_start))\n kvec[0].append(k_start)\n with h5py.File(\"GMPI_{}.h5\".format(myrank), \"w\") as f:\n f[\"/nvec\"] = [1]\n f[\"/KVEC\"] = np.asarray(kvec).T\n return kvec\n\n\ndef get_h1e_list_wannier(gwannier, corbs_list):\n # List of one-body parts of Hamiltonian.\n h1e_list = [[]]\n for i, corbs in enumerate(corbs_list):\n norbs = len(corbs)\n h1e_list[0].append(np.zeros((norbs,norbs), dtype=np.complex))\n for j1 in range(norbs):\n _j1 = corbs[j1]\n for j2 in range(norbs):\n _j2 = corbs[j2]\n h1e_list[0][-1][j1,j2] = gwannier.ham_r[(0,0,0)][\"h\"][_j1,_j2]\\\n /float(gwannier.ham_r[(0,0,0)][\"deg\"])\n # Unitary transformation from complex Harmonics to wannier.\n u_csh2wan_list = get_u_csh2wan_all([len(corbs) for corbs in corbs_list])\n\n for i, u_csh2wan in enumerate(u_csh2wan_list):\n h1e_list[0][i] = u_csh2wan.dot(h1e_list[0][i]).dot(u_csh2wan.T.conj())\n return h1e_list\n\n\ndef get_wann2csh(nbmax, corbs_list):\n '''\n get transformation from wannier basis to complex spherical harmonics basis.\n '''\n # basis transformation matrix which merges the corelated orbitals\n # to the first places, followed by the uncorrelated orbitals.\n ubasis = np.zeros((nbmax,nbmax), dtype=np.complex)\n # the spin-orbital index remapping accordingly.\n orbs_map = []\n for i, corbs in enumerate(corbs_list):\n norbs = len(corbs)\n for j1 in range(norbs):\n orbs_map.append(corbs[j1])\n # appending the uncorrelated orbitals\n for i in range(nbmax):\n if i not in orbs_map:\n orbs_map.append(i)\n # ubasis: \n for i in range(nbmax):\n ubasis[orbs_map[i],i] = 1.\n\n # Unitary transformation from complex Harmonics to wannier.\n u_csh2wan_list = get_u_csh2wan_all([len(corbs) for corbs in corbs_list])\n # get the transformation from wannier basis to correlated\n # orbital-ordered complex spherical Harmonics basis.\n u_csh2wan = block_diag(*u_csh2wan_list)\n ncorbs = u_csh2wan.shape[0]\n u_wan2csh = ubasis.copy()\n u_wan2csh[:,:ncorbs] = ubasis[:,:ncorbs].dot(u_csh2wan.T.conj())\n return u_wan2csh\n\n\ndef wrt_ginit(symbols, cell, scaled_positions, u_wan2csh, lrot_list=None):\n with h5py.File(\"ginit.h5\", \"w\") as f:\n f['/struct/symbols'] = symbols\n f['/struct/cell'] = cell\n f['/struct/scaled_positions'] = scaled_positions\n if lrot_list is not None:\n f['/struct/locrot_list'] = lrot_list\n f[\"/u_wan2csh\"] = u_wan2csh\n\n\ndef update_ginit(u_wan2csh):\n with h5py.File(\"ginit.h5\", \"a\") as f:\n u = f[\"/u_wan2csh\"][()]\n if u.shape != u_wan2csh.shape:\n del f[\"/u_wan2csh\"]\n f[\"/u_wan2csh\"] = u_wan2csh\n\n\ndef wrt_gparambands(numk, nbmax, ne_list, wk_list, kpoints, nelectron,\n h1e_list, iso=1, ispin=1, ismear=0, delta=0.0258):\n # single file for the dft band structure information\n # beyond that included in 'BAREHAM_$myrank.h5' files.\n with h5py.File('GPARAMBANDS.h5', 'w') as f:\n # spin-orbit coupling\n f['/iso/'] = [iso]\n # spin\n f['/ispin'] = [ispin]\n # k-points dimension\n f['/kptdim'] = [numk]\n # maximal number of bands\n f['/nbmax'] = [nbmax]\n # band indices associated with local orbital construction.\n f['/NE_LIST_SPIN1'] = ne_list\n # k-points weight\n f['/kptwt'] = wk_list\n # k-points\n f[\"/kpoints\"] = kpoints\n # brillouin zone integration method: fermi or gaussian smearing\n f['/ismear'] = [ismear]\n # smearing factor\n f['/delta'] = [delta]\n # number of valence electrons in the wannier manifold\n f['/nelectron'] = [nelectron]\n # number symmetry operations\n f['/symnop'] = [1]\n # the index of identity symmetry operation\n f['/symie'] = [1]\n for isp, h1es in enumerate(h1e_list):\n for i, h1e in enumerate(h1es):\n # local one-body of the dft hamiltonian\n f['/IMPURITY_{}/H1E_SPIN{}'.format(i+1, isp+1)] = h1e.T\n\n\ndef wannier_den_matrix(wannier_path=\"./\"):\n '''produce the file `wannier_den_matrix.dat` for the feedback from\n g-risb to dft.\n '''\n _, _, kpts, include_bands, wfwannier_list, bnd_es_in = \\\n mpiget_wannier_data(path=wannier_path)\n bnd_es, bnd_vs = mpiget_bndev(kpts, wfwannier_list=wfwannier_list,\n bnd_es_in=bnd_es_in, mode=\"risb\")\n nktot = len(kpts)\n with h5py.File(\"GPARAMBANDS.h5\", \"r\") as f:\n delta = f[\"/delta\"][0]\n ismear = f[\"/ismear\"][0]\n iso = f[\"/iso\"][0]\n num_elec = f[\"/nelectron\"][0]\n comm = MPI.COMM_WORLD\n rank = comm.Get_rank()\n # set wk_list\n wklist = [1./nktot for i in range(bnd_es.shape[1])]\n if rank == 0:\n efermi = get_fermi_level(bnd_es, wklist, num_elec, delta=delta, \\\n ismear=ismear, iso=iso)\n else:\n efermi = None\n efermi = comm.bcast(efermi, root=0)\n ncpu = comm.Get_size()\n nk_cpu = nktot//ncpu\n if nk_cpu*ncpu < nktot:\n nk_cpu += 1\n # reduce bnd_es to local part only\n if rank == 0:\n bnd_es = bnd_es[:nk_cpu]\n wklist = wklist[:nk_cpu]\n # set fermi weight\n ferwes = get_fermi_weight(efermi, bnd_es, wklist, delta=delta,\n ismear=ismear, iso=iso)\n # calculate wannier_den_matrix\n wan_den = get_wannier_den_matrix_risb(bnd_vs, ferwes, wklist, nktot)\n if rank == 0:\n fwrt_wan_den(wan_den, wfwannier_list, include_bands)\n\n\ndef wannier_den_matrix_lda_chk(wannier_path=\"./\"):\n '''produce the file `wannier_den_matrix.dat` for the feedback from\n g-risb to dft.\n '''\n _, _, kpts, include_bands, _, bnd_es = mpiget_wannier_data(\n path=wannier_path)\n nktot = len(kpts)\n with h5py.File(\"GPARAMBANDS.h5\", \"r\") as f:\n num_elec = f[\"/nelectron\"][0]\n\n # chop bnd_es\n nbnd = bnd_es.shape[2]\n nwan = int(num_elec/2+3)\n bnd_es = bnd_es[:,:,:nwan]\n # set wk_list\n wklist = [1./nktot for i in range(bnd_es.shape[1])]\n efermi = get_fermi_level(bnd_es, wklist, num_elec, ismear=-1)\n # set fermi weight\n ferwes = get_fermi_weight(efermi, bnd_es, wklist, ismear=-1)\n # setup trivial wannier_den data.\n wan_den = [[]]\n wfwannier_list = [[]]\n vmat = np.zeros((nbnd, nwan), dtype=np.complex)\n np.fill_diagonal(vmat, 1.0)\n for ik in range(nktot):\n wfwannier_list[-1].append(vmat)\n wan_den[0].append(np.diag(ferwes[0][ik]*nktot/(2+0.j)))\n wan_den = np.asarray(wan_den)\n wfwannier_list = np.asarray(wfwannier_list)\n fwrt_wan_den(wan_den, wfwannier_list, include_bands)\n\n\ndef wannier_den_matrix_lda_chk2(wannier_path=\"./\"):\n '''produce the file `wannier_den_matrix.dat` for the feedback from\n g-risb to dft.\n '''\n _, _, kpts, include_bands, wfwannier_list, bnd_es = mpiget_wannier_data(\n path=wannier_path)\n nktot = len(kpts)\n with h5py.File(\"GPARAMBANDS.h5\", \"r\") as f:\n num_elec = f[\"/nelectron\"][0]\n # set wk_list\n wklist = [1./nktot for i in range(bnd_es.shape[1])]\n efermi = get_fermi_level(bnd_es, wklist, num_elec, ismear=-1)\n # set fermi weight\n ferwes = get_fermi_weight(efermi, bnd_es, wklist, ismear=-1)\n # setup trivial wannier_den data.\n wan_den = [[]]\n for ik in range(nktot):\n dm = np.diag(ferwes[0][ik]*nktot/(2+0.j))\n wan_den[0].append(wfwannier_list[0][ik].T.conj().dot(dm).dot(\n wfwannier_list[0][ik]))\n wan_den = np.asarray(wan_den)\n fwrt_wan_den(wan_den, wfwannier_list, include_bands)\n\n\ndef wannier_den_matrix_lda_chk3(wannier_path=\"./\"):\n '''produce the file `wannier_den_matrix.dat` for the feedback from\n g-risb to dft.\n '''\n _, _, kpts, include_bands, wfwannier_list, bnd_es = mpiget_wannier_data(\n path=wannier_path)\n nktot = len(kpts)\n with h5py.File(\"GPARAMBANDS.h5\", \"r\") as f:\n num_elec = f[\"/nelectron\"][0]\n # set wk_list\n wklist = [1./nktot for i in range(bnd_es.shape[1])]\n # get eigen-vector from interpolation\n bnd_es2 = [[]]\n bnd_ev2 = [[]]\n for ik in range(nktot):\n hk = wfwannier_list[0][ik].T.conj().dot(np.diag(bnd_es[0][ik])).dot(\n wfwannier_list[0][ik])\n w, v = np.linalg.eigh(hk)\n bnd_es2[0].append(w)\n bnd_ev2[0].append(v)\n bnd_ev2 = np.asarray(bnd_ev2)\n with h5py.File(\"ev_lda_ref.h5\", \"w\") as f:\n f[\"e\"] = bnd_es2\n f[\"v\"] = bnd_ev2\n efermi = get_fermi_level(bnd_es2, wklist, num_elec, ismear=-1)\n # set fermi weight\n ferwes = get_fermi_weight(efermi, bnd_es2, wklist, ismear=-1)\n # setup trivial wannier_den data.\n wan_den = [[]]\n for ik in range(nktot):\n dm = np.diag(ferwes[0][ik]*nktot/(2+0.j))\n wan_den[0].append(bnd_ev2[0][ik].dot(dm).dot(\n bnd_ev2[0][ik].T.conj()))\n wan_den = np.asarray(wan_den)\n fwrt_wan_den(wan_den, wfwannier_list, include_bands)\n\n\ndef fwrt_wan_den(wan_den, wfwannier_list, include_bands):\n \"\"\"write wannier_den_matrix.dat file in fortran binary format.\n for spin-restricted case only as of now.\n note the index order wfwannier_list[isp, ibnd, iwann].\n \"\"\"\n nktot = wan_den.shape[1]\n wfwannier_list = wfwannier_list.swapaxes(2, 3)\n nband = wfwannier_list.shape[3]\n nwann = wfwannier_list.shape[2]\n with FortranFile('wannier_den_matrix.dat', 'w') as f:\n f.write_record(300.0)\n f.write_record(nktot)\n f.write_record([nband for k in range(nktot)])\n f.write_record([nwann for k in range(nktot)])\n f.write_record([include_bands for k in range(nktot)])\n f.write_record(wfwannier_list[0])\n f.write_record(wan_den[0].swapaxes(1, 2))\n\n\ndef get_risb_bndes(path=\"./\"):\n num_list = [int(x.split(\"_\")[1].split(\".\")[0]) \\\n for x in glob.glob(path+\"/GBANDS_*.h5\")]\n num_list.sort()\n bnd_es = []\n for isp in range(2):\n for i in num_list:\n fband = \"GBANDS_{}.h5\".format(i)\n with h5py.File(fband, \"r\") as f:\n if \"/ISPIN_{}\".format(isp+1) in f:\n if len(bnd_es) == isp:\n bnd_es.append([])\n ik_start = f[\"/IKP_START\"][0]\n ik_end = f[\"/IKP_END\"][0]\n for ik in range(ik_start, ik_end+1):\n bnd_es[isp].append(f[\"/ISPIN_{}/IKP_{}/ek\".format(\\\n isp+1, ik)][()])\n bnd_es = np.asarray(bnd_es)\n return bnd_es\n", "meta": {"hexsha": "f46e1e655eef6487880c06b9ce5b492ce13b7e23", "size": 19674, "ext": "py", "lang": "Python", "max_stars_repo_path": "ComRISB/pyglib/pyglib/iface/ifwannier.py", "max_stars_repo_name": "comscope/comsuite", "max_stars_repo_head_hexsha": "d51c43cad0d15dc3b4d1f45e7df777cdddaa9d6c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2019-06-15T18:08:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T05:01:29.000Z", "max_issues_repo_path": "ComRISB/pyglib/pyglib/iface/ifwannier.py", "max_issues_repo_name": "comscope/Comsuite", "max_issues_repo_head_hexsha": "b80ca9f34c519757d337487c489fb655f7598cc2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ComRISB/pyglib/pyglib/iface/ifwannier.py", "max_forks_repo_name": "comscope/Comsuite", "max_forks_repo_head_hexsha": "b80ca9f34c519757d337487c489fb655f7598cc2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2019-06-05T02:57:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T02:54:25.000Z", "avg_line_length": 38.652259332, "max_line_length": 79, "alphanum_fraction": 0.5947443326, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.24798742068237778, "lm_q1q2_score": 0.1326976791263068}} {"text": "import numpy as np\nfrom numbers import Number\nimport typing\nimport warnings\n\nfrom .steps import _ModelStep\nfrom ._model_utils import get_gap_from_model\nfrom ._step_utils import HeightOptimisationFunction, make_interpolation_func\n\n__all__ = ['QuasiStaticStep']\n\n\nclass QuasiStaticStep(_ModelStep):\n \"\"\"\n A model step for quasi static relative movement\n\n To be used for loading, unloading and sliding as well as quasi static impacts, can be used for rolling-sliding\n with appropriate sub models for tangential behaviour.\n\n Parameters\n ----------\n\n step_name: str\n An identifying name for the step used for errors and outputs\n number_of_steps: int\n The number of sub steps the problem will be split into, together with the time_period this controls the duration\n of the time steps used\n no_time: bool, optional (False)\n Set to true if there is no time dependence and the time steps can be solved in any order (no permanent changes\n between steps such as plastic deformation or heat generation), if True the model will be solved more efficiently\n time_period: float, optional (1.0)\n The total time period of this model step, used for solving sub-models and writing outputs\n off_set_x, off_set_y: float or Sequence of float, optional (0.0)\n The off set between the surfaces in the x and y directions, this can be a relative off set or an absolute off\n set, controlled by the relative_loading parameter:\n\n * A constant (float) value, indicating a constant offset between the surfaces (no relative movement of profiles)\n * A two element sequence of floats, indicating the the start and finish offsets, if this is used, the\n movement_interpolation_mode will be used to generate intermediate values\n * A 2 by n array of n absolute position values and n time values normalised to a 0-1 scale. array[0] should be\n position values and array[1] should be time values, time values must be between 0 and 1. The\n movement_interpolation_mode will be used to generate intermediate values\n interference, normal_load: float or Sequence of float, optional (None)\n The interference and normal load between the surfaces, only one of these can be set (the other will be solved\n for) setting neither keeps the interference as it is at the start of this model step. As above for the off sets,\n either of these parameters can be:\n\n * A constant (float) value, indicating a constant load/ interference between the surfaces.\n * A two element sequence of floats, indicating the the start and finish load. interference, if this is used, the\n movement_interpolation_mode will be used to generate intermediate values\n * A 2 by n array of n absolute position values and n time values normalised to a 0-1 scale. array[0] should be\n position values and array[1] should be time values, time values must be between 0 and 1. The\n movement_interpolation_mode will be used to generate intermediate values\n relative_loading: bool, optional (False)\n If True the load or displacement and off set will be applied relative to the value at the start of the step,\n otherwise the absolute value will be used. eg, if the previous step ended with a load of 10N and this step ramps\n from 0 to 10N setting relative_loading to True will ramp the total load form 10 to 20N over this step.\n adhesion: bool, optional (True)\n If True the adhesion model set for the contact model will be used, If set to false this step will ignore the\n adhesion model (typically used for loading steps)\n unloading: bool, optional (False)\n If True the contact nodes will be constrained to be a sub set of those found in the previous time step.\n fast_ld: bool, optional (False)\n If True the load and displacements can be swapped to give a faster simulation, eg: if 100 equally spaced load\n steps are specified by a start and finish load, the displacement at the maximum load will be found and instead\n 100 equally spaced displacement controlled steps will solved between just touching and the maximum deflection.\n This swapping makes the computation much faster as it removes an optimisation loop.\n impact_properties: list, optional (None)\n This is currently not supported, providing a value will cause an error\n movement_interpolation_mode: str or int, optional ('linear')\n Any valid input to scipy.interpolate.interp1d as the 'kind' parameter, using 'nearest', 'previous' or 'next'\n will cause a warning. This parameter controls how the offset and loading is interpolated over the step\n profile_interpolation_mode: {'nearest', 'linear'}, optional ('nearest')\n Used to generate the grid points for the second surface at the location of the grid points for the first\n surface, nearest ensures compatibility with sub models which change the profile, if the grid spacings of the\n surfaces match\n periodic_geometry: bool, optional (False)\n If True the surface profile will warp when applying the off set between the surfaces\n periodic_axes: tuple, optional ((False, False))\n For each True value the corresponding axis will be solved by circular convolution, meaning the result is\n periodic in that direction\n periodic_im_repeats: tuple, optional (1,1)\n The number of times the influence matrix should be wrapped along periodic dimensions, only used if at least one\n of periodic axes is True. This is necessary to ensure truly periodic behaviour, no physical limit exists\n method: {'auto', 'pk', 'double'}, optional ('auto')\n The method by which the normal contact is solved, only used for load controlled contact.\n 'pk' uses the Polonsky and Keer algorithm for elastic contact.\n 'double' uses a double iteration procedure, suitable for elastic contact with a maximum pressure.\n 'auto' automatically selects 'pk' if there is no maximum pressure and 'double' if there is.\n max_it_interference: int, optional (100)\n The maximum number of iterations used to find the interference between the surfaces, only used if\n a total normal load is specified (Not used if contact is displacement controlled)\n rtol_interference: float, optional (1e-3)\n The relative tolerance on the load used as the convergence criteria for the interference optimisation loop, only\n used if a total normal load is specified (Not used if contact is displacement controlled)\n max_it_displacement: int, optional (100)\n The maximum number of iterations used to find the surface pressures from the interference, used for all IM\n based materials\n rtol_displacement: float, optional (1e-4)\n The norm of the residual used to declare convergence of the bccg iterations\n no_update_warning: bool, optional (True)\n Change to False to suppress warning given when no movement or loading changes are specified\n upper: float, optional (4.0)\n For load controlled contact the upper bound for the interference between the bodies will be this factor\n multiplied by the largest just touching gap. 4 is suitable for flat on flat contacts but for ball on flat\n contacts a lower value will give faster converging solutions\n\n Examples\n --------\n In the following example we model the contact between a rough cylinder and a flat plane.\n Both surface are elastic. This code could be used to generate load displacement curves.\n\n >>> import slippy.surface as s\n >>> import slippy.contact as c\n >>> # define contact geometry\n >>> cylinder = s.RoundSurface((1 ,np.inf, 1), shape=(256, 256), grid_spacing=0.001)\n >>> roughness = s.HurstFractalSurface(1, 0.2, 1000, shape=(256, 256), grid_spacing=0.001,\n >>> generate = True)\n >>> combined = cylinder + roughness * 0.00001\n >>> flat = s.FlatSurface(shape=(256, 256), grid_spacing=0.001, generate = True)\n >>> # define material behaviour and assign to surfaces\n >>> material = c.Elastic('steel', properties = {'E':200e9, 'v':0.3})\n >>> combined.material = material\n >>> flat.material = material\n >>>\n >>> # make a contact model\n >>> my_model = c.ContactModel('qss_test', combined, flat)\n >>>\n >>> # make a modelling step to describe the problem\n >>> max_int = 0.002\n >>> n_time_steps = 20\n >>> my_step = c.QuasiStaticStep('loading', n_time_steps, no_time=True,\n >>> interference = [max_int*0.001, max_int],\n >>> periodic_geometry=True, periodic_axes = (False, True))\n >>> # add the steps to the model\n >>> my_model.add_step(my_step)\n >>> # add output requests\n >>> output_request = c.OutputRequest('Output-1',\n >>> ['interference', 'total_normal_load',\n >>> 'loads_z', 'total_displacement',\n >>> 'converged'])\n >>> my_step.add_output(output_request)\n >>> # solve the model\n >>> final_result = my_model.solve()\n \"\"\"\n _just_touching_gap = None\n _adhesion_model = None\n _initial_contact_nodes = None\n _upper = None\n\n def __init__(self, step_name: str, number_of_steps: int, no_time: bool = False,\n time_period: float = 1.0,\n off_set_x: typing.Union[float, typing.Sequence[float]] = 0.0,\n off_set_y: typing.Union[float, typing.Sequence[float]] = 0.0,\n interference: typing.Union[float, typing.Sequence[float]] = None,\n normal_load: typing.Union[float, typing.Sequence[float]] = None,\n relative_loading: bool = False,\n adhesion: bool = True,\n unloading: bool = False,\n fast_ld: bool = False,\n impact_properties: dict = None,\n movement_interpolation_mode: str = 'linear',\n profile_interpolation_mode: str = 'nearest',\n periodic_geometry: bool = False, periodic_axes: tuple = (False, False),\n periodic_im_repeats: tuple = (1, 1), method: str = 'auto',\n max_it_interference: int = 100, rtol_interference=1e-3,\n max_it_displacement: int = None, rtol_displacement=1e-5, no_update_warning: bool = True,\n upper: float = 4.0):\n\n # movement interpolation mode sort out movement interpolation mode make array of values\n if impact_properties is not None:\n raise NotImplementedError(\"Impacts are not yet implemented\")\n # work out the time step if needed:\n self._no_time = no_time\n self.total_time = time_period\n if not no_time and fast_ld:\n raise ValueError(\"Cannot have time dependence and fast_ld, either set no_time True or set fast_ld False\")\n self._periodic_im_repeats = periodic_im_repeats\n self._fast_ld = fast_ld\n self._relative_loading = relative_loading\n self.profile_interpolation_mode = profile_interpolation_mode\n self._periodic_profile = periodic_geometry\n self._periodic_axes = periodic_axes\n self._max_it_interference = max_it_interference\n self._rtol_interference = rtol_interference\n self._max_it_displacement = max_it_displacement\n self._rtol_displacement = rtol_displacement\n self.number_of_steps = number_of_steps\n\n if method not in {'auto', 'pk', 'double'}:\n raise ValueError(f\"Unrecognised method for step {step_name}: {method}\")\n\n self._method = method\n self._height_optimisation_func = None\n self._adhesion = adhesion\n self._unloading = unloading\n self._upper_factor = upper\n\n self.time_step = time_period / number_of_steps\n\n # check that something is actually changing\n self.update = set()\n\n if not isinstance(off_set_x, Number) or not isinstance(off_set_y, Number):\n if no_time:\n raise ValueError(\"Can not have no time dependence and sliding contact\")\n off_set_x = [off_set_x] * 2 if isinstance(off_set_x, Number) else off_set_x\n off_set_y = [off_set_y] * 2 if isinstance(off_set_y, Number) else off_set_y\n off_set_x_func = make_interpolation_func(off_set_x, movement_interpolation_mode, 'relative_off_set_x')\n off_set_y_func = make_interpolation_func(off_set_y, movement_interpolation_mode, 'relative_off_set_y')\n self._off_set_upd = lambda time: np.array([off_set_x_func(time), off_set_y_func(time)])\n self.update.add('off_set')\n self.off_set = None\n else:\n self.off_set = np.array([off_set_x, off_set_y])\n\n if normal_load is not None and interference is not None:\n raise ValueError(\"Both normal_load and interference are set, only one of these can be set\")\n if normal_load is None and interference is None:\n if relative_loading:\n interference = 0\n else:\n raise ValueError(\"Cannot have no set load or interference and not relative loading, set either the\"\n \"normal load, normal interference or change relative_loading to True\")\n\n if normal_load is not None:\n if isinstance(normal_load, Number):\n self.normal_load = normal_load\n else:\n self.normal_load = None\n self._normal_load_upd = make_interpolation_func(normal_load, movement_interpolation_mode,\n 'normal_load')\n self.update.add('normal_load')\n self.load_controlled = True\n else:\n self.normal_load = None\n\n if interference is not None:\n if isinstance(interference, Number):\n self.interference = interference\n else:\n self.interference = None\n self._interference_upd = make_interpolation_func(interference, movement_interpolation_mode,\n 'interference')\n self.update.add('interference')\n self.load_controlled = False\n\n if not self.update and no_update_warning:\n warnings.warn(\"Nothing set to update\")\n\n provides = {'off_set', 'loads_z', 'surface_1_displacement_z', 'surface_2_displacement_z',\n 'total_displacement_z', 'interference', 'just_touching_gap', 'surface_1_points', 'contact_nodes',\n 'surface_2_points', 'time', 'time_step', 'new_step', 'converged', 'gap', 'total_normal_load'}\n super().__init__(step_name, time_period, provides)\n\n def solve(self, previous_state, output_file):\n current_time = previous_state['time']\n if self._fast_ld:\n # solve the normal contact problem\n raise NotImplementedError(\"TODO\")\n # TODO\n # change to disp controlled, set the displacement variable\n\n for s in self.sub_models:\n s.no_time = self._no_time\n\n if self.load_controlled:\n update_func = self._solve_load_controlled\n else: # displacement controlled\n update_func = self._solve_displacement_controlled\n\n relative_time = np.linspace(0, 1, self.number_of_steps + 1)[1:]\n just_touching_gap = None\n\n original = dict()\n\n if self._relative_loading:\n original['normal_load'] = previous_state['total_normal_load'] if 'total_normal_load' in previous_state \\\n else 0\n original['interference'] = previous_state['interference'] if 'interference' in previous_state else 0\n original['off_set'] = np.array(previous_state['off_set']) if 'off_set' in previous_state else \\\n np.array([0, 0])\n\n self._adhesion_model = self.model.adhesion if self._adhesion else None\n\n current_state = dict()\n\n for i in range(self.number_of_steps):\n self.update_movement(relative_time[i], original)\n # find overlapping nodes\n if 'off_set' in self.update or just_touching_gap is None or not self._no_time:\n just_touching_gap, surface_1_points, surface_2_points \\\n = get_gap_from_model(self.model, interference=0, off_set=self.off_set,\n mode=self.profile_interpolation_mode, periodic=self._periodic_profile)\n self._just_touching_gap = just_touching_gap\n self._upper = None\n current_state = dict(just_touching_gap=just_touching_gap, surface_1_points=surface_1_points,\n surface_2_points=surface_2_points, off_set=self.off_set,\n time_step=self.time_step)\n if i == 0:\n current_state['new_step'] = True\n else:\n current_state['new_step'] = False\n # solve contact\n if self._unloading and 'contact_nodes' in previous_state:\n initial_contact_nodes = previous_state['contact_nodes']\n else:\n initial_contact_nodes = None\n\n self._initial_contact_nodes = initial_contact_nodes\n print('#####################################################\\nTime step:', i,\n '\\n#####################################################')\n print('Set load:', self.normal_load)\n\n results = update_func(current_state)\n current_state.update(results)\n current_state['gap'] = (just_touching_gap - current_state['interference'] +\n current_state['total_displacement_z'])\n current_time += self.time_step\n current_state['time'] = current_time\n # solve sub models\n self.solve_sub_models(current_state)\n self.save_outputs(current_state, output_file)\n\n return current_state\n\n @property\n def upper(self):\n if self._upper is None:\n self._upper = np.max(self._just_touching_gap) * self._upper_factor\n return self._upper\n\n def update_movement(self, relative_time, original):\n for name in self.update:\n if self._relative_loading:\n self.__setattr__(name, original[name] + self.__getattribute__(f'_{name}_upd')(relative_time))\n else:\n self.__setattr__(name, self.__getattribute__(f'_{name}_upd')(relative_time))\n\n def _solve_load_controlled(self, current_state) -> dict:\n # if there is time dependence or we don't already have one, make a new height optimiser\n if not self._no_time or self._height_optimisation_func is None:\n opt_func = HeightOptimisationFunction(just_touching_gap=self._just_touching_gap,\n model=self.model,\n adhesion_model=self._adhesion_model,\n initial_contact_nodes=self._initial_contact_nodes,\n max_it_inner=self._max_it_displacement,\n tol_inner=self._rtol_displacement,\n material_options=dict(),\n max_set_load=self.normal_load,\n tolerance=self._rtol_interference,\n periodic_axes=self._periodic_axes,\n periodic_im_repeats=self._periodic_im_repeats)\n self._height_optimisation_func = opt_func\n else:\n opt_func = self._height_optimisation_func\n\n if self._unloading and 'contact_nodes' in current_state:\n contact_nodes = current_state['contact_nodes']\n else:\n contact_nodes = None\n # contact_nodes = np.ones(self._just_touching_gap.shape, dtype=np.bool)\n if self._method == 'auto':\n if np.isinf(opt_func.max_pressure):\n self._method = 'pk'\n else:\n self._method = 'double'\n\n if self._method == 'pk':\n opt_func.contact_nodes = None\n opt_func.p_and_k(self.normal_load)\n else:\n opt_func.change_load(self.normal_load, contact_nodes)\n # need to set bounds and pick a sensible starting point\n upper = self.upper\n print(f'upper bound set at: {upper}')\n if self._no_time:\n brackets = opt_func.get_bounds_from_cache(0, upper)\n else:\n brackets = (0, upper)\n print(f'Bounds adjusted using cache to: {brackets}')\n print(f'Interference tolerance set to {self._rtol_interference} Relative')\n opt_func.brent(0, upper, r_tol=self._rtol_interference, max_iter=self._max_it_interference)\n\n # noinspection PyProtectedMember\n\n results = opt_func.results\n load_conv = (np.abs(results['total_normal_load'] - self.normal_load) / self.normal_load) < 0.05\n results['converged'] = bool(load_conv) and not opt_func.last_call_failed\n return results\n\n def _solve_displacement_controlled(self, current_state):\n if not self._no_time or self._height_optimisation_func is None:\n h_opt_func = HeightOptimisationFunction(just_touching_gap=self._just_touching_gap,\n model=self.model,\n adhesion_model=self._adhesion_model,\n initial_contact_nodes=self._initial_contact_nodes,\n max_it_inner=self._max_it_displacement,\n tol_inner=self._rtol_displacement,\n material_options=dict(),\n max_set_load=1,\n tolerance=self._rtol_interference,\n periodic_axes=self._periodic_axes,\n periodic_im_repeats=self._periodic_im_repeats)\n self._height_optimisation_func = h_opt_func\n else:\n h_opt_func = self._height_optimisation_func\n\n if self._unloading and 'contact_nodes' in current_state:\n contact_nodes = current_state['contact_nodes']\n else:\n contact_nodes = None\n # contact_nodes = np.ones(self._just_touching_gap.shape, dtype=np.bool)\n\n h_opt_func.change_load(1, contact_nodes)\n _ = h_opt_func(self.interference, current_state)\n results = h_opt_func.results\n results['interference'] = self.interference\n results['converged'] = not h_opt_func.last_call_failed\n return results\n\n def __repr__(self):\n return f'{self.name}: QuasiStaticStep'\n", "meta": {"hexsha": "1c25d32048c5874e72dc1095d828add057bd5b47", "size": 23277, "ext": "py", "lang": "Python", "max_stars_repo_path": "slippy/contact/quasi_static_step.py", "max_stars_repo_name": "KDriesen/slippy", "max_stars_repo_head_hexsha": "816723fe6ab9f5ed26b14b4fe0f66423649b85e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2020-12-06T15:30:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T06:37:15.000Z", "max_issues_repo_path": "slippy/contact/quasi_static_step.py", "max_issues_repo_name": "KDriesen/slippy", "max_issues_repo_head_hexsha": "816723fe6ab9f5ed26b14b4fe0f66423649b85e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slippy/contact/quasi_static_step.py", "max_forks_repo_name": "KDriesen/slippy", "max_forks_repo_head_hexsha": "816723fe6ab9f5ed26b14b4fe0f66423649b85e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-03-18T05:53:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T15:18:43.000Z", "avg_line_length": 54.8985849057, "max_line_length": 120, "alphanum_fraction": 0.6338445676, "include": true, "reason": "import numpy", "num_tokens": 4766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.24798742068237775, "lm_q1q2_score": 0.13269767912630678}} {"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\nfrom builtins import zip\nfrom builtins import next\nfrom builtins import str\nfrom builtins import range\nfrom builtins import object\n__all__ = [\"getColors\", \"nColors\", \"allmods\"]\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as mpl_colors\nfrom matplotlib import cm as cmx\nimport fsps\nfrom .generalTools import calcQ, air_to_vac, getEmis\nfrom .astrodata import dopita, sdss, vanzee, kewley\nimport pkg_resources\n\nc = 2.9979e18 #ang/s\nlsun = 3.839e33 #erg/s\nplanck = 6.626e-27\npc_to_cm = 3.08568e18\n\ndef getColors(vals, cname='CMRmap', minv=0.05, maxv=0.8, cmap=None,\n set_bad_vals=False, return_cNorm=False,\n logNorm=False, Ncol=100, return_cmap=False):\n '''\n sM = getColors(arr, cname='jet', minv=0.0, maxv=1.0)\n sM,cNorm = getColors(arr, cmap=cubehelix.cmap(), return_cNorm=True)\n '''\n if cmap is None:\n cmap = plt.get_cmap(cname)\n new_cmap = mpl_colors.LinearSegmentedColormap.from_list('trunc({0}, {1:.2f}, {2:.2f})'.format(cmap.name, minv, maxv), cmap(np.linspace(minv, maxv, Ncol)))\n if set_bad_vals:\n new_cmap.set_bad('white', alpha=1.0)\n if logNorm:\n cNorm = mpl_colors.LogNorm(vmin=vals.min(), vmax=vals.max())\n else:\n cNorm = mpl_colors.Normalize(vmin=vals.min(), vmax=vals.max())\n scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=new_cmap)\n if return_cNorm:\n return scalarMap, cNorm\n if return_cmap:\n color_list = new_cmap(np.linspace(minv, maxv, Ncol))\n cmap_name = new_cmap.name+str(Ncol)\n return new_cmap.from_list(cmap_name, color_list, Ncol)\n else:\n scalarMap.set_array(vals)\n return scalarMap\n\ndef nColors(n, **kwargs):\n '''\n n_colors(50, minv=0.5, maxv=1.0, cname='Blues')\n '''\n sM = getColors(np.linspace(0.0, 1.0), **kwargs)\n colors = [sM.to_rgba(v) for v in np.linspace(0.0, 1.0, n)]\n return colors\n\ndef sextract(text, par1=None, par2=None):\n '''\n to extract stuff from cloudy output\n '''\n if np.size(text) == 1:\n if type(par1) is int:\n str1 = text[par1::]\n elif type(par1) is str or type(par1) is str:\n str1 = text.split(par1)\n if len(str1) == 1:\n return ''\n else:\n str1 = str1[-1]\n else:\n str1 = text\n if type(par2) is int:\n str2 = str1[0:par2]\n elif type(par2) is str or type(par2) is str:\n str2 = str1.split(par2)\n if len(str2) == 1:\n return ''\n else:\n str2 = str2[0]\n else:\n str2 = str1\n return str2\n else:\n res = []\n for subtext in text:\n res1 = sextract(subtext, par1=par1, par2=par2)\n if res1 != '':\n res.append(res1)\n return res\n\nclass modObj(object):\n '''\n '''\n def __init__(self, dir_, prefix, parline, read_out=False, read_rad=False,\n read_cont=False, use_doublet=False, read_emis=False,\n read_heat=False, read_cool=False, **kwargs):\n '''\n this needs to be called from other class or given\n a line from a \".pars\" file\n [0]modnum; [1]logZ; [2]age; [3]logU; [4]logR; [5]logQ\n '''\n self.modnum = int(parline[0])\n self.logZ = parline[1]\n self.age = parline[2]\n self.logU = parline[3]\n self.logR = parline[4]\n self.logQ = parline[5]\n self.nH = parline[6]\n try:\n self.efrac = parline[7]\n except IndexError:\n self.efrac = -1.0\n try:\n self.fbhb = parline[8]\n except IndexError:\n self.fbhb = 0.0\n\n self.logq = np.log10((10.0**self.logQ)/(np.pi*4.0*self.nH*(10.0**self.logR)**2.0))\n self.fl = '{}{}{}'.format(dir_, prefix, self.modnum)\n self.load_lines(use_doublet=use_doublet)\n if read_out:\n self._read_out()\n if read_cont:\n self._load_cont()\n if read_rad:\n self._dat = dict()\n self._init_rad()\n eles = ['H', 'He', 'C', 'N', 'O', 'S', 'Si', 'Fe']\n self.ion_names, self.n_ions, self.ion_arr = dict(), dict(), dict()\n for ele in eles:\n self._init_ele(ele)\n self._init_phys()\n if read_emis:\n self._init_emis()\n if read_heat:\n self._init_heat()\n if read_cool:\n self._init_cool()\n return\n def add_lines(self, lines):\n line_info = np.genfromtxt(self.fl+'.lineflux')\n lam, flu = line_info[:,0], line_info[:,1]\n for name, wav in list(lines.items()):\n matchind = np.argmin(np.abs(lam-wav))\n self.__setattr__(name, flu[matchind])\n return\n def load_lines(self, use_doublet=False, **kwargs):\n names, vacwavs = getEmis()\n self.lines = dict(names=names, wavs=vacwavs)\n lines = {'Lya':1215.67,\n 'Ha':6564.60,\n 'HeI':5877.243,\n 'HeII':4687.015,\n 'HeIIu':1640.42,\n 'Hb':4862.71,\n 'Hg':4341.692,\n 'Hd':4102.892,\n 'OIIIa':4960.295,\n 'OIIIb':5008.240,\n 'NIIa':6549.86,\n 'NIIb':6585.27,\n 'OIIa':3727.10,\n 'OIIb':3729.86,\n 'SIIa':6718.294,\n 'SIIb':6732.673,\n 'OI':6302.046,\n 'NeIIIb':3869.86,\n 'NeIIIa':3968.59,\n 'SIII':6313.81,\n 'ArIII':7137.77}\n line_info = np.genfromtxt(self.fl+'.lineflux')\n lam, flu = line_info[:,0], line_info[:,1]\n for name, wav in list(lines.items()):\n matchind = np.argmin(np.abs(lam-wav))\n self.__setattr__(name, flu[matchind])\n self.HaHb = self.Ha/self.Hb\n def logify(a,b):\n return np.log10(a/b)\n def logHa(x):\n return np.log10(x/self.Ha)\n def logHb(x):\n return np.log10(x/self.Hb)\n self.log_NII_Ha = logHa(self.NIIa+self.NIIb)\n self.log_SII_Ha = logHa(self.SIIa+self.SIIb)\n self.log_OIII_Hb = logHb(self.OIIIa+self.OIIIb)\n #\n self.log_NIIa_Ha = logHa(self.NIIa)\n self.log_NIIb_Ha = logHa(self.NIIb)\n self.log_SIIa_Ha = logHa(self.SIIa)\n self.log_SIIb_Ha = logHa(self.SIIb)\n #\n self.log_OIIIa_Hb = logHb(self.OIIIa)\n self.log_OIIIb_Hb = logHb(self.OIIIb)\n #\n self.log_OIII_OII = logify(self.OIIIa+self.OIIIb, self.OIIa+self.OIIb)\n self.log_OIIIa_OII = logify(self.OIIIa, self.OIIa+self.OIIb)\n self.log_OIIIb_OII = logify(self.OIIIb, self.OIIa+self.OIIb)\n #\n self.log_OI_Ha = logHa(self.OI)\n self.log_NII_OII = logify(self.NIIa+self.NIIb, self.OIIa+self.OIIb)\n self.R23 = logHb(self.OIIa+self.OIIb+self.OIIIa+self.OIIIb)\n return\n def _load_cont(self, dist_corr=False, output_units=False, **kwargs):\n cont_info = np.genfromtxt(self.fl+'.contflux', skip_header=1)\n # erg / s / cm2\n self.lam, self.nebflu = cont_info[:,0], cont_info[:,3]\n self.incflu, self.attflu = cont_info[:,1], cont_info[:,2]\n self.spec_Q = calcQ(self.lam, self.incflu, f_nu=True)\n if dist_corr: # erg/s\n self.nebflu *= self.dist_fact\n self.attflu *= self.dist_fact\n self.incflu *= self.dist_fact\n self.spec_Q = calcQ(self.lam, self.incflu*c/self.lam, f_nu=True)\n elif output_units: # Lsun/Hz\n self.nebflu *= self.dist_fact/lsun * self.lam / c\n self.attflu *= self.dist_fact/lsun * self.lam / c\n self.incflu *= self.dist_fact/lsun * self.lam / c\n self.spec_Q = calcQ(self.lam, self.incflu*lsun, f_nu=True)\n return\n def get_fsps_spec(self, **kwargs):\n sp = fsps.StellarPopulation(zcontinuous=1)\n sp.params['logzsol'] = self.logZ\n lam, spec = sp.get_spectrum(tage=self.age*1.0e-9)\n self.__setattr__('fsps_lam', lam)\n self.__setattr__('fsps_spec', spec)\n self.__setattr__('fsps_Q', calcQ(lam, spec*lsun, f_nu=True))\n return\n def _read_f(self, key, delimiter='\\t', comments=';', names=True, **kwargs):\n '''\n self._read_f('.rad')\n '''\n file_ = self.fl+key\n try:\n return np.genfromtxt(file_,delimiter=delimiter,\n comments=comments,\n names=names, **kwargs)\n except IOError:\n return None\n\n def _init_rad(self):\n '''\n self._init_rad()\n attributes:\n n_zones\n zones\n depth\n thickness (cm)\n radius_all (cm)\n rad_pc (pc)\n dr_all (cm)\n dv_all (cm)\n r_in (cm)\n r_out (cm)\n '''\n self._dat['rad'] = self._read_f('.rad')\n if self._dat['rad'] is not None:\n self.n_zones = self._dat['rad'].size\n self.zones = np.arange(self.n_zones)\n self.depth = self._dat['rad']['depth']\n self.thickness = self.depth[-1]\n self.radius_all = self._dat['rad']['radius']\n self.rad_pc = self.radius_all/pc_to_cm\n self.dr_all = self._dat['rad']['dr']\n self.dv_all = 4.*np.pi*self.radius_all**2*self.dr_all\n self.r_in = self.radius_all[0] - self.dr_all[0]/2.\n self.r_out = self.radius_all[-1] + self.dr_all[0]/2.\n if self.Phi0 == 0.0:\n self.Phiarr = self.Qarr/(4.*np.pi*self.r_in**2.)\n self.Phi0 = self.Phiarr.sum()\n return\n def _init_emis(self):\n '''\n '''\n self._dat['emis'] = self._read_f('.emis')\n if self._dat['emis'] is not None:\n emis = self._dat['emis']\n self.depth = emis['depth']/pc_to_cm\n self.frac_depth = self.depth/(self.rad_pc[-1]-self.rad_pc[0])\n self.emis_labels = np.asarray(emis.dtype.names[1::])\n self.n_emis = np.size(self.emis_labels)\n self.emis_full = np.zeros((self.n_emis, np.size(emis)))\n trans_emis = lambda x: pow(10., x)\n for i, label in enumerate(self.emis_labels):\n self.emis_full[i] = trans_emis(emis[label])\n self.indHe = np.argmin(np.abs(self.ion_arr['He'][1]-0.5))\n self.indH = np.argmin(np.abs(self.ion_arr['H'][1]-0.5))\n return\n def _init_phys(self):\n '''\n self._init_phys()\n adds attributes:\n ne_all: electron density (cm^-3)\n nH_all: hydrogen density (cm^-3)\n Te: electron temperature (K)\n '''\n key = 'phys'\n self._dat[key] = self._read_f('.phys')\n if self._dat[key] is not None:\n self.ne_all = self._dat[key]['ne']\n self.nH_all = self._dat[key]['nH']\n self.nenH = self.ne_all*self.nH_all\n self.Te = self._dat[key]['Te']\n self.ff_all = self._dat[key]['fillfac']\n return\n def _init_cool(self):\n key = 'cool'\n try:\n self._dat[key] = self._read_f('.'+key, comments='#')\n except:\n self._dat[key] = None\n print(\"ERROR\")\n print(self.fl)\n if self._dat[key] is not None:\n attkeys = dict(cool_RecMet='hvFB', # heavy elem recomb cooling\n cool_ColMet='Hvin', # heavy elem collis ionization\n cool_FFC='FFcm', #F-F cooling (non e-)\n cool_H='H',\n cool_He='He',\n cool_N='N',\n cool_O='O',\n cool_S='S',\n cool_Ne='Ne',\n cool_C='C',\n cool_Ar='Ar',\n cool_Fe='Fe',\n cool_Al='Al',\n cool_Si='Si',\n cool_HminFB='Hfb')\n self.cool = self._dat[key]['Ctotergcm3s']\n self.Ctot = self._vol_integ(self.cool)\n for att,keyname in list(attkeys.items()):\n vals = self._dat[key][keyname]\n self.__setattr__(att, vals)\n self.__setattr__('frac_'+att, self._vol_integ(vals)/self.Ctot)\n CE_names = self._dat[key].dtype.names[5:33]\n self.cool_CE = np.sum([self._vol_integ(self._dat[key][elname]) for elname in CE_names])\n self.frac_cool_CE = np.sum([self._vol_integ(self._dat[key][elname])/self.Ctot for elname in CE_names])\n self.frac_cool_FF_FB = self.Cool_HFFc+self.Cool_HFBc\n return\n def _init_heat(self):\n htots, outfs = [], []\n heat_labs = []\n fname = self.fl+'.heat'\n file_ = open(fname, 'r')\n for line in file_:\n if line[0] == '#':\n continue\n line = line.split('\\n')[0]\n lps = line.split('\\t')\n htots.append(lps[2])\n x = lps[4::]\n labs = x[0::2]\n fracs = x[1::2]\n od = {}\n [od.__setitem__(key, float(val)) for key, val in zip(labs,fracs)]\n outfs.append(od)\n for lab in labs:\n if lab not in heat_labs:\n heat_labs.append(lab)\n hf = {}\n [hf.__setitem__(lab,\n np.array([outf[lab]\n if lab in list(outf.keys())\n else 0.0 for outf in outfs]))\n for lab in heat_labs]\n Htots = np.array([float(htot) for htot in htots])\n Htot = self._vol_integ(Htots)\n hr = {}\n for key, arr in list(hf.items()):\n hr.__setitem__(key, np.sum(self._vol_integ(arr*Htots))/Htot)\n self.__setattr__('heatfracs', hr)\n return\n def _init_ele(self, key):\n '''\n keys = [H, He, C, N, O, S, Si, Fe]\n attributes:\n ion_names['C'] = C__1, C__2,...C__n\n n_ions['C'] = n\n ion_arr['C'][0] = f1, f2,...,f_r\n '''\n self._dat[key] = self._read_f('.ele_'+key)\n if self._dat[key] is not None:\n ion_names = self._dat[key].dtype.names[1:]\n n_ions = np.size(ion_names)\n ion_arr = np.zeros((n_ions, self.n_zones))\n for i, ion in enumerate(ion_names):\n ion_arr[i,:] = self._dat[key][ion]\n self.ion_names[key] = ion_names\n self.n_ions[key] = n_ions\n self.ion_arr[key] = ion_arr\n return\n\n @property\n def dvff(self):\n try:\n return self.dv_all*self.ff_all\n except:\n return None\n\n def _quiet_div(self, a, b):\n if a is None or b is None:\n to_return = None\n else:\n np.seterr(all=\"ignore\")\n to_return = a/b\n np.seterr(all=None)\n return to_return\n def _vol_cum(self, a):\n if a is None or self.dvff is None:\n return None\n else:\n return (a*self.dvff).cumsum()\n def _vol_integ(self, a):\n if a is None or self.dvff is None:\n return None\n else:\n return (a*self.dvff).sum()\n def _dV(self, a):\n if a is None or self.dvff is None:\n return None\n else:\n return (a*self.dvff)\n def _vol_mean(self, a, b=1.):\n return self._quiet_div(self._vol_integ(a*b), self._vol_integ(b))\n\n @property\n def T0(self):\n try:\n return self._vol_mean(self.Te, self.nenH)\n except:\n return None\n\n @property\n def Tpiem(self):\n try:\n return self._vol_mean((self.Te - self.T0)**2./self.nenH, self.T0**2)\n except:\n return None\n def _i_emis(self, ref):\n '''\n get index for emissivity by label or index\n '''\n if type(ref) is str or type(ref) is np.string_:\n if ref in self.emis_labels:\n to_return = np.squeeze(np.where(self.emis_labels == ref)).item()\n else:\n return None\n elif type(ref) is int or type(ref) is np.int32:\n to_return = ref\n else:\n to_return = None\n return to_return\n def get_emis(self, ref):\n '''\n return emissivity.\n '''\n if self._i_emis(ref) is not None:\n return self.emis_full[self._i_emis(ref)]\n else:\n return None\n def get_cumVol_emis(self, ref):\n if self._i_emis(ref) is not None:\n return\n else:\n return None\n def get_emis_vol(self, ref):\n '''\n return integration of the emissivity on the volume\n '''\n return self._vol_integ(self.get_emis(ref))\n def get_frac_emis(self, ref):\n '''\n emiss dV / tot emiss\n '''\n return self._dV(self.get_emis(ref))/self.get_emis_vol(ref)\n def get_emis_rad(self, ref):\n '''\n return integration of the emissivity on the radius\n '''\n return self._rad_integ(self.get_emis(ref))\n def _read_out(self):\n '''\n self._read_out()\n attributes:\n dist_fact: 4 pi Rinner^2 (cm^2)\n Phi0: ionizing photon flux (s^-1 cm^-2)\n clogQ: Phi0 * dist_fact = Q (s-1)\n gasC, gasN, gasO: n relative to H\n DGR: dust to gas ratio\n Av_ex: extinction from extended source\n Av_pt: extinction from pt source\n '''\n filename = self.fl+'.out'\n self.out = {}\n file_ = open(filename, 'r')\n for line in file_:\n line = line.split('\\n')[0]\n if line[0:8] == ' #### 1':\n self.out['###First'] = line\n elif line[0:5] == ' ###':\n self.out['###Last'] = line\n elif 'Hi-Con' in line:\n for i in range(7):\n self.out['SED' + str(i+1)] = next(file_)\n elif line[0:15] == ' IONIZE PARMET:':\n self.out['INZ'] = line\n elif 'H :' in line:\n self.out['gascomp'] = line\n elif 'Dust to gas ratio' in line:\n self.out['dust'] = line\n elif 'ENERGY BUDGET' in line:\n self.out['energy'] = line\n elif 'Cooling:' in line:\n self.out['cool'] = line\n elif 'Heating:' in line:\n self.out['heat'] = line\n elif line[0:5] == ' HFBc':\n self.out['HFBc'] = line\n elif 'The geometry is' in line:\n self.out['geometry'] = line\n file_.close()\n self.dist_fact = 4.0*np.pi*(10.0**self.logR)**2.0\n try:\n self.H_Rec_Lum = float(sextract(sextract(self.out['HFBc'], 'HFBc', 18), 9, 8))\n except:\n self.H_Rec_Lum = 0.0\n #print(sextract(sextract(self.out['HFBc'], 'HFBc', 18), 9, 8))\n #self.Phi0 = float(sextract(self.out['SED2'], 'Ion pht flx:'))\n # Ion pht flx: phi(H) = Q/4piR2\n #self.clogQ = np.log10(self.Phi0*self.dist_fact)\n self.strom_logU = float(sextract(self.out['INZ'], 'U(sp):', 'Q(ion):'))\n # Q(ion) is exiting\n self.Qarr = np.zeros(4)\n self.Phiarr = np.zeros(4)\n try:\n self.Qarr[0] = float(sextract(self.out['SED2'], 'Q(1.0-1.8):', 'Q(1.8-4.0):'))\n self.Qarr[1] = float(sextract(self.out['SED2'], 'Q(1.8-4.0):', 'Q(4.0-20):'))\n self.Qarr[2] = float(sextract(self.out['SED2'], 'Q(4.0-20):', 'Q(20--):'))\n self.Qarr[3] = float(sextract(self.out['SED2'], 'Q(20--):', 'Ion pht'))\n self.Qarr = pow(10., self.Qarr)\n self.input_lum = True\n except:\n pass\n self.Qh = self.Qarr.sum()\n try:\n self.Phiarr[0] = float(sextract(self.out['SED2'], 'phi(1.0-1.8):', 'phi(1.8-4.0):'))\n self.Phiarr[1] = float(sextract(self.out['SED2'], 'phi(1.8-4.0):', 'phi(4.0-20):'))\n self.Phiarr[2] = float(sextract(self.out['SED2'], 'phi(4.0-20):', 'phi(20--):'))\n self.Phiarr[3] = float(sextract(self.out['SED2'], 'phi(20--):', 'Ion pht'))\n self.Phiarr = pow(10., self.Phiarr)\n self.input_lum = False\n except:\n pass\n self.Phi0 = self.Phiarr.sum()\n if self.Qh == 0.0:\n self.Qarr = self.Phiarr*self.dist_fact\n self.Qh = self.Qarr.sum()\n self.Qhe = self.Qarr[1::].sum()\n self.QhQhe = np.log10(self.Qh) - np.log10(self.Qhe)\n self._set_lineCool()\n try:\n self.Heat_BF = float(sextract(sextract(self.out['heat'], 'BFH1', 14), ':', 5))\n except:\n self.Heat_BF = 0.0\n self.Heat = float(sextract(self.out['energy'], 'Heat:', 'Coolg:'))\n self.Cool = float(sextract(self.out['energy'], 'Coolg:', 'Error:'))\n self.RecLin = float(sextract(self.out['energy'], 'Rec Lin:', 8))\n self.gasC = float(sextract(self.out['gascomp'], 'C :', 8))\n self.gasN = float(sextract(self.out['gascomp'], 'N :', 8))\n self.gasO = float(sextract(self.out['gascomp'], 'O :', 8))\n if 'dust' in self.out:\n self.DGR = float(sextract(self.out['dust'], '(by mass):',',' ))\n self.Av_ex = float(sextract(self.out['dust'], 'AV(ext):', '(pnt)'))\n self.Av_pt = float(sextract(self.out['dust'], ' (pnt):'))\n return\n def _set_lineCool(self):\n keys = ['HFBc', 'HFFc', 'Clin 912.000A:', 'N 2 6584.00A:',\n ' S II 6731.00A:','S II 6716.00A:', 'TOTL 3727.00A:',\n 'S 3 9532.00A:', 'O 3 5007.00A:', 'O 3 4959.00A:']\n keyattrs = ['HFBc', 'HFFc', 'Ly', 'NII', 'SIIb', 'SIIa',\n 'O_3727', 'SIII', 'O_5007', 'O_4959']\n self.cool_frac = {}\n for key, keyattr in zip(keys, keyattrs):\n if key[0] == 'H':\n try:\n val = float(sextract(sextract(self.out['cool'],\n key, 14),\n ':', 5))\n except:\n val = 0.0\n else:\n try:\n val = float(sextract(self.out['cool'], key, 5))\n except:\n val = 0.0\n self.__setattr__('Cool_'+keyattr, val)\n self.Cool_Otot = np.sum([self.Cool_O_3727,\n self.Cool_O_5007,\n self.Cool_O_4959])\n self.Cool_Stot = np.sum([self.Cool_SIIa,\n self.Cool_SIIb,\n self.Cool_SIII])\n return\n\nclass allmods(object):\n '''\n mods = outobj.allmods(dir, prefix, read_out=True, read_rad=False)\n '''\n def __init__(self, dir_, prefix, **kwargs):\n self.modpars = np.genfromtxt('{}{}.pars'.format(dir_, prefix))\n self.load_mods(dir_, prefix, **kwargs)\n self.set_pars()\n self.set_arrs()\n read_out = kwargs.get('read_out', False)\n read_rad = kwargs.get('read_rad', False)\n if read_out:\n self.add_arrs('gasC', 'gasN', 'gasO')\n if hasattr(self.mods[0], 'DGR'):\n self.add_arrs('DGR', 'Av_ex', 'Av_pt')\n if read_rad:\n self.add_arrs('Te')\n\n def load_mods(self, dir_, prefix, **kwargs):\n mods = []\n for par in self.modpars:\n mod = modObj(dir_, prefix, par, **kwargs)\n mods.append(mod)\n self.__setattr__('mods', mods)\n self.__setattr__('nmods', len(mods))\n return\n def set_pars(self):\n self.logZ_vals = np.unique(self.modpars[:,1])\n self.age_vals = np.unique(self.modpars[:,2])\n self.logU_vals = np.unique(self.modpars[:,3])\n self.logR_vals = np.unique(self.modpars[:,4])\n self.logQ_vals = np.unique(self.modpars[:,5])\n self.nH_vals = np.unique(self.modpars[:,6])\n try:\n self.efrac_vals = np.unique(self.modpars[:,7])\n except IndexError:\n self.efrac_vals = np.array([-1.0])\n try:\n self.fbhb_vals = np.unique(self.modpars[:,8])\n except IndexError:\n self.fbhb_vals = np.array([0.0])\n def set_arrs(self):\n iterstrings = ['logZ', 'age', 'logU', 'logR', 'logQ', 'nH',\n 'efrac','fbhb',\n 'log_NII_Ha','log_NIIa_Ha','log_NIIb_Ha',\n 'log_OIII_Hb','log_OIIIa_Hb','log_OIIIb_Hb',\n 'log_SII_Ha','log_SIIa_Ha','log_SIIb_Ha',\n 'HaHb', 'R23','log_NII_OII', 'log_OIII_OII']\n for i in iterstrings:\n vals = np.array([mod.__getattribute__(i) for mod in self.mods])\n self.__setattr__(i, vals)\n def add_arrs(self, *args):\n for item in args:\n try:\n vals = np.array([mod.__getattribute__(item) for mod in self.mods])\n self.__setattr__(item, vals)\n except AttributeError:\n continue\n return\n def add_lines(self, linedict={}):\n '''\n self.add_lines(linedict={'O3':1666.0})\n '''\n [mod.add_lines(linedict) for mod in self.mods]\n return\n def makeBPT(self, ax=None, plot_data=True, line_ratio='NIIb',\n gridnames=None, bpt_inds=None, axlabs=None, varsize=22,\n plt_pars={}, data_only=False, **kwargs):\n '''\n mo.makeBPT(ax=ax, const1='age', val1=0.5e6, const2=logR, val2=19.0,\n const3='nH', val3=10.0)\n default line_ratio is NII_b / Ha\n line_ratio = ['NII', 'SII', 'OII', 'OI', 'R23']\n or bpt_inds=['log_OIb_Ha', 'log_OIIIb_Hb']\n '''\n if axlabs is None:\n xlabel = r'\\textbf{log [N II] $\\lambda 6584$ / H$\\alpha$}'\n ylabel = r'\\textbf{log [O III] $\\lambda 5007$ / H$\\beta$}'\n else:\n xlabel=axlabs[0]\n ylabel=ylabs[0]\n if bpt_inds is None:\n xlabel = r'\\textbf{log [N II] $\\lambda 6584$ / H$\\alpha$}'\n ylabel = r'\\textbf{log [O III] $\\lambda 5007$ / H$\\beta$}'\n bpt_inds = ['log_NIIb_Ha', 'log_OIIIb_Hb']\n if line_ratio == 'NII':\n xlabel = r'\\textbf{log [N II] $\\lambda 6548,6584$ / H$\\alpha$}'\n ylabel = r'\\textbf{log [O III] $\\lambda 4959,5007$ / H$\\beta$}'\n bpt_inds = ['log_NII_Ha', 'log_OIII_Hb']\n if line_ratio == 'SII':\n bpt_inds[0] = 'log_SII_Ha'\n xlabel = r'\\textbf{log [S II] $\\lambda 6716,6731$ / H$\\alpha$}'\n if line_ratio == 'OI':\n bpt_inds[0] = 'log_OI_Ha'\n xlabel = r'\\textbf{log [O I] $\\lambda 6300$ / H$\\alpha$}'\n if line_ratio == 'OII':\n bpt_inds = ['log_NII_OII', 'log_OIII_OII']\n ylabel = r'\\textbf{log [O III] $\\lambda 4959,5007$ / [O II] $\\lambda 3726,3727$}'\n xlabel = r'\\textbf{log [N II] $\\lambda 6548,6584$ / [O II] $\\lambda 3726,3727$}'\n if line_ratio == 'R23':\n bpt_inds = ['R23','log_OIII_OII']\n ylabel = r'\\textbf{log [O III] $\\lambda 4959,5007$ / [O II] $\\lambda 3726,3727$}'\n xlabel = r'\\textbf{(log [O II] $\\lambda 3726,3727$ + [O III] $\\lambda 4959,5007$) / H$\\beta$}'\n if ax is None:\n fig = plt.figure()\n ax = fig.add_subplot(111)\n if data_only:\n vanzee.plot_bpt(plot_data, line_ratio=line_ratio, ax=ax, **plt_pars)\n sdss.plot_bpt(plot_data, line_ratio=line_ratio, ax=ax, **plt_pars)\n return\n pd = {'const1':'age',\n 'val1':0.5e6,\n 'const2':'logR',\n 'val2':19.0,\n 'const3':'nH',\n 'val3':100.0,\n 'const4':None,\n 'val4':0.0,\n 'const5':None,\n 'val5':0.0}\n for key, val in list(kwargs.items()):\n pd[key] = val\n allvars = ['nH', 'logZ', 'logR', 'logU', 'age', 'efrac', 'fbhb']\n [allvars.remove(x) for x in [pd['const1'], pd['const2'], pd['const3'], pd['const4'], pd['const5']] if x is not None]\n if gridnames is None:\n x_name, y_name = allvars[0], allvars[1]\n else:\n x_name, y_name = gridnames[0], gridnames[1]\n grid_x = self.__getattribute__(x_name+'_vals')\n grid_y = self.__getattribute__(y_name+'_vals')\n\n cut_z = kwargs.get('cut_z', None)\n if cut_z is not None:\n logZmin= cut_z[0]\n logZmax=cut_z[1]\n if x_name == 'logZ':\n grid_x = grid_x[(grid_x >= logZmin) & (grid_x <= logZmax)]\n if y_name == 'logZ':\n grid_y = grid_y[(grid_y >= logZmin) & (grid_y <= logZmax)]\n\n use_mods = [mod for mod in self.mods\n if (mod.__getattribute__(pd['const1']) == pd['val1'])\n & (mod.__getattribute__(pd['const2']) == pd['val2'])\n & (mod.__getattribute__(pd['const3']) == pd['val3'])]\n if pd['const4'] is not None:\n use_mods = [mod for mod in self.mods\n if (mod.__getattribute__(pd['const1']) == pd['val1'])\n & (mod.__getattribute__(pd['const2']) == pd['val2'])\n & (mod.__getattribute__(pd['const3']) == pd['val3'])\n & (mod.__getattribute__(pd['const4']) == pd['val4'])]\n\n gshape = (len(grid_y), len(grid_x))\n X, Y = np.meshgrid(grid_x, grid_y, indexing='xy')\n Zx = np.zeros(gshape)\n Zy = np.zeros(gshape)\n nrows = gshape[0]\n ncols = gshape[1]\n for ind, val in np.ndenumerate(X):\n arr = [mod for mod in use_mods if (mod.__getattribute__(x_name) == val) & (mod.__getattribute__(y_name) == Y[ind])]\n Zx[ind] = arr[0].__getattribute__(bpt_inds[0])\n Zy[ind] = arr[0].__getattribute__(bpt_inds[1])\n if plot_data:\n vanzee.plot_bpt(plot_data, line_ratio=line_ratio, ax=ax)\n sdss.plot_bpt(plot_data, line_ratio=line_ratio, ax=ax, **plt_pars)\n ax.set_xlabel(xlabel, fontsize=16)\n ax.set_ylabel(ylabel, fontsize=16)\n for i in range(nrows):\n color = kwargs.get('color', 'k')\n lw = kwargs.get('lw', 2)\n alpha = kwargs.get('alpha', 0.95)\n if i == 0:\n par_label = kwargs.get('par_label', '__nolegend__')\n ax.plot(Zx[i,:], Zy[i,:], color=color, lw=lw,\n alpha=alpha, label=par_label)\n else:\n ax.plot(Zx[i,:], Zy[i,:], color=color, lw=lw, alpha=alpha,\n label='__nolegend__')\n row_labs = [(Zx[i,0], Zy[i,0], r'${0:.1f}$'.format(float(np.unique(Y[i,:])))) for i in range(gshape[0])]\n for i in range(ncols):\n ax.plot(Zx[:,i], Zy[:,i], color=color, lw=lw, alpha=alpha,\n label='__nolegend__')\n col_labs = [(Zx[0, i], Zy[0, i], r'${0:.1f}$'.format(float(np.unique(X[:,i])))) for i in range(gshape[1])]\n\n var_label = kwargs.get('var_label', '__nolegend__')\n if var_label:\n for lab in col_labs:\n ax.annotate(lab[-1],\n xy=(lab[0], lab[1]), xycoords='data',\n xytext=(0, -10), textcoords='offset points',\n size=varsize,\n horizontalalignment='left',\n verticalalignment='top')\n ax.annotate(r'$\\log \\mathrm{Z}/\\mathrm{Z}_{\\odot}$',\n xy=(col_labs[2][0], col_labs[2][1]),\n xycoords='data', xytext=(0, -50),\n textcoords='offset points', size=varsize,\n horizontalalignment='left',\n verticalalignment='top')\n for lab in row_labs:\n ax.annotate(lab[-1],\n xy=(lab[0], lab[1]), xycoords='data',\n xytext=(-10, 0), textcoords='offset points',\n size=varsize,\n horizontalalignment='right',\n verticalalignment='bottom')\n ax.annotate(r'$\\log \\mathcal{U}_0$',\n xy=(row_labs[1][0], row_labs[1][1]),\n xycoords='data', xytext=(-50, 15),\n textcoords='offset points', size=varsize,\n horizontalalignment='right',\n verticalalignment='bottom')\n plt.legend(numpoints=1)\n return\n def group_mods(self, xval='logZ', yval='age', zval='NIIb',\n const='logU', cval=-2.0, make_cut=False, **kwargs):\n grid_x = self.__getattribute__(xval+'_vals')\n grid_y = self.__getattribute__(yval+'_vals')\n if make_cut:\n xlims = kwargs.get('xlims', (-1.0, 0.1))\n ylims = kwargs.get('ylims', (0.0, 10.e6))\n grid_x = grid_x[(grid_x >= xlims[0]) & (grid_x <= xlims[1])]\n grid_y = grid_y[(grid_y >= ylims[0]) & (grid_y <= ylims[1])]\n X, Y = np.meshgrid(grid_x, grid_y)\n Z = np.zeros_like(X)\n for index, x in np.ndenumerate(Z):\n mind = [i for i in range(self.nmods)\n if (self.mods[i].__getattribute__(xval) == X[index]\n and self.mods[i].__getattribute__(yval) == Y[index]\n and self.mods[i].__getattribute__(const) == cval)]\n try:\n Z[index] = self.mods[mind[0]].__getattribute__(zval)\n except AttributeError:\n print('not a valid attribute.')\n if xval == 'age':\n X*=1.0e-6\n if yval == 'age':\n Y*=1.0e-6\n return X,Y,Z\n def pxl_plot(self, xval='logZ', yval='age', zval='log_OIII_Hb',\n const='logU', cval=-2.0, ax=None, cname='CMRmap',\n cmap=None, sM=None, cNorm=None, cb_arr=None,\n no_cbar=False, show_grid=False, aspect='auto',\n xlabels=None, ylabels=None,**kwargs):\n '''\n mods.pxl_plot(xval='logZ', yval='age', zval='log_OIII_Hb',\n const='logR', cval=18, clab='log R (cm)')\n '''\n X, Y, Z = self.group_mods(xval=xval, yval=yval, zval=zval,\n const=const, cval=cval, **kwargs)\n masked_array = np.ma.array(Z, mask=np.isnan(Z))\n if (sM is None) or (cNorm is None):\n if cb_arr is not None:\n arr_in = cb_arr\n else:\n arr_in = masked_array\n if cmap is not None:\n sM, cNorm = getColors(arr_in, return_cNorm=True,\n set_bad_vals=True, cmap=cmap)\n else:\n sM, cNorm = getColors(arr_in, return_cNorm=True,\n set_bad_vals=True, cname=cname)\n cmap = plt.get_cmap(cname)\n if ax is None:\n fig = plt.figure()\n ax = fig.add_subplot(111)\n pf = ax.imshow(Z, norm=cNorm, aspect=aspect,\n interpolation='nearest', origin='lower',\n cmap=cmap)\n xCenters = X[0]\n yCenters = Y[:,0]\n if xlabels is None:\n xlabels = ['{0:.1f}'.format(x) for x in xCenters]\n if ylabels is None:\n ylabels = ['{0:.1f}'.format(y) for y in yCenters]\n for axis, labels in zip([ax.xaxis, ax.yaxis], [xlabels, ylabels]):\n locs = np.arange(len(labels))\n axis.set_ticks(locs + 0.5, minor=True)\n axis.set(ticks=locs, ticklabels=labels)\n if show_grid:\n ax.grid(True, which='minor')\n xlab = kwargs.get('xlab', None)\n ylab = kwargs.get('ylab', None)\n clab = kwargs.get('clab', None)\n if xlab is None:\n xlab = xval\n ylab = yval\n ax.set_xlabel(xlab)\n ax.set_ylabel(ylab)\n if no_cbar:\n return pf\n else:\n cb = plt.colorbar(pf, ax=ax)\n if clab is not None:\n clab_size=kwargs.get('clab_size', 14)\n cb.set_label(clab, size=clab_size)\n return ax\n\ndef nice_lines(key):\n lines = {'ha':[6562.50, r'H\\alpha', r'\\lambda6563'],\n 'hb':[4861.36, r'H\\beta', r'\\lambda4861'],\n 'o3':[5007.00, r'O III', r'\\lambda5007'],\n 'n2':[6584.00, r'N II', r'\\lambda6584'],\n 'an2':[6548.00, r'N II', r'\\lambda6548'],\n 'ao3':[4959.00, r'O III', r'\\lambda4959'],\n 'o2':[3727.00, r'O II', r'\\lambdalambda3726,9'],\n 's2a':[6716.00, r'S II', r'\\lambda6716'],\n 's2b':[6731.00, r'S II', r'\\lambda6731'],\n 'o1':[6300, r'O I', r'\\lambda6300']}\n return lines[key]\n\ndef calc_dim(X,Y,Z):\n extent = [np.min(X), np.max(X), np.min(Y), np.max(Y)]\n dx = (extent[1] - extent[0]) / float(Z.shape[1])\n dy = (extent[3] - extent[2]) / float(Z.shape[0])\n return extent, dx/dy\n\ndef add_dopita(**kwargs):\n dopita.plot_bpt(**kwargs)\n return\n", "meta": {"hexsha": "17ef9d169323f96f90926cd72eb301a2bc9f772a", "size": 37455, "ext": "py", "lang": "Python", "max_stars_repo_path": "cloudyfsps/outObj.py", "max_stars_repo_name": "prerakgarg07/cloudyfsps", "max_stars_repo_head_hexsha": "4a6a185343ed1e09b9f201a465c37e377ef42101", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-12-07T01:00:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T17:50:51.000Z", "max_issues_repo_path": "cloudyfsps/outObj.py", "max_issues_repo_name": "prerakgarg07/cloudyfsps", "max_issues_repo_head_hexsha": "4a6a185343ed1e09b9f201a465c37e377ef42101", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cloudyfsps/outObj.py", "max_forks_repo_name": "prerakgarg07/cloudyfsps", "max_forks_repo_head_hexsha": "4a6a185343ed1e09b9f201a465c37e377ef42101", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-12-08T22:57:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-30T15:04:33.000Z", "avg_line_length": 40.2741935484, "max_line_length": 158, "alphanum_fraction": 0.5038045655, "include": true, "reason": "import numpy", "num_tokens": 10547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.23091976292927183, "lm_q1q2_score": 0.13247368184657576}} {"text": "\"\"\"\nPathfinder/CHIME Telescope Model\n\nA model for both CHIME and Pathfinder telescopes. This attempts to query the\nconfiguration db (:mod:`~ch_analysis.pathfinder.configdb`) for the details of\nthe feeds and their positions.\n\"\"\"\n\nimport logging\n\nimport numpy as np\nimport h5py\nimport healpy\nfrom scipy.interpolate import RectBivariateSpline\n\nfrom caput import config, mpiutil\n\nfrom cora.util import coord, hputil\n\nfrom drift.core import telescope\nfrom drift.telescope import cylbeam\n\nfrom draco.core.containers import ContainerBase, GridBeam, HEALPixBeam\n\nfrom ch_util import ephemeris, tools\nfrom caput.cache import cached_property\n\n# Get the logger for the module\nlogger = logging.getLogger(__name__)\n\n\nclass CHIME(telescope.PolarisedTelescope):\n \"\"\"Model telescope for the CHIME/Pathfinder.\n\n This class currently uses a simple Gaussian model for the primary beams.\n\n Attributes\n ----------\n layout : datetime or int\n Specify which layout to use.\n correlator : string\n Restrict to a specific correlator.\n skip_non_chime : boolean\n Ignore non CHIME feeds in the BeamTransfers.\n stack_type : string, optional\n Stacking type.\n `redundant`: feeds of same polarization have same beam class (default).\n `redundant_cyl`: feeds of same polarization and cylinder have same beam\n class.\n `unique`: Each feed has a unique beam class.\n use_pathfinder_freq: boolean\n Use the pathfinder channelization of 1024 frequencies between 400 and\n 800 MHz. Setting this to True also enables the specification of a\n subset of these frequencies through the four attributes below. Default\n is True.\n channel_bin : int, optional\n Number of channels to bin together. Must exactly divide the total\n number. Binning is performed prior to selection of any subset. Default\n is 1.\n freq_physical : list, optional\n Select subset of frequencies using a list of physical frequencies in\n MHz. Finds the closests pathfinder channel.\n channel_range : list, optional\n Select subset of frequencies using a range of frequency channel indices,\n either [start, stop, step], [start, stop], or [stop] is acceptable.\n channel_index : list, optional\n Select subset of frequencies using a list of frequency channel indices.\n input_sel : list, optional\n Select a reduced set of feeds to use. Useful for generating small\n subsets of the data.\n baseline_masking_type : string, optional\n Select a subset of baselines. `total_length` selects baselines according to\n their total length. Need to specify `minlength` and `maxlength` properties\n (defined in baseclass). `individual_length` selects baselines according to\n their seperation in the North-South (specify `minlength_ns` and `maxlength_ns`)\n or the East-West (specify `minlength_ew` and `maxlength_ew`).\n minlength_ns, maxlength_ns : float\n Minimum and maximum North-South baseline lengths to include (in metres)\n minlength_ew, maxlength_ew: float\n Minimum and maximum East-West baseline lengths to include (in metres)\n dec_normalized: float, optional\n Normalize the beam by its magnitude at transit at this declination\n in degrees.\n skip_pol_pair : list\n List of antenna polarisation pairs to skip. Valid entries are \"XX\", \"XY\", \"YX\"\n or \"YY\". Like the skipped frequencies these pol pairs will have entries\n generated but their beam transfer matrices are implicitly zero and thus not\n calculated.\n \"\"\"\n\n # Configure which feeds and layout to use\n layout = config.Property(default=None)\n correlator = config.Property(proptype=str, default=None)\n skip_non_chime = config.Property(proptype=bool, default=False)\n\n # Redundancy settings\n stack_type = config.enum(\n [\"redundant\", \"redundant_cyl\", \"unique\"], default=\"redundant\"\n )\n\n # Configure frequency properties\n use_pathfinder_freq = config.Property(proptype=bool, default=True)\n channel_bin = config.Property(proptype=int, default=1)\n freq_physical = config.Property(proptype=list, default=[])\n channel_range = config.Property(proptype=list, default=[])\n channel_index = config.Property(proptype=list, default=[])\n\n # Input selection\n input_sel = config.Property(proptype=list, default=None)\n\n # Baseline masking options\n baseline_masking_type = config.enum(\n [\"total_length\", \"individual_length\"], default=\"individual_length\"\n )\n minlength_ew = config.Property(proptype=float, default=0.0)\n maxlength_ew = config.Property(proptype=float, default=1.0e7)\n minlength_ns = config.Property(proptype=float, default=0.0)\n maxlength_ns = config.Property(proptype=float, default=1.0e7)\n\n # Auto-correlations setting (overriding default in baseclass)\n auto_correlations = config.Property(proptype=bool, default=True)\n\n # Beam normalization\n dec_normalized = config.Property(proptype=float, default=None)\n # Skipping frequency/baseline parameters\n skip_pol_pair = config.list_type(type_=str, maxlength=4, default=[])\n\n # Fix base properties\n cylinder_width = 20.0\n cylinder_spacing = tools._PF_SPACE\n\n _exwidth = [0.7]\n _eywidth = _exwidth\n\n _hxwidth = [1.2]\n _hywidth = _hxwidth\n\n _pickle_keys = [\"_feeds\"]\n\n #\n # === Initialisation routines ===\n #\n\n def __init__(self, feeds=None):\n import datetime\n\n self._feeds = feeds\n\n # Set location properties\n self.latitude = ephemeris.CHIMELATITUDE\n self.longitude = ephemeris.CHIMELONGITUDE\n self.altitude = ephemeris.CHIMEALTITUDE\n\n # Set the LSD start epoch (i.e. CHIME/Pathfinder first light)\n self.lsd_start_day = datetime.datetime(2013, 11, 15)\n\n # Set the overall normalization of the beam\n self._set_beam_normalization()\n\n @classmethod\n def from_layout(cls, layout, correlator=None, skip=False):\n \"\"\"Create a CHIME/Pathfinder telescope description for the specified layout.\n\n Parameters\n ----------\n layout : integer or datetime\n Layout id number (corresponding to one in database), or datetime\n correlator : string, optional\n Name of the specific correlator. Needed to return a unique config\n in some cases.\n skip : boolean, optional\n Whether to skip non-CHIME antennas. If False, leave them in but\n set them to infinite noise (unsupported at the moment).\n\n Returns\n -------\n tel : CHIME\n \"\"\"\n\n tel = cls()\n\n tel.layout = layout\n tel.correlator = correlator\n tel.skip_non_chime = skip\n tel._load_layout()\n\n return tel\n\n def _load_layout(self):\n \"\"\"Load the CHIME/Pathfinder layout from the database.\n\n Generally this routine shouldn't be called directly. Use\n :method:`CHIME.from_layout` or configure from a YAML file.\n \"\"\"\n if self.layout is None:\n raise Exception(\"Layout attributes not set.\")\n\n # Fetch feed layout from database\n feeds = tools.get_correlator_inputs(self.layout, self.correlator)\n\n if mpiutil.size > 1:\n feeds = mpiutil.world.bcast(feeds, root=0)\n\n if self.skip_non_chime:\n raise Exception(\"Not supported.\")\n\n self._feeds = feeds\n\n def _finalise_config(self):\n # Override base method to implement automatic loading of layout when\n # configuring from YAML.\n\n if self.layout is not None:\n logger.debug(\"Loading layout: %s\", str(self.layout))\n self._load_layout()\n\n # Set the overall normalization of the beam\n self._set_beam_normalization()\n\n #\n # === Redefine properties of the base class ===\n #\n\n # Tweak the following two properties to change the beam width\n @cached_property\n def fwhm_ex(self):\n \"\"\"Full width half max of the E-plane antenna beam for X polarization.\"\"\"\n\n return np.polyval(np.array(self._exwidth) * 2.0 * np.pi / 3.0, self.frequencies)\n\n @cached_property\n def fwhm_hx(self):\n \"\"\"Full width half max of the H-plane antenna beam for X polarization.\"\"\"\n\n return np.polyval(np.array(self._hxwidth) * 2.0 * np.pi / 3.0, self.frequencies)\n\n @cached_property\n def fwhm_ey(self):\n \"\"\"Full width half max of the E-plane antenna beam for Y polarization.\"\"\"\n\n return np.polyval(np.array(self._eywidth) * 2.0 * np.pi / 3.0, self.frequencies)\n\n @cached_property\n def fwhm_hy(self):\n \"\"\"Full width half max of the H-plane antenna beam for Y polarization.\"\"\"\n\n return np.polyval(np.array(self._hywidth) * 2.0 * np.pi / 3.0, self.frequencies)\n\n # Set the approximate uv feed sizes\n @property\n def u_width(self):\n return self.cylinder_width\n\n # v-width property override\n @property\n def v_width(self):\n return 1.0\n\n # Set non-zero rotation angle for pathfinder and chime\n @property\n def rotation_angle(self):\n if self.correlator == \"pathfinder\":\n return tools._PF_ROT\n elif self.correlator == \"chime\":\n return tools._CHIME_ROT\n else:\n return 0.0\n\n def calculate_frequencies(self):\n \"\"\"Override default version to give support for specifying by frequency\n channel number.\n \"\"\"\n if self.use_pathfinder_freq:\n # Use pathfinder channelization of 1024 bins between 400 and 800 MHz.\n basefreq = np.linspace(800.0, 400.0, 1024, endpoint=False)\n\n # Bin the channels together\n if len(basefreq) % self.channel_bin != 0:\n raise Exception(\n \"Channel binning must exactly divide the total number of channels\"\n )\n\n basefreq = basefreq.reshape(-1, self.channel_bin).mean(axis=-1)\n\n # If requested, select subset of frequencies.\n if self.freq_physical:\n basefreq = basefreq[\n [np.argmin(np.abs(basefreq - freq)) for freq in self.freq_physical]\n ]\n\n elif self.channel_range and (len(self.channel_range) <= 3):\n basefreq = basefreq[slice(*self.channel_range)]\n\n elif self.channel_index:\n basefreq = basefreq[self.channel_index]\n\n # Save to object\n self._frequencies = np.unique(basefreq)[::-1]\n\n else:\n # Otherwise use the standard method\n telescope.TransitTelescope.calculate_frequencies(self)\n\n @property\n def feeds(self):\n \"\"\"Return a description of the feeds as a list of :class:`tools.CorrInput` instances.\"\"\"\n\n if self.input_sel is None:\n feeds = self._feeds\n else:\n feeds = [self._feeds[fi] for fi in self.input_sel]\n\n return feeds\n\n @property\n def input_index(self):\n \"\"\"An index_map describing the inputs known to the telescope. Useful\n for generating synthetic datasets.\n \"\"\"\n # Extract lists of channel ID and serial numbers\n channels, feed_sn = list(\n zip(*[(feed.id, feed.input_sn) for feed in self.feeds])\n )\n\n # Create an input index map and return it.\n from ch_util import andata\n\n return andata._generate_input_map(feed_sn, channels)\n\n _pos = None\n\n @property\n def feedpositions(self):\n \"\"\"The set of feed positions on *all* cylinders.\n\n This is constructed for the given layout and includes all rotations of\n the cylinder axis.\n\n Returns\n -------\n feedpositions : np.ndarray\n The positions in the telescope plane of the receivers. Packed as\n [[u1, v1], [u2, v2], ...].\n \"\"\"\n\n if self._pos is None:\n # Fetch cylinder relative positions\n pos = tools.get_feed_positions(self.feeds)\n\n # The above routine returns NaNs for non CHIME feeds. This is a bit\n # messy, so turn them into zeros.\n self._pos = np.nan_to_num(pos)\n\n return self._pos\n\n @property\n def beamclass(self):\n \"\"\"Beam class definition for the CHIME/Pathfinder.\n\n When `self.stack_type` is `redundant`, the X-polarisation feeds get\n `beamclass = 0`, and the Y-polarisation gets `beamclass = 1`.\n When `self.stack_type` is `redundant_cyl`, feeds of same polarisation\n and cylinder have same beam class. The beam class is given by\n `beamclass = 2*cyl + pol` where `cyl` is the cylinder number according to\n `ch_util.tools` convention and `pol` is the polarisation (0 for X and 1\n for Y polarisation)\n When `self.stack_type` is `unique`, then the feeds are just given an\n increasing unique class.\n In all cases, any other type of feed gets set to `-1` and should be\n ignored.\n \"\"\"\n # Make beam class just channel number.\n\n def _feedclass(f, redundant_cyl=False):\n if tools.is_array(f):\n if tools.is_array_x(f): # feed is X polarisation\n pol = 0\n else: # feed is Y polarisation\n pol = 1\n\n if redundant_cyl:\n return 2 * f.cyl + pol\n else:\n return pol\n return -1\n\n if self.stack_type == \"redundant\":\n return np.array([_feedclass(f) for f in self.feeds])\n elif self.stack_type == \"redundant_cyl\":\n return np.array([_feedclass(f, redundant_cyl=True) for f in self.feeds])\n else:\n beamclass = [\n fi if tools.is_array(feed) else -1 for fi, feed in enumerate(self.feeds)\n ]\n return np.array(beamclass)\n\n @property\n def polarisation(self):\n \"\"\"\n Polarisation map.\n\n Returns\n -------\n pol : np.ndarray\n One-dimensional array with the polarization for each feed ('X' or 'Y').\n \"\"\"\n\n def _pol(f):\n if tools.is_array(f):\n if tools.is_array_x(f): # feed is X polarisation\n return \"X\"\n else: # feed is Y polarisation\n return \"Y\"\n return \"N\"\n\n return np.asarray([_pol(f) for f in self.feeds], dtype=np.str)\n\n #\n # === Setup the primary beams ===\n #\n\n def beam(self, feed, freq, angpos=None):\n \"\"\"Primary beam implementation for the CHIME/Pathfinder.\n\n This only supports normal CHIME cylinder antennas. Asking for the beams\n for other types of inputs will cause an exception to be thrown. The\n beams from this routine are rotated by `self.rotation_angle` to account\n for the CHIME/Pathfinder rotation.\n\n Parameters\n ----------\n feed : int\n Index for the feed.\n freq : int\n Index for the frequency.\n angpos : np.ndarray[nposition, 2], optional\n Angular position on the sky (in radians).\n If not provided, default to the _angpos\n class attribute.\n\n Returns\n -------\n beam : np.ndarray[nposition, 2]\n Amplitude vector of beam at each position on the sky.\n \"\"\"\n # # Fetch beam parameters out of config database.\n\n feed_obj = self.feeds[feed]\n\n # Check that feed exists and is a CHIME cylinder antenna\n if feed_obj is None:\n raise ValueError(\"Craziness. The requested feed doesn't seem to exist.\")\n\n if not tools.is_array(feed_obj):\n raise ValueError(\"Requested feed is not a CHIME antenna.\")\n\n # If the angular position was not provided, then use the values in the\n # class attribute.\n if angpos is None:\n angpos = self._angpos\n\n # Get the beam rotation parameters.\n yaw = -self.rotation_angle\n pitch = 0.0\n roll = 0.0\n\n rot = np.radians([yaw, pitch, roll])\n\n # We can only support feeds angled parallel or perp to the cylinder\n # axis. Check for these and throw exception for anything else.\n if tools.is_array_y(feed_obj):\n beam = cylbeam.beam_y(\n angpos,\n self.zenith,\n self.cylinder_width / self.wavelengths[freq],\n self.fwhm_ey[freq],\n self.fwhm_hy[freq],\n rot=rot,\n )\n elif tools.is_array_x(feed_obj):\n beam = cylbeam.beam_x(\n angpos,\n self.zenith,\n self.cylinder_width / self.wavelengths[freq],\n self.fwhm_ex[freq],\n self.fwhm_hx[freq],\n rot=rot,\n )\n else:\n raise RuntimeError(\n \"Given polarisation (feed.pol=%s) not supported.\" % feed_obj.pol\n )\n\n # Normalize the beam\n if self._beam_normalization is not None:\n beam *= self._beam_normalization[freq, feed, np.newaxis, :]\n\n return beam\n\n #\n # === Override methods determining the feed pairs we should calculate ===\n #\n # These should probably get ported back into `driftscan` as options.\n\n def _sort_pairs(self):\n # Reimplemented sort pairs to ensure that returned array is in\n # channel order.\n\n # Create mask of included pairs, that are not conjugated\n tmask = np.logical_and(self._feedmask, np.logical_not(self._feedconj))\n uniq = telescope._get_indices(self._feedmap, mask=tmask)\n\n # Get channel id for each feed in the pair, this will be used for the sort\n ci, cj = np.array([(self.feeds[fi].id, self.feeds[fj].id) for fi, fj in uniq]).T\n\n # # Sort by constructing a numpy array with the keys as fields, and use\n # # np.argsort to get the indices\n\n # Create array of keys to sort\n dt = np.dtype(\"i4,i4\")\n sort_arr = np.zeros(ci.size, dtype=dt)\n sort_arr[\"f0\"] = ci\n sort_arr[\"f1\"] = cj\n\n # Get map which sorts\n sort_ind = np.argsort(sort_arr)\n\n # Invert mapping\n tmp_sort_ind = sort_ind.copy()\n sort_ind[tmp_sort_ind] = np.arange(sort_ind.size)\n\n # Remap feedmap entries\n fm_copy = self._feedmap.copy()\n wmask = np.where(self._feedmask)\n fm_copy[wmask] = sort_ind[self._feedmap[wmask]]\n\n self._feedmap = fm_copy\n\n def _make_ew(self):\n # # Reimplemented to make sure entries we always pick the upper\n # # triangle (and do not reorder to make EW baselines)\n if self.stack_type != \"unique\":\n super(CHIME, self)._make_ew()\n\n def _unique_baselines(self):\n # Reimplement unique baselines in order to mask out either according to total\n # baseline length or maximum North-South and East-West baseline seperation.\n\n from drift.core import telescope\n\n # Construct array of indices\n fshape = [self.nfeed, self.nfeed]\n f_ind = np.indices(fshape)\n\n # Construct array of baseline separations\n bl1 = self.feedpositions[f_ind[0]] - self.feedpositions[f_ind[1]]\n bl2 = np.around(bl1[..., 0] + 1.0j * bl1[..., 1], self._bl_tol)\n\n # Construct array of baseline lengths\n blen = np.sum(bl1 ** 2, axis=-1) ** 0.5\n\n if self.baseline_masking_type == \"total_length\":\n # Create mask of included baselines\n mask = np.logical_and(blen >= self.minlength, blen <= self.maxlength)\n else:\n mask_ew = np.logical_and(\n abs(bl1[..., 0]) >= self.minlength_ew,\n abs(bl1[..., 0]) <= self.maxlength_ew,\n )\n mask_ns = np.logical_and(\n abs(bl1[..., 1]) >= self.minlength_ns,\n abs(bl1[..., 1]) <= self.maxlength_ns,\n )\n mask = np.logical_and(mask_ew, mask_ns)\n\n # Remove the auto correlated baselines between all polarisations\n if not self.auto_correlations:\n mask = np.logical_and(blen > 0.0, mask)\n\n return telescope._remap_keyarray(bl2, mask), mask\n\n def _unique_beams(self):\n # Override to mask out any feed where the beamclass is less than zero.\n # This is used to get exclude feeds which are not normal CHIME cylinder\n # feeds\n\n beam_map, beam_mask = telescope.TransitTelescope._unique_beams(self)\n\n # Construct a mask including only the feeds where the beam class is\n # greater than zero\n bc_mask = self.beamclass >= 0\n bc_mask = np.logical_and(bc_mask[:, np.newaxis], bc_mask[np.newaxis, :])\n\n beam_mask = np.logical_and(beam_mask, bc_mask)\n\n return beam_map, beam_mask\n\n def _set_beam_normalization(self):\n \"\"\"Determine the beam normalization for each feed and frequency.\n\n The beam will be normalized by its value at transit at the declination\n provided in the dec_normalized config parameter. If this config parameter\n is set to None, then there is no additional normalization applied.\n \"\"\"\n\n self._beam_normalization = None\n\n if self.dec_normalized is not None:\n\n angpos = np.array(\n [(0.5 * np.pi - np.radians(self.dec_normalized)), 0.0]\n ).reshape(1, -1)\n\n beam = np.ones((self.nfreq, self.nfeed, 2), dtype=np.float64)\n\n beam_lookup = {}\n\n for fe, feed in enumerate(self.feeds):\n\n if not tools.is_array(feed):\n continue\n\n beamclass = self.beamclass[fe]\n\n if beamclass not in beam_lookup:\n\n beam_lookup[beamclass] = np.ones((self.nfreq, 2), dtype=np.float64)\n for fr in range(self.nfreq):\n beam_lookup[beamclass][fr] = self.beam(fe, fr, angpos)[0]\n\n beam[:, fe, :] = beam_lookup[beamclass]\n\n self._beam_normalization = tools.invert_no_zero(\n np.sqrt(np.sum(beam ** 2, axis=-1))\n )\n\n def _skip_baseline(self, bl_ind):\n \"\"\"Override to skip baselines based on which polarisation pair they are.\"\"\"\n\n # Pull in baseline skip choice from parent class\n skip_bl = super()._skip_baseline(bl_ind)\n\n pol_i, pol_j = self.polarisation[self.uniquepairs[bl_ind]]\n pol_pair = pol_i + pol_j\n\n skip_pol = pol_pair in self.skip_pol_pair\n\n return skip_bl or skip_pol\n\n\ndef _flat_top_gauss6(x, A, sig, x0):\n \"\"\"Flat-top gaussian. Power of 6.\"\"\"\n return A * np.exp(-abs((x - x0) / sig) ** 6)\n\n\ndef _flat_top_gauss3(x, A, sig, x0):\n \"\"\"Flat-top gaussian. Power of 3.\"\"\"\n return A * np.exp(-abs((x - x0) / sig) ** 3)\n\n\nclass CHIMEParameterizedBeam(CHIME):\n \"\"\"CHIME telescope that uses a parameterized fit to the driftscan beam.\n\n This speeds up evaluation of the beam model.\n \"\"\"\n\n SIGMA_EW = [14.87857614, 9.95746878]\n\n FUNC_NS = [_flat_top_gauss6, _flat_top_gauss3]\n PARAM_NS = np.array(\n [[9.97981768e-01, 1.29544939e00, 0.0], [9.86421047e-01, 8.10213326e-01, 0.0]]\n )\n\n def _sigma(self, pol_index, freq_index, dec):\n \"\"\"Width of the power beam in the EW direction.\"\"\"\n return self.SIGMA_EW[pol_index] / self.frequencies[freq_index] / np.cos(dec)\n\n def _beam_amplitude(self, pol_index, dec):\n \"\"\"Amplitude of the power beam at meridian.\"\"\"\n return self.FUNC_NS[pol_index](\n dec - np.radians(self.latitude), *self.PARAM_NS[pol_index]\n )\n\n def beam(self, feed, freq, angpos=None):\n \"\"\"Parameterized fit to driftscan cylinder beam model for CHIME telescope.\n\n Parameters\n ----------\n feed : int\n Index for the feed.\n freq : int\n Index for the frequency.\n angpos : np.ndarray[nposition, 2], optional\n Angular position on the sky (in radians).\n If not provided, default to the _angpos\n class attribute.\n\n Returns\n -------\n beam : np.ndarray[nposition, 2]\n Amplitude vector of beam at each position on the sky.\n \"\"\"\n\n feed_obj = self.feeds[feed]\n\n # Check that feed exists and is a CHIME cylinder antenna\n if feed_obj is None:\n raise ValueError(\"Craziness. The requested feed doesn't seem to exist.\")\n\n if not tools.is_array(feed_obj):\n raise ValueError(\"Requested feed is not a CHIME antenna.\")\n\n # If the angular position was not provided, then use the values in the\n # class attribute.\n if angpos is None:\n angpos = self._angpos\n\n dec = 0.5 * np.pi - angpos[:, 0]\n ha = angpos[:, 1]\n\n # We can only support feeds angled parallel or perp to the cylinder\n # axis. Check for these and throw exception for anything else.\n if tools.is_array_x(feed_obj):\n pol = 0\n elif tools.is_array_y(feed_obj):\n pol = 1\n else:\n raise RuntimeError(\n \"Given polarisation (feed.pol=%s) not supported.\" % feed_obj.pol\n )\n\n beam = np.zeros((angpos.shape[0], 2), dtype=np.float64)\n beam[:, 0] = np.sqrt(\n self._beam_amplitude(pol, dec)\n * np.exp(-((ha / self._sigma(pol, freq, dec)) ** 2))\n )\n\n # Normalize the beam\n if self._beam_normalization is not None:\n beam *= self._beam_normalization[freq, feed, np.newaxis, :]\n\n return beam\n\n\nclass CHIMEFitBeam(CHIME):\n \"\"\"Driftscan model with revised FWHM for north-south beam.\n\n Point source beam model was fit to a flat Gaussian at each frequency.\n Best-fit FWHM as a function of frequency was fit with a cubic\n polynomial. This class revises coefficients of FWHM from the\n fit. Detailed comparisons are documented in:\n https://bao.chimenet.ca/doc/documents/1448\n\n Note that the optimization was carried out in 585-800 MHz.\n This model will produce large extrapolation errors if used below that.\n \"\"\"\n\n _eywidth = (\n 3.0\n / (2 * np.pi)\n * np.array([1.15310483e-07, -2.30462590e-04, 1.50451290e-01, -3.07440520e01])\n )\n\n _hxwidth = (\n 3.0\n / (2 * np.pi)\n * np.array([2.97495306e-07, -6.00582101e-04, 3.99949759e-01, -8.66733249e01])\n )\n\n\nclass CHIMEExternalBeam(CHIME):\n \"\"\"Model telescope for the CHIME.\n\n This class uses an external beam model that is read in from a file.\n\n Attributes\n ----------\n primary_beam_filename : str\n Path to the file containing the primary beam. Can either be a Healpix beam or a\n GridBeam.\n freq_interp_beam : bool, optional\n Interpolate between neighbouring frequencies if we don't have a beam for every\n frequency channel.\n force_real_beam : bool, optional\n Ensure the output beam is real, regardless of what the datatype of the beam file\n is. This can help save memory if the saved beam is complex but you know the\n imaginary part is zero.\n \"\"\"\n\n primary_beam_filename = config.Property(proptype=str)\n freq_interp_beam = config.Property(proptype=bool, default=False)\n force_real_beam = config.Property(proptype=bool, default=False)\n\n def _finalise_config(self):\n \"\"\"Get the beam file object.\"\"\"\n\n logger.debug(\"Reading beam model from {}...\".format(self.primary_beam_filename))\n self._primary_beam = ContainerBase.from_file(\n self.primary_beam_filename, mode=\"r\", distributed=False, ondisk=True\n )\n\n self._is_grid_beam = isinstance(self._primary_beam, GridBeam)\n\n # cache axes\n self._beam_freq = self._primary_beam.freq[:]\n self._beam_nside = None if self._is_grid_beam else self._primary_beam.nside\n\n # TODO must use bytestring here because conversion doesn't work with ondisk=True\n if self._is_grid_beam:\n self._beam_pol_map = {\n \"X\": list(self._primary_beam.pol[:]).index(b\"XX\"),\n \"Y\": list(self._primary_beam.pol[:]).index(b\"YY\"),\n }\n else:\n self._beam_pol_map = {\n \"X\": list(self._primary_beam.pol[:]).index(b\"X\"),\n \"Y\": list(self._primary_beam.pol[:]).index(b\"Y\"),\n }\n\n if len(self._primary_beam.input) > 1:\n raise ValueError(\"Per-feed beam model not supported for now.\")\n\n complex_beam = np.issubclass_(\n self._primary_beam.beam.dtype.type, np.complexfloating\n )\n self._output_dtype = (\n np.complex128 if complex_beam and not self.force_real_beam else np.float64\n )\n\n super()._finalise_config()\n\n def beam(self, feed, freq_id):\n \"\"\"Get the beam pattern.\n\n Parameters\n ----------\n feed : int\n Feed index.\n freq_id : int\n Frequency ID.\n\n Returns\n -------\n beam : np.ndarray[pixel, pol]\n Return the vector beam response at each point in the Healpix grid. This\n array is of type `np.float64` if the input beam pattern is real, of\n `force_real_beam` is set, otherwise is is on type `np.complex128`.\n \"\"\"\n feed_obj = self.feeds[feed]\n tel_freq = self.frequencies\n nside = self._nside\n npix = healpy.nside2npix(nside)\n\n if feed_obj is None:\n raise ValueError(\"The requested feed doesn't seem to exist.\")\n\n if tools.is_array_x(feed_obj):\n pol_ind = self._beam_pol_map[\"X\"]\n elif tools.is_array_y(feed_obj):\n pol_ind = self._beam_pol_map[\"Y\"]\n else:\n raise ValueError(\"Polarisation not supported by this feed\", feed_obj)\n\n # find nearest frequency\n freq_sel = _nearest_freq(\n tel_freq, self._beam_freq, freq_id, single=(not self.freq_interp_beam)\n )\n # Raise an error if we can't find any suitable frequency\n if len(freq_sel) == 0:\n raise ValueError(f\"No beam model spans frequency {tel_freq[freq_id]}.\")\n\n if self._is_grid_beam:\n # Either we haven't set up interpolation coords yet, or the nside has\n # changed\n if (self._beam_nside is None) or (self._beam_nside != nside):\n self._beam_nside = nside\n self._setup_gridbeam_interpolation()\n\n # interpolate gridbeam onto HEALPix\n beam_map = self._interpolate_gridbeam(freq_sel, pol_ind)\n\n else: # Healpix input beam just need to change to the required resolution\n beam_map = self._primary_beam.beam[freq_sel, pol_ind, 0, :]\n\n # Check resolution and resample to a better resolution if needed\n if nside != self._beam_nside:\n\n if nside > self._beam_nside:\n logger.warning(\n f\"Requested nside={nside} higher than that of \"\n f\"beam {self._beam_nside}\"\n )\n\n logger.debug(\n \"Resampling external beam from nside {:d} to {:d}\".format(\n self._beam_nside,\n nside,\n )\n )\n beam_map_new = np.zeros((len(freq_sel), npix), dtype=beam_map.dtype)\n beam_map_new[\"Et\"] = healpy.ud_grade(beam_map[\"Et\"], nside)\n beam_map_new[\"Ep\"] = healpy.ud_grade(beam_map[\"Ep\"], nside)\n beam_map = beam_map_new\n\n map_out = np.empty((npix, 2), dtype=self._output_dtype)\n\n # Pull out the real part of the beam if we are forcing a conversion. This should\n # do nothing if the array is already real\n def _conv_real(x):\n if self.force_real_beam:\n x = x.real\n return x\n\n if len(freq_sel) == 1:\n # exact match\n map_out[:, 0] = _conv_real(beam_map[\"Et\"][0])\n map_out[:, 1] = _conv_real(beam_map[\"Ep\"][0])\n else:\n # interpolate between pair of frequencies\n freq_high = self._beam_freq[freq_sel[1]]\n freq_low = self._beam_freq[freq_sel[0]]\n freq_int = tel_freq[freq_id]\n\n alpha = (freq_high - freq_int) / (freq_high - freq_low)\n beta = (freq_int - freq_low) / (freq_high - freq_low)\n\n map_out[:, 0] = _conv_real(\n beam_map[\"Et\"][0] * alpha + beam_map[\"Et\"][1] * beta\n )\n map_out[:, 0] = _conv_real(\n beam_map[\"Ep\"][0] * alpha + beam_map[\"Ep\"][1] * beta\n )\n\n return map_out\n\n def _setup_gridbeam_interpolation(self):\n # grid beam coordinates\n self._x_grid = self._primary_beam.phi[:]\n self._y_grid = self._primary_beam.theta[:]\n\n # celestial coordinates\n angpos = hputil.ang_positions(self._nside)\n x_cel = coord.sph_to_cart(angpos).T\n\n # rotate to telescope coords\n # first align y with N, then polar axis with NCP\n self._x_tel = cylbeam.rotate_ypr(\n (1.5 * np.pi, np.radians(90.0 - self.latitude), 0), *x_cel\n )\n\n # mask any pixels outside grid\n x_t, y_t, z_t = self._x_tel\n self._pix_mask = (\n (z_t > 0)\n & (np.abs(x_t) < np.abs(self._x_grid.max()))\n & (np.abs(y_t) < np.abs(self._y_grid.max()))\n )\n\n # pre-compute polarisation pattern\n # taken from driftscan\n zenith = np.array([np.pi / 2.0 - np.radians(self.latitude), 0.0])\n that, phat = coord.thetaphi_plane_cart(zenith)\n xhat, yhat, zhat = cylbeam.rotate_ypr(\n [-self.rotation_angle, 0.0, 0.0], phat, -that, coord.sph_to_cart(zenith)\n )\n\n self._pvec_x = cylbeam.polpattern(angpos, xhat)\n self._pvec_y = cylbeam.polpattern(angpos, yhat)\n\n def _interpolate_gridbeam(self, f_sel, p_ind):\n x, y = self._x_grid, self._y_grid\n x_t, y_t, z_t = self._x_tel\n mask = self._pix_mask\n\n # interpolation routine requires increasing axes\n reverse_x = (np.diff(self._x_grid) < 0).any()\n if reverse_x:\n x = x[::-1]\n\n npix = healpy.nside2npix(self._nside)\n beam_out = np.zeros(\n (len(f_sel), npix), dtype=HEALPixBeam._dataset_spec[\"beam\"][\"dtype\"]\n )\n for i, fi in enumerate(f_sel):\n # For now we just use the magnitude. Assumes input is power beam\n beam = self._primary_beam.beam[fi, p_ind, 0]\n if reverse_x:\n beam = beam[:, ::-1]\n beam_spline = RectBivariateSpline(y, x, np.sqrt(np.abs(beam)))\n\n # beam amplitude\n amp = np.zeros(npix, dtype=beam.real.dtype)\n amp[mask] = beam_spline(y_t[mask], x_t[mask], grid=False)\n\n # polarisation projection\n pvec = self._pvec_x if self._beam_pol_map[\"X\"] == p_ind else self._pvec_y\n\n beam_out[i][\"Et\"] = amp * pvec[:, 0]\n beam_out[i][\"Ep\"] = amp * pvec[:, 1]\n\n return beam_out\n\n\ndef _nearest_freq(tel_freq, map_freq, freq_id, single=False):\n \"\"\"Find nearest neighbor frequencies. Assumes map frequencies\n are uniformly spaced.\n\n Parameters\n ----------\n tel_freq : float\n frequencies from telescope object.\n map_freq : float\n frequencies from beam map file.\n freq_id : int\n frequency selection.\n single : bool\n Only return the single nearest neighbour.\n\n Returns\n -------\n freq_ind : list of neighboring map frequencies matched to tel_freq.\n\n \"\"\"\n\n diff_freq = abs(map_freq - tel_freq[freq_id])\n if single:\n return np.array([np.argmin(diff_freq)])\n\n map_freq_width = abs(map_freq[1] - map_freq[0])\n match_mask = diff_freq < map_freq_width\n\n freq_ind = np.nonzero(match_mask)[0]\n\n return freq_ind\n", "meta": {"hexsha": "454edba35bdd8c3c83dc07492f06d23e8597f6bc", "size": 35900, "ext": "py", "lang": "Python", "max_stars_repo_path": "ch_pipeline/core/telescope.py", "max_stars_repo_name": "chime-experiment/ch_pipeline", "max_stars_repo_head_hexsha": "e09539f18cbe4cfafe05c362a5e3c1a19f32d5e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-24T23:22:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T23:22:47.000Z", "max_issues_repo_path": "ch_pipeline/core/telescope.py", "max_issues_repo_name": "chime-experiment/ch_pipeline", "max_issues_repo_head_hexsha": "e09539f18cbe4cfafe05c362a5e3c1a19f32d5e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2021-01-23T02:01:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-18T22:34:22.000Z", "max_forks_repo_path": "ch_pipeline/core/telescope.py", "max_forks_repo_name": "chime-experiment/ch_pipeline", "max_forks_repo_head_hexsha": "e09539f18cbe4cfafe05c362a5e3c1a19f32d5e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6859903382, "max_line_length": 96, "alphanum_fraction": 0.6093871866, "include": true, "reason": "import numpy,from scipy", "num_tokens": 8481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.2628418431456957, "lm_q1q2_score": 0.13244762663435275}} {"text": "# This file is part of QuTiP: Quantum Toolbox in Python.\n#\n# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names\n# of its contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n###############################################################################\nimport numpy as np\nfrom qutip.operators import sigmax, sigmay, sigmaz, identity\nfrom qutip.tensor import tensor\nfrom qutip.qip.circuit import QubitCircuit\nfrom qutip.qip.device.processor import Processor\nfrom qutip.qip.device.modelprocessor import ModelProcessor, GateDecomposer\n\n\n__all__ = ['SpinChain', 'LinearSpinChain', 'CircularSpinChain',\n 'SpinChainGateDecomposer']\n\n\nclass SpinChain(ModelProcessor):\n \"\"\"\n The processor based on the physical implementation of\n a spin chain qubits system.\n The available Hamiltonian of the system is predefined.\n The processor can simulate the evolution under the given\n control pulses either numerically or analytically.\n It is a base class and should not be used directly, please\n refer the the subclasses :class:`qutip.qip.LinearSpinChain` and\n :class:`qutip.qip.CircularSpinChain`.\n\n Parameters\n ----------\n N: int\n The number of qubits in the system.\n\n correct_global_phase: float\n Save the global phase, the analytical solution\n will track the global phase.\n It has no effect on the numerical solution.\n\n sx: int or list\n The delta for each of the qubits in the system.\n\n sz: int or list\n The epsilon for each of the qubits in the system.\n\n sxsy: int or list\n The interaction strength for each of the qubit pair in the system.\n\n t1: list or float\n Characterize the decoherence of amplitude damping for\n each qubit. A list of size ``N`` or a float for all qubits.\n\n t2: list of float\n Characterize the decoherence of dephasing for\n each qubit. A list of size ``N`` or a float for all qubits.\n\n Attributes\n ----------\n N: int\n The number of component systems.\n\n ctrls: list\n A list of the control Hamiltonians driving the evolution.\n\n tlist: array_like\n A NumPy array specifies the time of each coefficient.\n\n coeffs: array_like\n A 2d NumPy array of the shape, the length is dependent on the\n spline type\n\n t1: list\n Characterize the decoherence of amplitude damping for\n each qubit.\n\n t2: list\n Characterize the decoherence of dephasing for\n each qubit.\n\n noise: :class:`qutip.qip.Noise`, optional\n A list of noise objects. They will be processed when creating the\n noisy :class:`qutip.QobjEvo` from the processor or run the simulation.\n\n dims: list\n The dimension of each component system.\n Default is dim=[2,2,2,...,2]\n\n spline_kind: str\n Type of the coefficient interpolation.\n Note that they have different requirement for the length of ``coeffs``.\n\n -\"step_func\":\n The coefficient will be treated as a step function.\n E.g. ``tlist=[0,1,2]`` and ``coeffs=[3,2]``, means that the coefficient\n is 3 in t=[0,1) and 2 in t=[2,3). It requires\n ``coeffs.shape[1]=len(tlist)-1`` or ``coeffs.shape[1]=len(tlist)``, but\n in the second case the last element has no effect.\n\n -\"cubic\": Use cubic interpolation for the coefficient. It requires\n ``coeffs.shape[1]=len(tlist)``\n\n sx: list\n The delta for each of the qubits in the system.\n\n sz: list\n The epsilon for each of the qubits in the system.\n\n sxsy: list\n The interaction strength for each of the qubit pair in the system.\n\n sx_ops: list\n A list of sigmax Hamiltonians for each qubit.\n\n sz_ops: list\n A list of sigmaz Hamiltonians for each qubit.\n\n sxsy_ops: list\n A list of tensor(sigmax, sigmay)\n interacting Hamiltonians for each qubit.\n\n sx_u: array_like\n Pulse matrix for sigmax Hamiltonians.\n\n sz_u: array_like\n Pulse matrix for sigmaz Hamiltonians.\n\n sxsy_u: array_like\n Pulse matrix for tensor(sigmax, sigmay) interacting Hamiltonians.\n \"\"\"\n def __init__(self, N, correct_global_phase,\n sx, sz, sxsy, t1, t2):\n super(SpinChain, self).__init__(\n N, correct_global_phase=correct_global_phase, t1=t1, t2=t2)\n self.correct_global_phase = correct_global_phase\n self.spline_kind = \"step_func\"\n # params and ops are set in the submethods\n\n def set_up_ops(self, N):\n \"\"\"\n Generate the Hamiltonians for the spinchain model and save them in the\n attribute `ctrls`.\n\n Parameters\n ----------\n N: int\n The number of qubits in the system.\n \"\"\"\n # sx_ops\n self.ctrls += [tensor([sigmax() if m == n else identity(2)\n for n in range(N)])\n for m in range(N)]\n # sz_ops\n self.ctrls += [tensor([sigmaz() if m == n else identity(2)\n for n in range(N)])\n for m in range(N)]\n # sxsy_ops\n for n in range(N - 1):\n x = [identity(2)] * N\n x[n] = x[n + 1] = sigmax()\n y = [identity(2)] * N\n y[n] = y[n + 1] = sigmay()\n self.ctrls.append(tensor(x) + tensor(y))\n\n def set_up_params(self, sx, sz):\n \"\"\"\n Save the parameters in the attribute `params` and check the validity.\n\n Parameters\n ----------\n sx: float or list\n The coefficient of sigmax in the model\n\n sz: flaot or list\n The coefficient of sigmaz in the model\n\n Notes\n -----\n The coefficient of sxsy is defined in the submethods.\n All parameters will be multiplied by 2*pi for simplicity\n \"\"\"\n sx_para = super(SpinChain, self)._para_list(sx, self.N)\n self._paras[\"sx\"] = sx_para\n sz_para = super(SpinChain, self)._para_list(sz, self.N)\n self._paras[\"sz\"] = sz_para\n\n @property\n def sx_ops(self):\n return self.ctrls[: self.N]\n\n @property\n def sz_ops(self):\n return self.ctrls[self.N: 2*self.N]\n\n @property\n def sxsy_ops(self):\n return self.ctrls[2*self.N:]\n\n @property\n def sx_u(self):\n return self.coeffs[: self.N]\n\n @property\n def sz_u(self):\n return self.coeffs[self.N: 2*self.N]\n\n @property\n def sxsy_u(self):\n return self.coeffs[2*self.N:]\n\n def load_circuit(self, qc, setup):\n \"\"\"\n Decompose a :class:`qutip.QubitCircuit` in to the control\n amplitude generating the corresponding evolution.\n\n Parameters\n ----------\n qc: :class:`qutip.QubitCircuit`\n Takes the quantum circuit to be implemented.\n\n setup: string\n \"linear\" or \"circular\" for two sub-calsses.\n\n Returns\n -------\n tlist: array_like\n A NumPy array specifies the time of each coefficient\n\n coeffs: array_like\n A 2d NumPy array of the shape (len(ctrls), len(tlist)). Each\n row corresponds to the control pulse sequence for\n one Hamiltonian.\n \"\"\"\n gates = self.optimize_circuit(qc).gates\n\n dec = SpinChainGateDecomposer(\n self.N, self._paras, setup=setup,\n global_phase=0., num_ops=len(self.ctrls))\n self.tlist, self.coeffs, self.global_phase = dec.decompose(gates)\n\n return self.tlist, self.coeffs\n\n def adjacent_gates(self, qc, setup=\"linear\"):\n \"\"\"\n Method to resolve 2 qubit gates with non-adjacent control/s or target/s\n in terms of gates with adjacent interactions for linear/circular spin\n chain system.\n\n Parameters\n ----------\n qc: :class:`qutip.QubitCircuit`\n The circular spin chain circuit to be resolved\n\n setup: Boolean\n Linear of Circular spin chain setup\n\n Returns\n -------\n qc: :class:`qutip.QubitCircuit`\n Returns QubitCircuit of resolved gates for the qubit circuit in the\n desired basis.\n \"\"\"\n qc_t = QubitCircuit(qc.N, qc.reverse_states)\n swap_gates = [\"SWAP\", \"ISWAP\", \"SQRTISWAP\", \"SQRTSWAP\", \"BERKELEY\",\n \"SWAPalpha\"]\n N = qc.N\n\n for gate in qc.gates:\n if gate.name == \"CNOT\" or gate.name == \"CSIGN\":\n start = min([gate.targets[0], gate.controls[0]])\n end = max([gate.targets[0], gate.controls[0]])\n\n if (setup == \"linear\" or\n (setup == \"circular\" and (end - start) <= N // 2)):\n i = start\n while i < end:\n if (start + end - i - i == 1 and\n (end - start + 1) % 2 == 0):\n # Apply required gate if control and target are\n # adjacent to each other, provided |control-target|\n # is even.\n if end == gate.controls[0]:\n qc_t.add_gate(gate.name, targets=[i],\n controls=[i + 1])\n else:\n qc_t.add_gate(gate.name, targets=[i + 1],\n controls=[i])\n\n elif (start + end - i - i == 2 and\n (end - start + 1) % 2 == 1):\n # Apply a swap between i and its adjacent gate,\n # then the required gate if and then another swap\n # if control and target have one qubit between\n # them, provided |control-target| is odd.\n qc_t.add_gate(\"SWAP\", targets=[i, i + 1])\n if end == gate.controls[0]:\n qc_t.add_gate(gate.name, targets=[i + 1],\n controls=[i + 2])\n else:\n qc_t.add_gate(gate.name, targets=[i + 2],\n controls=[i + 1])\n qc_t.add_gate(\"SWAP\", [i, i + 1])\n i += 1\n\n else:\n # Swap the target/s and/or control with their\n # adjacent qubit to bring them closer.\n qc_t.add_gate(\"SWAP\", [i, i + 1])\n qc_t.add_gate(\"SWAP\", [start + end - i - 1,\n start + end - i])\n i += 1\n\n elif (end - start) < N - 1:\n \"\"\"\n If the resolving has to go backwards, the path is first\n mapped to a separate circuit and then copied back to the\n original circuit.\n \"\"\"\n\n temp = QubitCircuit(N - end + start)\n i = 0\n while i < (N - end + start):\n\n if (N + start - end - i - i == 1 and\n (N - end + start + 1) % 2 == 0):\n if end == gate.controls[0]:\n temp.add_gate(gate.name, targets=[i],\n controls=[i + 1])\n else:\n temp.add_gate(gate.name, targets=[i + 1],\n controls=[i])\n\n elif (N + start - end - i - i == 2 and\n (N - end + start + 1) % 2 == 1):\n temp.add_gate(\"SWAP\", targets=[i, i + 1])\n if end == gate.controls[0]:\n temp.add_gate(gate.name, targets=[i + 2],\n controls=[i + 1])\n else:\n temp.add_gate(gate.name, targets=[i + 1],\n controls=[i + 2])\n temp.add_gate(\"SWAP\", [i, i + 1])\n i += 1\n\n else:\n temp.add_gate(\"SWAP\", [i, i + 1])\n temp.add_gate(\"SWAP\",\n [N + start - end - i - 1,\n N + start - end - i])\n i += 1\n\n j = 0\n for gate in temp.gates:\n if (j < N - end - 2):\n if gate.name in [\"CNOT\", \"CSIGN\"]:\n qc_t.add_gate(gate.name, end + gate.targets[0],\n end + gate.controls[0])\n else:\n qc_t.add_gate(gate.name,\n [end + gate.targets[0],\n end + gate.targets[1]])\n elif (j == N - end - 2):\n if gate.name in [\"CNOT\", \"CSIGN\"]:\n qc_t.add_gate(gate.name, end + gate.targets[0],\n (end + gate.controls[0]) % N)\n else:\n qc_t.add_gate(gate.name,\n [end + gate.targets[0],\n (end + gate.targets[1]) % N])\n else:\n if gate.name in [\"CNOT\", \"CSIGN\"]:\n qc_t.add_gate(gate.name,\n (end + gate.targets[0]) % N,\n (end + gate.controls[0]) % N)\n else:\n qc_t.add_gate(gate.name,\n [(end + gate.targets[0]) % N,\n (end + gate.targets[1]) % N])\n j = j + 1\n\n elif (end - start) == N - 1:\n qc_t.add_gate(gate.name, gate.targets, gate.controls)\n\n elif gate.name in swap_gates:\n start = min([gate.targets[0], gate.targets[1]])\n end = max([gate.targets[0], gate.targets[1]])\n\n if (setup == \"linear\" or\n (setup == \"circular\" and (end - start) <= N // 2)):\n i = start\n while i < end:\n if (start + end - i - i == 1 and\n (end - start + 1) % 2 == 0):\n qc_t.add_gate(gate.name, [i, i + 1])\n elif ((start + end - i - i) == 2 and\n (end - start + 1) % 2 == 1):\n qc_t.add_gate(\"SWAP\", [i, i + 1])\n qc_t.add_gate(gate.name, [i + 1, i + 2])\n qc_t.add_gate(\"SWAP\", [i, i + 1])\n i += 1\n else:\n qc_t.add_gate(\"SWAP\", [i, i + 1])\n qc_t.add_gate(\"SWAP\", [start + end - i - 1,\n start + end - i])\n i += 1\n\n else:\n temp = QubitCircuit(N - end + start)\n i = 0\n while i < (N - end + start):\n\n if (N + start - end - i - i == 1 and\n (N - end + start + 1) % 2 == 0):\n temp.add_gate(gate.name, [i, i + 1])\n\n elif (N + start - end - i - i == 2 and\n (N - end + start + 1) % 2 == 1):\n temp.add_gate(\"SWAP\", [i, i + 1])\n temp.add_gate(gate.name, [i + 1, i + 2])\n temp.add_gate(\"SWAP\", [i, i + 1])\n i += 1\n\n else:\n temp.add_gate(\"SWAP\", [i, i + 1])\n temp.add_gate(\"SWAP\", [N + start - end - i - 1,\n N + start - end - i])\n i += 1\n\n j = 0\n for gate in temp.gates:\n if(j < N - end - 2):\n qc_t.add_gate(gate.name, [end + gate.targets[0],\n end + gate.targets[1]])\n elif(j == N - end - 2):\n qc_t.add_gate(gate.name,\n [end + gate.targets[0],\n (end + gate.targets[1]) % N])\n else:\n qc_t.add_gate(gate.name,\n [(end + gate.targets[0]) % N,\n (end + gate.targets[1]) % N])\n j = j + 1\n\n else:\n qc_t.add_gate(gate.name, gate.targets, gate.controls,\n gate.arg_value, gate.arg_label)\n\n return qc_t\n\n def eliminate_auxillary_modes(self, U):\n return U\n\n def optimize_circuit(self, qc):\n \"\"\"\n Take a quantum circuit/algorithm and convert it into the\n optimal form/basis for the desired physical system.\n\n Parameters\n ----------\n qc: :class:`qutip.QubitCircuit`\n Takes the quantum circuit to be implemented.\n\n Returns\n -------\n qc: :class:`qutip.QubitCircuit`\n The circuit representation with elementary gates\n that can be implemented in this model.\n \"\"\"\n self.qc0 = qc\n self.qc1 = self.adjacent_gates(self.qc0)\n self.qc2 = self.qc1.resolve_gates(\n basis=[\"SQRTISWAP\", \"ISWAP\", \"RX\", \"RZ\"])\n return self.qc2\n\n\nclass LinearSpinChain(SpinChain):\n \"\"\"\n A processor based on the physical implementation of\n a linear spin chain qubits system.\n The available Hamiltonian of the system is predefined.\n The processor can simulate the evolution under the given\n control pulses either numerically or analytically.\n\n Parameters\n ----------\n N: int\n The number of qubits in the system.\n\n correct_global_phase: float\n Save the global phase, the analytical solution\n will track the global phase.\n It has no effect on the numerical solution.\n\n sx: int or list\n The delta for each of the qubits in the system.\n\n sz: int or list\n The epsilon for each of the qubits in the system.\n\n sxsy: int or list\n The interaction strength for each of the qubit pair in the system.\n\n t1: list or float, optional\n Characterize the decoherence of amplitude damping for\n each qubit.\n\n t2: list of float, optional\n Characterize the decoherence of dephasing for\n each qubit.\n \"\"\"\n def __init__(self, N, correct_global_phase=True,\n sx=0.25, sz=1.0, sxsy=0.1, t1=None, t2=None):\n\n super(LinearSpinChain, self).__init__(\n N, correct_global_phase=correct_global_phase,\n sx=sx, sz=sz, sxsy=sxsy, t1=t1, t2=t2)\n self.set_up_params(sx=sx, sz=sz, sxsy=sxsy)\n self.set_up_ops(N)\n\n def set_up_ops(self, N):\n super(LinearSpinChain, self).set_up_ops(N)\n\n def set_up_params(self, sx, sz, sxsy):\n # Doc same as in the parent class\n super(LinearSpinChain, self).set_up_params(sx, sz)\n sxsy_para = self._para_list(sxsy, self.N-1)\n self._paras[\"sxsy\"] = sxsy_para\n\n @property\n def sxsy_ops(self):\n return self.ctrls[2*self.N: 3*self.N-1]\n\n @property\n def sxsy_u(self):\n return self.coeffs[2*self.N: 3*self.N-1]\n\n def load_circuit(self, qc):\n return super(LinearSpinChain, self).load_circuit(qc, \"linear\")\n\n def get_ops_labels(self):\n return ([r\"$\\sigma_x^%d$\" % n for n in range(self.N)] +\n [r\"$\\sigma_z^%d$\" % n for n in range(self.N)] +\n [r\"$\\sigma_x^%d\\sigma_x^{%d} + \\sigma_y^%d\\sigma_y^{%d}$\"\n % (n, n, n + 1, n + 1) for n in range(self.N - 1)])\n\n def adjacent_gates(self, qc):\n return super(LinearSpinChain, self).adjacent_gates(qc, \"linear\")\n\n\nclass CircularSpinChain(SpinChain):\n \"\"\"\n A processor based on the physical implementation of\n a circular spin chain qubits system.\n The available Hamiltonian of the system is predefined.\n The processor can simulate the evolution under the given\n control pulses either numerically or analytically.\n\n Parameters\n ----------\n N: int\n The number of qubits in the system.\n\n correct_global_phase: float\n Save the global phase, the analytical solution\n will track the global phase.\n It has no effect on the numerical solution.\n\n sx: int or list\n The delta for each of the qubits in the system.\n\n sz: int or list\n The epsilon for each of the qubits in the system.\n\n sxsy: int or list\n The interaction strength for each of the qubit pair in the system.\n\n t1: list or float, optional\n Characterize the decoherence of amplitude damping for\n each qubit.\n\n t2: list of float, optional\n Characterize the decoherence of dephasing for\n each qubit.\n \"\"\"\n def __init__(self, N, correct_global_phase=True,\n sx=0.25, sz=1.0, sxsy=0.1, t1=None, t2=None):\n\n super(CircularSpinChain, self).__init__(\n N, correct_global_phase=correct_global_phase,\n sx=sx, sz=sz, sxsy=sxsy, t1=t1, t2=t2)\n self.set_up_params(sx=sx, sz=sz, sxsy=sxsy)\n self.set_up_ops(N)\n\n def set_up_ops(self, N):\n super(CircularSpinChain, self).set_up_ops(N)\n x = [identity(2)] * N\n x[0] = x[N - 1] = sigmax()\n y = [identity(2)] * N\n y[0] = y[N - 1] = sigmay()\n self.ctrls.append(tensor(x) + tensor(y))\n\n def set_up_params(self, sx, sz, sxsy):\n # Doc same as in the parent class\n super(CircularSpinChain, self).set_up_params(sx, sz)\n sxsy_para = self._para_list(sxsy, self.N)\n self._paras[\"sxsy\"] = sxsy_para\n\n @property\n def sxsy_ops(self):\n return self.ctrls[2*self.N: 3*self.N]\n\n @property\n def sxsy_u(self):\n return self.coeffs[2*self.N: 3*self.N]\n\n def load_circuit(self, qc):\n return super(CircularSpinChain, self).load_circuit(qc, \"circular\")\n\n def get_ops_labels(self):\n return ([r\"$\\sigma_x^%d$\" % n for n in range(self.N)] +\n [r\"$\\sigma_z^%d$\" % n for n in range(self.N)] +\n [r\"$\\sigma_x^%d\\sigma_x^{%d} + \\sigma_y^%d\\sigma_y^{%d}$\"\n % (n, n, (n + 1) % self.N, (n + 1) % self.N)\n for n in range(self.N)])\n\n def adjacent_gates(self, qc):\n return super(CircularSpinChain, self).adjacent_gates(qc, \"circular\")\n\n\nclass SpinChainGateDecomposer(GateDecomposer):\n \"\"\"\n Decompose a :class:`qutip.QubitCircuit` into\n the pulse sequence for the processor.\n\n Parameters\n ----------\n N: int\n The number of qubits in the system.\n\n params: dict\n A Python dictionary contains the name and the value of the parameters,\n such as laser frequency, detuning etc.\n\n setup: string\n \"linear\" or \"circular\" for two sub-calsses.\n\n global_phase: bool\n Record of the global phase change and will be returned.\n\n num_ops: int\n Number of Hamiltonians in the processor.\n\n Attributes\n ----------\n N: int\n The number of the component systems.\n\n params: dict\n A Python dictionary contains the name and the value of the parameters,\n such as laser frequency, detuning etc.\n\n num_ops: int\n Number of control Hamiltonians in the processor.\n\n gate_decomps: dict\n The Python dictionary in the form of {gate_name: decompose_function}.\n It saves the decomposition scheme for each gate.\n\n setup: string\n \"linear\" or \"circular\" for two sub-calsses.\n\n global_phase: bool\n Record of the global phase change and will be returned.\n \"\"\"\n def __init__(self, N, params, setup, global_phase, num_ops):\n super(SpinChainGateDecomposer, self).__init__(\n N=N, params=params, num_ops=num_ops)\n self.gate_decomps = {\"ISWAP\": self.iswap_dec,\n \"SQRTISWAP\": self.sqrtiswap_dec,\n \"RZ\": self.rz_dec,\n \"RX\": self.rx_dec,\n \"GLOBALPHASE\": self.globalphase_dec\n }\n self.N = N\n self._sx_ind = list(range(0, N))\n self._sz_ind = list(range(N, 2*N))\n if setup == \"circular\":\n self._sxsy_ind = list(range(2*N, 3*N))\n elif setup == \"linear\":\n self._sxsy_ind = list(range(2*N, 3*N-1))\n self.global_phase = global_phase\n\n def decompose(self, gates):\n tlist, coeffs = super(SpinChainGateDecomposer, self).decompose(gates)\n return tlist, coeffs, self.global_phase\n\n def rz_dec(self, gate):\n \"\"\"\n Decomposer for the RZ gate\n \"\"\"\n pulse = np.zeros(self.num_ops)\n q_ind = gate.targets[0]\n g = self.params[\"sz\"][q_ind]\n pulse[self._sz_ind[q_ind]] = np.sign(gate.arg_value) * g\n t = abs(gate.arg_value) / (2 * g)\n self.dt_list.append(t)\n self.coeff_list.append(pulse)\n\n def rx_dec(self, gate):\n \"\"\"\n Decomposer for the RX gate\n \"\"\"\n pulse = np.zeros(self.num_ops)\n q_ind = gate.targets[0]\n g = self.params[\"sx\"][q_ind]\n pulse[self._sx_ind[q_ind]] = np.sign(gate.arg_value) * g\n t = abs(gate.arg_value) / (2 * g)\n self.dt_list.append(t)\n self.coeff_list.append(pulse)\n\n def iswap_dec(self, gate):\n \"\"\"\n Decomposer for the ISWAP gate\n \"\"\"\n pulse = np.zeros(self.num_ops)\n q1, q2 = min(gate.targets), max(gate.targets)\n g = self.params[\"sxsy\"][q1]\n if q1 == 0 and q2 == self.N - 1:\n pulse[self._sxsy_ind[self.N - 1]] = -g\n else:\n pulse[self._sxsy_ind[q1]] = -g\n t = np.pi / (4 * g)\n self.dt_list.append(t)\n self.coeff_list.append(pulse)\n\n def sqrtiswap_dec(self, gate):\n \"\"\"\n Decomposer for the SQRTISWAP gate\n \"\"\"\n pulse = np.zeros(self.num_ops)\n q1, q2 = min(gate.targets), max(gate.targets)\n g = self.params[\"sxsy\"][q1]\n if q1 == 0 and q2 == self.N - 1:\n pulse[self._sxsy_ind[self.N - 1]] = -g\n else:\n pulse[self._sxsy_ind[q1]] = -g\n t = np.pi / (8 * g)\n self.dt_list.append(t)\n self.coeff_list.append(pulse)\n\n def globalphase_dec(self, gate):\n \"\"\"\n Decomposer for the GLOBALPHASE gate\n \"\"\"\n self.global_phase += gate.arg_value\n", "meta": {"hexsha": "65f7387f119273591248430e7e1f18cec06ecc51", "size": 28880, "ext": "py", "lang": "Python", "max_stars_repo_path": "qutip/qip/device/spinchain.py", "max_stars_repo_name": "dweigand/qutip", "max_stars_repo_head_hexsha": "b57d5e4b4846880e894afa390c62f4d095c642e1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "qutip/qip/device/spinchain.py", "max_issues_repo_name": "dweigand/qutip", "max_issues_repo_head_hexsha": "b57d5e4b4846880e894afa390c62f4d095c642e1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qutip/qip/device/spinchain.py", "max_forks_repo_name": "dweigand/qutip", "max_forks_repo_head_hexsha": "b57d5e4b4846880e894afa390c62f4d095c642e1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9782330346, "max_line_length": 79, "alphanum_fraction": 0.5108033241, "include": true, "reason": "import numpy", "num_tokens": 6801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.26284184314569564, "lm_q1q2_score": 0.13244762663435272}} {"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport shutil\nimport os\nimport copy\nimport xml.etree.ElementTree as ET\nimport glob\nimport pdb\nimport time\n\nimport openmc\nimport openmc.mgxs as mgxs\nfrom openbu.cell import Cell\nfrom openbu.system import System\nfrom openbu import salameche\nfrom .openmc_fix import *\n\nfrom openbu import utils\nfrom openbu import data\n\n\nclass Couple_openmc(object):\n\n\t# One-group energy bin\n\tenergy_bin = openmc.EnergyFilter([0., 20.0e6])\n\n\t# Multigroup energy bin\n\tminorder = -3\n\tmaxorder = 7\n\tmg_energy = np.logspace(minorder, maxorder, (maxorder - minorder) * 30 + 1)\n\tmg_energy_mid_points = [(x+y)/2 for x,y in zip(mg_energy[1:],mg_energy[:-1])]\n\t#mg_energy = np.logspace(-3, 7, num=300, base=10.0)\n\tmg_energy_bin = openmc.EnergyFilter(mg_energy)\n\n\tzero_dens_1_atm = 1E-24\n\n\tdef __init__(self, MC_input_path = None, xs_mode = 'no constant lib', MPI = None):\n\n\t\t# If no MC_input_path is input, it is set to cwd\n\t\tif MC_input_path == None:\n\t\t\tMC_input_path = os.getcwd()\n\t\tself._MC_input_path = MC_input_path\n\n\t\t# If no mode is input by the user, mode is set by default to 'const_lib'\n\t\tif xs_mode == None:\n\t\t\txs_mode == 'constant lib'\n\t\tself._xs_mode = xs_mode\n\n\t\t# # If MPI is not set to on by the user, MPI is set to off\n\t\t# if MPI == None:\n\t\t# \tMPI == 'off'\n\t\t# self._MPI = MPI\n\t\tself._MPI = None\n\n\t\tself._volume_set = 'no'\n\n\t\t# List of selected cells to deplete\n\t\tself.selected_bucells_name_list = None\n\t\t# Dict of selected cells to deplete with their user defined nucl list\n\t\tself.selected_bucells_nucl_list_dict = None\n\n\t\tself._fy_lib_set = 'no'\n\t\tself._decay_lib_set = 'no'\n\t\tself._xs_lib_set = 'no'\n\n\t\tself._sampled_isomeric_branching_data = None\n\t\tself._sampled_ng_cross_section_data = None\n\n\t\t# This is the path set in OpenMC for the hdf5 point-wise cross sections\n\t\tself._cross_sections_path = None\n\n\t\tself._openmc_bin_path = None\n\n\t\t# Old way of defaulting MC_input_path to cwd\n\t\t# if args:\n\t\t# \tself._MC_input_path = arg[0]\n\t\t# else:\n\t\t# \tself._MC_input_path = os.getcwd()\n\n# This method is used within the code to create a new material that is \n# uniquely associated to a particular cell\n\n\t@property\n\tdef MC_input_path(self):\n\n\t\treturn self._MC_input_path\n\n\t@property\n\tdef xs_mode(self):\n\t\treturn self._xs_mode\n\t\n\t@property\n\tdef nucl_list_dict(self):\n\n\t\treturn self._nucl_list_dict\n\n\t@property\n\tdef root_cell(self):\n\n\t\treturn self._root_cell\n\n\t@property\n\tdef MPI(self):\n\t\treturn self._MPI\n\n\tdef set_MPI(self, execu, tasks):\n\n\t\tself._MPI = 'on'\n\t\tself._tasks = tasks\n\t\tself._exec = execu\n\t\n\t# for no_const_lib mode, defines the list of nucl that will be simulated\n\t# for mat id #\n\t# def set_nucl_list(self, mat_name, nucl_list):\n\n\t# \tself._nucl_list_dict[mat_name] = nucl_list\n\n\tdef select_bucells(self, bucell_list):\n\n\t\tself.selected_bucells_name_list = []\n\t\tself.selected_bucells_nucl_list_dict = {}\n\n\t\tfor arg in bucell_list:\n\t\t\t# If this element is a tuple (bucell , nucl list)\n\t\t\tif isinstance(arg,tuple):\t\n\t\t\t\tbucell_name = arg[0].name\n\t\t\t\tself.selected_bucells_name_list.append(bucell_name)\n\t\t\t\tself.selected_bucells_nucl_list_dict[bucell_name] = arg[1]\n\t\t\telse:\n\t\t\t\tself.selected_bucells_name_list.append(arg.name)\n\n\tdef get_nucl_to_be_tallied(self, bucell):\n\n\t\t# If the user has provided a list of nuclide to be tallied\n\t\tif bucell.name in self.selected_bucells_nucl_list_dict:\n\t\t\tnucl_list_input = self.selected_bucells_nucl_list_dict[bucell.name]\n\t\t\tif nucl_list_input == 'initial nuclides':\n\t\t\t\tnucl_list = bucell.init_nucl\n\t\t\telif nucl_list_input == 'NAX':\n\t\t\t\tNAX_nucl_list_name = utils.zamid_list_to_name_list(data.NAX_nucl_list)\n\t\t\t\tNAX_nucl_list_name_new_format = utils.bu_namelist_to_mc_namelist(NAX_nucl_list_name)\n\t\t\t\t# I add init_nucl because I believe it is important for init nuclides to be tallied\n\t\t\t\t# Their density is usually high enough that their change can influence spectrum etc...\n\t\t\t\tnucl_list = [x for x in NAX_nucl_list_name_new_format if x in self.MC_XS_nucl_list] + bucell.init_nucl\n\t\t\t\t# Here we remove the potential duplicates\n\t\t\t\tnucl_list = list(dict.fromkeys(nucl_list))\n\t\t\telse:\n\t\t\t\tnucl_list = nucl_list_input\n\t\telse:\n\t\t\tnucl_list = self.MC_XS_nucl_list\n\n\t\treturn nucl_list\n\n\n\t# @property\n\t# def nucl_list(self):\n\n\t# \treturn self._nucl_list\n\t\n\n\t# # for no_const_lib mode, defines a unique nuclide list for all materials\n\t# @nucl_list.setter\n\t# def nucl_list(self, nucl_list):\n\n\t# \tself._nucl_list = nucl_list\n\n\t# \tmat_dict = self.root_cell.get_all_materials()\n\t# \tfor mat_id in mat_dict:\n\t# \t\tmat = mat_dict[mad_id]\n\t# \t\tmat_name = mat.name\n\t# \t\tself._nucl_list_dict[mat_id] = nucl_list\n\n\n\n\t@property\n\tdef system(self):\n\n\t\treturn self._system\n\n\t@system.setter\n\tdef system(self, system):\n\n\t\tself._system = system\n\t\n\n\tdef import_openmc(self, root_cell):\n\n\t\t#Instantiate a system\n\t\tsystem = System(1)\n\t\tself.system = system\n\n\t\t# read periodic surfaces (openmc summary forgets the periodic surfaces coupling)\n\t\t# This function stores the periodic coupling of surfaces and it will be used later\n\t\tself._periodic_surfaces_dict = read_periodic_surfaces()\n\n\t\t# prerun to access cells and materials objects, to set cell volumes and if chosen\n\t\t# add 0 density nuclides\n\t\tself._pre_run(root_cell)\n\n\t\tbucell_dict = self.get_bucell_from_cell()\n\t\tsystem.bucell_dict = bucell_dict\n\t\tsystem.bounding_box = self.bounding_box\n\n\t\t# reads, modifies and set settings\n\t\tself._read_user_settings()\n\n\n\t\t# Move input files to input file folder\n\t\tself.gen_user_input_folder()\n\t\tself.copy_user_input()\n\n\t\t# MOVED TO OPENMC RUN\n\t\t# # New material xml file needs to be written with zero dens nuclides\n\t\t# self.export_material_to_xml()\n\t\t# # New geometry xml file needs to be written with new materials id\n\t\t# self.export_geometry_to_xml()\n\t\t# # Tallies xml files needs to be writen\n\t\t# self.export_tallies_to_xml()\n\t\t# # New settings xml files needs to be written\n\t\t# self.export_settings_to_xml()\n\n\t# Proably for when OpenBU pass dens to OpenMC\n\n\t@property\n\tdef bounding_box(self):\n\n\t\treturn self._bounding_box\n\t \n\tdef set_bounding_box(self, ll, ur):\n\n\t\tself._bounding_box = [ll, ur]\n\n\t# def _set_material_nuclides(self, cell):\n\n\t# \tcell_id = cell.id\n\t# \tpasslist = cell.passlists\n\t# \ttotal_dens = cell.total_dens\n\n\t# \tmaterial = openmc.Material(cell_id)\n\n\t# \tmaterial.set_density('atom/b-cm', total_dens)\n\n\t# \tfor nuc in passlist:\n\n\t# \t\tnuc_name = nuc.name.replace('-', '')\n\t# \t\tnuc_ao = nuc.dens/total_dens\n\t# \t\tmaterial.add_nuclide(nuc_name, nuc_ao)\n\n\n\tdef set_settings(self, settings, init_dist):\n\t# OpenMC simulation parameters\n\t\tbatches = settings['batches']\n\t\tinactive = settings['inactive']\t\n\t\tparticles = settings['particles']\n\n\t\t# Instantiate a Settings object\n\t\tsettings_file = openmc.Settings()\n\t\tsettings_file.batches = batches\n\t\tsettings_file.inactive = inactive\n\t\tsettings_file.particles = particles\n\t\tsettings_file.output = {'tallies': True}\n\n\t\t# Create an initial uniform spatial source distribution over fissionable zones\n\t\tinit_dist = setting.init_dist\n\t\tshape = init_dist['shape']\n\t\tlow_left_bound = init_dist['low_left']\n\t\tup_right_bound = init_dist['up_right']\n\t\tif shape == 'Box':\n\t\t\tuniform_dist = openmc.stats.Box(low_left_bound, up_right_bound, only_fissionable=True)\n\t\tsettings_file.source = openmc.source.Source(space=uniform_dist)\n\n\t\t# Export to \"settings.xml\"\n\t\tsettings_file.export_to_xml()\n\n\tdef gen_user_input_folder(self):\n\n\t\tutils.gen_folder('user_input')\n\n\tdef copy_user_input(self):\n\n\t\tMC_input_path = self.MC_input_path\n\t\tuser_input_folder_path = os.getcwd() + '/user_input'\n\t\tshutil.copyfile(MC_input_path + '/geometry.xml', user_input_folder_path + '/geometry.xml')\n\t\tshutil.copyfile(MC_input_path + '/materials.xml', user_input_folder_path + '/materials.xml')\n\t\tshutil.copyfile(MC_input_path + '/settings.xml', user_input_folder_path + '/settings.xml')\n\n\t# Probably obsolete\n\n\t# def get_summary(self):\n\n\t# \tMC_input_path = self.MC_input_path\n\n\t# \tget_summary_dir_path = MC_input_path +'/get_summary_dir'\n\t# \tos.mkdir(get_summary_dir_path)\n\n\t# \t# Instantiate a Settings object\n\t# \tsettings_file = openmc.Settings()\n\t# \tsettings_file.batches = 2\n\t# \tsettings_file.inactive = 1\n\t# \tsettings_file.particles = 8\n\n\t# \t# Copy the geometry and material file to the new dummy dir\n\n\t# \tshutil.copyfile(MC_input_path + '/geometry.xml', get_summary_dir_path + '/geometry.xml')\n\t# \tshutil.copyfile(MC_input_path + '/materials.xml', get_summary_dir_path + '/materials.xml')\n\n\t# \t# Export to \"settings.xml\"\n\t# \tsettings_file.export_to_xml(path = get_summary_dir_path + '/settings.xml')\n\n\t# \topenmc.run(cwd = get_summary_dir_path)\n\n\t# \tsummary = openmc.Summary(get_summary_dir_path + '/summary.h5')\n\t# \t# geo = summary.geometry\n\t# \t# cells = geo.get_all_cells()\n\t# \tshutil.rmtree(get_summary_dir_path)\n\n\t# \treturn summary\n\n\t#def pre_read_xml(self):\n\n\t\t# To be able to launch the prerun, OpenBU needs at least to extract the list of \n\t\t# openmc cells and the boundingbox of the system\n\t\t# For that, the user needs to provide the \n\n\n\n\tdef _pre_run(self, root_cell):\n\n\t\tMC_input_path = self.MC_input_path\n\t\tpre_run_path = os.getcwd() +'/pre_run'\n\t\ttry:\n\t\t\tshutil.rmtree(pre_run_path)\n\t\texcept OSError:\n\t\t\tpass\n\t\tos.mkdir(pre_run_path)\n\n\t\t# Prepare the volume calculation\n\t\t#bounding_box = root_cell.bounding_box\n\t\tll = self.bounding_box[0]\n\t\tur = self.bounding_box[1]\n\t\tcell_dict = root_cell.get_all_cells()\n\t\tcell_list = utils.cell_dict_to_cell_list(cell_dict)\n\t\tcell_list.append(root_cell) # Add root_cell so that the total volume is calculated\n\t\tvol1 = openmc.VolumeCalculation(cell_list, 100000, lower_left = ll, upper_right = ur)\n\n\t\tsettings = openmc.Settings()\n\t\tsettings.volume_calculations = [vol1]\n\t\tsettings.temperature = {'method':'interpolation'}\n\t\tsettings.run_mode='volume'\n\t\tsettings.export_to_xml(path = pre_run_path + '/settings.xml')\n\n\t\t# Copy the geometry and material file to the new dummy dir\n\t\tshutil.copyfile(MC_input_path + '/geometry.xml', pre_run_path + '/geometry.xml')\n\t\tshutil.copyfile(MC_input_path + '/materials.xml', pre_run_path + '/materials.xml')\n\n\t\t# By default, the openm_exec is set to 'openmc'\n\t\t# For some reasons, this does not work on the cluster (della)\n\t\t# On della, we need to explicitly define the absolute path to the bin we want to use\n\t\t# Right now a temporary path that depends on my installation is used\n\n\t\t#openmc.calculate_volumes(cwd = pre_run_path, openmc_exec='/tigress/jdtdl/openmc/py3-mpi-190324/bin/openmc')\n\t\topenmc.calculate_volumes(cwd = pre_run_path, openmc_exec=self.openmc_bin_path)\n\t\t#openmc.run()\n\n\t\t# Read and set initial nuclides dict\n\t\tself.set_init_nucl_dict(root_cell)\n\n\t\t# # Read each material object and add 1atm nuclides chosen by the user\n\t\t# if self.mode == 'no_const_lib':\n\t\t# \tself.add_zero_dens_nuclides(self.nucl_list_dict)\n\n\t\tself._set_initial_summary(pre_run_path)\n\t\tself._set_cross_sections_path(pre_run_path)\n\t\t# Read cross sections xml files, create MC_XS_nucl_list\n\t\tself.set_MC_XS_nucl_list()\n\t\tself.set_root_universe()\n\t\troot_cell_name = 'root cell' # \tneed to be specified by the user at some point\n\t\tself._set_root_cell(root_cell_name)\n\n\t\t# Extract cells from summary, add 1 atm nuclides to their material\n\t\tself._change_cell_materials()\n\n\t\t# Read and distribute volumes to cells\n\t\tself.set_vol_to_cell(vol1, pre_run_path)\n\n\t\t# pdb.set_trace()\n\n\t\tshutil.rmtree(pre_run_path)\n\n\tdef set_vol_to_cell(self, vol1, pre_run_path):\n\n\t\troot_cell = self.root_cell\n\t\tcell_dict = root_cell.get_all_cells()\n\t\tcell_list = utils.cell_dict_to_cell_list(cell_dict)\n\t\tvol2 = vol1.from_hdf5(pre_run_path + '/volume_1.h5')\n\t\tfor cell in cell_list:\n\t\t\tcell.add_volume_information(vol2)\n\n\t\t# Add volume for the root cell too and set it to system\n\t\troot_cell.add_volume_information(vol2)\n\n\t\t# This is now done in pass_vol when user does not define vol manually\n\t\t# system = self.system\n\t\t# system.total_vol = root_cell.volume\n\n\n\n\t# About summary\n\t# There are two type of OpenMC summary stored in openbu: initial_summary and updated_summary\n\t# I have noticed that updating the initial summary was causing some problem in OpenBU, i.e., the material xml file\n\t# would not update the density. The material was updating densities normaly when relying on the initial summary\n\t# A temporary solution for that is to separate the initial summary (that will be used to set dens to cells) and the\n\t# updated summary that will be used to extract densities to get 1g xs for bucells\n\n\t@property\n\tdef initial_summary(self):\n\n\t\treturn self._initial_summary\n\t\n\tdef _set_initial_summary(self, path = os.getcwd()):\n\n\t\tinitial_summary = openmc.Summary(path + '/summary.h5')\n\n\t\t######### OpenMC Summary src does not close the hdf5 file it opens\n\t\t######### When OpenBU tries to shutil.rmtree the pre_run folder, it can't because\n\t\t######### a stream to summary.h5 is still open\n\t\t######### We therefore close it here\n\t\t######### !!!! This should be modified in OpenMC at some points ###########\n\t\tinitial_summary._f.close()\n\t\t######### !!!! This should be modified in OpenMC at some points ###########\n\t\t\n\t\tself._initial_summary = initial_summary\n\n\t@property\n\tdef updated_summary(self):\n\n\t\treturn self._updated_summary\n\t\n\tdef _set_updated_summary(self, path = os.getcwd()):\n\n\t\tupdated_summary = openmc.Summary(path + '/summary.h5')\n\n\t\t######### OpenMC Summary src does not close the hdf5 file it opens\n\t\t######### When OpenBU tries to shutil.rmtree the pre_run folder, it can't because\n\t\t######### a stream to summary.h5 is still open\n\t\t######### We therefore close it here\n\t\t######### !!!! This should be modified in OpenMC at some points ###########\n\t\tupdated_summary._f.close()\n\t\t######### !!!! This should be modified in OpenMC at some points ###########\n\t\t\n\t\tself._updated_summary = updated_summary\n\n\t@property\n\tdef statepoint(self):\n\n\t\treturn self._statepoint\n\n\tdef _set_statepoint(self, path = os.getcwd()):\n\n\t\tfile_list = os.listdir()\n\t\tfor file in file_list:\n\t\t\tif 'statepoint' in file:\n\t\t\t\tst_name = file\n\t\tstatepoint = openmc.StatePoint(path + '/{}'.format(st_name))\n\t\tself._statepoint = statepoint\n\n\tdef _set_kinf(self):\n\n\t\tstatepoint = self.statepoint\n\t\tkinf = statepoint.k_combined\n\n\t\tsystem = self.system\n\t\tsequence = system.sequence\n\t\tsequence._set_macrostep_kinf(kinf)\n\t\n\n\t@property\n\tdef root_cell(self):\n\n\t\treturn self._root_cell\n\t\n\tdef set_root_universe(self):\n\n\t\tsummary = self.initial_summary\n\t\tgeometry = summary.geometry\n\t\troot_universe = geometry.root_universe\n\t\tself._root_universe = root_universe\n\n\tdef _set_root_cell(self, root_cell_name):\n\n\t\tsummary = self.initial_summary\n\t\t# get_cells_by_name returns a list hence the index 0\n\t\tself._root_cell = summary.geometry.get_cells_by_name(root_cell_name)[0]\n\n\t\tadd_periodic_surfaces(self._root_cell, self._periodic_surfaces_dict)\n\n\t\tregion = self._root_cell.region\n\t\t#print (region.get_surfaces())\n\t\tfor surface_id in region.get_surfaces():\n\t\t\tsurface = region.get_surfaces()[surface_id]\n\n\t# While the most convenient way would be to extract path from summary.materials. It looks like\n\t# summary does not store the cross sections path in materials\n\tdef _set_cross_sections_path(self, pre_run_path):\n\n\t\tpath_to_materials_xml = pre_run_path + '/materials.xml'\n\t\ttree = ET.parse(path_to_materials_xml)\n\t\troot = tree.getroot()\n\t\tfor child in root:\n\t\t\tif child.tag == 'cross_sections':\n\t\t\t\tself._cross_sections_path = child.text.replace('/cross_sections.xml', '')\n\n\n\t@property\n\tdef materials(self):\n\n\t\treturn self._materials\n\t\n\tdef _change_cell_materials(self):\n\n\t\tsummary = self.initial_summary\n\t\tmaterials = summary.materials\n\t\tfor bucell_name in self.selected_bucells_name_list:\n\t\t\t# If bucell should only tally initial nuclide, no need to add 1 atm nuclides\n\t\t\tif self.selected_bucells_nucl_list_dict != {}:\n\t\t\t\tif bucell_name in self.selected_bucells_nucl_list_dict:\n\t\t\t\t\tif self.selected_bucells_nucl_list_dict[bucell_name] == 'initial nuclides':\n\t\t\t\t\t\tcontinue\n\t\t\tcell = summary.geometry.get_cells_by_name(bucell_name)[0]\n\t\t\tself.add_zero_dens_nuclides(cell)\n\n\n\t# def _change_cells_materials(self):\n\n\t# \troot_cell = self.root_cell\n\t# \tprint (root_cell)\n\t# \tcell_dict = root_cell.get_all_cells()\n\t# \t# materials with 1atm nuclides\n\t# \tmaterials = self.materials\n\t# \tfor cell_id in cell_dict:\n\t# \t\tcell = cell_dict[cell_id]\n\t# \t\tcell.get_all_materials\n\t# \t\tmaterial_dict = cell.get_all_materials()\n\t# \t\tmaterial = material_dict[list(material_dict.keys())[0]]\n\t# \t\tmat_name = material.name\n\t# \t\tfor new_mat in materials:\n\t# \t\t\tif new_mat.name == mat_name:\n\t# \t\t\t\tprint(new_mat.get_nuclides(), material.get_nuclides())\n\n\n\n\t# Add zero dens nuclide for each material\n\tdef add_zero_dens_nuclides(self, cell):\n\n\t\tmaterial_dict = cell.get_all_materials()\n\t\tmaterial = material_dict[list(material_dict.keys())[0]]\t\n\n\t\tinit_nucl = material.get_nuclides()\n\t\tcell_name = cell.name\n\t\tmat_name = material.name\n\t\t# Not sure if this is necessary\n\t\tif self.selected_bucells_nucl_list_dict != {}:\n\t\t\tif cell_name in self.selected_bucells_nucl_list_dict:\n\t\t\t\tnucl_list_input = self.selected_bucells_nucl_list_dict[cell_name]\n\t\t\t\tif nucl_list_input == 'initial nuclides':\n\t\t\t\t\tnucl_list = init_nucl\n\t\t\t\telif nucl_list_input == 'NAX':\n\t\t\t\t\tNAX_nucl_list_name = utils.zamid_list_to_name_list(data.NAX_nucl_list)\n\t\t\t\t\tNAX_nucl_list_name_new_format = utils.bu_namelist_to_mc_namelist(NAX_nucl_list_name)\n\t\t\t\t\t# I add init_nucl because I believe it is important for init nuclides to be tallied\n\t\t\t\t\t# Their density is usually high enough that their change can influence spectrum etc...\n\t\t\t\t\tnucl_list = [x for x in NAX_nucl_list_name_new_format if x in self.MC_XS_nucl_list] + init_nucl\n\t\t\t\t\t# Here we remove the potential duplicates\n\t\t\t\t\tnucl_list = list(dict.fromkeys(nucl_list))\n\t\t\t\telse:\n\t\t\t\t\t nucl_list = nucl_list_input\n\t\t\telse:\n\t\t\t\tnucl_list = self.MC_XS_nucl_list\n\t\t\t\t#nucl_list = utils.bu_namelist_to_mc_namelist(nucl_list)\n\n\t\telse:\n\t\t\tnucl_list = self.MC_XS_nucl_list\n\n\t\tif not utils.is_lista_in_listb(init_nucl, nucl_list):\n\t\t\traise Initial_nuclides_not_in_nuclide_list('Some initial nuclides in cell {} material {} are not included in nucl_list'.format(cell_name, mat_name))\n\t\tfor nucl in nucl_list:\n\t\t\tif nucl not in init_nucl:\n\t\t\t\tmaterial.add_nuclide(nucl, self.zero_dens_1_atm)\n\n\t\t# Material is rename 'cell name' + 'mat'\n\t\t# New material id is 'mat id' + 'cell id'\n\t\tmaterial.name = '{} mat'.format(cell_name)\n\t\tmaterial.id = int('{}{}'.format(material.id, cell.id))\t\t\n\n\t@property\n\tdef sequence(self):\n\n\t\treturn self._sequence\n\t\n\t@sequence.setter\n\tdef sequence(self, sequence):\n\n\t\tself._sequence = sequence\n\n\tdef set_sequence(self, sequence):\n\n\t\tself.sequence = sequence\n\t\tsystem = self.system\n\t\tsystem.set_sequence(sequence, mode = 'couple')\n\n\t# Add zero dens nuclide for each cell\n\t# Sort of complicated\n\t# Will deal with that later\n\t# def add_zero_dens_nuclides(self, root_cell, nucl_list_dict):\n\n\t# \tcell_dict = root_cell.get_all_cells()\n\n\t# \tfor cell_id in cell_dict:\n\t# \t\tcell = cell_dict[cell_id]\n\t# \t\tmaterial_dict = cell.get_all_materials()\n\t# \t\tmaterial = copy.deepcopy(material_dict[material_dict.key()[0]])\n\t# \t\tinit_nucl = material.get_nuclides()\n\t# \t\tnucl_list = nucl_list_dict[cell_id]\n\t# \t\tnucl_list = utils.bu_namelist_to_mc_namelist(nucl_list)\n\t# \t\tif not is_lista_in_listb(init_nucl, nucl_list):\n\t# \t\t\traise Initial_nuclides_not_in_nuclide_list('Some initial nuclides of material {} are not included in nucl_list'.format(mat_id))\n\t# \t\tfor nucl in nucl_list:\n\t# \t\t\tif nucl not in init_nucl:\n\t# \t\t\t\tmaterial.add_nuclide(nucl, 1E-22)\n\n\t@property\n\tdef init_nucl_dict(self):\n\n\t\treturn self._init_nucl_dict\n\n\t# Create a dict with initial nuclides of each cell before\n\t# cell material is added 1 atm nuclides\n\tdef set_init_nucl_dict(self, root_cell):\n\n\t\tcell_dict = root_cell.get_all_cells()\n\n\t\tinit_nucl_dict = {}\n\t\tfor cell_id in cell_dict:\n\t\t\tcell = cell_dict[cell_id]\n\t\t\tmaterial_dict = cell.get_all_materials()\n\t\t\tmaterial = material_dict[list(material_dict.keys())[0]]\n\t\t\tinit_nucl = material.get_nuclides()\n\t\t\tinit_nucl_dict[cell_id] = init_nucl\n\n\t\tself._init_nucl_dict = init_nucl_dict\n\n\t\t# # If no nucl list has been defined, nucl_list_dict = init_nucl\n\t\t# if self.nucl_list_dict == None:\n\t\t# \tself.nucl_list_dict = self.init_nucl_dict\n\n\t# Use init_nucl_dict and distribute init_nucl to each bucell\n\tdef set_init_nucl(self, cell_dict, bucell_dict):\n\n\t\tinit_nucl_dict = self.init_nucl_dict\n\t\tfor bucell_id in bucell_dict:\n\t\t\tbucell = bucell_dict[bucell_id]\n\t\t\tbucell.init_nucl = init_nucl_dict[bucell_id]\n\n\t@property\n\tdef MC_XS_nucl_list(self):\n\n\t\treturn self._MC_XS_nucl_list\n\n\t@MC_XS_nucl_list.setter\n\tdef MC_XS_nucl_list(self, MC_XS_nucl_list):\n\n\t\tself._MC_XS_nucl_list = MC_XS_nucl_list\n\n\tdef set_MC_XS_nucl_list(self):\n\n\t\t#path_to_xs_xml = os.environ['OPENMC_CROSS_SECTIONS']\n\t\tpath_to_xs_xml = self._cross_sections_path + '/cross_sections.xml'\n\n\t\tself.MC_XS_nucl_list = []\n\n\t\ttree = ET.parse(path_to_xs_xml)\n\t\troot = tree.getroot()\n\n\t\tfor child in root:\n\t\t\tif child.attrib['type'] == 'neutron':\n\t\t\t\tself._MC_XS_nucl_list.append(child.attrib['materials'])\n\n\t\t# Remove trouble makers\tthat appears in JEFF32 cross section\t\n\t\t# For some reason, OpenMC can't find these nuclides in jeff lib at 800K\n\t\t# self._MC_XS_nucl_list.remove('Cu63')\n\t\t# self._MC_XS_nucl_list.remove('Cu65')\n\t\t# self._MC_XS_nucl_list.remove('Mn55')\n\t\t# # THose are not handled by OpenBU\n\t\t# self._MC_XS_nucl_list.remove('C0')\n\t\t# self._MC_XS_nucl_list.remove('V0')\n\t\t# self._MC_XS_nucl_list.remove('Zn0')\n\n\t\t# Remove trouble makers\tthat appears in ENDFVIII cross section\t\n\t\t# For some reason, OpenMC can't find these nuclides in jeff lib at 800K\n\t\t# self._MC_XS_nucl_list.remove('Cu63')\n\t\t# self._MC_XS_nucl_list.remove('Cu65')\n\t\t# self._MC_XS_nucl_list.remove('Mn55')\n\t\t# # THose are not handled by OpenBU\n\t\ttry:\n\t\t\tself._MC_XS_nucl_list.remove('C0')\n\t\texcept ValueError:\n\t\t\tpass\n\t\ttry:\n\t\t\tself._MC_XS_nucl_list.remove('V0')\n\t\texcept ValueError:\n\t\t\tpass\n\t\ttry:\n\t\t\tself._MC_XS_nucl_list.remove('Zn0')\n\t\texcept ValueError:\n\t\t\tpass\n\n\n\n\t# When volume is passed from OpenMC to OpenBU\n\tdef pass_vol(self, cell_dict, bucell_dict):\n\n\t\t# Need to loop over bucell_dict because there might be more cells than bucells\n\t\tfor i in bucell_dict:\n\n\t\t\tcell = cell_dict[i]\n\t\t\tcell_volume = cell.volume\n\t\t\tbucell = bucell_dict[i]\n\t\t\tbucell.vol = cell_volume\n\n\t\t# root_cell is not in bucell_dict but it contains the info on the total volume\n\t\t# Here, the total volume is set to system\n\t\tsystem = self.system\n\t\tsystem.total_vol = self.root_cell.volume\n\n\t# When volume is set directly by user\n\t# Right now this should bet set after import openmc as it overwrites volume calculated by openmc\n\tdef set_vol(self, vol_dict):\n\n\t\tsystem = self.system\n\t\tbucell_dict = system.bucell_dict\n\n\t\t# Need to loop over bucell_dict because there might be more cells than bucells\n\t\tfor i in bucell_dict:\n\t\t\tbucell = bucell_dict[i]\n\t\t\tif bucell.name in vol_dict:\n\t\t\t\tbucell.vol = vol_dict[bucell.name]\n\n\t\t# We treat total volume separately\n\t\tsystem.total_vol = vol_dict['total volume']\n\n\t\tself._volume_set = 'yes'\n\n\n\tdef pass_nuclide_densities(self, cell_dict, bucell_dict):\n\n\t\tfor i in bucell_dict:\n\t\t\tbucell = bucell_dict[i]\n\t\t\tcell = cell_dict[i]\n\t\t\t#init_nucl = self.init_nucl_dict[i]\n\t\t\tinit_nucl = bucell.init_nucl\n\t\t\tmaterials = cell.get_all_materials()\n\t\t\topenmc_dens_dict = materials[list(materials.keys())[0]].get_nuclide_atom_densities()\n\t\t\topenbu_dens_dict = {}\n\n\t\t\tfor nucl in openmc_dens_dict:\n\t\t\t\t#OpenMC xs has cross section for element carbon and Vanadinium (C0, V0) only. OpenBU can't handle that\n\t\t\t\tif nucl == 'C0' or nucl == 'V0':\n\t\t\t\t\tcontinue\n\t\t\t\topenbu_nucl = utils.openmc_name_to_openbu_name(nucl)\n\t\t\t\t# if nucl is one of the initial non-zero initial nuclide, pass the density\n\t\t\t\tif nucl in init_nucl:\n\t\t\t\t\topenbu_dens_dict[openbu_nucl] = openmc_dens_dict[nucl][1]\n\t\t\t\t# if nucl is not one of the non-zero initial nuclide, set densiy to zero\n\t\t\t\telse:\n\t\t\t\t\topenbu_dens_dict[openbu_nucl] = 0.0\n\n\t\t\tbucell = bucell_dict[i]\n\t\t\tbucell.set_initial_dens(openbu_dens_dict)\n\n\tdef get_bucell_from_cell(self):\n\n\t\troot_cell = self.root_cell\n\t\tbucell_dict = {}\n\t\tcell_dict = root_cell.get_all_cells()\n\n\t\tfor i in cell_dict:\n\t\t\tcell = cell_dict[i]\n\t\t\tcell_name = cell.name\n\t\t\tif cell_name in self.selected_bucells_name_list:\t\t\t\n\t\t\t\tbucell_dict[i] = Cell(i, cell_name)\n\n\t\tself.set_init_nucl(cell_dict, bucell_dict)\n\t\tself.pass_vol(cell_dict, bucell_dict)\n\t\tself.pass_nuclide_densities(cell_dict, bucell_dict)\n\n\t\treturn bucell_dict\n\n\n\tdef get_flux_tally(self, bucell):\n\n\t\tflux = openmc.Tally(name='{} flux'.format(bucell.name))\n\t\tflux.filters = [openmc.CellFilter(bucell.id)]\n\t\tflux.filters.append(self.energy_bin)\n\t\tflux.scores = ['flux']\n\n\t\treturn flux\n\n\tdef get_flux_spectrum_tally(self, bucell):\n\n\t\tflux_spectrum = openmc.Tally(name='{} flux spectrum'.format(bucell.name))\n\t\tflux_spectrum.filters = [openmc.CellFilter(bucell.id)]\n\t\tflux_spectrum.filters.append(self.mg_energy_bin)\n\t\tflux_spectrum.scores = ['flux']\n\n\t\treturn flux_spectrum\n\n\t# Every nuclide presents in cell material will have its tally taken\n\tdef get_all_nucl_rxn_tally(self, bucell):\n\n\t\tnucl_list = self.get_nucl_to_be_tallied(bucell)\n\t\tprint ('bucell name',bucell.name)\n\t\tprint ('nucl list when set to tally',nucl_list)\n\t\tnucl_list = utils.bu_namelist_to_mc_namelist(nucl_list)\n\t\trxn = openmc.Tally(name='{} rxn rate'.format(bucell.name))\n\t\trxn.filters = [openmc.CellFilter(bucell.id)]\n\t\trxn.filters.append(self.energy_bin)\n\t\trxn.scores = ['fission', '(n,gamma)', '(n,2n)', '(n,3n)', '(n,p)', '(n,a)']\n\t\t#rxn.scores = ['fission', '(n,gamma)']\n\t\t#rxn.scores = ['fission', '(n,gamma)', '(n,2n)']\n\t\trxn.nuclides = nucl_list\n\t\t\n\t\treturn rxn\n\n\tdef export_material_to_xml(self):\n\n\t\t# Collect materials from each cells and put them into a materials object\n\t\tmaterials = openmc.Materials()\n\t\troot_cell = self.root_cell\n\t\tcell_dict = root_cell.get_all_cells()\n\t\t# When different cells have the same material, the material should not be\n\t\t# counted twice\n\t\tid_list = []\n\t\tfor cell_id in cell_dict:\n\t\t\tcell = cell_dict[cell_id]\n\t\t\tmaterial_dict = cell.get_all_materials()\n\t\t\tmaterial = material_dict[list(material_dict.keys())[0]]\n\t\t\tif material.id not in id_list:\n\t\t\t\tmaterials.append(material)\n\t\t\t\tid_list.append(material.id)\n\n\t\t# If the input materials.xml file is in cwd, remove it\n\t\ttry:\n\t\t\tos.remove(os.getcwd() + '/materials.xml')\n\t\texcept OSError:\n\t\t\tpass\n\n\t\t# Set the cross section path again to materials\n\t\tmaterials.cross_sections = self._cross_sections_path +'/cross_sections.xml'\n\n\t\tmaterials.export_to_xml()\n\n\tdef export_geometry_to_xml(self):\n\n\t\t# Collect each cells and put them into a geometry object\n\t\t# Need to re-instantiate a universe that will be filled with the modified root cell\n\t\troot_universe = self._root_universe\n\t\tgeometry = openmc.Geometry(root_universe)\n\n\t\tregion = self.root_cell.region\n\t\t#print (region.get_surfaces())\n\t\tfor surface_id in region.get_surfaces():\n\t\t\tsurface = region.get_surfaces()[surface_id]\n\t\t#quit()\n\n\t\t# If the input materials.xml file is in cwd, remove it\n\t\ttry:\n\t\t\tos.remove(os.getcwd() + '/geometry.xml')\n\t\texcept OSError:\n\t\t\tpass\n\n\t\tgeometry.export_to_xml()\n\n\n\tdef export_tallies_to_xml(self):\n\n\t\tsystem = self.system\n\n\t\tbucell_dict = system.bucell_dict\n\n\t\ttallies = openmc.Tallies()\n\n\t\tfor bucell_id in bucell_dict:\n\t\t\tbucell = bucell_dict[bucell_id]\n\t\t\tflux = self.get_flux_tally(bucell)\n\t\t\tflux_spectrum = self.get_flux_spectrum_tally(bucell)\n\t\t\trxn = self.get_all_nucl_rxn_tally(bucell)\n\t\t\ttallies.append(flux)\n\t\t\ttallies.append(flux_spectrum)\n\t\t\ttallies.append(rxn)\n\n\t\t# If the input tallies.xml file is in cwd, remove it\n\t\ttry:\n\t\t\tos.remove(os.getcwd() + '/tallies.xml')\n\t\texcept OSError:\n\t\t\tpass\n\n\t\ttallies.export_to_xml()\n\n\t# settings.xml as provided by the user is read\n\t# It is then modified and set to couple\n\t# Since it will not change during the simulation, it is not going\n\t# to be modified again\n\n\t@property\n\tdef settings(self):\n\n\t\treturn self._settings\n\n\tdef _read_user_settings(self):\n\n\t\tsystem = self.system\n\t\tMC_input_path = self.MC_input_path\n\n\t\tfile_path = MC_input_path + '/settings.xml'\n\t\ttree = ET.parse(file_path)\n\t\troot = tree.getroot()\n\t\tsettings = openmc.Settings()\n\n\t\tfor child in root:\n\t\t\tif child.tag == 'particles':\n\t\t\t\tsettings.particles = int(child.text)\n\t\t\t\tself.partices = int(child.text)\n\t\t\tif child.tag == 'batches':\n\t\t\t\tsettings.batches = int(child.text)\n\t\t\t\tself.batches = int(child.text)\n\t\t\tif child.tag == 'inactive':\n\t\t\t\tsettings.inactive = int(child.text)\n\t\t\t\tself.inactive = int(child.text)\n\n\t\tsettings.output = {'tallies': False}\n\t\tsettings.temperature = {'method': 'interpolation'}\n\n\t\tll = self.bounding_box[0]\n\t\tur = self.bounding_box[1]\n\t\t#uniform_dist = openmc.stats.Box(ll, ur, only_fissionable=True)\n\t\tpoint = openmc.stats.Point(xyz=(0.0, 0.0, 0.0))\n\t\tsettings.source = openmc.source.Source(space=point)\n\t\t# To reduce the size of the statepoint file\n\t\tsettings.sourcepoint['write'] = False\n\n\t\tself._settings = settings\n\n\n\t# the setting file created by the user should be stored somewhere\n\tdef export_settings_to_xml(self):\n\n\t\tsettings = self.settings\n\n\t\t# If the input settings.xml file is in cwd, remove it\n\t\ttry:\n\t\t\tos.remove(os.getcwd() + '/settings.xml')\n\t\texcept OSError:\n\t\t\tpass\n\n\t\tsettings.export_to_xml()\n\n\t@property\n\tdef particles(self):\n\n\t\treturn self._particles\n\n\t@particles.setter\n\tdef particles(self, particles):\n\n\t\tself._particles = particles\n\n\t@property\n\tdef batches(self):\n\n\t\treturn self._batches\n\n\t@batches.setter\n\tdef batches(self, batches):\n\n\t\tself._batches = batches\n\n\t@property\n\tdef inactive(self):\n\n\t\treturn self._inactive\n\n\t@inactive.setter\n\tdef inactive(self, inactive):\n\n\t\tself._inactive = inactive\n\n\t@property\n\tdef openmc_bin_path(self):\n\n\t\treturn self._openmc_bin_path\n\n\t@openmc_bin_path.setter\n\tdef openmc_bin_path(self, openmc_bin_path):\n\n\t\tself._openmc_bin_path = openmc_bin_path\n\n\tdef run_openmc(self):\n\n\t\t# New material xml file needs to be written with zero dens nuclides\n\t\tself.export_material_to_xml()\n\t\t# New geometry xml file needs to be written with new materials id\n\t\tself.export_geometry_to_xml()\n\t\t# Tallies xml files needs to be writen\n\t\tself.export_tallies_to_xml()\n\t\t# Settings xml files needs to be written\n\t\tself.export_settings_to_xml()\n\n\t\t#openmc_bin_path = '/tigress/jdtdl/openmc/py3-mpi-190324/bin/openmc'\n\t\t#openpc_bin_path = '/tigress/mkutt/openmc/py3-mpi/bin/openmc'\n\n\t\tif self.MPI == 'on':\n\t\t\topenmc.run(mpi_args=[self._exec, '-n', self._tasks], openmc_exec = self.openmc_bin_path)\n\t\telse:\n\t\t\topenmc.run(openmc_exec = self.openmc_bin_path)\n\n\t\tself._set_statepoint()\n\t\tself._set_updated_summary()\n\t\t# Append the new kinf to system sequence\n\t\tself._set_kinf()\n\n\t# This method set decay_lib_set to yes\n\t# It can be used when the user does not want the system to be set any decay data\n\tdef no_decay(self):\n\n\t\tself._decay_lib_set = 'yes'\n\n\tdef set_decay_lib(self, decay_lib_path):\n\n\t\tsystem = self.system\n\t\tself._decay_lib_set = 'yes'\n\t\tself._decay_lib_path = decay_lib_path\n\t\tsystem.set_decay_for_all(decay_lib_path)\n\n\tdef set_default_decay_lib(self):\n\n\t\tsystem = self.system\n\t\tself._decay_lib_set = 'yes'\n\t\t#system.set_default_decay_for_all_no_add()\n\t\tself._decay_lib_path = 'default'\n\t\tsystem.set_default_decay_for_all()\n\n\tdef set_decay_from_object(self, bucell, object):\n\n\t\tsystem = self.system\n\t\t# This should not set yes since it is only for one bucell\n\t\t# Need to be fixed later\n\t\tself._decay_lib_set = 'yes'\n\t\tbucell = system.get_bucell(bucell)\n\t\tbucell.set_decay(object)\n\n\tdef set_xs_lib(self, xs_lib_path):\n\n\t\tsystem = self.system\n\t\tself._xs_lib_set = 'yes'\n\t\tsystem.set_xs_for_all(xs_lib_path)\n\n\tdef set_default_xs_lib(self):\n\n\t\tsystem = self.system\n\t\tself._xs_lib_set = 'yes'\n\t\t#system.set_default_decay_for_all_no_add()\n\t\tsystem.set_default_xs_for_all()\n\n\tdef set_fy_lib(self, fy_lib_path):\n\n\t\tsystem = self.system\n\t\tself._fy_lib_set = 'yes'\n\t\tself._fy_lib_path = fy_lib_path\n\t\tsystem.set_fy_for_all(fy_lib_path)\n\n\tdef set_default_fy_lib(self):\n\n\t\tsystem = self.system\n\t\tself._fy_lib_set = 'yes'\n\t\tself._fy_lib_path = 'default'\n\t\t#system.set_default_fy_for_all_no_add()\n\t\tsystem.set_default_fy_for_all()\n\n\tdef set_fy_from_object(self, bucell, object):\n\n\t\tsystem = self.system\n\t\t# This should not set yes since it is only for one bucell\n\t\t# Need to be fixed later\n\t\tself._fy_lib_set = 'yes'\n\t\tbucell = system.get_bucell(bucell)\n\t\tbucell.set_fy(object)\n\n\t# This method reads, samples the isomeric branching data and xs data\n\t# using the mg energy bin mid points data and fold them together\n\t# def fold_sampled_isomeric_xs_data(self):\n\n\t# \tsampled_iso_data = self.get_sampled_isomeric_branching_data()\n\t# \tsampled_xs_data = self.get_sampled_ng_cross_section_data()\n\n\t# \tiso_xs_data = {}\n\t# \tfor nucl in sampled_iso_data:\n\t# \t\tiso_data = sampled_iso_data[nucl]\n\t# \t\txs_data = sampled_xs_data[nucl]\n\t# \t\tiso_xs_data[nucl] = {}\n\t# \t\tiso_xs_data[nucl]['0'] = [x*y for x,y in zip(iso_data['0'], xs_data)]\n\t# \t\tiso_xs_data[nucl]['1'] = [x*y for x,y in zip(iso_data['1'], xs_data)]\n\t\t\n\t# \tself._iso_xs_data = iso_xs_data\n\n\tdef set_sampled_isomeric_branching_data(self):\n\n\t\tprint ('\\n\\n\\n***********Sampling isomeric branching data***********\\n\\n\\n')\n\t\tisomeric_branching_data = data.read_isomeric_data()\n\t\tsampled_isomeric_branching_data = {}\n\n\t\tfor nucl in isomeric_branching_data:\n\t\t\tnucl_data = isomeric_branching_data[nucl]\n\n\t\t\t# print (nucl_data['0'])\n\t\t\tsampled_isomeric_branching_data[nucl] = {}\n\t\t\tsampled_isomeric_branching_data[nucl]['0'] = nucl_data['0'](self.mg_energy_mid_points)\n\t\t\tsampled_isomeric_branching_data[nucl]['1'] = nucl_data['1'](self.mg_energy_mid_points)\n\n\t\tself._sampled_isomeric_branching_data = sampled_isomeric_branching_data\n\n\t# This method reads and samples the point-wise cross section for ng of the nuclides that\n\t# have ng isomeric branching data only\n\tdef set_sampled_ng_cross_section_data(self):\n\n\t\tprint ('\\n\\n\\n***********Sampling point-wise cross section data***********\\n\\n\\n')\n\t\tsampled_isomeric_branching_data = self._sampled_isomeric_branching_data\n\t\tsampled_ng_cross_section_data = {}\n\t\tcross_section_path = self._cross_sections_path\n\t\tcross_sections_files_name = os.listdir(cross_section_path)\n\n\t\ttotal_count = 1\n\t\tfile_name_list = []\n\t\tfor file_name in cross_sections_files_name:\n\t\t\tnucl_name = file_name.replace('.h5', '')\n\t\t\tif nucl_name in sampled_isomeric_branching_data:\n\t\t\t\ttotal_count += 1\n\t\t\t\tfile_name_list.append(file_name)\n\n\t\tstart = time.time()\n\t\tcount = 1\n\t\tfor file_name in file_name_list:\n\t\t\tnucl_name = file_name.replace('.h5', '')\n\t\t\tif nucl_name in ['Pm147', 'Am241']: # make it a shorter\n\t\t\t\tnucl_path = cross_section_path+'/{}'.format(file_name)\n\t\t\t\txs_data = openmc.data.IncidentNeutron.from_hdf5(nucl_path)\n\t\t\t\tng_xs_data = xs_data[102].xs['294K']\n\t\t\t\tprint ('--- Sampling {} (n,gamma) point-wise cross section --- [{}/{}]'.format(nucl_name, count, total_count))\n\t\t\t\tsampled_ng_xs_data = ng_xs_data(self.mg_energy_mid_points)\n\t\t\t\tsampled_ng_cross_section_data[nucl_name] = sampled_ng_xs_data\n\t\t\t\tcount += 1\n\t\tend = time.time()\n\t\tprint('\\n Time to sample cross sections: {}'.format(end - start))\n\n\t\tself._sampled_ng_cross_section_data = sampled_ng_cross_section_data\n\n\tdef set_tallies_to_bucells(self, s):\n\n\t\tsystem = self.system\n\t\tbucell_dict = system.bucell_dict\n\t\tsp = self.statepoint\n\t\tsummary = self.updated_summary\n\t\txs_mode = self.xs_mode\n\t\tsampled_isomeric_branching_data = self._sampled_isomeric_branching_data\n\t\tsampled_ng_cross_section_data = self._sampled_ng_cross_section_data\n\n\t\tfor bucell_id in bucell_dict:\n\t\t\tbucell = bucell_dict[bucell_id]\n\n\t\t\t# densities from OpenMC are extracted\n\t\t\t# This is for nuclides which are zero in OpenBU but set to 1E-24 in OpenMC\n\t\t\t# 1E-24 fraction percent does not translate into 1E-24 atm/cm3 always\n\t\t\t# Therefore, the code needs to divide the reaction rate by the correct densities\n\t\t\t# taken from summary.geometry.cell.material\n\t\t\tcell = summary.geometry.get_cells_by_name(bucell.name)[0]\n\t\t\tmaterial_dict = cell.get_all_materials()\n\t\t\tmaterial = material_dict[list(material_dict.keys())[0]]\n\t\t\tmc_nuclides_densities = material.get_nuclide_atom_densities()\n\n\t\t\tflux_tally = sp.get_tally(name = '{} flux'.format(bucell.name))\n\t\t\tflux_spectrum_tally = sp.get_tally(name = '{} flux spectrum'.format(bucell.name))\n\t\t\trxn_rate_tally = sp.get_tally(name = '{} rxn rate'.format(bucell.name))\n\t\t\tbucell._set_MC_tallies(mc_nuclides_densities, flux_tally, flux_spectrum_tally, rxn_rate_tally, sampled_isomeric_branching_data, sampled_ng_cross_section_data, xs_mode, s)\n\n\t\t# YOU NEED TO CREATE LIST TO STORE EACH NEW XS\n\n\t# Normalize the flux in each cell with the FMF after each openmc calculation\n\t# Calculate the power of each cell from the normalized flux\n\tdef step_normalization(self, s):\n\n\t\tsystem = self.system\n\t\tsequence = self.sequence\n\t\tFMF = sequence.get_FMF1(system, s)\n\n\t\tbucell_list = system.get_bucell_list()\n\t\tfor bucell in bucell_list:\n\t\t\tbucell_sequence = bucell.sequence\n\t\t\tMC_flux = bucell_sequence.current_MC_flux\n\t\t\t# MC_flux is volume integrated (unit cm.sp\n\t\t\t# FMF is in sp.s\n\t\t\t# to have flux in cm.s you need to divide by volule of the cell\n\t\t\tflux = FMF*MC_flux/bucell.vol\n\t\t\tpow_dens = bucell._update_pow_dens(flux)\n\t\t\tprint ('initial', pow_dens)\n\t\t\tbucell_sequence._set_macrostep_flux(flux)\n\t\t\tbucell_sequence._set_macrostep_pow_dens(pow_dens)\n\n\t# Normalize the flux in each cell with the FMF after each openmc calculation\n\t# Calculate the power of each cell from the normalized flux\n\tdef initial_couple_step_normalization(self, norma_mode):\n\n\t\tsystem = self.system\n\t\tsequence = self.sequence\n\t\tFMF = sequence.get_FMF1(system, 0)\n\n\t\tbucell_list = system.get_bucell_list()\n\t\tfor bucell in bucell_list:\n\t\t\tbucell_sequence = bucell.sequence\n\t\t\tMC_flux = bucell_sequence.current_MC_flux\n\t\t\tflux = FMF*MC_flux\n\t\t\tpow_dens = bucell._update_pow_dens(flux)\n\t\t\tbucell_sequence._set_initial_flux(flux)\n\t\t\tbucell_sequence._set_initial_pow_dens(pow_dens)\n\n\tdef copy_MC_files(self, s):\n\n\t\tstep_folder = '/step_{}'.format(s)\n\t\topenmc_file_path = os.getcwd()+step_folder+'/OpenMC'\n\n\t\tos.mkdir(openmc_file_path)\n\n\t\tall_MC_files = glob.glob('*.xml') + glob.glob('tallies.out') + glob.glob('*.h5')\n\t\tfor file_name in all_MC_files:\n\t\t\ttry:\n\t\t\t\tshutil.copyfile(os.getcwd()+'/{}'.format(file_name), openmc_file_path + '/{}'.format(file_name))\n\t\t\texcept IOError:\n\t\t\t\tcontinue\n\n\t\tfor file_name in all_MC_files:\n\t\t\tos.remove(os.getcwd() + '/{}'.format(file_name))\n\n\tdef set_dens_to_cells(self):\n\n\t\tsummary = self.initial_summary\n\t\tsystem = self.system\n\t\tbucell_dict = system.bucell_dict\n\t\tfor bucell_id in bucell_dict:\n\t\t\tbucell = bucell_dict[bucell_id]\n\t\t\ttally_nucl_list = utils.mc_namelist_to_bu_namelist(self.get_nucl_to_be_tallied(bucell))\n\t\t\tcell = summary.geometry.get_cells_by_name(bucell.name)[0]\n\t\t\tmaterial_dict = cell.get_all_materials()\n\t\t\tmaterial = material_dict[list(material_dict.keys())[0]]\n\t\t\t### WARNING Openmc add_nuclide in atom percent is not in absolute atom percent\n\t\t\t### but in relative ao, i.e., setting U235 and U238 to 0.34 and 0.34 will be the same\n\t\t\t### as setting them to 50% and 50 %\n\t\t\t### Therefore the ao value that needs to be updated needs to be normalize by the tot dens of\n\t\t\t### only the nuclides to be tallied and not by the total dens of all nuclide in bucell\n\t\t\ttally_nucl_list_dens = bucell.get_subtotal_dens_counting_zero_dens(tally_nucl_list)\n\t\t\tmaterial.set_density('atom/b-cm', tally_nucl_list_dens)\n\t\t\tfor nucl in tally_nucl_list:\n\t\t\t\topenmc_nucl_name = utils.openbu_name_to_openmc_name(nucl)\n\t\t\t\tmaterial.remove_nuclide(openmc_nucl_name) \n\t\t\t\t# No need to calculate ao, just directly give density\n\t\t\t\t#nucl_subao = bucell.get_nucl_subao(nucl, tally_nucl_list)\n\t\t\t\tnucl_dens = bucell.get_nucl_dens_for_openmc(nucl)\n\t\t\t\tmaterial.add_nuclide(openmc_nucl_name, nucl_dens)\n\n\tdef set_MC_XS_nuc_list_to_bucells(self):\n\n\t\tsystem = self.system\n\t\tbucell_dict = system.bucell_dict\n\t\tMC_XS_nucl_list = self.MC_XS_nucl_list\n\t\tMC_XS_nucl_list_obu_name = utils.mc_namelist_to_bu_namelist(MC_XS_nucl_list)\n\t\tMC_XS_nucl_list_zamid = utils.name_list_to_zamid_list(MC_XS_nucl_list_obu_name)\n\t\tfor bucell_id in bucell_dict:\n\t\t\tbucell = bucell_dict[bucell_id]\n\t\t\tbucell.MC_XS_nucl_list = MC_XS_nucl_list_zamid\n\n\n\tdef burn(self):\n\n\t\tstart_time = time.time()\n\n\t\t# If no decay libs and fy libs have been set, set default libs\n\t\tif self._decay_lib_set == 'no':\n\t\t\tself.set_default_decay_lib()\n\t\t\tprint ('\\n\\n\\n---- Default decay constants library set for system ----\\n---- {} ----'.format(data.default_decay_b_lib_path))\n\t\telse:\n\t\t\tprint ('\\n\\n\\n---- User defined path for decay library ----\\n\\n')\n\t\t\tprint ('---- {} ----\\n\\n\\n'.format(self._decay_lib_path))\n\t\t\n\t\tif self._fy_lib_set == 'no':\n\t\t\tself.set_default_fy_lib()\n\t\t\tprint ('\\n\\n\\n---- Default fission yields library set for system ----\\n---- {} ----'.format(data.default_fy_lib_path))\n\t\telse:\n\t\t\tprint ('\\n\\n\\n---- User defined path for fission yields library ----\\n\\n')\n\t\t\tprint ('---- {} ----\\n\\n\\n'.format(self._fy_lib_path))\n\t\t\n\t\t#print (self.xs_mode, self._xs_lib_set)\n\t\tif self.xs_mode == 'constant lib' and self._xs_lib_set == 'no':\n\t\t\tself.set_default_xs_lib()\n\t\t\tprint ('\\n\\n\\n----Default cross section library set for system----\\n\\n\\n')\n\t\telse:\n\t\t\t# This method simply pass the MC_XS_nucl_list to each cell so that each cell\n\t\t\t# can then build it own lib_nucl_list\n\t\t\tself.set_MC_XS_nuc_list_to_bucells()\n\n\t\t\tprint ('\\n\\n\\n---- Path for cross sections library ----\\n\\n')\n\t\t\tprint ('---- {} ----\\n\\n\\n'.format(self._cross_sections_path))\n\n\t\tself.set_sampled_isomeric_branching_data()\n\t\tself.set_sampled_ng_cross_section_data()\n\n\n\n\t\tsystem = self.system\n\t\tsequence = system.sequence\n\t\tnorma_mode = sequence.norma_unit\n\n\t\t# Check consistency of nuclides list &\n\t\t# Generate leaves for each cell\n\t\t# I attempted to update set_all_leaves in order to be able to \n\t\t# sort out nuclides and reduce nuclide set\n\t\t# But it is too complicated and risk to break the code\n\t\tbucell_list = system.get_bucell_list()\n\t\tfor bucell in bucell_list:\n\t\t\t# Check if different nuclide list (initial list, lib list and nucl set (user defined set of nuclides to be considered))\n\t\t\t# are consistent with each other\n\t\t\tbucell._check_nucl_list_consistency()\n\t\t\t# Create a list of all nuclides that should be produced, i.e., that belong to the network tree\n\t\t\t#bucell._reduce_nucl_set()\n\n\n\t\t# This should be somewhere else but for now it is done here\n\t\tsystem.zam_order_passlist()\n\n\t\t#steps_number = sequence.steps_number\n\t\tsteps_number = sequence.macrosteps_number\n\t\t# Shift loop from 1 in order to align loop s and step indexes\n\t\tfor s in range(1, steps_number+1):\n\n\t\t\tprint ('\\n\\n\\n\\n====== STEP {}======\\n\\n\\n\\n'.format(s))\n\t\t\tsequence.gen_step_folder(s)\n\t\t\tprint (('\\n\\n\\n=== OpenMC Transport {}===\\n\\n\\n'.format(s)))\n\t\t\tself.run_openmc()\n\t\t\tself.set_tallies_to_bucells(s)\n\t\t\tself.step_normalization(s)\n\t\t\tself.copy_MC_files(s)\n\t\t\tprint (('\\n\\n\\n=== Salameche Burn {}===\\n\\n\\n'.format(s)))\n\t\t\tsalameche.burn_step(system, s, 'couple')\n\t\t\tself.set_dens_to_cells()\n\t\t\n\t\t# This last openmc_run is used to compute the last burnup/time point kinf\n\t\tprint ('\\n\\n\\n=== OpenMC Transport for Final Point===\\n\\n\\n')\n\t\tself.run_openmc()\n\n\t\tsystem._gen_output_summary_folder()\n\t\tsystem._print_summary_allreacs_rank()\n\t\tsystem._print_summary_subdens()\n\t\tsystem._print_summary_dens()\n\t\tsystem._print_summary_xs()\n\t\tsystem._print_summary_flux_spectrum(self.mg_energy)\n\t\tsystem._print_summary_kinf()\n\t\tsystem._print_summary_param()\n\t\tsystem._print_summary_isomeric_branching_ratio()\n\n\t\trun_time = time.time() - start_time\n\t\tprint ('\\n\\n\\n >>>>>> OpenBU burn took {} seconds <<<<<<< \\n\\n\\n'.format(run_time))\n\nclass Initial_nuclides_not_in_nuclide_list(Exception):\n\t\"\"\"Raise when some initial nuclides are not included in nucl_list \"\"\"\n\tpass\n\nclass STOP(Exception):\n\t\"\"\"Just a way to stop the code\"\"\"\n\tpass", "meta": {"hexsha": "a5393c1b7663dd8eeb41e0e5273180f745e27ba3", "size": 43585, "ext": "py", "lang": "Python", "max_stars_repo_path": "openbu/couple/couple_openmc.py", "max_stars_repo_name": "bam241/ONIX", "max_stars_repo_head_hexsha": "021c9da664eb4b85ede1c0993555341b87011c29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "openbu/couple/couple_openmc.py", "max_issues_repo_name": "bam241/ONIX", "max_issues_repo_head_hexsha": "021c9da664eb4b85ede1c0993555341b87011c29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openbu/couple/couple_openmc.py", "max_forks_repo_name": "bam241/ONIX", "max_forks_repo_head_hexsha": "021c9da664eb4b85ede1c0993555341b87011c29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4693140794, "max_line_length": 173, "alphanum_fraction": 0.736446025, "include": true, "reason": "import numpy", "num_tokens": 12563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.2568319856991699, "lm_q1q2_score": 0.13242768682118075}} {"text": "from . import nn, rl, util, RaggedArray, ContinuousSpace, FiniteSpace, optim, thutil, gmmil\nimport numpy as np\nfrom contextlib import contextmanager\nimport theano; from theano import tensor\n\nfrom scipy.optimize import fmin_l_bfgs_b\n\n\nclass BehavioralCloningOptimizer(object):\n def __init__(self, mdp, policy, lr, batch_size, obsfeat_fn, ex_obs, ex_a, eval_sim_cfg, eval_freq, train_frac):\n self.mdp, self.policy, self.lr, self.batch_size, self.obsfeat_fn = mdp, policy, lr, batch_size, obsfeat_fn\n\n # Randomly split data into train/val\n assert ex_obs.shape[0] == ex_a.shape[0]\n num_examples = ex_obs.shape[0]\n num_train = int(train_frac * num_examples)\n shuffled_inds = np.random.permutation(num_examples)\n train_inds, val_inds = shuffled_inds[:num_train], shuffled_inds[num_train:]\n assert len(train_inds) >= 1 and len(val_inds) >= 1\n print '{} training examples and {} validation examples'.format(len(train_inds), len(val_inds))\n self.train_ex_obsfeat, self.train_ex_a = self.obsfeat_fn(ex_obs[train_inds]), ex_a[train_inds]\n self.val_ex_obsfeat, self.val_ex_a = self.obsfeat_fn(ex_obs[val_inds]), ex_a[val_inds]\n\n self.eval_sim_cfg = eval_sim_cfg\n self.eval_freq = eval_freq\n\n self.total_time = 0.\n self.curr_iter = 0\n\n def step(self):\n with util.Timer() as t_all:\n # Subsample expert transitions for SGD\n inds = np.random.choice(self.train_ex_obsfeat.shape[0], size=self.batch_size)\n batch_obsfeat_B_Do = self.train_ex_obsfeat[inds,:]\n batch_a_B_Da = self.train_ex_a[inds,:]\n # Take step\n loss = self.policy.step_bclone(batch_obsfeat_B_Do, batch_a_B_Da, self.lr)\n\n # Roll out trajectories when it's time to evaluate our policy\n val_loss = val_acc = trueret = avgr = ent = np.nan\n avglen = -1\n if self.eval_freq != 0 and self.curr_iter % self.eval_freq == 0:\n val_loss = self.policy.compute_bclone_loss(self.val_ex_obsfeat, self.val_ex_a)\n # Evaluate validation accuracy (independent of standard deviation)\n if isinstance(self.mdp.action_space, ContinuousSpace):\n val_acc = -np.square(self.policy.compute_actiondist_mean(self.val_ex_obsfeat) - self.val_ex_a).sum(axis=1).mean()\n else:\n assert self.val_ex_a.shape[1] == 1\n # val_acc = (self.policy.sample_actions(self.val_ex_obsfeat)[1].argmax(axis=1) == self.val_ex_a[1]).mean()\n val_acc = -val_loss # val accuracy doesn't seem too meaningful so just use this\n\n\n # Log\n self.total_time += t_all.dt\n fields = [\n ('iter', self.curr_iter, int),\n ('bcloss', loss, float), # supervised learning loss\n ('valloss', val_loss, float), # loss on validation set\n ('valacc', val_acc, float), # loss on validation set\n ('trueret', trueret, float), # true average return for this batch of trajectories\n ('avgr', avgr, float), # average reward encountered\n ('avglen', avglen, int), # average traj length\n ('ent', ent, float), # entropy of action distributions\n ('ttotal', self.total_time, float), # total time\n ]\n self.curr_iter += 1\n return fields\n\n\nclass TransitionClassifier(nn.Model):\n '''Reward/adversary for generative-adversarial training'''\n\n def __init__(self, obsfeat_space, action_space, hidden_spec, max_kl, adam_lr, adam_steps, ent_reg_weight, enable_inputnorm, include_time, time_scale, favor_zero_expert_reward, varscope_name):\n self.obsfeat_space, self.action_space = obsfeat_space, action_space\n self.hidden_spec = hidden_spec\n self.max_kl = max_kl\n self.adam_steps = adam_steps\n self.ent_reg_weight = ent_reg_weight; assert ent_reg_weight >= 0\n self.include_time = include_time\n self.time_scale = time_scale\n self.favor_zero_expert_reward = favor_zero_expert_reward\n\n with nn.variable_scope(varscope_name) as self.__varscope:\n # Map (s,a) pairs to classifier scores (log probabilities of classes)\n obsfeat_B_Df = tensor.matrix(name='obsfeat_B_Df')\n a_B_Da = tensor.matrix(name='a_B_Da', dtype=theano.config.floatX if self.action_space.storage_type == float else 'int64')\n t_B = tensor.vector(name='t_B')\n\n scaled_t_B = self.time_scale * t_B\n\n if isinstance(self.action_space, ContinuousSpace):\n # For a continuous action space, map observation-action pairs to a real number (reward)\n trans_B_Doa = tensor.concatenate([obsfeat_B_Df, a_B_Da], axis=1)\n trans_dim = self.obsfeat_space.dim + self.action_space.dim\n # Normalize\n with nn.variable_scope('inputnorm'):\n self.inputnorm = (nn.Standardizer if enable_inputnorm else nn.NoOpStandardizer)(self.obsfeat_space.dim + self.action_space.dim)\n normedtrans_B_Doa = self.inputnorm.standardize_expr(trans_B_Doa)\n if self.include_time:\n net_input = tensor.concatenate([normedtrans_B_Doa, scaled_t_B[:,None]], axis=1)\n net_input_dim = trans_dim + 1\n else:\n net_input = normedtrans_B_Doa\n net_input_dim = trans_dim\n # Compute scores\n with nn.variable_scope('hidden'):\n net = nn.FeedforwardNet(net_input, (net_input_dim,), self.hidden_spec)\n with nn.variable_scope('out'):\n out_layer = nn.AffineLayer(net.output, net.output_shape, (1,), initializer=np.zeros((net.output_shape[0], 1)))\n scores_B = out_layer.output[:,0]\n\n else:\n # For a finite action space, map observation observations to a vector of rewards\n\n # Normalize observations\n with nn.variable_scope('inputnorm'):\n self.inputnorm = (nn.Standardizer if enable_inputnorm else nn.NoOpStandardizer)(self.obsfeat_space.dim)\n normedobs_B_Df = self.inputnorm.standardize_expr(obsfeat_B_Df)\n if self.include_time:\n net_input = tensor.concatenate([normedobs_B_Df, scaled_t_B[:,None]], axis=1)\n net_input_dim = self.obsfeat_space.dim + 1\n else:\n net_input = normedobs_B_Df\n net_input_dim = self.obsfeat_space.dim\n # Compute scores\n with nn.variable_scope('hidden'):\n net = nn.FeedforwardNet(net_input, (net_input_dim,), self.hidden_spec)\n with nn.variable_scope('out'):\n out_layer = nn.AffineLayer(\n net.output, net.output_shape, (self.action_space.size,),\n initializer=np.zeros((net.output_shape[0], self.action_space.size)))\n scores_B = out_layer.output[tensor.arange(normedobs_B_Df.shape[0]), a_B_Da[:,0]]\n\n\n if self.include_time:\n self._compute_scores = thutil.function([obsfeat_B_Df, a_B_Da, t_B], scores_B) # scores define the conditional distribution p(label | (state,action))\n else:\n compute_scores_without_time = thutil.function([obsfeat_B_Df, a_B_Da], scores_B)\n self._compute_scores = lambda _obsfeat_B_Df, _a_B_Da, _t_B: compute_scores_without_time(_obsfeat_B_Df, _a_B_Da)\n\n if self.favor_zero_expert_reward:\n # 0 for expert-like states, goes to -inf for non-expert-like states\n # compatible with envs with traj cutoffs for good (expert-like) behavior\n # e.g. mountain car, which gets cut off when the car reaches the destination\n rewards_B = thutil.logsigmoid(scores_B)\n else:\n # 0 for non-expert-like states, goes to +inf for expert-like states\n # compatible with envs with traj cutoffs for bad (non-expert-like) behavior\n # e.g. walking simulations that get cut off when the robot falls over\n rewards_B = -tensor.log(1.-tensor.nnet.sigmoid(scores_B))\n if self.include_time:\n self._compute_reward = thutil.function([obsfeat_B_Df, a_B_Da, t_B], rewards_B)\n else:\n compute_reward_without_time = thutil.function([obsfeat_B_Df, a_B_Da], rewards_B)\n self._compute_reward = lambda _obsfeat_B_Df, _a_B_Da, _t_B: compute_reward_without_time(_obsfeat_B_Df, _a_B_Da)\n\n param_vars = self.get_trainable_variables()\n\n # Logistic regression loss, regularized by negative entropy\n labels_B = tensor.vector(name='labels_B')\n weights_B = tensor.vector(name='weights_B')\n losses_B = thutil.sigmoid_cross_entropy_with_logits(scores_B, labels_B)\n ent_B = thutil.logit_bernoulli_entropy(scores_B)\n loss = ((losses_B - self.ent_reg_weight*ent_B)*weights_B).sum(axis=0)\n lossgrad_P = thutil.flatgrad(loss, param_vars)\n\n if self.include_time:\n self._adamstep = thutil.function(\n [obsfeat_B_Df, a_B_Da, t_B, labels_B, weights_B], loss,\n updates=thutil.adam(loss, param_vars, lr=adam_lr))\n else:\n adamstep_without_time = thutil.function(\n [obsfeat_B_Df, a_B_Da, labels_B, weights_B], loss,\n updates=thutil.adam(loss, param_vars, lr=adam_lr))\n self._adamstep = lambda _obsfeat_B_Df, _a_B_Da, _t_B, _labels_B, _weights_B: adamstep_without_time(_obsfeat_B_Df, _a_B_Da, _labels_B, _weights_B)\n\n @property\n def varscope(self): return self.__varscope\n\n def compute_reward(self, obsfeat_B_Df, a_B_Da, t_B):\n return self._compute_reward(obsfeat_B_Df, a_B_Da, t_B)\n\n def fit(self, obsfeat_B_Df, a_B_Da, t_B, exobs_Bex_Do, exa_Bex_Da, ext_Bex):\n # Transitions from the current policy go first, then transitions from the expert\n obsfeat_Ball_Df = np.concatenate([obsfeat_B_Df, exobs_Bex_Do])\n a_Ball_Da = np.concatenate([a_B_Da, exa_Bex_Da])\n t_Ball = np.concatenate([t_B, ext_Bex])\n\n # Update normalization\n self.update_inputnorm(obsfeat_Ball_Df, a_Ball_Da)\n\n B = obsfeat_B_Df.shape[0] # number of examples from the current policy\n Ball = obsfeat_Ball_Df.shape[0] # Ball - b = num examples from expert\n\n # Label expert as 1, current policy as 0\n labels_Ball = np.zeros(Ball)\n labels_Ball[B:] = 1.\n\n # Evenly weight the loss terms for the expert and the current policy\n weights_Ball = np.zeros(Ball)\n weights_Ball[:B] = 1./B\n weights_Ball[B:] = 1./(Ball - B); assert len(weights_Ball[B:]) == Ball-B\n\n # Optimize\n for _ in range(self.adam_steps):\n loss, kl, num_bt_steps = self._adamstep(obsfeat_Ball_Df, a_Ball_Da, t_Ball, labels_Ball, weights_Ball), None, 0\n\n # Evaluate\n scores_Ball = self._compute_scores(obsfeat_Ball_Df, a_Ball_Da, t_Ball); assert scores_Ball.shape == (Ball,)\n accuracy = .5 * (weights_Ball * ((scores_Ball < 0) == (labels_Ball == 0))).sum()\n accuracy_for_currpolicy = (scores_Ball[:B] <= 0).mean()\n accuracy_for_expert = (scores_Ball[B:] > 0).mean()\n assert np.allclose(accuracy, .5*(accuracy_for_currpolicy + accuracy_for_expert))\n\n return [\n ('rloss', loss, float), # reward function fitting loss\n ('racc', accuracy, float), # reward function accuracy\n ('raccpi', accuracy_for_currpolicy, float), # reward function accuracy\n ('raccex', accuracy_for_expert, float), # reward function accuracy\n ('rkl', kl, float),\n ('rbt', num_bt_steps, int),\n # ('rpnorm', util.maxnorm(self.get_params()), float),\n # ('snorm', util.maxnorm(scores_Ball), float),\n ]\n\n def update_inputnorm(self, obs_B_Do, a_B_Da):\n if isinstance(self.action_space, ContinuousSpace):\n self.inputnorm.update(np.concatenate([obs_B_Do, a_B_Da], axis=1))\n else:\n self.inputnorm.update(obs_B_Do)\n\n def plot(self, ax, idx1, idx2, range1, range2, n=100):\n assert len(range1) == len(range2) == 2 and idx1 != idx2\n x, y = np.mgrid[range1[0]:range1[1]:(n+0j), range2[0]:range2[1]:(n+0j)]\n\n if isinstance(self.action_space, ContinuousSpace):\n points_B_Doa = np.zeros((n*n, self.obsfeat_space.storage_size + self.action_space.storage_size))\n points_B_Doa[:,idx1] = x.ravel()\n points_B_Doa[:,idx2] = y.ravel()\n obsfeat_B_Df, a_B_Da = points_B_Doa[:,:self.obsfeat_space.storage_size], points_B_Doa[:,self.obsfeat_space.storage_size:]\n assert a_B_Da.shape[1] == self.action_space.storage_size\n t_B = np.zeros(a_B_Da.shape[0]) # XXX make customizable\n z = self.compute_reward(obsfeat_B_Df, a_B_Da, t_B).reshape(x.shape)\n else:\n obsfeat_B_Df = np.zeros((n*n, self.obsfeat_space.storage_size))\n obsfeat_B_Df[:,idx1] = x.ravel()\n obsfeat_B_Df[:,idx2] = y.ravel()\n a_B_Da = np.zeros((obsfeat_B_Df.shape[0], 1), dtype=np.int32) # XXX make customizable\n t_B = np.zeros(a_B_Da.shape[0]) # XXX make customizable\n z = self.compute_reward(obsfeat_B_Df, a_B_Da, t_B).reshape(x.shape)\n\n ax.pcolormesh(x, y, z, cmap='viridis')\n ax.contour(x, y, z, levels=np.log(np.linspace(2., 3., 10)))\n # ax.contourf(x, y, z, levels=[np.log(2.), np.log(2.)+.5], alpha=.5) # high-reward region is highlighted\n\n\nclass LinearReward(object):\n # things to keep in mind\n # - continuous vs discrete actions\n # - simplex or l2 ball\n # - input norm\n # - shifting so that 0 == expert or 0 == non-expert\n\n def __init__(self,\n obsfeat_space, action_space,\n mode, enable_inputnorm, favor_zero_expert_reward,\n include_time,\n time_scale,\n exobs_Bex_Do, exa_Bex_Da, ext_Bex,\n sqscale=.01,\n quadratic_features=False):\n\n self.obsfeat_space, self.action_space = obsfeat_space, action_space\n assert mode in ['l2ball', 'simplex']\n print 'Linear reward function type: {}'.format(mode)\n self.simplex = mode == 'simplex'\n self.favor_zero_expert_reward = favor_zero_expert_reward\n self.include_time = include_time\n self.time_scale = time_scale\n self.sqscale = sqscale\n self.quadratic_features = quadratic_features\n self.exobs_Bex_Do, self.exa_Bex_Da, self.ext_Bex = exobs_Bex_Do, exa_Bex_Da, ext_Bex\n with nn.variable_scope('inputnorm'):\n # Standardize both observations and actions if actions are continuous\n # otherwise standardize observations only.\n self.inputnorm = (nn.Standardizer if enable_inputnorm else nn.NoOpStandardizer)(\n (obsfeat_space.dim + action_space.dim) if isinstance(action_space, ContinuousSpace)\n else obsfeat_space.dim)\n self.inputnorm_updated = False\n self.update_inputnorm(self.exobs_Bex_Do, self.exa_Bex_Da) # pre-standardize with expert data\n\n # Expert feature expectations\n self.expert_feat_Df = self._compute_featexp(self.exobs_Bex_Do, self.exa_Bex_Da, self.ext_Bex)\n # The current reward function\n feat_dim = self.expert_feat_Df.shape[0]\n print 'Linear reward: {} features'.format(feat_dim)\n if self.simplex:\n # widx is the index of the most discriminative reward function\n self.widx = np.random.randint(feat_dim)\n else:\n # w is a weight vector\n self.w = np.random.randn(feat_dim)\n self.w /= np.linalg.norm(self.w) + 1e-8\n\n self.reward_bound = 0.\n\n def _featurize(self, obsfeat_B_Do, a_B_Da, t_B):\n assert self.inputnorm_updated\n assert obsfeat_B_Do.shape[0] == a_B_Da.shape[0] == t_B.shape[0]\n B = obsfeat_B_Do.shape[0]\n\n # Standardize observations and actions\n if isinstance(self.action_space, ContinuousSpace):\n trans_B_Doa = self.inputnorm.standardize(np.concatenate([obsfeat_B_Do, a_B_Da], axis=1))\n obsfeat_B_Do, a_B_Da = trans_B_Doa[:,:obsfeat_B_Do.shape[1]], trans_B_Doa[:,obsfeat_B_Do.shape[1]:]\n assert obsfeat_B_Do.shape[1] == self.obsfeat_space.dim and a_B_Da.shape[1] == self.action_space.dim\n else:\n assert a_B_Da.shape[1] == 1 and np.allclose(a_B_Da, a_B_Da.astype(int)), 'actions must all be ints'\n obsfeat_B_Do = self.inputnorm.standardize(obsfeat_B_Do)\n\n # Concatenate with other stuff to get final features\n scaledt_B_1 = t_B[:,None]*self.time_scale\n if isinstance(self.action_space, ContinuousSpace):\n if self.quadratic_features:\n feat_cols = [obsfeat_B_Do, a_B_Da]\n if self.include_time:\n feat_cols.extend([scaledt_B_1])\n feat = np.concatenate(feat_cols, axis=1)\n quadfeat = (feat[:,:,None] * feat[:,None,:]).reshape((B,-1))\n feat_B_Df = np.concatenate([feat,quadfeat,np.ones((B,1))], axis=1)\n else:\n feat_cols = [obsfeat_B_Do, a_B_Da, (self.sqscale*obsfeat_B_Do)**2, (self.sqscale*a_B_Da)**2]\n if self.include_time:\n feat_cols.extend([scaledt_B_1, scaledt_B_1**2, scaledt_B_1**3])\n feat_cols.append(np.ones((B,1)))\n feat_B_Df = np.concatenate(feat_cols, axis=1)\n\n else:\n assert not self.quadratic_features\n # Observation-only features\n obsonly_feat_cols = [obsfeat_B_Do, (.01*obsfeat_B_Do)**2]\n if self.include_time:\n obsonly_feat_cols.extend([scaledt_B_1, scaledt_B_1**2, scaledt_B_1**3])\n obsonly_feat_B_f = np.concatenate(obsonly_feat_cols, axis=1)\n\n # To get features that include actions, we'll have blocks of obs-only features,\n # one block for each action.\n assert a_B_Da.shape[1] == 1\n action_inds = [np.flatnonzero(a_B_Da[:,0] == a) for a in xrange(self.action_space.size)]\n assert sum(len(inds) for inds in action_inds) == B\n action_block_size = obsonly_feat_B_f.shape[1]\n # Place obs features into their appropriate blocks\n blocked_feat_B_Dfm1 = np.zeros((obsonly_feat_B_f.shape[0], action_block_size*self.action_space.size))\n for a in range(self.action_space.size):\n blocked_feat_B_Dfm1[action_inds[a],a*action_block_size:(a+1)*action_block_size] = obsonly_feat_B_f[action_inds[a],:]\n assert np.isfinite(blocked_feat_B_Dfm1).all()\n feat_B_Df = np.concatenate([blocked_feat_B_Dfm1, np.ones((B,1))], axis=1)\n\n if self.simplex:\n feat_B_Df = np.concatenate([feat_B_Df, -feat_B_Df], axis=1)\n\n assert feat_B_Df.ndim == 2 and feat_B_Df.shape[0] == B\n return feat_B_Df\n\n\n def _compute_featexp(self, obsfeat_B_Do, a_B_Da, t_B):\n return self._featurize(obsfeat_B_Do, a_B_Da, t_B).mean(axis=0)\n\n\n def fit(self, obsfeat_B_Do, a_B_Da, t_B, _unused_exobs_Bex_Do, _unused_exa_Bex_Da, _unused_ext_Bex):\n # Ignore expert data inputs here, we'll use the one provided in the constructor.\n\n # Current feature expectations\n curr_feat_Df = self._compute_featexp(obsfeat_B_Do, a_B_Da, t_B)\n\n # Compute adversary reward\n if self.simplex:\n v = curr_feat_Df - self.expert_feat_Df\n self.widx = np.argmin(v)\n return [('vmin', v.min(), float)]\n else:\n self.w = self.expert_feat_Df - curr_feat_Df\n l2 = np.linalg.norm(self.w)\n self.w /= l2 + 1e-8\n return [('l2', l2, float)]\n\n\n def compute_reward(self, obsfeat_B_Do, a_B_Da, t_B):\n feat_B_Df = self._featurize(obsfeat_B_Do, a_B_Da, t_B)\n r_B = (feat_B_Df[:,self.widx] if self.simplex else feat_B_Df.dot(self.w)) / float(feat_B_Df.shape[1])\n assert r_B.shape == (obsfeat_B_Do.shape[0],)\n\n if self.favor_zero_expert_reward:\n self.reward_bound = max(self.reward_bound, r_B.max())\n else:\n self.reward_bound = min(self.reward_bound, r_B.min())\n shifted_r_B = r_B - self.reward_bound\n if self.favor_zero_expert_reward:\n assert (shifted_r_B <= 0).all()\n else:\n assert (shifted_r_B >= 0).all()\n\n return shifted_r_B\n\n def update_inputnorm(self, obs_B_Do, a_B_Da):\n if isinstance(self.action_space, ContinuousSpace):\n self.inputnorm.update(np.concatenate([obs_B_Do, a_B_Da], axis=1))\n else:\n self.inputnorm.update(obs_B_Do)\n self.inputnorm_updated = True\n\nimport pickle\n\nclass ImitationOptimizer(object):\n def __init__(self, mdp, discount, lam, policy, sim_cfg, step_func, reward_func, value_func,\n policy_obsfeat_fn, reward_obsfeat_fn, policy_ent_reg, ex_obs, ex_a, ex_t):\n self.mdp, self.discount, self.lam, self.policy = mdp, discount, lam, policy\n self.sim_cfg = sim_cfg\n self.step_func = step_func\n self.reward_func = reward_func\n self.value_func = value_func\n # assert value_func is not None, 'not tested'\n self.policy_obsfeat_fn = policy_obsfeat_fn\n self.reward_obsfeat_fn = reward_obsfeat_fn\n self.policy_ent_reg = policy_ent_reg\n util.header('Policy entropy regularization: {}'.format(self.policy_ent_reg))\n\n assert ex_obs.ndim == ex_a.ndim == 2 and ex_t.ndim == 1 and ex_obs.shape[0] == ex_a.shape[0] == ex_t.shape[0]\n self.ex_pobsfeat, self.ex_robsfeat, self.ex_a, self.ex_t = policy_obsfeat_fn(ex_obs), reward_obsfeat_fn(ex_obs), ex_a, ex_t\n\n self.total_num_trajs = 0\n self.total_num_sa = 0\n self.total_time = 0.\n self.curr_iter = 0\n self.last_sampbatch = None # for outside access for debugging\n\n def step(self):\n with util.Timer() as t_all:\n # Sample trajectories using current policy\n # print 'Sampling'\n with util.Timer() as t_sample:\n sampbatch = self.mdp.sim_mp(\n policy_fn=lambda obsfeat_B_Df: self.policy.sample_actions(obsfeat_B_Df),\n obsfeat_fn=self.policy_obsfeat_fn,\n cfg=self.sim_cfg)\n samp_pobsfeat = sampbatch.obsfeat\n self.last_sampbatch = sampbatch\n # if self.curr_iter % 50 == 0:\n # print('Save batch (s,a) pair information into pickle file sa_info.pk ...')\n # with open('sa_info.pk', 'wb') as saf:\n # pickle.dump(samp_pobsfeat, saf)\n #print len(sampbatch.trajs)\n #print sampbatch.trajs[0].obs_T_Do\n\n # Compute baseline / advantages\n # print 'Computing advantages'\n\n with util.Timer() as t_adv:\n # Compute observation features for reward input\n samp_robsfeat_stacked = self.reward_obsfeat_fn(sampbatch.obs.stacked)\n # Reward is computed wrt current reward function\n # TODO: normalize rewards\n rcurr_stacked = self.reward_func.compute_reward(samp_robsfeat_stacked, sampbatch.a.stacked, sampbatch.time.stacked)\n assert rcurr_stacked.shape == (samp_robsfeat_stacked.shape[0],)\n\n # If we're regularizing the policy, add negative log probabilities to the rewards\n # Intuitively, the policy gets a bonus for being less certain of its actions\n orig_rcurr_stacked = rcurr_stacked.copy()\n if self.policy_ent_reg is not None and self.policy_ent_reg != 0:\n assert self.policy_ent_reg > 0\n # XXX probably faster to compute this from sampbatch.adist instead\n actionlogprobs_B = self.policy.compute_action_logprobs(samp_pobsfeat.stacked, sampbatch.a.stacked)\n policyentbonus_B = -self.policy_ent_reg * actionlogprobs_B\n rcurr_stacked += policyentbonus_B\n else:\n policyentbonus_B = np.zeros_like(rcurr_stacked)\n\n rcurr = RaggedArray(rcurr_stacked, lengths=sampbatch.r.lengths)\n\n # Compute advantages using these rewards\n advantages, qvals, vfunc_r2, simplev_r2 = rl.compute_advantage(\n rcurr, samp_pobsfeat, sampbatch.time, self.value_func, self.discount, self.lam)\n\n # Take a step\n # print 'Fitting policy'\n with util.Timer() as t_step:\n\n params0_P = self.policy.get_params()\n step_print = self.step_func(\n self.policy, params0_P,\n samp_pobsfeat.stacked, sampbatch.a.stacked, sampbatch.adist.stacked,\n advantages.stacked)\n\n self.policy.update_obsnorm(samp_pobsfeat.stacked)\n\n # Fit reward function\n # print 'Fitting reward'\n with util.Timer() as t_r_fit:\n if True:#self.curr_iter % 20 == 0:\n # Subsample expert transitions to the same sample count for the policy\n inds = np.random.choice(self.ex_robsfeat.shape[0], size=samp_pobsfeat.stacked.shape[0])\n exbatch_robsfeat = self.ex_robsfeat[inds,:]\n exbatch_pobsfeat = self.ex_pobsfeat[inds,:] # only used for logging\n exbatch_a = self.ex_a[inds,:]\n exbatch_t = self.ex_t[inds]\n rfit_print = self.reward_func.fit(samp_robsfeat_stacked, sampbatch.a.stacked, sampbatch.time.stacked, exbatch_robsfeat, exbatch_a, exbatch_t)\n else:\n rfit_print = []\n\n # Fit value function for next iteration\n # print 'Fitting value function'\n with util.Timer() as t_vf_fit:\n if self.value_func is not None:\n # Recompute q vals # XXX: this is only necessary if fitting reward after policy\n # qnew = qvals\n\n # TODO: this should be a byproduct of reward fitting\n\n if isinstance(self.reward_func, gmmil.MMDReward):\n rnew = RaggedArray(self.reward_func.current_reward, lengths=sampbatch.r.lengths)\n else:\n rnew = RaggedArray(\n self.reward_func.compute_reward(samp_robsfeat_stacked, sampbatch.a.stacked, sampbatch.time.stacked),\n lengths=sampbatch.r.lengths)\n\n qnew, _ = rl.compute_qvals(rnew, self.discount)\n vfit_print = self.value_func.fit(samp_pobsfeat.stacked, sampbatch.time.stacked, qnew.stacked)\n else:\n vfit_print = []\n\n # Log\n self.total_num_trajs += len(sampbatch)\n self.total_num_sa += sum(len(traj) for traj in sampbatch)\n self.total_time += t_all.dt\n fields = [\n ('iter', self.curr_iter, int),\n ('trueret', sampbatch.r.padded(fill=0.).sum(axis=1).mean(), float), # average return for this batch of trajectories\n ('iret', rcurr.padded(fill=0.).sum(axis=1).mean(), float), # average return on imitation reward\n ('avglen', int(np.mean([len(traj) for traj in sampbatch])), int), # average traj length\n ('ntrajs', self.total_num_trajs, int), # total number of trajs sampled over the course of training\n ('nsa', self.total_num_sa, int), # total number of state-action pairs sampled over the course of training\n ('ent', self.policy._compute_actiondist_entropy(sampbatch.adist.stacked).mean(), float), # entropy of action distributions\n ('vf_r2', vfunc_r2, float),\n ('tdvf_r2', simplev_r2, float),\n ('dx', util.maxnorm(params0_P - self.policy.get_params()), float), # max parameter difference from last iteration\n ] + step_print + vfit_print + rfit_print + [\n ('avgr', rcurr_stacked.mean(), float), # average regularized reward encountered\n ('avgunregr', orig_rcurr_stacked.mean(), float), # average unregularized reward\n ('avgpreg', policyentbonus_B.mean(), float), # average policy regularization\n # ('bcloss', -self.policy.compute_action_logprobs(exbatch_pobsfeat, exbatch_a).mean(), float), # negative log likelihood of expert actions\n # ('bcloss', np.square(self.policy.compute_actiondist_mean(exbatch_pobsfeat) - exbatch_a).sum(axis=1).mean(axis=0), float),\n ('tsamp', t_sample.dt, float), # time for sampling\n ('tadv', t_adv.dt + t_vf_fit.dt, float), # time for advantage computation\n ('tstep', t_step.dt, float), # time for step computation\n ('ttotal', self.total_time, float), # total time\n ]\n self.curr_iter += 1\n return fields\n", "meta": {"hexsha": "31173e545e81e01a9c8195167929ee376560b4f1", "size": 29097, "ext": "py", "lang": "Python", "max_stars_repo_path": "policyopt/imitation.py", "max_stars_repo_name": "KAIST-AILab/gmmil", "max_stars_repo_head_hexsha": "f49d3c9bf6221cb534142b8ddf22d60dd9fa711f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-07-06T07:50:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T08:38:02.000Z", "max_issues_repo_path": "policyopt/imitation.py", "max_issues_repo_name": "KAIST-AILab/gmmil", "max_issues_repo_head_hexsha": "f49d3c9bf6221cb534142b8ddf22d60dd9fa711f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "policyopt/imitation.py", "max_forks_repo_name": "KAIST-AILab/gmmil", "max_forks_repo_head_hexsha": "f49d3c9bf6221cb534142b8ddf22d60dd9fa711f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-07-06T07:50:50.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-11T04:41:37.000Z", "avg_line_length": 52.0518783542, "max_line_length": 195, "alphanum_fraction": 0.6277623123, "include": true, "reason": "import numpy,from scipy,import theano,from theano", "num_tokens": 7169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.24220562872535942, "lm_q1q2_score": 0.1324230578495745}} {"text": "#! /usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\n ********\n Crosslet\n ********\n\n :class:`~nenupy.crosslet.crosslet.Crosslet` is the main class\n for both :class:`~nenupy.crosslet.xstdata.XST_Data` and\n :class:`~nenupy.crosslet.tvdata.TV_Data`, which inherit from\n it.\n\n This enables *beamforming* with the \n :meth:`~nenupy.crosslet.crosslet.Crosslet.beamform` method\n (see also :ref:`tuto_beamforming` for a detailed tutorial)\n and *imaging* with the\n :meth:`~nenupy.crosslet.crosslet.Crosslet.image` method\n (see also :ref:`tuto_tv` for a detailed tutorial) from \n cross-correlation statistics data.\n\"\"\"\n\n\n__author__ = 'Alan Loh'\n__copyright__ = 'Copyright 2020, nenupy'\n__credits__ = ['Alan Loh']\n__maintainer__ = 'Alan'\n__email__ = 'alan.loh@obspm.fr'\n__status__ = 'Production'\n__all__ = [\n 'Crosslet'\n]\n\n\nimport numpy as np\nimport astropy.units as un\ntry:\n from tqdm import tqdm\nexcept ModuleNotFoundError:\n def tqdm(func):\n \"\"\" Overdefine tqdm to return `range` or `enumerate`\n \"\"\"\n return func\n\nfrom nenupy.astro import wavelength, HpxSky, eq_zenith\nfrom nenupy.instru import nenufar_loc, read_cal_table, ma_pos\nfrom nenupy.crosslet import UVW\nfrom nenupy.beamlet.sdata import SData\n\nimport logging\nlog = logging.getLogger(__name__)\n\n\n# ============================================================= #\n# ------------------------- Functions ------------------------- #\n# ============================================================= #\ntry:\n from numba import jit,prange\nexcept ModuleNotFoundError:\n from functools import wraps\n def jit(**kwargs):\n \"\"\" Override numba.jit function by defining a decorator\n which does nothing but returning the decorated\n function.\n \"\"\"\n def inner_function(function):\n @wraps(function)\n def wrapper(*args, **kwargs):\n function(*args, **kwargs)\n return wrapper\n return inner_function\n log.warning(\n 'numba module not found, operations will take longer.'\n )\n\n@jit(nopython=True, parallel=True, fastmath=True)\ndef ft_mul(x, y):\n return x * y\n\n@jit(nopython=True, parallel=True, fastmath=True)\ndef ft_phase(ul, vm):\n return np.exp(\n - 2.j * np.pi * (ul + vm)\n )\n\n@jit(nopython=True, parallel=True, fastmath=True)\ndef ft_sum(vis, exptf):\n return np.mean(\n vis * exptf,\n )\n# ============================================================= #\n\n\n# ============================================================= #\n# ------------------------- Crosslet -------------------------- #\n# ============================================================= #\nclass Crosslet(object):\n \"\"\" :class:`~nenupy.crosslet.crosslet.Crosslet` class is not\n designed to be called directly but rather as a base class\n for both :class:`~nenupy.crosslet.xstdata.XST_Data` and\n :class:`~nenupy.crosslet.tvdata.TV_Data` (see their \n related documentation for further instructions on how\n to load these data sets).\n \"\"\"\n\n def __init__(self):\n self.freqs = None\n self.mas = None\n self.dt = None\n self.times = None\n self.vis = None\n\n\n # --------------------------------------------------------- #\n # --------------------- Getter/Setter --------------------- #\n @property\n def mas(self):\n \"\"\" Mini-Arrays used to get the cross-correlation\n statistics data.\n\n :setter: Mini-Array list\n \n :getter: Mini-Array list\n \n :type: :class:`~numpy.ndarray`\n \"\"\"\n return self._mas\n @mas.setter\n def mas(self, m):\n if m is not None:\n self._mas_idx = np.arange(m.size)\n self._ant1, self._ant2 = np.tril_indices(m.size, 0)\n self._mas = m\n return\n\n\n @property\n def xx(self):\n \"\"\" Extracts the XX polarization from the cross-correlation\n statistics data. Also refered to as ``'NW'``.\n Array is shaped like (time, frequencies, baselines).\n\n :getter: XX polarization\n \n :type: :class:`~numpy.ndarray`\n \"\"\"\n xx = self.vis[:, :, self._get_cross_idx('X', 'X')]\n log.info(\n 'XX loaded.'\n )\n return xx\n\n\n @property\n def yy(self):\n \"\"\" Extracts the YY polarization from the cross-correlation\n statistics data. Also refered to as ``'NE'``.\n Array is shaped like (time, frequencies, baselines).\n\n :getter: YY polarization\n \n :type: :class:`~numpy.ndarray`\n \"\"\"\n yy = self.vis[:, :, self._get_cross_idx('Y', 'Y')]\n log.info(\n 'YY loaded.'\n )\n return yy\n\n\n @property\n def yx(self):\n \"\"\" Extracts the YX polarization from the cross-correlation\n statistics data.\n Array is shaped like (time, frequencies, baselines).\n\n :getter: YX polarization\n \n :type: :class:`~numpy.ndarray`\n \"\"\"\n yx = self.vis[:, :, self._get_cross_idx('Y', 'X')]\n log.info(\n 'YX loaded.'\n )\n return yx\n\n\n @property\n def xy(self):\n \"\"\" Extracts the XY polarization from the cross-correlation\n statistics data. This polarization is not recorded by\n default for the NenuFAR auto-correlations. However\n this can be computed as it is the complex conjugate\n of :attr:`~nenupy.crosslet.crosslet.Crosslet.yx`\n auto-correlations.\n Array is shaped like (time, frequencies, baselines).\n\n :getter: XY polarization\n \n :type: :class:`~numpy.ndarray`\n \"\"\"\n # Deal with lack of auto XY cross in XST-like data\n ma1, ma2 = np.tril_indices(self.mas.size, 0)\n auto = ma1 == ma2\n cross = ~auto\n _xy = np.zeros(\n (list(self.yx.shape[:-1]) + [ma1.size]),\n dtype=np.complex\n )\n _xy[:, :, auto] = self.yx[:, :, auto].conj()\n # Get XY correlations\n indices = self._get_cross_idx('X', 'Y')\n _xy[:, :, cross] = self.vis[:, :, indices]\n log.info(\n 'XY loaded.'\n )\n return _xy\n\n\n @property\n def stokes_i(self):\n r\"\"\" Computes the stokes parameter I from the\n cross-correlation statistics data using\n :attr:`~nenupy.crosslet.crosslet.Crosslet.xx` and \n :attr:`~nenupy.crosslet.crosslet.Crosslet.yy`.\n \n .. math::\n \\mathbf{I}(t, \\nu) = \\frac{1}{2} \\left[\n \\mathbf{XX}(t, \\nu) + \\mathbf{YY}(t, \\nu)\n \\right]\n\n Array is shaped like (time, frequencies, baselines).\n\n :getter: Stokes I data\n \n :type: :class:`~numpy.ndarray`\n \"\"\"\n return 0.5*(self.xx + self.yy)\n\n\n @property\n def mask_auto(self):\n \"\"\" Masks auto-correlations. In particular, this is used \n to compute the image (see \n :meth:`~nenupy.crosslet.crosslet.Crosslet.image`).\n\n :getter: Auto-correlation mask\n \n :type: :class:`~numpy.ndarray`\n \"\"\"\n ma1, ma2 = np.tril_indices(self.mas.size, 0)\n auto = ma1 == ma2\n return ~auto\n \n\n\n # --------------------------------------------------------- #\n # ------------------------ Methods ------------------------ #\n # def plot(self):\n # \"\"\"\n # \"\"\"\n # mat = np.zeros(\n # (self.mas.size, self.mas.size),\n # dtype=np.float\n # )\n # mat[np.tril_indices(self.mas.size, 0)] = np.abs(self.xy[0, 0, :])\n # fig = plt.figure(figsize=(10, 10))\n # plt.imshow(mat, origin='lower')\n # return\n\n\n def beamform(self, az, el, pol='NW', ma=None, calibration='default'):\n r\"\"\" Converts cross correlation statistics data XST, \n :math:`\\mathbf{X}(t, \\nu)`, in beamformed data BST,\n :math:`B(t, \\nu)`, where :math:`t` and :math:`\\nu` are\n the time and the frequency respectively.\n :math:`\\mathbf{X}(t, \\nu)` is a subset of XST data at\n the required polarization ``pol``.\n\n This is done for a given phasing direction in local\n sky coordinates :math:`\\varphi` (azimuth, ``az``) and\n :math:`\\theta` (elevation, ``el``), with a selection\n of Mini-Arrays ``ma`` (numbered :math:`a`).\n\n .. math::\n B (t, \\nu) = \\operatorname{Re} \\left\\{\n \\sum\n \\left[\n \\underset{\\scriptscriptstyle a \\times 1}{\\mathbf{C}}\n \\cdot\n \\underset{\\scriptscriptstyle 1 \\times a}{\\mathbf{C}^{H}}\n \\right](\\nu)\n \\cdot\n \\underset{\\scriptscriptstyle a \\times a}{\\mathbf{X}} (t, \\nu)\n \\cdot\n \\left[\n \\underset{\\scriptscriptstyle a \\times 1}{\\mathbf{P}}\n \\cdot\n \\underset{\\scriptscriptstyle 1 \\times a}{\\mathbf{P}^{H}}\n \\right](\\nu)\n \\right\\}\n\n .. math::\n \\rm{with} \\quad\n \\cases{\n \\mathbf{C}(\\nu ) = e^{2 \\pi i \\nu \\mathbf{ t }} \\quad \\rm{the~calibration~ file}\\\\\n \\mathbf{P} (\\nu) = e^{-2 \\pi i \\frac{\\nu}{c} (\\mathbf{b} \\cdot \\mathbf{u})} \\quad \\rm{phasing}\\\\\n \\underset{\\scriptscriptstyle a \\times 3}{\\mathbf{b}} = \\mathbf{a}_{1} - \\mathbf{a}_{2} \\quad \\rm{baseline~positions}\\\\\n \\underset{\\scriptscriptstyle 3 \\times 1}{\\mathbf{u}} = \\left[\n \\cos(\\theta)\\cos(\\varphi),\n \\cos(\\theta)\\sin(\\varphi),\n \\sin(\\theta) \\right]\n }\n\n :param az:\n Azimuth coordinate used for beamforming (default\n unit is degrees in `float` input).\n :type az: `float` or :class:`~astropy.units.Quantity`\n :param el:\n Elevation coordinate used for beamforming (default\n unit is degrees in `float` input).\n :type el: `float` or :class:`~astropy.units.Quantity`\n :param pol:\n Polarization (either ``'NW'`` or ``'NE'``.\n :type pol: `str`\n :param ma:\n Subset of Mini-Arrays (minimum 2) used for\n beamforming.\n :type ma: `list` or :class:`~numpy.ndarray`\n :param calibration:\n Antenna delay calibration file (i.e, :math:`\\mathbf{C}`).\n If ``'none'``, no calibration is applied.\n If ``'default'``, the standard calibration file is\n used, otherwise the calibration file name should\n be given (see also :func:`~nenupy.instru.instru.read_cal_table`).\n :type calibration: `str`\n\n :returns: Beamformed data.\n :rtype: :class:`~nenupy.beamlet.sdata.SData`\n\n :Example:\n >>> from nenupy.crosslet import XST_Data\n >>> xst = XST_Data('20191129_141900_XST.fits')\n >>> bf = xst.beamform(\n az=180,\n el=90,\n pol='NW',\n ma=[17, 44],\n calibration='default'\n )\n \"\"\"\n log.info(\n 'Beamforming towards az={}, el={}, pol={}'.format(\n az,\n el,\n pol\n )\n )\n # Mini-Array selection\n if ma is None:\n ma = self.mas.copy()\n mas = self._mas_idx[np.isin(self.mas, ma)]\n # Calibration table\n if calibration.lower() == 'none':\n # No calibration\n cal = np.ones(\n (self.sb_idx.size, mas.size)\n )\n else:\n pol_idx = {'NW': [0], 'NE': [1]}\n cal = read_cal_table(\n calfile=calibration\n )\n cal = cal[np.ix_(\n self.sb_idx,\n mas,\n pol_idx[pol]\n )].squeeze()\n # Matrix of BSTs\n c = np.zeros(\n (\n self.times.size,\n self.freqs.size,\n mas.size,\n mas.size\n ),\n dtype=np.complex\n )\n # Matrix of phasings\n p = np.ones(\n (\n self.freqs.size,\n mas.size,\n mas.size\n ),\n dtype=np.complex\n )\n # Pointing direction\n if isinstance(az, un.Quantity):\n az = az.to(un.deg).value\n if isinstance(el, un.Quantity):\n el = el.to(un.deg).value\n az = np.radians(az)\n el = np.radians(el)\n u = np.array([\n np.cos(el) * np.cos(az),\n np.cos(el) * np.sin(az),\n np.sin(el)\n ])\n # Polarization selection\n mask = np.isin(self._ant1, mas) & np.isin(self._ant2, mas)\n log.info(\n 'Loading data...'\n )\n if pol.upper() == 'NW':\n cpol = self.xx[:, :, mask]\n else:\n cpol = self.yy[:, :, mask]\n log.info(\n 'Data of shape {} loaded for beamforming'.format(\n cpol.shape\n )\n )\n # Put the Xcorr in a matrix\n trix, triy = np.tril_indices(mas.size, 0)\n c[:, :, trix, triy] = cpol\n c[:, :, triy, trix] = c[:, :, trix, triy].conj()\n # Calibrate the Xcorr with the caltable\n for fi in prange(c.shape[1]):\n cal_i = np.expand_dims(cal[fi], axis=1)\n cal_i_h = np.expand_dims(cal[fi].T.conj(), axis=0)\n mul = np.dot(cal_i, cal_i_h)\n c[:, fi, :, :] *= mul[np.newaxis, :, :]\n # Phase the Xcorr\n dphi = np.dot(\n ma_pos[self._ant1[mask]] - ma_pos[self._ant2[mask]],\n u\n )\n wavel = wavelength(self.freqs).value\n p[:, trix, triy] = np.exp(\n -2.j*np.pi/wavel[:, None] * dphi\n )\n p[:, triy, trix] = p[:, trix, triy].conj()\n data = np.sum((c * p).real, axis=(2, 3))\n log.info(\n 'Beamforming complete.'\n )\n return SData(\n data=np.expand_dims(data, axis=2),\n time=self.times,\n freq=self.freqs,\n polar=np.array([pol.upper()])\n )\n\n\n def image(self, resolution=1, fov=50):\n r\"\"\" Converts NenuFAR-TV-like data sets containing\n visibilities (:math:`V(u,v,\\nu , t)`) into images\n :math:`I(l, m, \\nu)` phase-centered at the local\n zenith while time averaging the visibilities.\n The Field of View ``fov`` argument defines the\n diameter angular size (zenith-centered) above which\n the image is not computed.\n \n .. math::\n I(l, m, \\nu) = \\int\n \\langle V(u, v, \\nu, t) \\rangle_t e^{\n 2 \\pi i \\frac{\\nu}{c} \\left(\n \\langle u(t) \\rangle_t l + \\langle v(t) \\rangle_t m\n \\right)\n }\n \\, du \\, dv\n\n :param resolution:\n Resoltion (in degrees if a `float` is given) of\n the HEALPix grid (passed to initialize the \n :class:`~nenupy.astro.hpxsky.HpxSky` object).\n :type resolution: `float` or :class:`~astropy.units.Quantity`\n :param fov:\n Field of view diameter of the image (in degrees\n if a `float` is given).\n :type fov: `float` or :class:`~astropy.units.Quantity`\n\n :returns: HEALPix sky object embedding the computed\n image.\n :rtype: :class:`~nenupy.astro.hpxsky.HpxSky`\n\n :Example:\n >>> from nenupy.crosslet import TV_Data\n >>> import astropy.units as u\n >>> tv = TV_Data('20191204_132113_nenufarTV.dat')\n >>> im = tv.image(\n resolution=0.2*u.deg,\n fov=60*u.deg\n )\n\n .. seealso::\n :class:`~nenupy.astro.hpxsky.HpxSky`,\n :meth:`~nenupy.astro.hpxsky.HpxSky.lmn`,\n :meth:`~nenupy.crosslet.uvw.UVW.from_tvdata`\n\n .. warning::\n This method is intended to be used for NenuFAR-TV\n data and relatively small XST datasets. It is not\n suited to long observations for which a MS\n conversion is required before using imaging\n dedicated softwares.\n \"\"\"\n if not isinstance(fov, un.Quantity):\n fov *= un.deg\n f_idx = 0 # Frequency index\n # Sky preparation\n sky = HpxSky(resolution=resolution)\n exposure = self.times[-1] - self.times[0]\n sky.time = self.times[0] + exposure/2.\n sky._is_visible = sky._ho_coords.alt >= 90*un.deg - fov/2.\n phase_center = eq_zenith(sky.time)\n l, m, n = sky.lmn(phase_center=phase_center)\n # UVW coordinates\n uvw = UVW.from_tvdata(self)\n u = np.mean( # Mean in time\n uvw.uvw[:, :, 0],\n axis=0\n )[self.mask_auto]/wavelength(self.freqs[f_idx]).value\n v = np.mean(\n uvw.uvw[:, :, 1],\n axis=0\n )[self.mask_auto]/wavelength(self.freqs[f_idx]).value\n w = np.mean( # Mean in time\n uvw.uvw[:, :, 2],\n axis=0\n )[self.mask_auto]/wavelength(self.freqs[f_idx]).value\n # Mulitply (u, v) by (l, m) and compute FT exp\n ul = ft_mul(\n x=np.tile(u, (l.size, 1)).T,\n y= np.tile(l, (u.size, 1))\n )\n vm = ft_mul(\n x=np.tile(v, (m.size, 1)).T,\n y=np.tile(m, (v.size, 1))\n )\n phase = ft_phase(ul, vm)\n # Phase visibilities\n vis = np.mean( # Mean in time\n self.stokes_i,\n axis=0\n )[f_idx, :][self.mask_auto]\n im = np.zeros(l.size)\n for i in tqdm(prange(l.size)):\n im[i] = np.real(\n ft_sum(vis, phase[:, i])\n )\n sky.skymap[sky._is_visible] = im\n return sky\n\n\n def nearfield(self, resolution):\n \"\"\"\n \"\"\"\n return\n\n\n # --------------------------------------------------------- #\n # ----------------------- Internal ------------------------ #\n def _get_cross_idx(self, c1='X', c2='X'):\n \"\"\"\n \"\"\"\n corr = np.array(['X', 'Y']*self.mas.size)\n i_ant1, i_ant2 = np.tril_indices(self.mas.size*2, 0)\n corr_mask = (corr[i_ant1] == c1) & (corr[i_ant2] == c2)\n indices = np.arange(i_ant1.size)[corr_mask]\n return indices\n# ============================================================= #\n\n", "meta": {"hexsha": "7d989a171e5f7c1b4ac7cd543ae928e3172a4148", "size": 19139, "ext": "py", "lang": "Python", "max_stars_repo_path": "nenupy/crosslet/crosslet.py", "max_stars_repo_name": "lucilecoutouly/nenupy", "max_stars_repo_head_hexsha": "8bfcab9558087f0696080d750293d9b8edc30665", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nenupy/crosslet/crosslet.py", "max_issues_repo_name": "lucilecoutouly/nenupy", "max_issues_repo_head_hexsha": "8bfcab9558087f0696080d750293d9b8edc30665", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nenupy/crosslet/crosslet.py", "max_forks_repo_name": "lucilecoutouly/nenupy", "max_forks_repo_head_hexsha": "8bfcab9558087f0696080d750293d9b8edc30665", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2274305556, "max_line_length": 138, "alphanum_fraction": 0.4762004284, "include": true, "reason": "import numpy,from numba,import astropy", "num_tokens": 4615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.22000709974589316, "lm_q1q2_score": 0.13204570022208387}} {"text": "\"\"\"Contains the classes that deal with constant temperature dynamics.\n\nCopyright (C) 2013, Joshua More and Michele Ceriotti\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see .\n\n\nContains the algorithms which propagate the thermostatting steps in the constant\ntemperature ensembles. Includes the new GLE thermostat, which can be used to\nrun PI+GLE dynamics, reducing the number of path integral beads required.\n\nClasses:\n Thermostat: Base thermostat class with the generic methods and attributes.\n ThermoLangevin: Holds the algorithms for a langevin thermostat.\n ThermoPILE_L: Holds the algorithms for a path-integral langevin equation\n thermostat, with a thermostat coupled directly to the\n centroid coordinate of each bead.\n ThermoPILE_G: Holds the algorithms for a path-integral langevin equation\n thermostat, with a thermostat coupled to the kinetic energy for\n the entire system.\n ThermoSVR: Holds the algorithms for a stochastic velocity rescaling\n thermostat.\n ThermoGLE: Holds the algorithms for a generalised langevin equation\n thermostat.\n ThermoNMGLE: Holds the algorithms for a generalised langevin equation\n thermostat in the normal mode representation.\n ThermoNMGLEG: Holds the algorithms for a generalised langevin equation\n thermostat in the normal mode representation, with kinetic energy as\n well as potential energy sampling optimization.\n\"\"\"\n\n__all__ = ['Thermostat', 'ThermoLangevin', 'ThermoPILE_L', 'ThermoPILE_G',\n 'ThermoSVR', 'ThermoGLE', 'ThermoNMGLE', 'ThermoNMGLEG']\n\nimport numpy as np\nfrom ipi.utils.depend import *\nfrom ipi.utils.units import *\nfrom ipi.utils.mathtools import matrix_exp, stab_cholesky, root_herm\nfrom ipi.utils.prng import Random\nfrom ipi.utils.messages import verbosity, warning, info\nfrom ipi.engine.beads import Beads\nfrom ipi.engine.normalmodes import NormalModes\n\nclass Thermostat(dobject):\n \"\"\"Base thermostat class.\n\n Gives the standard methods and attributes needed in all the thermostat\n classes.\n\n Attributes:\n prng: A pseudo random number generator object.\n ndof: The number of degrees of freedom that the thermostat will be\n attached to.\n\n Depend objects:\n dt: The time step used in the algorithms. Depends on the simulation dt.\n temp: The simulation temperature. Higher than the system temperature by\n a factor of the number of beads. Depends on the simulation temp.\n ethermo: The total energy exchanged with the bath due to the thermostat.\n p: The momentum vector that the thermostat is coupled to. Depends on the\n beads p object.\n m: The mass vector associated with p. Depends on the beads m object.\n sm: The square root of the mass vector.\n \"\"\"\n\n def __init__(self, temp = 1.0, dt = 1.0, ethermo=0.0):\n \"\"\"Initialises Thermostat.\n\n Args:\n temp: The simulation temperature. Defaults to 1.0.\n dt: The simulation time step. Defaults to 1.0.\n ethermo: The initial heat energy transferred to the bath.\n Defaults to 0.0. Will be non-zero if the thermostat is\n initialised from a checkpoint file.\n \"\"\"\n\n dset(self,\"temp\", depend_value(name='temp', value=temp))\n dset(self,\"dt\", depend_value(name='dt', value=dt))\n dset(self,\"ethermo\",depend_value(name='ethermo',value=ethermo))\n\n def bind(self, beads=None, atoms=None, pm=None, prng=None, fixdof=None):\n \"\"\"Binds the appropriate degrees of freedom to the thermostat.\n\n This takes an object with degrees of freedom, and makes their momentum\n and mass vectors members of the thermostat. It also then creates the\n objects that will hold the data needed in the thermostat algorithms\n and the dependency network.\n\n Args:\n beads: An optional beads object to take the mass and momentum vectors\n from.\n atoms: An optional atoms object to take the mass and momentum vectors\n from.\n pm: An optional tuple containing a single momentum value and its\n conjugate mass.\n prng: An optional pseudo random number generator object. Defaults to\n Random().\n fixdof: An optional integer which can specify the number of constraints\n applied to the system. Defaults to zero.\n\n Raises:\n TypeError: Raised if no appropriate degree of freedom or object\n containing a momentum vector is specified for\n the thermostat to couple to.\n \"\"\"\n\n if prng is None:\n warning(\"Initializing thermostat from standard random PRNG\", verbosity.medium)\n self.prng = Random()\n else:\n self.prng = prng\n\n if not beads is None:\n dset(self,\"p\",beads.p.flatten())\n dset(self,\"m\",beads.m3.flatten())\n elif not atoms is None:\n dset(self,\"p\",dget(atoms, \"p\"))\n dset(self,\"m\",dget(atoms, \"m3\"))\n elif not pm is None:\n dset(self,\"p\",pm[0])\n dset(self,\"m\",pm[1])\n else:\n raise TypeError(\"Thermostat.bind expects either Beads, Atoms, NormalModes, or a (p,m) tuple to bind to\")\n\n if fixdof is None:\n self.ndof = len(self.p)\n else:\n self.ndof = float(len(self.p) - fixdof)\n\n dset(self, \"sm\",\n depend_array(name=\"sm\", value=np.zeros(len(dget(self,\"m\"))),\n func=self.get_sm, dependencies=[dget(self,\"m\")]))\n\n def get_sm(self):\n \"\"\"Retrieves the square root of the mass matrix.\n\n Returns:\n A vector of the square root of the mass matrix with one value for\n each degree of freedom.\n \"\"\"\n\n return np.sqrt(self.m)\n\n def step(self):\n \"\"\"Dummy thermostat step.\"\"\"\n\n pass\n\n\nclass ThermoLangevin(Thermostat):\n \"\"\"Represents a langevin thermostat.\n\n Depend objects:\n tau: Thermostat damping time scale. Larger values give a less strongly\n coupled thermostat.\n T: Coefficient of the diffusive contribution of the thermostat, i.e. the\n drift back towards equilibrium. Depends on tau and the time step.\n S: Coefficient of the stochastic contribution of the thermostat, i.e.\n the uncorrelated Gaussian noise. Depends on T and the temperature.\n \"\"\"\n\n def get_T(self):\n \"\"\"Calculates the coefficient of the overall drift of the velocities.\"\"\"\n\n return np.exp(-0.5*self.dt/self.tau)\n\n def get_S(self):\n \"\"\"Calculates the coefficient of the white noise.\"\"\"\n\n return np.sqrt(Constants.kb*self.temp*(1 - self.T**2))\n\n def __init__(self, temp = 1.0, dt = 1.0, tau = 1.0, ethermo=0.0):\n \"\"\"Initialises ThermoLangevin.\n\n Args:\n temp: The simulation temperature. Defaults to 1.0.\n dt: The simulation time step. Defaults to 1.0.\n tau: The thermostat damping timescale. Defaults to 1.0.\n ethermo: The initial heat energy transferred to the bath.\n Defaults to 0.0. Will be non-zero if the thermostat is\n initialised from a checkpoint file.\n \"\"\"\n\n super(ThermoLangevin,self).__init__(temp, dt, ethermo)\n\n dset(self,\"tau\",depend_value(value=tau,name='tau'))\n dset(self,\"T\",\n depend_value(name=\"T\",func=self.get_T,\n dependencies=[dget(self,\"tau\"), dget(self,\"dt\")]))\n dset(self,\"S\",\n depend_value(name=\"S\",func=self.get_S,\n dependencies=[dget(self,\"temp\"), dget(self,\"T\")]))\n\n def step(self):\n \"\"\"Updates the bound momentum vector with a langevin thermostat.\"\"\"\n\n p = depstrip(self.p).copy()\n sm = depstrip(self.sm)\n\n p /= sm\n\n self.ethermo += np.dot(p,p)*0.5\n p *= self.T\n p += self.S*self.prng.gvec(len(p))\n self.ethermo -= np.dot(p,p)*0.5\n\n p *= sm\n\n self.p = p\n\n\nclass ThermoPILE_L(Thermostat):\n \"\"\"Represents a PILE thermostat with a local centroid thermostat.\n\n Attributes:\n _thermos: The list of the different thermostats for all the ring polymer\n normal modes.\n nm: A normal modes object to attach the thermostat to.\n prng: Random number generator used in the stochastic integration\n algorithms.\n\n Depend objects:\n tau: Centroid thermostat damping time scale. Larger values give a\n less strongly coupled centroid thermostat.\n tauk: Thermostat damping time scale for the non-centroid normal modes.\n Depends on the ring polymer spring constant, and thus the simulation\n temperature.\n pilescale: A float used to reduce the intensity of the PILE thermostat if\n required.\n \"\"\"\n\n def __init__(self, temp = 1.0, dt = 1.0, tau = 1.0, ethermo=0.0, scale=1.0):\n \"\"\"Initialises ThermoPILE_L.\n\n Args:\n temp: The simulation temperature. Defaults to 1.0.\n dt: The simulation time step. Defaults to 1.0.\n tau: The centroid thermostat damping timescale. Defaults to 1.0.\n ethermo: The initial conserved energy quantity. Defaults to 0.0. Will\n be non-zero if the thermostat is initialised from a checkpoint file.\n scale: A float used to reduce the intensity of the PILE thermostat if\n required.\n\n Raises:\n TypeError: Raised if the thermostat is used with any object other than\n a beads object, so that we make sure that the objects needed for the\n normal mode transformation exist.\n \"\"\"\n\n super(ThermoPILE_L,self).__init__(temp,dt,ethermo)\n dset(self,\"tau\",depend_value(value=tau,name='tau'))\n dset(self,\"pilescale\",depend_value(value=scale,name='pilescale'))\n\n def bind(self, nm=None, prng=None, bindcentroid=True, fixdof=None):\n \"\"\"Binds the appropriate degrees of freedom to the thermostat.\n\n This takes a beads object with degrees of freedom, and makes its momentum\n and mass vectors members of the thermostat. It also then creates the\n objects that will hold the data needed in the thermostat algorithms\n and the dependency network.\n\n Gives the interface for both the PILE_L and PILE_G thermostats, which\n only differ in their treatment of the centroid coordinate momenta.\n\n Args:\n nm: An optional normal mode object to take the mass and momentum\n vectors from.\n prng: An optional pseudo random number generator object. Defaults to\n Random().\n bindcentroid: An optional boolean which decides whether a Langevin\n thermostat is attached to the centroid mode of each atom\n separately, or the total kinetic energy. Defaults to True, which\n gives a thermostat bound to each centroid momentum.\n fixdof: An optional integer which can specify the number of constraints\n applied to the system. Defaults to zero.\n\n Raises:\n TypeError: Raised if no appropriate degree of freedom or object\n containing a momentum vector is specified for\n the thermostat to couple to.\n \"\"\"\n\n if nm is None or not type(nm) is NormalModes:\n raise TypeError(\"ThermoPILE_L.bind expects a NormalModes argument to bind to\")\n if prng is None:\n self.prng = Random()\n else:\n self.prng = prng\n\n prev_ethermo = self.ethermo\n\n # creates a set of thermostats to be applied to individual normal modes\n self._thermos = [ ThermoLangevin(temp=1, dt=1, tau=1) for b in range(nm.nbeads) ]\n # optionally does not bind the centroid, so we can re-use all of this\n # in the PILE_G case\n if not bindcentroid:\n self._thermos[0] = None\n\n self.nm = nm\n\n dset(self,\"tauk\",\n depend_array(name=\"tauk\", value=np.zeros(nm.nbeads-1,float),\n func=self.get_tauk, dependencies=[dget(self,\"pilescale\"), dget(nm,\"dynomegak\")] ) )\n\n # must pipe all the dependencies in such a way that values for the nm thermostats\n # are automatically updated based on the \"master\" thermostat\n def make_taugetter(k):\n return lambda: self.tauk[k-1]\n it = 0\n for t in self._thermos:\n if t is None:\n it += 1\n continue\n if it > 0:\n fixdof = None # only the centroid thermostat may have constraints\n\n # bind thermostat t to the it-th bead\n t.bind(pm=(nm.pnm[it,:],nm.dynm3[it,:]),prng=self.prng, fixdof=fixdof)\n # pipes temp and dt\n deppipe(self,\"temp\", t, \"temp\")\n deppipe(self,\"dt\", t, \"dt\")\n\n # for tau it is slightly more complex\n if it == 0:\n deppipe(self,\"tau\", t, \"tau\")\n else:\n # Here we manually connect _thermos[i].tau to tauk[i].\n # Simple and clear.\n dget(t,\"tau\").add_dependency(dget(self,\"tauk\"))\n dget(t,\"tau\")._func = make_taugetter(it)\n dget(self,\"ethermo\").add_dependency(dget(t,\"ethermo\"))\n it += 1\n\n # since the ethermo will be \"delegated\" to the normal modes thermostats,\n # one has to split\n # any previously-stored value between the sub-thermostats\n if bindcentroid:\n for t in self._thermos:\n t.ethermo = prev_ethermo/nm.nbeads\n dget(self,\"ethermo\")._func = self.get_ethermo;\n # if we are not binding the centroid just yet, this bit of the piping\n # is delegated to the function which is actually calling this\n\n def get_tauk(self):\n \"\"\"Computes the thermostat damping time scale for the non-centroid\n normal modes.\n\n Returns:\n An array with the damping time scales for the non-centroid modes.\n \"\"\"\n\n # Also include an optional scaling factor to reduce the intensity of NM thermostats\n return np.array([ self.pilescale/(2*self.nm.dynomegak[k]) for k in range(1,len(self._thermos)) ])\n\n def get_ethermo(self):\n \"\"\"Computes the total energy transferred to the heat bath for all the\n thermostats.\n \"\"\"\n\n et = 0.0;\n for t in self._thermos:\n et += t.ethermo\n return et\n\n def step(self):\n \"\"\"Updates the bound momentum vector with a PILE thermostat.\"\"\"\n\n # super-cool! just loop over the thermostats! it's as easy as that!\n for t in self._thermos:\n t.step()\n\n\nclass ThermoSVR(Thermostat):\n \"\"\"Represents a stochastic velocity rescaling thermostat.\n\n Depend objects:\n tau: Centroid thermostat damping time scale. Larger values give a\n less strongly coupled centroid thermostat.\n K: Scaling factor for the total kinetic energy. Depends on the\n temperature.\n et: Parameter determining the strength of the thermostat coupling.\n Depends on tau and the time step.\n \"\"\"\n\n def get_et(self):\n \"\"\"Calculates the damping term in the propagator.\"\"\"\n\n return np.exp(-0.5*self.dt/self.tau)\n\n def get_K(self):\n \"\"\"Calculates the average kinetic energy per degree of freedom.\"\"\"\n\n return Constants.kb*self.temp*0.5\n\n def __init__(self, temp = 1.0, dt = 1.0, tau = 1.0, ethermo=0.0):\n \"\"\"Initialises ThermoSVR.\n\n Args:\n temp: The simulation temperature. Defaults to 1.0.\n dt: The simulation time step. Defaults to 1.0.\n tau: The thermostat damping timescale. Defaults to 1.0.\n ethermo: The initial conserved energy quantity. Defaults to 0.0. Will\n be non-zero if the thermostat is initialised from a checkpoint file.\n \"\"\"\n\n super(ThermoSVR,self).__init__(temp,dt,ethermo)\n\n dset(self,\"tau\",depend_value(value=tau,name='tau'))\n dset(self,\"et\",\n depend_value(name=\"et\",func=self.get_et,\n dependencies=[dget(self,\"tau\"), dget(self,\"dt\")]))\n dset(self,\"K\",\n depend_value(name=\"K\",func=self.get_K, dependencies=[dget(self,\"temp\")]))\n\n def step(self):\n \"\"\"Updates the bound momentum vector with a stochastic velocity rescaling\n thermostat. See G Bussi, D Donadio, M Parrinello,\n Journal of Chemical Physics 126, 014101 (2007)\n \"\"\"\n\n K = np.dot(depstrip(self.p),depstrip(self.p)/depstrip(self.m))*0.5\n\n # rescaling is un-defined if the KE is zero\n if K == 0.0:\n return\n\n # gets the stochastic term (basically a Gamma distribution for the kinetic energy)\n r1 = self.prng.g\n if (self.ndof-1)%2 == 0:\n rg = 2.0*self.prng.gamma((self.ndof-1)/2)\n else:\n rg = 2.0*self.prng.gamma((self.ndof-2)/2) + self.prng.g**2\n\n alpha2 = self.et + self.K/K*(1 - self.et)*(r1**2 + rg) + 2.0*r1*np.sqrt(self.K/K*self.et*(1 - self.et))\n alpha = np.sqrt(alpha2)\n if (r1 + np.sqrt(2*K/self.K*self.et/(1 - self.et))) < 0:\n alpha *= -1\n\n self.ethermo += K*(1 - alpha2)\n self.p *= alpha\n\n\nclass ThermoPILE_G(ThermoPILE_L):\n \"\"\"Represents a PILE thermostat with a global centroid thermostat.\n\n Simply replaces the Langevin thermostat for the centroid normal mode with\n a global velocity rescaling thermostat.\n \"\"\"\n\n def __init__(self, temp = 1.0, dt = 1.0, tau = 1.0, ethermo=0.0, scale = 1.0):\n \"\"\"Initialises ThermoPILE_G.\n\n Args:\n temp: The simulation temperature. Defaults to 1.0.\n dt: The simulation time step. Defaults to 1.0.\n tau: The centroid thermostat damping timescale. Defaults to 1.0.\n ethermo: The initial conserved energy quantity. Defaults to 0.0. Will\n be non-zero if the thermostat is initialised from a checkpoint file.\n scale: A float used to reduce the intensity of the PILE thermostat if\n required.\n \"\"\"\n\n super(ThermoPILE_G,self).__init__(temp,dt,tau,ethermo)\n dset(self,\"pilescale\",depend_value(value=scale,name='pilescale'))\n\n def bind(self, nm=None, prng=None, fixdof=None):\n \"\"\"Binds the appropriate degrees of freedom to the thermostat.\n\n This takes a beads object with degrees of freedom, and makes its momentum\n and mass vectors members of the thermostat. It also then creates the\n objects that will hold the data needed in the thermostat algorithms\n and the dependency network.\n\n Uses the PILE_L bind interface, with bindcentroid set to false so we can\n specify that thermostat separately, by binding a global\n thermostat to the centroid mode.\n\n Args:\n beads: An optional beads object to take the mass and momentum vectors\n from.\n prng: An optional pseudo random number generator object. Defaults to\n Random().\n fixdof: An optional integer which can specify the number of constraints\n applied to the system. Defaults to zero.\n\n \"\"\"\n\n # first binds as a local PILE, then substitutes the thermostat on the centroid\n prev_ethermo = self.ethermo\n super(ThermoPILE_G,self).bind(nm=nm,prng=prng,bindcentroid=False, fixdof=fixdof)\n\n #centroid thermostat\n self._thermos[0] = ThermoSVR(temp=1, dt=1, tau=1)\n\n t = self._thermos[0]\n t.bind(pm=(nm.pnm[0,:],nm.dynm3[0,:]),prng=self.prng, fixdof=fixdof)\n deppipe(self,\"temp\", t, \"temp\")\n deppipe(self,\"dt\", t, \"dt\")\n deppipe(self,\"tau\", t, \"tau\")\n dget(self,\"ethermo\").add_dependency(dget(t,\"ethermo\"))\n\n # splits any previous ethermo between the thermostats, and finishes to bind ethermo to the sum function\n for t in self._thermos:\n t.ethermo = prev_ethermo/nm.nbeads\n dget(self,\"ethermo\")._func = self.get_ethermo;\n\n\nclass ThermoGLE(Thermostat):\n \"\"\"Represents a GLE thermostat.\n\n This is similar to a langevin thermostat, in that it uses Gaussian random\n numbers to simulate a heat bath acting on the system, but simulates a\n non-Markovian system by using a Markovian formulation in an extended phase\n space. This allows for a much greater degree of flexibility, and this\n thermostat, properly fitted, can give the an approximation to the correct\n quantum ensemble even for a classical, 1-bead simulation. More reasonably,\n using this thermostat allows for a far smaller number of replicas of the\n system to be used, as the convergence of the properties\n of the system is accelerated with respect to number of beads when PI+GLE\n are used in combination. (See M. Ceriotti, D. E. Manolopoulos, M. Parinello,\n J. Chem. Phys. 134, 084104 (2011)).\n\n Attributes:\n ns: The number of auxilliary degrees of freedom.\n s: An array holding all the momenta, including the ones for the\n auxilliary degrees of freedom.\n\n Depend objects:\n A: Drift matrix giving the damping time scales for all the different\n degrees of freedom.\n C: Static covariance matrix.\n Satisfies A.C + C.transpose(A) = B.transpose(B), where B is the\n diffusion matrix, giving the strength of the coupling of the system\n with the heat bath, and thus the size of the stochastic\n contribution of the thermostat.\n T: Matrix for the diffusive contribution of the thermostat, i.e. the\n drift back towards equilibrium. Depends on A and the time step.\n S: Matrix for the stochastic contribution of the thermostat, i.e.\n the uncorrelated Gaussian noise. Depends on C and T.\n \"\"\"\n\n def get_T(self):\n \"\"\"Calculates the matrix for the overall drift of the velocities.\"\"\"\n\n return matrix_exp(-0.5*self.dt*self.A)\n\n def get_S(self):\n \"\"\"Calculates the matrix for the coloured noise.\"\"\"\n\n SST = Constants.kb*(self.C - np.dot(self.T,np.dot(self.C,self.T.T)))\n\n # Uses a symetric decomposition rather than Cholesky, since it is more stable\n return root_herm(SST)\n\n def get_C(self):\n \"\"\"Calculates C from temp (if C is not set explicitly)\"\"\"\n\n rC = np.identity(self.ns + 1,float)*self.temp\n return rC[:]\n\n def __init__(self, temp = 1.0, dt = 1.0, A = None, C = None, ethermo=0.0):\n \"\"\"Initialises ThermoGLE.\n\n Args:\n temp: The simulation temperature. Defaults to 1.0.\n dt: The simulation time step. Defaults to 1.0.\n A: An optional matrix giving the drift matrix. Defaults to a single\n value of 1.0.\n C: An optional matrix giving the covariance matrix. Defaults to an\n identity matrix times temperature with the same dimensions as the\n total number of degrees of freedom in the system.\n ethermo: The initial heat energy transferred to the bath.\n Defaults to 0.0. Will be non-zero if the thermostat is\n initialised from a checkpoint file.\n \"\"\"\n\n super(ThermoGLE,self).__init__(temp,dt,ethermo)\n\n if A is None:\n A = np.identity(1,float)\n dset(self,\"A\",depend_value(value=A.copy(),name='A'))\n\n self.ns = len(self.A) - 1;\n\n # now, this is tricky. if C is taken from temp, then we want it to be updated\n # as a depend of temp. Otherwise, we want it to be an independent beast.\n if C is None:\n C = np.identity(self.ns+1,float)*self.temp\n dset(self,\"C\",\n depend_value(name='C', func=self.get_C,\n dependencies=[dget(self,\"temp\")]))\n else:\n dset(self,\"C\",depend_value(value=C.copy(),name='C'))\n\n dset(self,\"T\",\n depend_value(name=\"T\",func=self.get_T,\n dependencies=[dget(self,\"A\"), dget(self,\"dt\")]))\n dset(self,\"S\",\n depend_value(name=\"S\",func=self.get_S,\n dependencies=[dget(self,\"C\"), dget(self,\"T\")]))\n\n self.s = np.zeros(0)\n\n def bind(self, beads=None, atoms=None, pm=None, prng=None, fixdof=None):\n \"\"\"Binds the appropriate degrees of freedom to the thermostat.\n\n This takes an object with degrees of freedom, and makes their momentum\n and mass vectors members of the thermostat. It also then creates the\n objects that will hold the data needed in the thermostat algorithms\n and the dependency network.\n\n Args:\n beads: An optional beads object to take the mass and momentum vectors\n from.\n atoms: An optional atoms object to take the mass and momentum vectors\n from.\n pm: An optional tuple containing a single momentum value and its\n conjugate mass.\n prng: An optional pseudo random number generator object. Defaults to\n Random().\n fixdof: An optional integer which can specify the number of constraints\n applied to the system. Defaults to zero.\n\n Raises:\n TypeError: Raised if no appropriate degree of freedom or object\n containing a momentum vector is specified for\n the thermostat to couple to.\n \"\"\"\n\n super(ThermoGLE,self).bind(beads,atoms,pm,prng,fixdof)\n\n # allocates, initializes or restarts an array of s's\n if self.s.shape != (self.ns + 1, len(dget(self,\"m\"))):\n if len(self.s) > 0:\n warning(\"Mismatch in GLE s array size on restart, will reinitialise to free particle.\", verbosity.low)\n self.s = np.zeros((self.ns + 1, len(dget(self,\"m\"))))\n\n # Initializes the s vector in the free-particle limit\n info(\" GLE additional DOFs initialised to the free-particle limit.\", verbosity.low)\n SC = stab_cholesky(self.C*Constants.kb)\n self.s[:] = np.dot(SC, self.prng.gvec(self.s.shape))\n else:\n info(\"GLE additional DOFs initialised from input.\", verbosity.medium)\n\n def step(self):\n \"\"\"Updates the bound momentum vector with a GLE thermostat\"\"\"\n\n p = depstrip(self.p).copy()\n\n self.s[0,:] = self.p/self.sm\n\n self.ethermo += np.dot(self.s[0],self.s[0])*0.5\n self.s[:] = np.dot(self.T,self.s) + np.dot(self.S,self.prng.gvec(self.s.shape))\n self.ethermo -= np.dot(self.s[0],self.s[0])*0.5\n\n self.p = self.s[0]*self.sm\n\n\nclass ThermoNMGLE(Thermostat):\n \"\"\"Represents a 'normal-modes' GLE thermostat.\n\n An extension to the GLE thermostat which is applied in the\n normal modes representation, and which allows to use a different\n GLE for each normal mode\n\n Attributes:\n ns: The number of auxilliary degrees of freedom.\n nb: The number of beads.\n s: An array holding all the momenta, including the ones for the\n auxilliary degrees of freedom.\n\n Depend objects:\n A: Drift matrix giving the damping time scales for all the different\n degrees of freedom (must contain nb terms).\n C: Static covariance matrix.\n Satisfies A.C + C.transpose(A) = B.transpose(B), where B is the\n diffusion matrix, giving the strength of the coupling of the system\n with the heat bath, and thus the size of the stochastic\n contribution of the thermostat.\n \"\"\"\n\n def get_C(self):\n \"\"\"Calculates C from temp (if C is not set explicitly).\"\"\"\n\n rv = np.ndarray((self.nb, self.ns+1, self.ns+1), float)\n for b in range(0,self.nb):\n rv[b] = np.identity(self.ns + 1,float)*self.temp\n return rv[:]\n\n def __init__(self, temp = 1.0, dt = 1.0, A = None, C = None, ethermo=0.0):\n \"\"\"Initialises ThermoGLE.\n\n Args:\n temp: The simulation temperature. Defaults to 1.0.\n dt: The simulation time step. Defaults to 1.0.\n A: An optional matrix giving the drift matrix. Defaults to a single\n value of 1.0.\n C: An optional matrix giving the covariance matrix. Defaults to an\n identity matrix times temperature with the same dimensions as the\n total number of degrees of freedom in the system.\n ethermo: The initial heat energy transferred to the bath.\n Defaults to 0.0. Will be non-zero if the thermostat is\n initialised from a checkpoint file.\n \"\"\"\n\n super(ThermoNMGLE,self).__init__(temp,dt,ethermo)\n\n if A is None:\n A = np.identity(1,float)\n dset(self,\"A\",depend_value(value=A.copy(),name='A'))\n\n self.nb = len(self.A)\n self.ns = len(self.A[0]) - 1;\n\n # now, this is tricky. if C is taken from temp, then we want it to be\n # updated as a depend of temp.\n # Otherwise, we want it to be an independent beast.\n if C is None:\n dset(self,\"C\",depend_value(name='C', func=self.get_C, dependencies=[dget(self,\"temp\")]))\n else:\n dset(self,\"C\",depend_value(value=C.copy(),name='C'))\n\n def bind(self, nm=None, prng=None, fixdof=None):\n \"\"\"Binds the appropriate degrees of freedom to the thermostat.\n\n This takes an object with degrees of freedom, and makes their momentum\n and mass vectors members of the thermostat. It also then creates the\n objects that will hold the data needed in the thermostat algorithms\n and the dependency network. Actually, this specific thermostat requires\n being called on a beads object.\n\n Args:\n nm: An optional normal modes object to take the mass and momentum\n vectors from.\n prng: An optional pseudo random number generator object. Defaults to\n Random().\n fixdof: An optional integer which can specify the number of constraints\n applied to the system. Defaults to zero.\n\n Raises:\n TypeError: Raised if no beads object is specified for\n the thermostat to couple to.\n \"\"\"\n\n if nm is None or not type(nm) is NormalModes:\n raise TypeError(\"ThermoNMGLE.bind expects a NormalModes argument to bind to\")\n\n if prng is None:\n self.prng = Random()\n else:\n self.prng = prng\n\n if (nm.nbeads != self.nb):\n raise IndexError(\"The parameters in nm_gle options correspond to a bead number \"+str(self.nb)+ \" which does not match the number of beads in the path\" + str(nm.nbeads) )\n\n # allocates, initializes or restarts an array of s's\n if self.s.shape != (self.nb, self.ns + 1, nm.natoms *3) :\n if len(self.s) > 0:\n warning(\"Mismatch in GLE s array size on restart, will reinitialise to free particle.\", verbosity.low)\n self.s = np.zeros((self.nb, self.ns + 1, nm.natoms*3))\n\n # Initializes the s vector in the free-particle limit\n info(\" GLE additional DOFs initialised to the free-particle limit.\", verbosity.low)\n for b in range(self.nb):\n SC = stab_cholesky(self.C[b]*Constants.kb)\n self.s[b] = np.dot(SC, self.prng.gvec(self.s[b].shape))\n else:\n info(\"GLE additional DOFs initialised from input.\", verbosity.medium)\n\n prev_ethermo = self.ethermo\n\n # creates a set of thermostats to be applied to individual normal modes\n self._thermos = [ThermoGLE(temp=1, dt=1, A=self.A[b], C=self.C[b]) for b in range(self.nb)]\n\n # must pipe all the dependencies in such a way that values for the nm\n # thermostats are automatically updated based on the \"master\" thermostat\n def make_Agetter(k):\n return lambda: self.A[k]\n def make_Cgetter(k):\n return lambda: self.C[k]\n\n it = 0\n for t in self._thermos:\n t.s = self.s[it] # gets the s's as a slice of self.s\n t.bind(pm=(nm.pnm[it,:],nm.dynm3[it,:]), prng=self.prng) # bind thermostat t to the it-th normal mode\n\n # pipes temp and dt\n deppipe(self,\"temp\", t, \"temp\")\n deppipe(self,\"dt\", t, \"dt\")\n\n # here we pipe the A and C of individual NM to the \"master\" arrays\n dget(t,\"A\").add_dependency(dget(self,\"A\"))\n dget(t,\"A\")._func = make_Agetter(it)\n dget(t,\"C\").add_dependency(dget(self,\"C\"))\n dget(t,\"C\")._func = make_Cgetter(it)\n dget(self,\"ethermo\").add_dependency(dget(t,\"ethermo\"))\n it += 1\n\n # since the ethermo will be \"delegated\" to the normal modes thermostats,\n # one has to split\n # any previously-stored value between the sub-thermostats\n for t in self._thermos:\n t.ethermo = prev_ethermo/self.nb\n\n dget(self,\"ethermo\")._func = self.get_ethermo;\n\n def step(self):\n \"\"\"Updates the thermostat in NM representation by looping over the\n individual DOFs.\n \"\"\"\n\n for t in self._thermos:\n t.step()\n\n def get_ethermo(self):\n \"\"\"Computes the total energy transferred to the heat bath for all the nm\n thermostats.\n \"\"\"\n\n et = 0.0;\n for t in self._thermos:\n et += t.ethermo\n return et\n\n\nclass ThermoNMGLEG(ThermoNMGLE):\n \"\"\"Represents a 'normal-modes' GLE thermostat + SVR.\n\n An extension to the above NMGLE thermostat which also adds a stochastic velocity\n rescaling to the centroid.\n\n Depend objects:\n tau: Thermostat damping time scale. Larger values give a less strongly\n coupled thermostat.\n \"\"\"\n\n def __init__(self, temp = 1.0, dt = 1.0, A = None, C = None, tau=1.0, ethermo=0.0):\n\n super(ThermoNMGLEG,self).__init__(temp, dt, A, C, ethermo)\n dset(self,\"tau\",depend_value(value=tau,name='tau'))\n\n def bind(self, nm=None, prng=None, fixdof=None):\n \"\"\"Binds the appropriate degrees of freedom to the thermostat.\n\n This takes an object with degrees of freedom, and makes their momentum\n and mass vectors members of the thermostat. It also then creates the\n objects that will hold the data needed in the thermostat algorithms\n and the dependency network. Actually, this specific thermostat requires\n being called on a beads object.\n\n Args:\n nm: An optional normal modes object to take the mass and momentum\n vectors from.\n prng: An optional pseudo random number generator object. Defaults to\n Random().\n fixdof: An optional integer which can specify the number of constraints\n applied to the system. Defaults to zero.\n \"\"\"\n\n super(ThermoNMGLEG,self).bind(nm, prng, fixdof)\n\n t = ThermoSVR(self.temp, self.dt, self.tau)\n\n t.bind(pm=(nm.pnm[0,:],nm.dynm3[0,:]), prng=self.prng) # bind global thermostat to centroid\n\n # pipes temp and dt\n deppipe(self,\"temp\", t, \"temp\")\n deppipe(self,\"dt\", t, \"dt\")\n deppipe(self,\"tau\", t, \"tau\")\n\n dget(self,\"ethermo\").add_dependency(dget(t,\"ethermo\"))\n self._thermos.append(t)\n\n", "meta": {"hexsha": "1fb048ec27c8becd0c96f6d526bf97fce0f3f0c9", "size": 34428, "ext": "py", "lang": "Python", "max_stars_repo_path": "lammps-master/tools/i-pi/ipi/engine/thermostats.py", "max_stars_repo_name": "rajkubp020/helloword", "max_stars_repo_head_hexsha": "4bd22691de24b30a0f5b73821c35a7ac0666b034", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lammps-master/tools/i-pi/ipi/engine/thermostats.py", "max_issues_repo_name": "rajkubp020/helloword", "max_issues_repo_head_hexsha": "4bd22691de24b30a0f5b73821c35a7ac0666b034", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lammps-master/tools/i-pi/ipi/engine/thermostats.py", "max_forks_repo_name": "rajkubp020/helloword", "max_forks_repo_head_hexsha": "4bd22691de24b30a0f5b73821c35a7ac0666b034", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9016949153, "max_line_length": 178, "alphanum_fraction": 0.6522016963, "include": true, "reason": "import numpy", "num_tokens": 8430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.2309197682220399, "lm_q1q2_score": 0.13159024218527207}} {"text": "\"\"\"\nCommon RGB Colour Models Utilities\n==================================\n\nDefines various RGB colour models common utilities.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom colour.colorimetry import CCS_ILLUMINANTS\nfrom colour.hints import ArrayLike, Boolean, Literal, NDArray, Optional, Union\nfrom colour.models.rgb import RGB_COLOURSPACES, RGB_to_XYZ, XYZ_to_RGB\n\n__author__ = \"Colour Developers\"\n__copyright__ = \"Copyright 2013 Colour Developers\"\n__license__ = \"New BSD License - https://opensource.org/licenses/BSD-3-Clause\"\n__maintainer__ = \"Colour Developers\"\n__email__ = \"colour-developers@colour-science.org\"\n__status__ = \"Production\"\n\n__all__ = [\n \"XYZ_to_sRGB\",\n \"sRGB_to_XYZ\",\n]\n\n\ndef XYZ_to_sRGB(\n XYZ: ArrayLike,\n illuminant: ArrayLike = CCS_ILLUMINANTS[\n \"CIE 1931 2 Degree Standard Observer\"\n ][\"D65\"],\n chromatic_adaptation_transform: Optional[\n Union[\n Literal[\n \"Bianco 2010\",\n \"Bianco PC 2010\",\n \"Bradford\",\n \"CAT02 Brill 2008\",\n \"CAT02\",\n \"CAT16\",\n \"CMCCAT2000\",\n \"CMCCAT97\",\n \"Fairchild\",\n \"Sharp\",\n \"Von Kries\",\n \"XYZ Scaling\",\n ],\n str,\n ]\n ] = \"CAT02\",\n apply_cctf_encoding: Boolean = True,\n) -> NDArray:\n \"\"\"\n Convert from *CIE XYZ* tristimulus values to *sRGB* colourspace.\n\n Parameters\n ----------\n XYZ\n *CIE XYZ* tristimulus values.\n illuminant\n Source illuminant chromaticity coordinates.\n chromatic_adaptation_transform\n *Chromatic adaptation* transform.\n apply_cctf_encoding\n Whether to apply the *sRGB* encoding colour component transfer function\n / inverse electro-optical transfer function.\n\n Returns\n -------\n :class:`numpy.ndarray`\n *sRGB* colour array.\n\n Notes\n -----\n +------------+-----------------------+---------------+\n | **Domain** | **Scale - Reference** | **Scale - 1** |\n +============+=======================+===============+\n | ``XYZ`` | [0, 1] | [0, 1] |\n +------------+-----------------------+---------------+\n\n +------------+-----------------------+---------------+\n | **Range** | **Scale - Reference** | **Scale - 1** |\n +============+=======================+===============+\n | ``RGB`` | [0, 1] | [0, 1] |\n +------------+-----------------------+---------------+\n\n Examples\n --------\n >>> import numpy as np\n >>> XYZ = np.array([0.20654008, 0.12197225, 0.05136952])\n >>> XYZ_to_sRGB(XYZ) # doctest: +ELLIPSIS\n array([ 0.7057393..., 0.1924826..., 0.2235416...])\n \"\"\"\n\n sRGB = RGB_COLOURSPACES[\"sRGB\"]\n\n return XYZ_to_RGB(\n XYZ,\n illuminant,\n sRGB.whitepoint,\n sRGB.matrix_XYZ_to_RGB,\n chromatic_adaptation_transform,\n sRGB.cctf_encoding if apply_cctf_encoding else None,\n )\n\n\ndef sRGB_to_XYZ(\n RGB: ArrayLike,\n illuminant: ArrayLike = CCS_ILLUMINANTS[\n \"CIE 1931 2 Degree Standard Observer\"\n ][\"D65\"],\n chromatic_adaptation_transform: Optional[\n Union[\n Literal[\n \"Bianco 2010\",\n \"Bianco PC 2010\",\n \"Bradford\",\n \"CAT02 Brill 2008\",\n \"CAT02\",\n \"CAT16\",\n \"CMCCAT2000\",\n \"CMCCAT97\",\n \"Fairchild\",\n \"Sharp\",\n \"Von Kries\",\n \"XYZ Scaling\",\n ],\n str,\n ]\n ] = \"CAT02\",\n apply_cctf_decoding: Boolean = True,\n) -> NDArray:\n \"\"\"\n Convert from *sRGB* colourspace to *CIE XYZ* tristimulus values.\n\n Parameters\n ----------\n RGB\n *sRGB* colourspace array.\n illuminant\n Source illuminant chromaticity coordinates.\n chromatic_adaptation_transform\n *Chromatic adaptation* transform.\n apply_cctf_decoding\n Whether to apply the *sRGB* decoding colour component transfer function\n / electro-optical transfer function.\n\n Returns\n -------\n :class:`numpy.ndarray`\n *CIE XYZ* tristimulus values.\n\n Notes\n -----\n +------------+-----------------------+---------------+\n | **Domain** | **Scale - Reference** | **Scale - 1** |\n +============+=======================+===============+\n | ``RGB`` | [0, 1] | [0, 1] |\n +------------+-----------------------+---------------+\n\n +------------+-----------------------+---------------+\n | **Range** | **Scale - Reference** | **Scale - 1** |\n +============+=======================+===============+\n | ``XYZ`` | [0, 1] | [0, 1] |\n +------------+-----------------------+---------------+\n\n Examples\n --------\n >>> import numpy as np\n >>> RGB = np.array([0.70573936, 0.19248266, 0.22354169])\n >>> sRGB_to_XYZ(RGB) # doctest: +ELLIPSIS\n array([ 0.2065429..., 0.1219794..., 0.0513714...])\n \"\"\"\n\n sRGB = RGB_COLOURSPACES[\"sRGB\"]\n\n return RGB_to_XYZ(\n RGB,\n sRGB.whitepoint,\n illuminant,\n sRGB.matrix_RGB_to_XYZ,\n chromatic_adaptation_transform,\n sRGB.cctf_decoding if apply_cctf_decoding else None,\n )\n", "meta": {"hexsha": "e6c741ecb1a36212e23d9aa3f94791dda3f1de1c", "size": 5341, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/models/rgb/common.py", "max_stars_repo_name": "tjdcs/colour", "max_stars_repo_head_hexsha": "09413da71b5da57408eb812797c5db1300d4791a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "colour/models/rgb/common.py", "max_issues_repo_name": "tjdcs/colour", "max_issues_repo_head_hexsha": "09413da71b5da57408eb812797c5db1300d4791a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colour/models/rgb/common.py", "max_forks_repo_name": "tjdcs/colour", "max_forks_repo_head_hexsha": "09413da71b5da57408eb812797c5db1300d4791a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8702702703, "max_line_length": 79, "alphanum_fraction": 0.4688260625, "include": true, "reason": "import numpy", "num_tokens": 1358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.25683199138751883, "lm_q1q2_score": 0.13142519461223054}} {"text": "from os.path import exists\nfrom pathlib import Path\nimport numpy as np\nfrom . import util\n\n# comparison of the correlations between CD4/CD8 expression levels and\n# either the old cd8 score or this new one on two 10x datasets\n# Looks like this new one is a better predictor (which is should be!)\n#\n# based on this I am switching this to be the default\n#\n# R Pearson P Spearman Kendall dataset\n# old corr: CD4 -0.171 1.10e-19 5.25e-20 1.07e-19 hs_pbmc3\n# new corr: CD4 -0.184 1.60e-22 1.03e-23 2.27e-23 hs_pbmc3\n# old corr: CD8A 0.360 3.56e-86 1.42e-91 4.98e-85 hs_pbmc3\n# new corr: CD8A 0.384 1.57e-98 7.91e-109 6.17e-100 hs_pbmc3\n# old corr: CD8B 0.312 5.94e-64 3.23e-74 1.25e-69 hs_pbmc3\n# new corr: CD8B 0.329 3.76e-71 1.55e-91 1.28e-84 hs_pbmc3\n# old corr: CD4 -0.136 8.38e-08 8.22e-08 1.02e-07 hs_pbmc\n# new corr: CD4 -0.154 1.37e-09 4.40e-09 5.52e-09 hs_pbmc\n# old corr: CD8A 0.348 3.83e-45 2.75e-46 2.76e-43 hs_pbmc\n# new corr: CD8A 0.400 2.49e-60 1.46e-63 1.40e-57 hs_pbmc\n# old corr: CD8B 0.258 8.65e-25 2.64e-30 1.75e-28 hs_pbmc\n# new corr: CD8B 0.303 5.09e-34 5.89e-45 1.38e-41 hs_pbmc\n\namino_acids = ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', \\\n 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y']\n\n# read the model parameters\nall_models = {}\n\nfor ab in 'AB':\n model_params = {\n 'window_size':None,\n 'min_lenbin':None,\n 'max_lenbin':None,\n 'NV':None,\n 'NJ':None,\n 'NL':None,\n 'NC':None,\n }\n model_file = Path.joinpath( Path(util.path_to_data),f'cd8_logreg_params_{ab}.txt')\n mtags, weights = [], []\n #print(f'loading cd8 model for chain {ab} {model_file}')\n with open(model_file, 'r') as data:\n for line in data:\n l = line.split()\n tag, value = l\n if tag in model_params:\n model_params[tag] = int(value)\n else:\n mtags.append(tag)\n weights.append(float(value))\n NV, NJ, NL, NC = [model_params[x] for x in 'NV NJ NL NC'.split()]\n NTOT = NV + NJ + NL + NC\n assert mtags[-1] == 'BIAS'\n bias = float(weights[-1])\n assert len(weights) == NTOT+1\n weights = np.array(weights)\n vgenes = mtags[:NV-1] # last is UNK gene\n jgenes = mtags[NV:NV+NJ-1]\n assert all(x.startswith(f'TR{ab}V') for x in vgenes)\n assert all(x.startswith(f'TR{ab}J') for x in jgenes)\n vgene_indexer = {x:i for i,x in enumerate(vgenes)}\n jgene_indexer = {x:i for i,x in enumerate(jgenes)}\n\n model_params['weights'] = weights\n model_params['vgene_indexer'] = vgene_indexer\n model_params['jgene_indexer'] = jgene_indexer\n\n all_models[ab] = model_params\n\n\ndef get_lenbin(L, min_lenbin, max_lenbin):\n if L <= min_lenbin:\n return min_lenbin\n elif L >= max_lenbin:\n return max_lenbin\n else:\n return L\n\ndef get_allele(g):\n assert g.count('*')==1\n return g[:g.index('*')]\n\ndef encode_single_chain_tcr(vgene, jgene, cdr3, model_params):\n ''' vgene and jgene still include '*01' (e.g.)\n '''\n window_size = model_params['window_size']\n min_lenbin = model_params['min_lenbin']\n max_lenbin = model_params['max_lenbin']\n vgene_indexer = model_params['vgene_indexer']\n jgene_indexer = model_params['jgene_indexer']\n NV = len(vgene_indexer)+1\n NJ = len(jgene_indexer)+1\n NL = max_lenbin-min_lenbin+1\n NC = 20 * (2*window_size+1)\n NTOT = NV + NJ + NL + NC\n\n # 1-hot encode the V/J genes and length\n x = np.zeros((NTOT+1,))\n iv = vgene_indexer.get(get_allele(vgene), NV-1)\n x[iv] = 1.0\n\n ij = jgene_indexer.get(get_allele(jgene), NJ-1)\n x[NV+ij] = 1.0\n\n il = get_lenbin(len(cdr3), min_lenbin, max_lenbin) - min_lenbin\n x[NV+NJ+il] = 1.0\n\n # 1-hot encode aas in the nterminal and cterminal cdr3 windows\n # k-hot encode the middle of the tcr\n nterm = min(window_size, len(cdr3)//2)\n cterm = min(window_size, len(cdr3)-nterm)\n #middle = len(cdr3)-nterm-cterm\n for i in range(window_size):\n if i2*window_size # sanity check\n istart = NV+NJ+NL+40*window_size\n x[istart+amino_acids.index(aa)] += 1.0\n\n x[NTOT] = 1. # for the bias term\n return x\n\n\ndef make_cd8_score_table_column(tcrs, use_sigmoid=False):\n ''' We fit a logistic regression model on single-chain bulk TCR data\n from sorted CD4/CD8 subsets. Here we just average the alpha-chain and beta-chain\n scores.\n '''\n global all_models\n score_totals = np.zeros((len(tcrs),))\n for iab, ab in enumerate('AB'):\n model = all_models[ab]\n tcr_vectors = [ encode_single_chain_tcr(x[iab][0], x[iab][1], x[iab][2], model)\n for x in tcrs ]\n tcr_vectors = np.vstack(tcr_vectors)\n weights = model['weights']\n assert tcr_vectors.shape == (len(tcrs), weights.shape[0])\n ab_scores = np.dot( tcr_vectors, weights)\n if use_sigmoid:\n ab_scores = 1.0/(1.0+np.exp(-1*ab_scores))\n score_totals += 0.5 * ab_scores\n return score_totals\n\n\n\n\n\n", "meta": {"hexsha": "c302e859dcbf860d42aa017d7596cd6b9121012b", "size": 5379, "ext": "py", "lang": "Python", "max_stars_repo_path": "conga/cd8_scoring.py", "max_stars_repo_name": "phbradley/conga", "max_stars_repo_head_hexsha": "ce7257ab5ac9283305800dafc8a238ccf53ee084", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2020-06-09T18:43:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T07:47:47.000Z", "max_issues_repo_path": "conga/cd8_scoring.py", "max_issues_repo_name": "phbradley/conga", "max_issues_repo_head_hexsha": "ce7257ab5ac9283305800dafc8a238ccf53ee084", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32, "max_issues_repo_issues_event_min_datetime": "2020-08-25T10:00:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T17:54:01.000Z", "max_forks_repo_path": "conga/cd8_scoring.py", "max_forks_repo_name": "phbradley/conga", "max_forks_repo_head_hexsha": "ce7257ab5ac9283305800dafc8a238ccf53ee084", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2020-06-19T14:08:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-14T08:43:41.000Z", "avg_line_length": 34.4807692308, "max_line_length": 87, "alphanum_fraction": 0.609406953, "include": true, "reason": "import numpy", "num_tokens": 1897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199306096344, "lm_q2_score": 0.2538610013242243, "lm_q1q2_score": 0.13089579188728884}} {"text": "\nimport model\nimport utils\nimport numpy as np\n\nclass ThomasModel(model.Model):\n \n def __init__(self, dog_day_prob, message_prob, n_messengers = 1):\n \"\"\"\n >>> m = ThomasModel(0.1, 0.25)\n >>> m.probs\n {(1, 1, 1, 0, 0): 0.0015625000000000003, (1, 0, 1, 1, 0): 0.0046874999999999981, (1, 1, 0, 1, 1): 0.0046874999999999981, (1, 0, 0, 0, 0): 0.014062500000000011, (0, 0, 0, 0, 1): 0.12656249999999999, (1, 0, 1, 0, 0): 0.0046874999999999981, (0, 0, 1, 1, 1): 0.042187499999999989, (1, 1, 1, 1, 0): 0.0015625000000000003, (0, 1, 0, 1, 1): 0.042187499999999989, (1, 0, 0, 1, 0): 0.014062500000000011, (0, 0, 1, 0, 1): 0.042187499999999989, (0, 1, 1, 1, 0): 0.014062500000000011, (0, 0, 1, 0, 0): 0.042187499999999989, (1, 1, 1, 0, 1): 0.0015625000000000003, (0, 1, 0, 0, 0): 0.042187499999999989, (1, 0, 1, 1, 1): 0.0046874999999999981, (1, 1, 0, 1, 0): 0.0046874999999999981, (1, 1, 0, 0, 0): 0.0046874999999999981, (1, 0, 1, 0, 1): 0.0046874999999999981, (0, 0, 1, 1, 0): 0.042187499999999989, (0, 1, 1, 0, 0): 0.014062500000000011, (0, 0, 0, 1, 0): 0.12656249999999999, (1, 0, 0, 0, 1): 0.014062500000000011, (0, 0, 0, 0, 0): 0.12656249999999999, (1, 1, 1, 1, 1): 0.0015625000000000003, (0, 0, 0, 1, 1): 0.12656249999999999, (1, 0, 0, 1, 1): 0.014062500000000011, (0, 1, 0, 0, 1): 0.042187499999999989, (0, 1, 1, 0, 1): 0.014062500000000011, (0, 1, 0, 1, 0): 0.042187499999999989, (1, 1, 0, 0, 1): 0.0046874999999999981, (0, 1, 1, 1, 1): 0.014062500000000011}\n >>> utils.print_partition(m.partitions)\n player 0\n (1, 1, None, None) [(1, 1, 0, 0, 0), (1, 1, 0, 0, 1), (1, 1, 1, 0, 0), (1, 1, 1, 0, 1)]\n (1, 1, 0, None) [(1, 1, 0, 1, 0), (1, 1, 0, 1, 1)]\n (0, 1, 0, None) [(0, 1, 0, 1, 0), (0, 1, 0, 1, 1)]\n (None, None, None, None) [(0, 0, 0, 0, 0), (0, 0, 0, 0, 1), (0, 0, 0, 1, 0), (0, 0, 0, 1, 1), (0, 0, 1, 0, 0), (0, 0, 1, 0, 1), (0, 0, 1, 1, 0), (0, 0, 1, 1, 1), (1, 0, 0, 0, 0), (1, 0, 0, 0, 1), (1, 0, 0, 1, 0), (1, 0, 0, 1, 1), (1, 0, 1, 0, 0), (1, 0, 1, 0, 1), (1, 0, 1, 1, 0), (1, 0, 1, 1, 1)]\n (0, 1, 1, 1) [(0, 1, 1, 1, 1)]\n (1, 1, 1, 1) [(1, 1, 1, 1, 1)]\n (0, 1, 1, 0) [(0, 1, 1, 1, 0)]\n (0, 1, None, None) [(0, 1, 0, 0, 0), (0, 1, 0, 0, 1), (0, 1, 1, 0, 0), (0, 1, 1, 0, 1)]\n (1, 1, 1, 0) [(1, 1, 1, 1, 0)]\n player 1\n (1, 0, 1, None) [(1, 0, 1, 0, 0), (1, 0, 1, 0, 1), (1, 0, 1, 1, 0), (1, 0, 1, 1, 1)]\n (0, 0, 1, None) [(0, 0, 1, 0, 0), (0, 0, 1, 0, 1), (0, 0, 1, 1, 0), (0, 0, 1, 1, 1)]\n (None, None, None, None) [(0, 0, 0, 0, 0), (0, 0, 0, 0, 1), (0, 0, 0, 1, 0), (0, 0, 0, 1, 1), (0, 1, 0, 0, 0), (0, 1, 0, 0, 1), (0, 1, 0, 1, 0), (0, 1, 0, 1, 1), (1, 0, 0, 0, 0), (1, 0, 0, 0, 1), (1, 0, 0, 1, 0), (1, 0, 0, 1, 1), (1, 1, 0, 0, 0), (1, 1, 0, 0, 1), (1, 1, 0, 1, 0), (1, 1, 0, 1, 1)]\n (0, 1, 1, 1) [(0, 1, 1, 1, 1)]\n (1, 1, 1, 1) [(1, 1, 1, 1, 1)]\n (1, 1, 1, None) [(1, 1, 1, 0, 0), (1, 1, 1, 1, 0)]\n (1, 1, 1, 0) [(1, 1, 1, 0, 1)]\n (0, 1, 1, 0) [(0, 1, 1, 0, 1)]\n (0, 1, 1, None) [(0, 1, 1, 0, 0), (0, 1, 1, 1, 0)]\n \"\"\"\n self.dog_day_prob = dog_day_prob\n self.message_prob = message_prob\n self.n_messengers = n_messengers\n self.message_length = 4\n super(ThomasModel, self).__init__([(0,1)]*(1 + self.message_length*self.n_messengers), 2)\n\n def run(self, variables):\n \"\"\"\n >>> m = ThomasModel(0.1, 0.25)\n >>> m.run((1,0,1,0,0))\n [(None, None, None, None), (1, 0, 1, None)]\n >>> m.run((1,0,1,1,0))\n [(None, None, None, None), (1, 0, 1, None)]\n >>> m.run((1,1,0,0,0))\n [(1, 1, None, None), (None, None, None, None)]\n >>> m.run((1,1,0,1,0))\n [(1, 1, 0, None), (None, None, None, None)]\n >>> m.run((1,1,1,1,0))\n [(1, 1, 1, 0), (1, 1, 1, None)]\n >>> m = ThomasModel(0.1, 0.25, 2)\n >>> m.run((1,1,1,1,0,0,1,0,0))\n [(1, 1, 1, 0, None, None, None, None), (1, 1, 1, None, 1, 0, 1, None)]\n >>> m.run((1,0,0,0,0,1,1,1,1))\n [(None, None, None, None, 1, 1, 1, 1), (None, None, None, None, 1, 1, 1, 1)]\n \"\"\"\n\n out = [[] for i in range(self.n_players)]\n\n dog_day = variables[0]\n for i in range(self.n_messengers):\n this_out = self.messenger(dog_day, *variables[(1 + i*self.message_length):(1 + (i+1)*self.message_length)])\n for j in range(self.n_players):\n out[j] += this_out[j]\n \n out = [tuple(out[i]) for i in range(self.n_players)]\n \n return out\n\n # encodes the generative model of the messenger\n # d indicates if it is a \"dog day\"\n def messenger(self, d, m0, m1, tp, wtp):\n\n out = []\n \n if m0 == 1: # visiting player 0\n if tp == 1: # tell plan\n if m1 == 1: # visiting player 1\n out += [[d, m0, m1, wtp]]\n else:\n out += [[d, m0, m1, None]]\n else:\n out += [[d, m0, None, None]]\n else:\n out += [[None, None, None, None]]\n \n if m1 == 1: # visiting player 1\n if m0 == 1 and wtp == 1: # will tell player 0 plan to player 1, if it exists\n out += [[d, m0, m1, tp]]\n else:\n out += [[d, m0, m1, None]]\n else:\n out += [[None, None, None, None]]\n \n return out\n \n def evaluate(self, variables, log = False):\n \"\"\"\n >>> m = ThomasModel(0.1, 0.25)\n >>> np.abs(m.evaluate((1,0,1,0,0)) - 0.1 * 0.75 * 0.25 * 0.5 * 0.5) < 1e-8\n True\n >>> np.abs(np.exp(m.evaluate((1,0,1,0,0), True)) - 0.1 * 0.75 * 0.25 * 0.5 * 0.5) < 1e-8\n True\n >>> m = ThomasModel(0.1, 0.25, 2)\n >>> np.abs(np.exp(m.evaluate((1,0,1,0,0,1,1,0,0), True)) - 0.1 * 0.75 * 0.25 * 0.5 * 0.5 * 0.25 * 0.25 * 0.5 * 0.5) < 1e-8\n True\n \"\"\"\n \n log_p = 0\n \n log_p += utils.log_bernoulli(variables[0], self.dog_day_prob)\n for i in range(self.n_messengers):\n log_p += self.messenger_log_prob(*variables[(1 + i*self.message_length):(1 + (i+1)*self.message_length)])\n \n if log:\n return log_p\n else:\n return np.exp(log_p)\n\n def messenger_log_prob(self, m0, m1, tp, wtp):\n \n log_p = 0\n log_p += utils.log_bernoulli(m0, self.message_prob)\n log_p += utils.log_bernoulli(m1, self.message_prob)\n log_p += utils.log_bernoulli(tp, 0.5)\n log_p += utils.log_bernoulli(wtp, 0.5)\n \n return log_p\n \n \nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n", "meta": {"hexsha": "1b81885e3a47bea111a6c94bd3c65166f3ada9a7", "size": 6751, "ext": "py", "lang": "Python", "max_stars_repo_path": "thomas_model.py", "max_stars_repo_name": "pkrafft/Modeling-Human-Ad-Hoc-Coordination", "max_stars_repo_head_hexsha": "0217302d740b6acd2b86fa0485f1bc6e3995b73d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-07T12:25:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-07T12:25:09.000Z", "max_issues_repo_path": "thomas_model.py", "max_issues_repo_name": "pkrafft/Modeling-Human-Ad-Hoc-Coordination", "max_issues_repo_head_hexsha": "0217302d740b6acd2b86fa0485f1bc6e3995b73d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thomas_model.py", "max_forks_repo_name": "pkrafft/Modeling-Human-Ad-Hoc-Coordination", "max_forks_repo_head_hexsha": "0217302d740b6acd2b86fa0485f1bc6e3995b73d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.2773722628, "max_line_length": 1264, "alphanum_fraction": 0.4578580951, "include": true, "reason": "import numpy", "num_tokens": 3328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.2538610069692489, "lm_q1q2_score": 0.130895791018844}} {"text": "#!/usr/bin/env python\n'''\nmcu: Modeling and Crystallographic Utilities\nCopyright (C) 2019 Hung Q. Pham. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nEmail: Hung Q. Pham \n'''\n\nimport numpy as np\nimport re, argparse\nfrom ..utils.misc import check_exist\nfrom ..vasp import const\nfrom ..cell import utils as cell_utils \n\n\nlattice_MATCH = re.compile(r'''\n[\\w\\W]*\n Lattice [ ]* vectors [ ]* \\:\n(?P\n [\\s\\S]*?(?=\\n.*?[ ] $|\\n[ ]\\n) # match everything until next blank line or EOL\n)\n''', re.VERBOSE)\n \nspecies_MATCH = re.compile(r'''\n[ ]*\n Species [ ]* \\:\n(?P\n [\\s\\S]*?(?=\\n.*?[ ] $|\\n[ ]\\n) # match everything until next blank line or EOL\n)\n''', re.VERBOSE)\n\nkmesh_MATCH = re.compile(r'''\n[\\w\\W]* k-point [ ]* grid [ ]* \\: [ ]* (?P\\S+) [ ]* (?P\\S+) [ ]* (?P\\S+)\n''', re.VERBOSE)\n\nkoffset_MATCH = re.compile(r'''\n[\\w\\W]* k-point [ ]* offset [ ]* \\: [ ]* (?P\\S+) [ ]* (?P\\S+) [ ]* (?P\\S+)\n''', re.VERBOSE)\n\ntotal_charge_MATCH = re.compile(r'''\n[\\w\\W]*\nTotal [ ]* nuclear [ ]* charge [ ]* \\: [ ]* (?P\\S+) [ ]* \\n \nTotal [ ]* core [ ]* charge [ ]* \\: [ ]* (?P\\S+) [ ]* \\n \nTotal [ ]* valence [ ]* charge [ ]* \\: [ ]* (?P\\S+) [ ]* \\n \nTotal [ ]* excess [ ]* charge [ ]* \\: [ ]* (?P\\S+) [ ]* \\n \nTotal [ ]* electronic [ ]* charge [ ]* \\: [ ]* (?P\\S+) \n''', re.VERBOSE)\n\nstates_charge_MATCH = re.compile(r'''\n[\\w\\W]*\nNumber [ ]* of [ ]* empty [ ]* states [ ]* \\: [ ]* (?P\\S+) [ ]* \\n\nTotal [ ]* number [ ]* of [ ]* valence [ ]* states [ ]* \\: [ ]* (?P\\S+) [ ]* \\n\nTotal [ ]* number [ ]* of [ ]* core [ ]* states [ ]* \\: [ ]* (?P\\S+)\n''', re.VERBOSE)\n\n############ For SCF loops ################## \nenergies_MATCH = re.compile(r'''\n[ ]*\n Energies [ ]* \\:\n(?P\n [\\s\\S]*?(?=\\n.*?[ ] $|\\n[ ]\\n) # match everything until next blank line or EOL\n)\n''', re.VERBOSE)\n\ncharges_MATCH = re.compile(r'''\n[ ]*\n Charges [ ]* \\:\n(?P\n [\\s\\S]*?(?=\\n.*?[ ] $|\\n[ ]\\n) # match everything until next blank line or EOL\n)\n''', re.VERBOSE)\n\ndef read_info(filename): \n '''Read the INFO.OUT file'''\n assert check_exist(filename), 'Cannot find : ' + filename\n with open(filename, \"r\") as data_file:\n data = data_file.read()\n\n # spin\n spin = int('spin-polarised' in data)\n soc = 'spin-orbit coupling' in data\n if soc: spin = False\n\n # Cell information\n # row-vectors instead of column-vectors as in elk output\n tmp = lattice_MATCH.match(data)['content']\n lattice = np.float64(tmp.split()).reshape(3,3, order='F') \n \n # Get atom info\n species_blocks = []\n atom = []\n magnetic = []\n frac_coords = []\n for atoms in species_MATCH.finditer(data):\n atoms_data = atoms.groupdict()['content']\n tmp = atoms_data.split('\\n')\n species = {}\n species['atom type'] = re.findall(r\"\\((?P\\S+)\\)\", tmp[0])[0]\n species['parameters'] = tmp[1].split(':')[1].strip()\n species['name'] = tmp[2].split(':')[1].strip()\n species['nuclear charge'] = float(tmp[3].split(':')[1])\n species['electronic charge'] = float(tmp[4].split(':')[1])\n species['atomic mass'] = float(tmp[5].split(':')[1])\n species['muffin-tin radius'] = float(tmp[6].split(':')[1])\n species['muffin-tin radial'] = int(tmp[7].split(':')[1])\n species['muffin-tin inner'] = int(tmp[8].split(':')[1])\n for atm in tmp[10:]:\n atom.append(species['atom type'])\n atm_split = atm.split()\n frac_coords.append(np.float64(atm_split[2:5]))\n magnetic.append(np.float64(atm_split[5:]))\n\n species_blocks.append(species)\n \n # Make the cell tuple\n atom_number = cell_utils.convert_atomtype(atom)\n cell = (lattice * const.AUTOA, frac_coords, atom_number)\n \n # kmesh\n tmp = kmesh_MATCH.match(data)\n kmesh = np.int64([tmp['kx'], tmp['ky'], tmp['kz']])\n tmp = koffset_MATCH.match(data)\n kmesh_shift = np.float64([tmp['kx'], tmp['ky'], tmp['kz']])\n \n # total charge\n charge_data = total_charge_MATCH.match(data)\n charge = {}\n charge['nuclear'] = float(charge_data['nuclear'])\n charge['core'] = float(charge_data['core'])\n charge['valence'] = float(charge_data['valence'])\n charge['excess'] = float(charge_data['excess'])\n charge['electronic'] = float(charge_data['electronic'])\n \n # Total states:\n states_data = states_charge_MATCH.match(data)\n states = {}\n states['empty'] = states_data['empty']\n states['core'] = states_data['core']\n states['valence'] = states_data['valence']\n \n \n # Collect the SCF cycles\n energies_blocks = []\n for cycle in energies_MATCH.finditer(data):\n energies_data = cycle.groupdict()['content']\n tmp = energies_data.split('\\n')\n energies = {}\n energies['Fermi'] = float(tmp[1].split(':')[1])\n energies['sum of eigenvalues'] = float(tmp[2].split(':')[1])\n energies['electron kinetic'] = float(tmp[3].split(':')[1])\n energies['core electron kinetic'] = float(tmp[4].split(':')[1])\n energies['Coulomb'] = float(tmp[5].split(':')[1])\n energies['Coulomb potential'] = float(tmp[6].split(':')[1])\n energies['nuclear-nuclear'] = float(tmp[7].split(':')[1])\n energies['electron-nuclear'] = float(tmp[8].split(':')[1])\n energies['Hartree'] = float(tmp[9].split(':')[1])\n energies['Madelung'] = float(tmp[10].split(':')[1])\n energies['xc potential'] = float(tmp[11].split(':')[1])\n energies['exchange'] = float(tmp[12].split(':')[1])\n energies['correlation'] = float(tmp[13].split(':')[1])\n energies['electron entropic'] = float(tmp[14].split(':')[1])\n energies['total energy'] = float(tmp[15].split(':')[1])\n energies_blocks.append(energies) \n\n out = {}\n out['Species'] = species_blocks\n out['Energies'] = energies_blocks\n out['charge'] = charge\n out['states'] = states\n out['atom'] = atom\n out['cell'] = cell\n out['soc'] = soc\n out['spin'] = spin\n \n return out \n\ndef read_kpoints(filename): \n '''Read the KPOINTS.OUT file'''\n assert check_exist(filename), 'Cannot find : ' + filename\n with open(filename, \"r\") as data_file:\n data = data_file.read()\n tmp = np.float64(\" \".join(data.split('\\n')[1:-1]).split()).reshape(-1, 6)\n return tmp[:,1:4], tmp[:,4] # kpts and kpts weight\n \neigval_MATCH = re.compile(r'''\n[ ]*\n \\([ ]* state, [ ]* eigenvalue [ ]* and [ ]* occupancy [ ]* below\\)\n(?P\n [\\s\\S]*?(?=\\n.*?[ ] $|\\n[ ]\\n) # match everything until next blank line or EOL\n)\n''', re.VERBOSE)\n\ndef read_eigval(filename): \n '''Read the KPOINTS.OUT file\n Return:\n eigvals[spin, kpt, band, eigenvalues]\n occ[spin, kpt, band, occupancy]\n '''\n assert check_exist(filename), 'Cannot find : ' + filename\n with open(filename, \"r\") as data_file:\n data = data_file.read()\n\n eigvals = []\n occ = []\n for eigval in eigval_MATCH.finditer(data):\n eigval_data = eigval['content']\n tmp = np.float64(eigval_data.split()).reshape(-1, 3)\n eigvals.append(tmp[:,1])\n occ.append(tmp[:,2])\n \n eigvals = np.asarray(eigvals)\n nkpts = eigvals.shape[0]\n nband = eigvals.shape[1]\n occ = np.asarray(occ)\n \n # Check if this is a spin-polarized calculation \n if (occ[0] <= 1.0).any() and abs((-occ[0]).argsort() - np.arange(occ[0].shape[0])).sum() > 1e-3: \n assert np.mod(nband,2) == 0, \"This is not a spin-polarised calculation\"\n nband = nband//2\n \n eigvals = eigvals.reshape(nkpts, nband, -1).transpose(2, 0, 1) \n occ = occ.reshape(nkpts, nband, -1).transpose(2, 0, 1) \n return eigvals, occ \n \n############ Read BAND***.OUT - begin ################## \ndef read_bandlines(filename): \n '''Read the BANDLINES.OUT file\n '''\n assert check_exist(filename), 'Cannot find : ' + filename\n with open(filename, \"r\") as data_file:\n data = np.float64(data_file.read().split()).reshape(-1,2)\n nkpoint = data.shape[0] // 2\n return data[2*np.arange(nkpoint), 0] / const.AUTOA\n\ndef read_band(filename, spin_polarized=False):\n '''Read BAND.OUT or BAND_Sss_Aaaaa.OUT\n\n Depends on the tasks, BAND.OUT or BAND_Sss_Aaaaa.OUT contains different projection\n For tasks 20: kpt | e (a.u.)\n For tasks 21: kpt | e (a.u.) | Total | s | p | d | f |\n For tasks 22: kpt | e (a.u.) | s | p(-1,0,+1) | d(-2,-1,0,+1,+2) | f(-3,-2,-1,0,+1,+2,+3)\n For tasks 23: kpt | e (a.u.) | up | down |\n \n Return:\n bands[spin, kpt, band-th, projected contribution] \n '''\n assert check_exist(filename), 'Cannot find : ' + filename\n with open(filename, 'r') as data_file:\n data = data_file.read()\n tmp = data.split('\\n \\n')[:-1]\n \n # Figure out how many kpt and how many column\n nband = len(tmp)\n tmp2 = tmp[0].split('\\n')\n nkpts = len(tmp2)\n ncol = len(tmp2[0].split())\n bands = []\n for i, band in enumerate(tmp):\n formatted_band = np.float64(band.split()).reshape(-1, ncol) \n if i == 0: proj_kpath = formatted_band[:,0] / const.AUTOA # in Angstrom-1\n bands.append(formatted_band[:,1:]) \n\n if spin_polarized: \n assert np.mod(nband,2) == 0, \"This is not a spin-polarised calculation\"\n nband = nband//2\n \n bands = np.asarray(bands).reshape(-1, nband, nkpts, ncol - 1).transpose(0, 2, 1, 3) * const.AUTOEV \n return proj_kpath, bands \n\ndef read_plot1d(filename):\n '''Read the plot1d of elk.in'''\n \n with open(filename, 'r') as data_file:\n data = data_file.read()\n assert 'plot1d' in data, \"plot1d block cannot be found in the elk.in\" \n tmp_with_comments = data.split('\\n')\n tmp = [item for item in tmp_with_comments if not '!' in item] # remove comments\n for i, item in enumerate(tmp):\n if 'plot1d' in item:\n where_plot1d = i\n break\n \n nkpoint, npts = np.int64(tmp[where_plot1d + 1].split()[:2])\n sym_kvecs = np.float64([tmp[i].split()[:3] for i in range(where_plot1d + 2, where_plot1d + nkpoint + 2)])\n \n return sym_kvecs, npts\n \n############ Read DOS - begin ################## \ndef read_dos(filename, spin_polarized=False):\n '''Read TDOS.OUT, IDOS.OUT, PDOS_Sss_Aaaaa.OUT\n\n For PDOS_Sss_Aaaaa.OUT: \n e (a.u.) | s | p(-1,0,+1) | d(-2,-1,0,+1,+2) | f(-3,-2,-1,0,+1,+2,+3)\n Return:\n dos[spin, e, dos] \n '''\n assert check_exist(filename), 'Cannot find : ' + filename\n with open(filename, 'r') as data_file:\n data = data_file.read()\n tmp = data.split('\\n \\n')[:-1]\n \n # Figure out how many kpt and how many column\n ndos = len(tmp)\n nepsilon = len(tmp[0].split('\\n'))\n dos = []\n for i, block in enumerate(tmp):\n formatted_dos = np.float64(block.split()).reshape(nepsilon, 2) \n if i == 0: epsilon = formatted_dos[:,0] * const.AUTOEV # in eV\n dos.append(formatted_dos[:,1]) \n\n if spin_polarized: \n assert np.mod(ndos,2) == 0, \"This is not a spin-polarised calculation\"\n ndos = ndos//2\n \n dos = np.asarray(dos).reshape(-1, ndos, nepsilon).transpose(0, 2, 1)\n return epsilon, dos ", "meta": {"hexsha": "b9358577acc11985d5d9459c1d15f9cf661c8e45", "size": 12603, "ext": "py", "lang": "Python", "max_stars_repo_path": "mcu/elk/elk_io.py", "max_stars_repo_name": "faradaymahe/mcu", "max_stars_repo_head_hexsha": "220a18fd6ba23e3b8522ef0459357d023a31cb85", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mcu/elk/elk_io.py", "max_issues_repo_name": "faradaymahe/mcu", "max_issues_repo_head_hexsha": "220a18fd6ba23e3b8522ef0459357d023a31cb85", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mcu/elk/elk_io.py", "max_forks_repo_name": "faradaymahe/mcu", "max_forks_repo_head_hexsha": "220a18fd6ba23e3b8522ef0459357d023a31cb85", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4237804878, "max_line_length": 113, "alphanum_fraction": 0.537253035, "include": true, "reason": "import numpy", "num_tokens": 3578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.24798742624020279, "lm_q1q2_score": 0.13076786744683058}} {"text": "#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\nEmcee-based sampler for singlepix SED MCMC.\n\"\"\"\n\nimport time\nimport numpy as np\nfrom collections import OrderedDict\n\nimport emcee\nimport fsps\nfrom astropy.table import Table, hstack, Column\n\nfrom sedbot.photconv import micro_jy_to_luminosity\nfrom sedbot.chain import SinglePixelChain\n\n\nclass SinglePixelSampler(object):\n \"\"\"Emcee-based sampler for single pixel SEDs.\n\n Parameters\n ----------\n model : object\n A model instance (see :mod:`sedbot.models`).\n n_walkers : int\n Number of emcee walkers.\n \"\"\"\n def __init__(self, model, n_walkers=100):\n super(SinglePixelSampler, self).__init__()\n self.model = model\n self.n_walkers = n_walkers\n self._sampler = None\n self._run_time = 0.\n self._call_time = np.nan\n\n def generate_initial_point(self, x0, x_sigma):\n \"\"\"Generate a chain starting point given an array of Gaussian\n dispersions to build balls from for each parameter.\n\n Parameters\n ----------\n x0 : ndarray\n Initial points in parameter space. Shape ``(n_params,)``.\n x_sigma : ndarray\n Gaussian standard deviations to disperse starting points for each\n walkers. Shape ``(n_params,)``.\n \"\"\"\n ndim = len(x0)\n assert len(x0) == len(x_sigma), \"Lengths do not match\"\n assert ndim == self.model.n_params\n p0 = np.random.randn(ndim * self.n_walkers).reshape((self.n_walkers,\n ndim))\n for i, (x, sigma) in enumerate(zip(x0, x_sigma)):\n p0[:, i] = sigma * p0[:, i] + x\n priorf = self.model.priors[self.model.param_names[i]]\n p0[:, i][p0[:, i] < priorf.lower_limit] = priorf.lower_limit\n p0[:, i][p0[:, i] > priorf.upper_limit] = priorf.upper_limit\n return p0\n\n def sample(self, n_steps, theta0=None, chain=None):\n \"\"\"Sample for `n_steps` Emcee steps.\n\n Parameters\n ----------\n n_steps : int\n Number of emcee steps. The total number of samples will be\n ``n_steps x n_walkers``.\n theta0 : ndarray\n Initial locations of the walkers; shape\n \"\"\"\n self.sampler = emcee.EnsembleSampler(\n self.n_walkers,\n self.model.n_params, self.model)\n\n # Do burn-in + run\n with EmceeTimer(n_steps, self.n_walkers) as emcee_timer:\n self.sampler.run_mcmc(theta0, n_steps)\n print(emcee_timer)\n\n self._run_time += emcee_timer.interval\n self._call_time = emcee_timer.seconds_per_call\n\n @property\n def table(self):\n \"\"\"An :class:`astropy.table.Table` with the chain.\"\"\"\n if self.sampler is None:\n return None\n msuns = np.array([fsps.get_filter(n).msun_ab\n for n in self.model.computed_bands])\n meta = OrderedDict((\n ('observed_bands', self.model.observed_bands),\n ('instruments', self.model.instruments),\n ('computed_bands', self.model.computed_bands),\n ('msun_ab', msuns),\n ('d', self.model.d), # expected distance in parsecs\n ('band_indices', self.model.band_indices),\n ('theta_params', self.model.param_names),\n ('compute_time', self._run_time),\n ('step_time', self._call_time),\n ('sed', self.model._sed),\n ('sed_err', self.model._err),\n ('pixels', self.model.pixel_metadata),\n ('area', self.model._area),\n ('n_walkers', self.n_walkers),\n (\"f_accept\", self.sampler.acceptance_fraction),\n (\"acor\", self.sampler.acor)))\n\n # Convert flatchain into a structured array\n nwalkers, nsteps, ndim = self.sampler.chain.shape\n flatchain_arr = self.sampler.chain[:, :, :].reshape((-1, ndim))\n dt = [(n, np.float) for n in self.model.param_names]\n flatchain = np.empty(flatchain_arr.shape[0], dtype=np.dtype(dt))\n for i, n in enumerate(self.model.param_names):\n flatchain[n][:] = flatchain_arr[:, i]\n\n # Flatten the blob list and make a structured array\n blobs = self.sampler.blobs\n blobchain = np.empty(nwalkers * nsteps, self.model.blob_dtype)\n blobchain.fill(np.nan)\n for i in xrange(nsteps):\n for j in xrange(nwalkers):\n for k in self.model.blob_dtype.names:\n blobchain[k][i * self.n_walkers + j] = blobs[i][j][k]\n\n chain_table = Table(flatchain, meta=meta)\n blob_table = Table(blobchain)\n tbl = SinglePixelChain(hstack((chain_table, blob_table),\n join_type='exact'))\n\n # Add M/L computations for each computed band.\n for i, (band_name, msun) in enumerate(zip(self.model.computed_bands,\n msuns)):\n # Either use expected distance or the chain distance\n # FIXME fragile code\n if 'd' in self.model.param_names:\n d = np.array(tbl['d'])\n else:\n d = self.model.d\n logLsol = micro_jy_to_luminosity(tbl['model_sed'][:, i], msun, d)\n ml = tbl['logMstar'] - logLsol\n colname = \"logML_{0}\".format(band_name)\n tbl.add_column(Column(name=colname, data=ml))\n\n return tbl\n\n\nclass EmceeTimer(object):\n \"\"\"Timer for emcee runs. Computes total run time and mean time of each\n likelihood call.\n\n Example::\n\n >>> with EmceeTimer(n_steps, n_walkers) as emceet:\n >>> sampler.run_mcmc(p0, n_steps)\n >>> print emceet\n\n Parameters\n ----------\n nsteps : int\n Number of emcee steps.\n nwalkers : int\n Number of emcee walkers.\n \"\"\"\n def __init__(self, nsteps, nwalkers):\n super(EmceeTimer, self).__init__()\n self._nsteps = nsteps\n self._nwalkers = nwalkers\n self._start = None\n self._stop = None\n self._endtime = None\n self._interval = None\n\n def __enter__(self):\n self._start = time.clock()\n return self\n\n def __exit__(self, *args):\n self._end = time.clock()\n self._endtime = time.localtime()\n self._interval = self._end - self._start\n\n def __str__(self):\n dt, unit = self._human_time(self._interval)\n ct, cunit = self._human_time(self.seconds_per_call)\n enddate = time.strftime('%Y-%m-%d %H:%M:%S', self._endtime)\n l1 = \"Finished emcee run at {enddate}\"\n l2 = \"\\tRun time: {dt} {unit}\"\n l3 = \"\\t{ct} {cunit} per call\"\n return \"\\n\".join((l1, l2, l3)).format(dt=dt, unit=unit,\n ct=ct, cunit=cunit,\n enddate=enddate)\n\n def _human_time(self, interval):\n \"\"\"Return a time interval scaled to human-usable units.\"\"\"\n if interval < 60.:\n dt, unit = interval, \"seconds\"\n if interval >= 60.:\n dt, unit = interval / 60., \"minutes\"\n elif interval >= 3600.:\n dt, unit = interval / 3600., \"hours\"\n elif interval >= 86400:\n dt, unit = interval / 86400., \"days\"\n return dt, unit\n\n @property\n def seconds_per_call(self):\n \"\"\"The mean number of seconds elapsed per likelihood call.\n\n Returns\n -------\n interval : float\n Description\n \"\"\"\n return self._interval / float(self._nsteps * self._nwalkers)\n\n @property\n def interval(self):\n \"\"\"The timer interval in secods.\"\"\"\n return self._interval\n", "meta": {"hexsha": "981186ff1bb7bcc970be99894fdf5978bb3b4162", "size": 7694, "ext": "py", "lang": "Python", "max_stars_repo_path": "sedbot/singlepix/sampler.py", "max_stars_repo_name": "jonathansick/sedbot", "max_stars_repo_head_hexsha": "3114ebb36a8618800b3b556fe1a63372b4b5e054", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sedbot/singlepix/sampler.py", "max_issues_repo_name": "jonathansick/sedbot", "max_issues_repo_head_hexsha": "3114ebb36a8618800b3b556fe1a63372b4b5e054", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sedbot/singlepix/sampler.py", "max_forks_repo_name": "jonathansick/sedbot", "max_forks_repo_head_hexsha": "3114ebb36a8618800b3b556fe1a63372b4b5e054", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.814479638, "max_line_length": 77, "alphanum_fraction": 0.5678450741, "include": true, "reason": "import numpy,from astropy", "num_tokens": 1858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.256831980010821, "lm_q1q2_score": 0.1304223265758144}} {"text": "import numpy\ndef BREMSCASC(J11,EGAMMA,X0,Y0,Z0,T0,GDCX,GDCY,GDCZ,ILOW):\n\t# IMPLICIT #real*8(A-H,O-Z)\n\t# IMPLICIT #integer*8(I-N)\n\t#CHARACTER*6 SCR(17),SCR1(17)\n\t# COMMON/COMP/LCMP,LCFLG,LRAY,LRFLG,LPAP,LPFLG,LBRM,LBFLG,LPEFLG\n\t# COMMON/COMPTOUT/EGAM,EELEC,THETAG,THETAE\n\t# COMMON/PRIM4/MSUM1,MCOMP1,MRAYL1,MPAIR1,MPHOT1,MVAC1\n\t# COMMON/GENCAS/ELEV[17,79],NSDEG(17),AA[17],BB[17],SCR,SCR1\n\t# COMMON/MIXC/PRSH(6,3,17,17),ESH(6,3,17),AUG(6,3,17,17,17),RAD[6,3,17,17],PRSHBT(6,3,17),IZ[6,3],INIOCC(6,3,17),ISHLMX(6,3),AMZ[6,3]\n\t# COMMON/UPD/NOCC(6,3,17),AUGR(6,3,17,17,17),RADR(6,3,17,17)\n\t# COMMON/CALCASB/IONSUM(10),IFLSUM(10),ESTORE(10,28),EPHOTON(10,28),DRXE(10,28),DRYE(10,28),DRZE(10,28),DRX(10,28),DRY(10,28),DRZ[10,28]\n\t# COMMON/CALCAS1B/IONSUM1(10),IFLSUM1(10),ESTOR1(10,28),EPHOTG1(10,28),DRXE1(10,28),DRYE1(10,28),DRZE1(10,28),DRX1(10,28),DRY1(10,28),DRZ1(10,28)\n\t# COMMON/CALCAS2B/IONSUM2(10),IFLSUM2(10),ESTOR2(10,28),EPHOTG2(10,28),DRXE2(10,28),DRYE2(10,28),DRZE2(10,28),DRX2(10,28),DRY2(10,28),DRZ2(10,28)\n\t# COMMON/CALCAS3B/IONSUM3(10),IFLSUM3(10),ESTOR3(10,28),EPHOTG3(10,28),DRXE3(10,28),DRYE3(10,28),DRZE3(10,28),DRX3(10,28),DRY3(10,28),DRZ3(10,28)\n\t# COMMON/CALCAS4B/IONSUM4(10),IFLSUM4(10),ESTOR4(10,28),EPHOTG4(10,28),DRXE4(10,28),DRYE4(10,28),DRZE4(10,28),DRX4(10,28),DRY4(10,28),DRZ4(10,28)\n\t# COMMON/CALCAS5B/IONSUM5(10),IFLSUM5(10),ESTOR5(10,28),EPHOTG5(10,28),DRXE5(10,28),DRYE5(10,28),DRZE5(10,28),DRX5(10,28),DRY5(10,28),DRZ5(10,28)\n\t# COMMON/RESB/IONSM(10),IFLSM(10),ESTOR(10,28),EPHOT(10,28),X10(10,28),Y10(10,28),Z10(10,28),DRX01(10,28),DRY01(10,28),DRZ01(10,28)\n\t# COMMON/GENB1/IONF1(10),ESTF1(10,28),X11(10,28),Y11(10,28),Z11(10,28),DRX11(10,28),DRY11(10,28),DRZ11(10,28)\n\t# COMMON/GENB2/IONF2(10),ESTF2(10,28),X21(10,28),Y21(10,28),Z21(10,28),DRX21(10,28),DRY21(10,28),DRZ21(10,28)\n\t# COMMON/GENB3/IONF3(10),ESTF3(10,15),X31(10,15),Y31(10,15),Z31(10,15),DRX31(10,15),DRY31(10,15),DRZ31(10,15)\n\t# COMMON/GENB4/IONF4(10),ESTF4(10,12),X41(10,12),Y41(10,12),Z41(10,12),DRX41(10,12),DRY41(10,12),DRZ41(10,12)\n\t# COMMON/GENB5/IONF5(10),ESTF5(10,5),X51(10,5),Y51(10,5),Z51(10,5),DRX51(10,5),DRY51(10,5),DRZ51(10,5)\n\t# COMMON/COUTE/ECMP(10),ECDRX(10),ECDRY(10),ECDRZ[10],XCPOS(10),YCPOS(10),ZCPOS(10),KCGAS(10),LCGAS(10),ICSHELL(10)\n\t# COMMON/COUTTB/TT(10),TTP\n\t# COMMON/PPSTRB/NPTP,EPPST[2],XPP[2],YPP[2],ZPP[2],DRXPP[2],DRYPP[2],DRZPP[2]\n\t# COMMON/COMP/\n\tglobal LCMP,LCFLG,LRAY,LRFLG,LPAP,LPFLG,LBRM,LBFLG,LPEFLG\n\t#COMMON/COMPTOUT/\n\tglobal EGAM,EELEC,THETAG,THETAE\n\t#COMMON/PRIM4/\n\tglobal MSUM1,MCOMP1,MRAYL1,MPAIR1,MPHOT1,MVAC1\n\t#COMMON/GENCAS/\n\tglobal ELEV#(17,79)\n\tglobal NSDEG#(17)\n\tglobal AA#(17)\n\tglobal BB#(17)\n\tglobal SCR,SCR1\n\t#COMMON/MIXC/\n\tglobal PRSH#(6,3,17,17)\n\tglobal ESH#(6,3,17)\n\tglobal AUG#(6,3,17,17,17)\n\tglobal RAD#(6,3,17,17)\n\tglobal PRSHBT#(6,3,17)\n\tglobal IZ#(6,3)\n\tglobal INIOCC#(6,3,17)\n\tglobal ISHLMX#(6,3)\n\tglobal AMZ#(6,3)\n\t#COMMON/UPD/\n\tglobal NOCC#(6,3,17)\n\tglobal AUGR#(6,3,17,17,17)\n\tglobal RADR#(6,3,17,17)\n\t#COMMON/CALCASB/\n\tglobal IONSUM#(10)\n\tglobal IFLSUM#(10)\n\tglobal ESTORE#(10,28)\n\tglobal EPHOTON#(10,28)\n\tglobal DRXE#(10,28)\n\tglobal DRYE#(10,28)\n\tglobal DRZE#(10,28)\n\tglobal DRX#(10,28)\n\tglobal DRY#(10,28)\n\tglobal DRZ#(10,28)\n\t#COMMON/CALCAS1B/\n\tglobal IONSUM1#(10)\n\tglobal IFLSUM1#(10)\n\tglobal ESTOR1#(10,28)\n\tglobal EPHOTG1#(10,28)\n\tglobal DRXE1#(10,28)\n\tglobal DRYE1#(10,28)\n\tglobal DRZE1#(10,28)\n\tglobal DRX1#(10,28)\n\tglobal DRY1#(10,28)\n\tglobal DRZ1#(10,28)\n\t#COMMON/CALCAS2B/\n\tglobal IONSUM2#(10)\n\tglobal IFLSUM2#(10)\n\tglobal ESTOR2#(10,28)\n\tglobal EPHOTG2#(10,28)\n\tglobal DRXE2#(10,28)\n\tglobal DRYE2#(10,28)\n\tglobal DRZE2#(10,28)\n\tglobal DRX2#(10,28)\n\tglobal DRY2#(10,28)\n\tglobal DRZ2#(10,28)\n\t#COMMON/CALCAS3B/\n\tglobal IONSUM3#(10)\n\tglobal IFLSUM3#(10)\n\tglobal ESTOR3#(10,28)\n\tglobal EPHOTG3#(10,28)\n\tglobal DRXE3#(10,28)\n\tglobal DRYE3#(10,28)\n\tglobal DRZE3#(10,28)\n\tglobal DRX3#(10,28)\n\tglobal DRY3#(10,28)\n\tglobal DRZ3#(10,28)\n\t#COMMON/CALCAS4B/\n\tglobal IONSUM4#(10)\n\tglobal IFLSUM4#(10)\n\tglobal ESTOR4#(10,28)\n\tglobal EPHOTG4#(10,28)\n\tglobal DRXE4#(10,28)\n\tglobal DRYE4#(10,28)\n\tglobal DRZE4#(10,28)\n\tglobal DRX4#(10,28)\n\tglobal DRY4#(10,28)\n\tglobal DRZ4#(10,28)\n\t#COMMON/CALCAS5B/\n\tglobal IONSUM5#(10)\n\tglobal IFLSUM5#(10)\n\tglobal ESTOR5#(10,28)\n\tglobal EPHOTG5#(10,28)\n\tglobal DRXE5#(10,28)\n\tglobal DRYE5#(10,28)\n\tglobal DRZE5#(10,28)\n\tglobal DRX5#(10,28)\n\tglobal DRY5#(10,28)\n\tglobal DRZ5#(10,28)\n\t#COMMON/RESB/\n\tglobal IONSM#(10)\n\tglobal IFLSM#(10)\n\tglobal ESTOR#(10,28)\n\tglobal EPHOT#(10,28)\n\tglobal X10#(10,28)\n\tglobal Y10#(10,28)\n\tglobal Z10#(10,28)\n\tglobal DRX01#(10,28)\n\tglobal DRY01#(10,28)\n\tglobal DRZ01#(10,28)\n\t#COMMON/GENB1/\n\tglobal IONF1#(10)\n\tglobal ESTF1#(10,28)\n\tglobal X11#(10,28)\n\tglobal Y11#(10,28)\n\tglobal Z11#(10,28)\n\tglobal DRX11#(10,28)\n\tglobal DRY11#(10,28)\n\tglobal DRZ11#(10,28)\n\t#COMMON/GENB2/\n\tglobal IONF2#(10)\n\tglobal ESTF2#(10,28)\n\tglobal X21#(10,28)\n\tglobal Y21#(10,28)\n\tglobal Z21#(10,28)\n\tglobal DRX21#(10,28)\n\tglobal DRY21#(10,28)\n\tglobal DRZ21#(10,28)\n\t#COMMON/GENB3/\n\tglobal IONF3#(10)\n\tglobal ESTF3#(10,15)\n\tglobal X31#(10,15)\n\tglobal Y31#(10,15)\n\tglobal Z31#(10,15)\n\tglobal DRX31#(10,15)\n\tglobal DRY31#(10,15)\n\tglobal DRZ31#(10,15)\n\t#COMMON/GENB4/\n\tglobal IONF4#(10)\n\tglobal ESTF4#(10,12)\n\tglobal X41#(10,12)\n\tglobal Y41#(10,12)\n\tglobal Z41#(10,12)\n\tglobal DRX41#(10,12)\n\tglobal DRY41#(10,12)\n\tglobal DRZ41#(10,12)\n\t#COMMON/GENB5/\n\tglobal IONF5#(10)\n\tglobal ESTF5#(10,5)\n\tglobal X51#(10,5)\n\tglobal Y51#(10,5)\n\tglobal Z51#(10,5)\n\tglobal DRX51#(10,5)\n\tglobal DRY51#(10,5)\n\tglobal DRZ51#(10,5)\n\t#COMMON/COUTE/\n\tglobal ECMP#(10)\n\tglobal ECDRX#(10)\n\tglobal ECDRY#(10)\n\tglobal ECDRZ#(10)\n\tglobal XCPOS#(10)\n\tglobal YCPOS#(10)\n\tglobal ZCPOS#(10)\n\tglobal KCGAS#(10)\n\tglobal LCGAS#(10)\n\tglobal ICSHELL#(10)\n\t#COMMON/COUTTB/\n\tglobal TT#(10)\n\tglobal TTP\n\t#COMMON/PPSTRB/\n\tglobal NPTP\n\tglobal EPPST#(2)\n\tglobal XPP#(2)\n\tglobal YPP#(2)\n\tglobal ZPP#(2)\n\tglobal DRXPP#(2)\n\tglobal DRYPP#(2)\n\tglobal DRZPP#(2)\n\t#----------------------------------------------------------------------\n\t# BREMSSTRAHLUNG CASCADE TREE:\n\t# SET OR ZERO SOME VARIABLES \n\t# CREATE INTERACTION TREE FOR PE COMPTON RAYLEIGH AND PAIR PRODUCTION\n\t# STORE ELECTRON ENERGY DIRECTION COSINES AND POSITION WITH SHELL\n\t# LEVEL AND GAS IDENTITY IN COMMON/COUT/ FOR EACH COMPTON AND PE EVENT\n\t# STORE PAIR PRODUCTION ELECTRON AND POSITRON DATA IN COMMON/PPSTR/\n\t# STORE FINAL CASCADE RESULTS IN COMMON/CASRSB/\n\t#----------------------------------------------------------------------\n\tAPI=numpy.arccos(-1.00)\n\tTWOPI=2.00*API\n\tIDBG=0\n\t# IF(J11 == 2) IDBG=1\n\tdef GOTO5():\n\t\tILOW=0\n\t\t# USE VELOCITY IN METRES/PICOSECONDS\n\t\tVV=2.99792458E-4 \n\t\t# \n\t\tLFIX=0\n\t\t# ALLOW FLUORESCENCE CALCULATION\n\t\tdef GOTO123():\n\t\t\tICONPH=1\n\t\t\t# PHOTON ORIGIN\n\t\t\tX=X0\n\t\t\tY=Y0\n\t\t\tZ=Z0\n\t\t\tTSUM=T0\n\t\t\t# LOAD INITIAL DIRECTION COSINES BEFORE INTERACTION \n\t\t\tDRXS=GDCX\n\t\t\tDRYS=GDCY\n\t\t\tDRZS=GDCZ\n\t\t\t# INITIAL ENERGY\n\t\t\tENERGY=EGAMMA\n\t\t\t#\n\t\t\t# ZERO SOME ARRAYS\n\t\t\tEPPST[1]=0.00\n\t\t\tEPPST[2]=0.00\n\t\t\tfor K in range(1,10):\n\t\t\t\tfor J in range(1,28):\n\t\t\t\t\tEPHOTON[K][J]=0.0\n\t\t\t\t\tEPHOTG1[K][J]=0.0\n\t\t\t\t\tEPHOTG2[K][J]=0.0\n\t\t\t\t\tEPHOTG3[K][J]=0.0\n\t\t\t\t\tEPHOTG4[K][J]=0.0\n\t\t\t\t\tEPHOTG5[K][J]=0.0\n\t\t\t\t\tESTORE[K][J]=0.0\n\t\t\t\t\tESTOR1[K][J]=0.0\n\t\t\t\t\tESTOR2[K][J]=0.0\n\t\t\t\t\tESTOR3[K][J]=0.0\n\t\t\t\t\tESTOR4[K][J]=0.0\n\t\t\t\t\tESTOR5[K][J]=0.0\n\t\t\t\t\tESTOR[K][J]=0.0\n\t\t\t\t\tESTF1[K][J]=0.0\n\t\t\t\t\tESTF2[K][J]=0.0\n\t\t\t\tfor J in range(1,15):\n\t\t\t\t\tESTF3[K][J]=0.0\n\t\t\t\tfor J in range(1,12):\n\t\t\t\t\tESTF4[K][J]=0.0\n\t\t\t\tfor J in range(1,5):\n\t\t\t\t\tESTF5[K][J]=0.0\n\t\t\t\tIFLSUM[K]=0\n\t\t\t\tIFLSUM1[K]=0\n\t\t\t\tIFLSUM2[K]=0\n\t\t\t\tIFLSUM3[K]=0\n\t\t\t\tIFLSUM4[K]=0\n\t\t\t\tIFLSUM5[K]=0\n\t\t\t\tIONSUM[K]=0\n\t\t\t\tIONSUM1[K]=0\n\t\t\t\tIONSUM2[K]=0\n\t\t\t\tIONSUM3[K]=0\n\t\t\t\tIONSUM4[K]=0\n\t\t\t\tIONSUM5[K]=0\n\t\t\t\tIONSM[K]=0\n\t\t\t\tIONF1[K]=0\n\t\t\t\tIONF2[K]=0\n\t\t\t\tIONF3[K]=0\n\t\t\t\tIONF4[K]=0\n\t\t\t\tIONF5[K]=0\n\t\t\t\tKCGAS[K]=0\n\t\t\t\tLCGAS[K]=0\n\t\t\t\tICSHELL[K]=0\n\t\t\t\tECMP[K]=0.0\n\t\t\tNCOMP=0\n\t\t\tNRAYL=0\n\t\t\tNPAIR=0\n\t\t\tNPHOT=0\n\t\t\tNVAC=0\n\t\t\tNPTP=0\n\t\t\t# \n\t\t\tIFIRST=1\n\t\t\tISECOND=2\n\t\t\tdef GOTO2(): \n\t\t\t\tNTOTI=NCOMP+NRAYL+NPAIR+NPHOT\n\t\t\t\t# PHOTONS\n\t\t\t\tABSO(IFIRST,ENERGY,ISHELL,KGAS,LGAS,DIST)\n\t\t\t\t# IF(IDBG == 1) :\n\t\t\t\t# WRITE(6,888) ENERGY,ISHELL,J11\n\t\t\t\t# 888 print(' AFTER ABSO ENERGY=',D12.5,' ISHELL=',I3,' EVENT NO=',I4)\n\t\t\t\t# # endIF\n\t\t\t\tif(ISHELL == -1):\n\t\t\t\t\t# BREMSSTRAHLUNG GAMMA TOO LOW IN ENERGY TO IONISE\n\t\t\t\t\tILOW=1\n\t\t\t\t\treturn\n\t\t\t\t# endif\n\t\t\t\t# \n\t\t\t\t# CREATE INTERACTION TREE\n\t\t\t\tflag=0\n\t\t\t\tif(LPEFLG == 1):\n\t\t\t\t\tflag=100\n\t\t\t\tif(LCFLG == 1):\n\t\t\t\t\tflag=10\t\t\t###############################\n\t\t\t\telif(LRFLG == 1):\t##\t\t\t\t\t\t\t ##\n\t\t\t\t\tflag=20\t\t\t## Made significant changes ##\n\t\t\t\telif(LPFLG == 1):\t##\t\t\t\t\t\t\t ##\n\t\t\t\t\tflag=30\t\t\t###############################\n\t\t\t\t# COMPTON SCATTERING\n\t\t\t\tif(flag==10 or flag==0): \n\t\t\t\t\tCOMPTON(KGAS,LGAS,ENERGY)\n\t\t\t\t\tNCOMP=NCOMP+1\n\t\t\t\t\tNVAC=NVAC+1\n\t\t\t\t\tif(NVAC > 10):\n\t\t\t\t\t\t# MAXIMUM OF 10 PRIMARY INTERACTIONS\n\t\t\t\t\t\t# NJHIGH=NJHIGH+1\n\t\t\t\t\t\tGOTO123()\n\t\t\t\t\t# endif\n\t\t\t\t\t# RANDOMISE ANGLE PHI\n\t\t\t\t\tR3=DRAND48(RDUM)\n\t\t\t\t\tPHI=TWOPI*R3\n\t\t\t\t\t# CALCULATE COMPTON ELECTRON DIRECTION COSINES USING THETAE AND PHI\n\t\t\t\t\tDRCOS(DRXS,DRYS,DRZS,THETAE,PHI,DRXX,DRYY,DRZZ)\n\t\t\t\t\t# FOR COMPTON EFFECT STORE ELECTRON DIRECTION COSINES\n\t\t\t\t\tECDRX[NVAC]=DRXX\n\t\t\t\t\tECDRY[NVAC]=DRYY\n\t\t\t\t\tECDRZ[NVAC]=DRZZ\n\t\t\t\t\t# CALCULATE WHICH SHELL HAS VACANCY FROM COMPTON EVENT\n\t\t\t\t\tCVAC(KGAS,LGAS,EELEC,KSHELL,KBAD)\n\t\t\t\t\t# REJECT EVENT WITHOUT SUFFICIENT ENERGY TO IONISE SHELLS\n\t\t\t\t\tif(KBAD == 1):\n\t\t\t\t\t\tGOTO123()\n\t\t\t\t\t# STORE ELECTRON ENERGY SHELL VACANCY ISHELL KGAS LGAS POSITION \n\t\t\t\t\tECMP[NVAC]=EELEC\n\t\t\t\t\tICSHELL[NVAC]=KSHELL\n\t\t\t\t\tKCGAS[NVAC]=KGAS\n\t\t\t\t\tLCGAS[NVAC]=LGAS\n\t\t\t\t\t# INTERACTION POSITIONS\n\t\t\t\t\tXCPOS[NVAC]=X+DIST*DRXS\n\t\t\t\t\tYCPOS[NVAC]=Y+DIST*DRYS\n\t\t\t\t\tZCPOS[NVAC]=Z+DIST*DRZS\n\t\t\t\t\tTT[NVAC]=TSUM+DIST/VV \n\t\t\t\t\t# UPDATE PHOTON STARTING ENERGY POSITION AND ANGLES\n\t\t\t\t\tENERGY=EGAM\n\t\t\t\t\tX=XCPOS[NVAC]\n\t\t\t\t\tY=YCPOS[NVAC]\n\t\t\t\t\tZ=ZCPOS[NVAC]\n\t\t\t\t\tPHIG=PHI+API\n\t\t\t\t\tif(PHIG >= TWOPI):\n\t\t\t\t\t\tPHIG=PHI-API\n\t\t\t\t\tDRCOS(DRXS,DRYS,DRZS,THETAG,PHIG,DRXX,DRYY,DRZZ)\n\t\t\t\t\t# NEW DIRECTION COSINES\n\t\t\t\t\tDRXS=DRXX\n\t\t\t\t\tDRYS=DRYY\n\t\t\t\t\tDRZS=DRZZ\n\t\t\t\t\t# LOOP BACK \n\t\t\t\t\tGOTO2()\n\t\t\t\t\t\n\t\t\t\tif(flag==20 or flag==0):\n\t\t\t\t\t# RAYLEIGH SCATTERING\n\t\t\t\t\tRAYLEIGH(KGAS,LGAS,ENERGY,THETAR)\n\t\t\t\t\tNRAYL=NRAYL+1\n\t\t\t\t\t# CALCULATE ENERGY LOSS IN RAYLEIGH SCATTERING\n\t\t\t\t\tRAYLOS(KGAS,LGAS,ENERGY,THETAR,ELRAY)\n\t\t\t\t\t# IF(IDBG == 1) WRITE(6,776) ENERGY,ELRAY\n\t\t\t\t\t# 776 print(' AFTER RAYLOS ENERGY=','%.4f' % ,' ELRAY=','%.4f' % )\n\t\t\t\t\t# UPDATE X-RAY STARTING ENERGY POSITION AND ANGLES\n\t\t\t\t\tENERGY=ENERGY-ELRAY\n\t\t\t\t\tX=X+DIST*DRXS\n\t\t\t\t\tY=Y+DIST*DRYS\n\t\t\t\t\tZ=Z+DIST*DRZS\n\t\t\t\t\tTSUM=TSUM+DIST/VV\n\t\t\t\t\t# RANDOMISE ANGLE PHI\n\t\t\t\t\tR3=DRAND48(RDUM)\n\t\t\t\t\tPHIR=TWOPI*R3\n\t\t\t\t\tDRCOS(DRXS,DRYS,DRZS,THETAR,PHIR,DRXX,DRYY,DRZZ)\n\t\t\t\t\tDRXS=DRXX\n\t\t\t\t\tDRYS=DRYY\n\t\t\t\t\tDRZS=DRZZ\n\t\t\t\t\t# LOOP BACK\n\t\t\t\t\tGOTO2()\n\t\t\t\t\n\t\t\t\tif(flag==30 or flag==0): \n\t\t\t\t\t# PAIR PRODUCTION\n\t\t\t\t\tPAIR(KGAS,LGAS,ENERGY,E1,E2,THET1,PHI1,THET2,PHI2)\n\t\t\t\t\tNPAIR=NPAIR+1\n\t\t\t\t\tif(NPAIR > 2):\n\t\t\t\t\t\tprint(' ERROR NPAIR GT 2 =',NPAIR,' IN BREMSCASC EVENT NO =',J11)\n\t\t\t\t\t\tsys.exit()\n\t\t\t\t\t# endif\n\t\t\t\t\tNPTP=NPAIR\n\t\t\t\t\t# STORE ELECTRON AND POSITRON ENERGY POSITION AND ANGLES\n\t\t\t\t\tEPPST[1]=E1\n\t\t\t\t\tEPPST[2]=E2\n\t\t\t\t\tif(NVAC == 0):\n\t\t\t\t\t\t# FIRST INTERACTION IS PAIR PRODUCTION\n\t\t\t\t\t\tXPP[1]=X\n\t\t\t\t\t\tYPP[1]=Y\n\t\t\t\t\t\tZPP[1]=Z\n\t\t\t\t\t\tXPP[2]=X\n\t\t\t\t\t\tYPP[2]=Y\n\t\t\t\t\t\tZPP[2]=Z\n\t\t\t\t\t\tTTP=TSUM\n\t\t\t\t\t\tpass\n\t\t\t\t\t# endif\n\t\t\t\t\telse:\n\t\t\t\t\t\tXPP[1]=X+DIST*DRXS\n\t\t\t\t\t\tYPP[1]=Y+DIST*DRYS\n\t\t\t\t\t\tZPP[1]=Z+DIST*DRZS\n\t\t\t\t\t\tXPP[2]=XPP[1]\n\t\t\t\t\t\tYPP[2]=YPP[1]\n\t\t\t\t\t\tZPP[2]=ZPP[1]\n\t\t\t\t\t\tTTP=TSUM+DIST/VV\n\t\t\t\t\tDRCOS(DRXS,DRYS,DRZS,THET1,PHI1,DRXX,DRYY,DRZZ)\n\t\t\t\t\tDRXPP[1]=DRXX\n\t\t\t\t\tDRYPP[1]=DRYY\n\t\t\t\t\tDRZPP[1]=DRZZ\n\t\t\t\t\tDRCOS(DRXS,DRYS,DRZS,THET2,PHI2,DRXX,DRYY,DRZZ)\n\t\t\t\t\tDRXPP[2]=DRXX\n\t\t\t\t\tDRYPP[2]=DRYY\n\t\t\t\t\tDRZPP[2]=DRZZ\n\t\t\t\t\tflag=200\n\t\t\t\t\t# PHOTOELECTRIC ABSORPTION\n\t\t\t\t\t# STORE ENERGY ISHELL KGAS\n\t\t\t\tif(flag==100 or flag==0): \n\t\t\t\t\tNVAC=NVAC+1\n\t\t\t\t\tif(NVAC > 10):\n\t\t\t\t\t\t# ONLY ALLOW MAXIMUM OF 10 PRIMARY INTERACTIONS\n\t\t\t\t\t\tGOTO123()\n\t\t\t\t\t\tsys.exit()\n\t\t\t\t\t# endif\n\t\t\t\t\n\t\t\t\t\tNPHOT=NPHOT+1\n\t\t\t\t\t# ECMP= TOTAL ENERGY= EGAMMA = ELECTRON KINETIC ENERGY+ VACANCY ENERGY\n\t\t\t\t\tECMP[NVAC]=ENERGY\n\t\t\t\t\tICSHELL[NVAC]=ISHELL\n\t\t\t\t\tXCPOS[NVAC]=X+DIST*DRXS\n\t\t\t\t\tYCPOS[NVAC]=Y+DIST*DRYS\n\t\t\t\t\tZCPOS[NVAC]=Z+DIST*DRZS\n\t\t\t\t\tTT[NVAC]=TSUM+DIST/VV\n\t\t\t\t\tKCGAS[NVAC]=KGAS\n\t\t\t\t\tLCGAS[NVAC]=LGAS\n\t\t\t\t\t# FOR PE EFFECT STORE PHOTON INCIDENT ANGLE\n\t\t\t\t\tECDRX[NVAC]=DRXS\n\t\t\t\t\tECDRY[NVAC]=DRYS\n\t\t\t\t\tECDRZ[NVAC]=DRZS\n\t\t\t\t# LOOP OVER SHELL VACANCIES\n\t\t\t\tif(flag==200 or flag==0):\n\t\t\t\t\t# STORE NUMBER AND TYPE OF PRIMARY INTERACTIONS\n\t\t\t\t\tMSUM1=NTOTI\n\t\t\t\t\tMCOMP1=NCOMP\n\t\t\t\t\tMRAYL1=NRAYL\n\t\t\t\t\tMPAIR1=NPAIR\n\t\t\t\t\tMPHOT1=NPHOT\n\t\t\t\t\tMVAC1=NVAC\n\t\t\t\t\t# LOOP OVER SHELL INTERACTIONS\n\t\t\t\t\t# IF(IDBG == 1) :\n\t\t\t\t\t# WRITE(6,54) NVAC\n\t\t\t\t\t# 54 print(' NVAC=',I3)\n\t\t\t\t\t# for 6 in range(M1=1,NVAC):\n\t\t\t\t\t# WRITE(6,55) M1, (ESTORE(M1,K1),K1=1,28)\n\t\t\t\t\t# 55 print(' M1=',I3,/,' ESTORE(M1,K)=',4(7'%.4f' % ,/))\n\t\t\t\t\t# 56 CONTINUE\n\t\t\t\t\t# for 8 in range(M1=1,NVAC):\n\t\t\t\t\t# WRITE(6,57) (EPHOTON(M1,K1),K1=1,28)\n\t\t\t\t\t# 57 print(' EPHOTON=',4(7'%.4f' % ,/))\n\t\t\t\t\t# 58 CONTINUE \n\t\t\t\t\t# # endIF\n\t\t\t\t\tfor K in range(1,NVAC):\n\t\t\t\t\t\tCONTROLB(IDBG,K)\n\t\t\t\t\t# COMPRESS AUGER AND FLUORESCENCE DATA INTO BLOCKS\n\t\t\t\t\tCOMPRESS(IDBG,ENSUM)\n\t\t\t\t\t# CATCH DROPPED KSHELL FLUORESCENCE\n\t\t\t\t\tif(abs(ENSUM-EGAMMA)> 2200.) :\n\t\t\t\t\t\tDIF=ENSUM-EGAMMA\n\t\t\t\t\tif(IDBG == 1):\n\t\t\t\t\t\tprint('\\n Dif=','%.6f' % DIF,' J11=',J11,'\\n') \n\t\t\t\t\t\tGOTO5()\n\t\t\t\t\t# endif\n\t\t\t\t\t# ADD PAIR DATA AND LOAD INTO COMMON/CASRSB/\n\t\t\t\t\tCASRESB()\n\t\t\tGOTO2()\n\t\tGOTO123()\n\tGOTO5()\n\treturn\n\t# end", "meta": {"hexsha": "c7ce37fa095caca47ad15aebc0ebb4eb1ea2bef4", "size": 13488, "ext": "py", "lang": "Python", "max_stars_repo_path": "Bremscasc.py", "max_stars_repo_name": "fireballpoint1/fortranTOpy", "max_stars_repo_head_hexsha": "55843a62c6f0a2f8e2a777ef70193940d3d2d141", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-26T05:10:56.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-26T05:10:56.000Z", "max_issues_repo_path": "Bremscasc.py", "max_issues_repo_name": "fireballpoint1/fortranTOpy", "max_issues_repo_head_hexsha": "55843a62c6f0a2f8e2a777ef70193940d3d2d141", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Bremscasc.py", "max_forks_repo_name": "fireballpoint1/fortranTOpy", "max_forks_repo_head_hexsha": "55843a62c6f0a2f8e2a777ef70193940d3d2d141", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-06-26T18:06:44.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-26T18:06:44.000Z", "avg_line_length": 27.5265306122, "max_line_length": 146, "alphanum_fraction": 0.6172153025, "include": true, "reason": "import numpy", "num_tokens": 6291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.20946967639529512, "lm_q1q2_score": 0.13038635761019154}} {"text": "# Standard library\nimport os\n\n# Third-party\nimport numpy as np\nfrom numpy.lib.recfunctions import append_fields\nfrom scipy.integrate import quad\nfrom scipy.interpolate import interp1d\nfrom astropy.table import Table\nfrom astropy import units as u\n\n# Project\nfrom ._read_mist_models import IsoCmdReader, IsoReader\nfrom .imf import imf_dict, IMFIntegrator\nfrom .. import MIST_PATH\nfrom ..log import logger\nfrom ..filters import phot_system_list, get_filter_names\nfrom ..filters import load_zero_point_converter\nfrom ..util import check_units, fetch_mist_grid_if_needed\nphot_str_helper = {p.lower():p for p in phot_system_list}\n\n\n__all__ = ['fetch_mist_iso_cmd', 'Isochrone', 'MISTIsochrone']\n\n\nclass Isochrone(object):\n \"\"\"\n Class for storing generic isochrones. It also has methods for calculating\n IMF-weighted properties of a simple stellar population with the given\n age and metallicity.\n\n Parameters\n ----------\n mini : `~numpy.ndarray`\n Initial stellar masses. The masses must be monotonically increasing.\n mact : `~numpy.ndarray`\n Actual stellar masses after mass loss.\n mag_table : `~astropy.table.Table`, dict, or structured `~numpy.ndarray`\n The stellar magnitudes.\n eep : `~numpy.ndarray`, optional\n The Primary Equivalent Evolutionary Points. Needed to identify phases\n of stellar evolution.\n log_L : `~numpy.ndarray`, optional\n Stellar luminosities.\n log_Teff : `~numpy.ndarray`, optional\n Stellar effective temperatures.\n \"\"\"\n\n def __init__(self, mini, mact, mags, eep=None, log_L=None,\n log_Teff=None):\n self.mini = np.asarray(mini)\n self.mact = np.asarray(mact)\n if (np.diff(self.mini) < 0).sum() > 0:\n raise Exception('Initial masses must be monotonically increasing.')\n self.eep = None if eep is None else np.asarray(eep)\n self.log_L = None if log_L is None else np.asarray(log_L)\n self.log_Teff = None if log_Teff is None else np.asarray(log_Teff)\n if type(mags) == dict or type(mags) == np.ndarray:\n self.mag_table = Table(mags)\n elif type(mags) == Table:\n self.mag_table = mags\n else:\n raise Exception(f'{type(mags)} is not a valid type for mags')\n\n @property\n def m_min(self):\n \"\"\"The minimum mass of the isochrone.\"\"\"\n return self.mini.min()\n\n @property\n def m_max(self):\n \"\"\"The maximum mass of the isochrone.\"\"\"\n return self.mini.max()\n\n @property\n def filters(self):\n \"\"\"List of filters in the given photometric system(s).\"\"\"\n return self.mag_table.colnames\n\n @staticmethod\n def from_parsec(file_name, log_age=None, zini=None, num_filters=None):\n \"\"\"\n Read isochrone generated from the `PARSEC website\n `_. If more than one age and/or\n metallicity is included in the file, you must provide the log_age\n and/or zini parameters.\n\n\n Parameters\n ----------\n file_name : str\n Isochrone file name.\n log_age : float, optional\n Log of age in years. You must provided this parameter if there is\n more than one age in the isochrone file. Note this function does\n not interpolate ages, so it must be included in the file.\n zini : float, optional\n Initial metal fraction. You must provided this parameter if there\n is more than one metallicity in the isochrone file. Note this\n function does not interpolate metallicity, so it must be included\n in the file.\n num_filters : int, optional\n Number of filters included in the isochrone file. If None, will\n assume the last non-filter parameter is `mbolmag`.\n\n Returns\n -------\n iso : `artpop.stars.Isochrone`\n PARSEC Isochrone object.\n \"\"\"\n if os.path.isfile(file_name):\n file = open(file_name, 'r')\n lines = file.readlines()\n file.close()\n for l in lines:\n if 'Zini' in l.split()[1]:\n names = l.split()[1:]\n break\n data = np.loadtxt(file_name)\n parsec = Table(data, names=names)\n else:\n raise Exception(f'{file_name} does not exist.')\n isochrone_full = parsec.copy()\n if log_age is not None:\n age_cut = np.abs(parsec['logAge'] - log_age) < 1e-5\n if age_cut.sum() < 1:\n raise Exception(f'log_age = {log_age} not found.')\n parsec = parsec[age_cut]\n if zini is not None:\n zini_cut = np.abs(parsec['Zini'] - zini) < 1e-8\n if zini_cut.sum() < 1:\n raise Exception(f'Zini = {zini} not found.')\n parsec = parsec[zini_cut]\n if num_filters is None:\n filt_idx = np.argwhere(np.array(names) == 'mbolmag')[0][0] + 1\n else:\n filt_idx = len(names) - num_filters\n iso = Isochrone(mini=parsec['Mini'],\n mact=parsec['Mass'],\n mags=parsec[names[filt_idx:]],\n log_L=parsec['logL'],\n log_Teff=parsec['logTe'])\n iso.isochrone_full = isochrone_full\n return iso\n\n def interpolate(self, y_name, x_interp, x_name='mini',\n slice_interp=np.s_[:], **kwargs):\n \"\"\"\n Interpolate isochrone.\n\n Parameters\n ----------\n y_name : str\n Parameter name of interpolated variable.\n x_interp : `~numpy.ndarray`\n New x values to interpolate over.\n x_name : str\n Parameter name of x values. Usually want this to be initial mass.\n\n Returns\n -------\n y_interp : `~numpy.ndarray`\n Interpolated y values.\n \"\"\"\n x = self.mag_table[x_name] if x_name in self.filters\\\n else getattr(self, x_name)\n y = self.mag_table[y_name] if y_name in self.filters\\\n else getattr(self, y_name)\n x = x[slice_interp]\n y = y[slice_interp]\n y_interp = interp1d(x, y, **kwargs)(x_interp)\n return y_interp\n\n def mag_to_mass(self, mag, bandpass):\n \"\"\"\n Interpolate isochrone to calculate initial stellar masses that have\n the given magnitude. Since more than one mass can have the same\n magnitude (from stars being in different phases of stellar evolution),\n we step through each isochrone and check if the given magnitude falls\n between two bins, in which case we interpolate the associated mass.\n\n Parameters\n ----------\n mag : float\n Magnitude to be converted in to stellar mass(es).\n bandpass : str\n Photometric bandpass of the `mag`.\n\n Returns\n -------\n mass_interp : `~numpy.ndarray`\n Interpolated mass(es) associated with `mag`.\n \"\"\"\n y = self.mini\n x = self.mag_table[bandpass]\n\n if mag < x.min() or mag > x.max():\n raise Exception(f'mag = {mag} is outside the isochrone range.')\n\n y_interp = []\n # Loop over isochrone and check if desired magnitude is in between two\n # bins. If it is, interpolate the mass. Looping like this is necessary\n # because different masses can have the same magnitude due to\n # being at different phases of stellar evolution.\n for i in range(len(x)):\n if x[i] == mag:\n y_interp.append(y[i])\n continue\n if i < len(x) - 1:\n _x = [x[i], x[i + 1]]\n _y = [y[i], y[i + 1]]\n dx = x[i + 1] - x[i]\n if dx > 0:\n if (mag <= x[i + 1]) and (mag > x[i]):\n y_interp.append(interp1d(_x, _y)([mag])[0])\n else:\n if (mag >= x[i + 1]) and (mag < x[i]):\n y_interp.append(interp1d(_x, _y)([mag])[0])\n mass_interp = np.array(y_interp)\n\n return mass_interp\n\n def calculate_mag_limit(self, imf, bandpass, frac_mass_sampled=None,\n frac_num_sampled=None, distance=10*u.pc):\n \"\"\"\n Calculate the limiting faint magnitude to sample a given fraction\n of mass or number of a stellar population. This is used for when you\n only what to sample stars that are brighter than a magnitude limit.\n You must specify either `frac_mass_sampled` or `frac_num_sampled`.\n\n .. note::\n You must give `frac_mass_sampled` *or* `frac_num_sampled`.\n\n Parameters\n ----------\n imf : str\n Name for the IMF.\n bandpass : str\n Observation bandpass of the limiting magnitude.\n frac_mass_sampled: float, optional\n Fraction of mass that will be sampled if only stars that are\n brighter than the magnitude limit are sampled.\n frac_num_sampled: float, optional\n Fraction of stars by number that will be sampled if only stars that\n are brighter than the magnitude limit are sampled.\n distance : float or `~astropy.units.Quantity`, optional\n Distance to source. If float is given, the units are assumed\n to be `~astropy.units.Mpc`. Default distance is 10\n `~astropy.units.pc` (i.e., the mags are in absolute units).\n\n Returns\n -------\n mag_limit : float\n The desired limiting magnitude.\n mass_limit : float\n Mass of stars (in solar masses) that have the limiting magnitude.\n \"\"\"\n mfint = IMFIntegrator(imf, self.m_min, self.m_max)\n m_vals = np.logspace(np.log10(self.m_min), np.log10(self.m_max), 500)\n err_msg = 'You must give a fraction such that 0 < fraction <= 1.'\n if frac_mass_sampled is not None:\n assert frac_mass_sampled > 0 and frac_mass_sampled <= 1, err_msg\n frac_interp = frac_mass_sampled\n fracs = [mfint.m_integrate(_m, self.m_max, True) for _m in m_vals]\n elif frac_num_sampled is not None:\n assert frac_num_sampled > 0 and frac_num_sampled <= 1, err_msg\n frac_interp = frac_num_sampled\n fracs = [mfint.integrate(_m, self.m_max, True) for _m in m_vals]\n else:\n msg = 'You must give either frac_mass_sampled or frac_num_sampled.'\n raise Exception(msg)\n d = check_units(distance, 'Mpc')\n mass_limit = interp1d(fracs, m_vals)([frac_interp])[0]\n mag_limit = self.interpolate(bandpass, [mass_limit])[0]\n mag_limit = mag_limit + 5 * np.log10(d.to('pc').value) - 5\n return mag_limit, mass_limit\n\n def nearest_mini(self, m):\n \"\"\"\n Find the nearest mass to `m` in the initial mass array.\n\n Parameters\n ----------\n m : float:\n The mass for which we want the nearest initial mass.\n\n Returns\n -------\n m_nearest : float\n Value of the nearest mass.\n arg_nearest : int\n Argument of the nearest mass.\n \"\"\"\n arg_nearest = np.abs(self.mini - m).argmin()\n m_nearest = self.mini[arg_nearest]\n return m_nearest, arg_nearest\n\n def imf_weights(self, imf, m_min_norm=None, m_max_norm=None,\n norm_type='mass', **kwargs):\n \"\"\"\n Calculate IMF weights.\n\n Parameters\n ----------\n imf : str or callable function that takes mass as its argument\n Stellar Initial mass function.\n m_min_norm : None or float, optional\n Minimum mass for the normalization. Must be less than or equal to\n the mini mass of isochrone, which will be used if None is given.\n m_max_norm : float, optional\n Maximum mass for normalization.\n norm_type : str, optional\n Type of IMF normalization (mass or number).\n\n Returns\n -------\n wght : `~numpy.ndarray`\n IMF weights calculated such that an integral over mass is simply\n given by SUM(m * wght).\n \"\"\"\n m_min = m_min_norm if m_min_norm else self.mini.min()\n m_max = m_max_norm if m_max_norm else self.mini.max()\n if m_min > self.m_min:\n raise Exception('Minimum mass must be <= isochrone min mass.')\n if callable(imf):\n imf_func = imf\n else:\n imf_func = lambda m: imf_dict[imf](m, norm_type=None)\n m_imf_func = lambda m: m * imf_func(m)\n norm_func = dict(mass=m_imf_func, number=imf_func)[norm_type]\n norm = quad(norm_func, m_min, m_max, **kwargs)[0]\n\n wght = []\n mini = self.mini\n # Assume mass is constant in each bin and integrate.\n # This means an integral over mass is simply SUM(m * wght)\n # This trick was stolen from Charlie Conroy's FSPS code :)\n for i in range(len(mini)):\n if i == 0:\n m1 = m_min\n else:\n m1 = mini[i] - 0.5 * (mini[i] - mini[i-1])\n if i == len(mini) - 1:\n m2 = mini[i]\n else:\n m2 = mini[i] + 0.5 * (mini[i+1] - mini[i])\n if m2 < m1:\n raise Exception('Masses must be monotonically increasing.')\n wght.append(quad(imf_func, m1, m2, **kwargs)[0])\n wght = np.array(wght) / norm\n return wght\n\n def ssp_color(self, blue, red, imf='kroupa', **kwargs):\n \"\"\"\n Calculate IMF-weighted integrated color.\n\n Parameters\n ----------\n blue : str\n Blue bandpass.\n red : str\n Red bandpass.\n imf : str, optional\n IMF name.\n\n Returns\n -------\n color : float\n Integrated color of stellar population.\n \"\"\"\n wght = self.imf_weights(imf, **kwargs)\n lum_blue = np.sum(wght * 10**(-0.4 * self.mag_table[blue]))\n lum_red = np.sum(wght * 10**(-0.4 * self.mag_table[red]))\n color = -2.5 * np.log10(lum_blue / lum_red)\n return color\n\n def ssp_sbf_mag(self, bandpass, imf='kroupa', **kwargs):\n \"\"\"\n Calculate IMF-weighted SBF magnitude.\n\n Parameters\n ----------\n bandpass : str\n Bandpass to of SBF mag.\n imf : str, optional\n IMF name.\n\n Returns\n -------\n sbf : float\n SBF magnitude of stellar population.\n \"\"\"\n wght = self.imf_weights(imf, **kwargs)\n lumlum = np.sum(wght * 10**(-0.8 * self.mag_table[bandpass]))\n lum = np.sum(wght * 10**(-0.4 * self.mag_table[bandpass]))\n sbf = -2.5 * np.log10(lumlum / lum)\n return sbf\n\n def ssp_mag(self, bandpass, imf='kroupa', norm_type='mass', **kwargs):\n \"\"\"\n Calculate IMF-weighted magnitude.\n\n Parameters\n ----------\n bandpass : str\n Bandpass to of mean mag.\n imf : str, optional\n IMF name.\n norm_type : str, optional\n Normalization type (mass or number)\n\n Returns\n -------\n m : float\n Integrated magnitude of stellar population.\n \"\"\"\n wght = self.imf_weights(imf, norm_type=norm_type, **kwargs)\n lum = np.sum(wght * 10**(-0.4 * self.mag_table[bandpass]))\n m = -2.5 * np.log10(lum)\n return m\n\n def ssp_mean_star_mass(self, imf):\n \"\"\"\n Calculate IMF-weighted mean stellar mass, where the IMF is normalized\n by number to one star formed. The mean stellar mass is equivalent to\n dividing a large of samples (distributed according to the IMF) by the\n number of stars.\n\n Parameters\n ----------\n imf : str:\n Initial mass function name.\n\n Returns\n -------\n mean_mass : float\n The mean stellar mass.\n \"\"\"\n w = self.imf_weights(imf, norm_type='number',\n m_max_norm=self.mini.max())\n mean_mass = np.sum(self.mact * w)\n return mean_mass\n\n def ssp_surviving_mass(self, imf, m_min=None, m_max=120,\n add_remnants=True, mlim_bh=40.0, mlim_ns=8.5):\n \"\"\"\n Calculate IMF-weighted mass normalized such that 1 solar mass is\n formed by the age of the population.\n\n The initial-mass-dependent remnant formulae are taken\n from `Renzini & Ciotti 1993\n `_.\n\n Parameters\n ----------\n imf : str\n IMF name.\n add_remnants : bool\n If True, add stellar remnants to surviving mass.\n\n Returns\n -------\n mass : float\n Total surviving mass.\n \"\"\"\n m_min = m_min if m_min else self.mini.min()\n m_max = m_max if m_max else self.mini.max()\n wght = self.imf_weights(imf, m_min_norm=m_min, m_max_norm=m_max)\n mass = np.sum(self.mact * wght)\n\n if add_remnants:\n imf_func = lambda m: imf_dict[imf](m, norm_type=None)\n m_imf_func = lambda m: m * imf_func(m)\n norm = quad(m_imf_func, m_min, m_max)[0]\n\n # BH remnants\n m_low = max(mlim_bh, self.m_max)\n mass = mass + 0.5 * quad(m_imf_func, m_low, m_max)[0] / norm\n\n # NS remnants\n if self.m_max <= mlim_bh:\n m_low = max(mlim_ns, self.m_max)\n mass = mass + 1.4 * quad(imf_func, m_low, mlim_bh)[0] / norm\n\n # WD remnants\n if self.m_max < mlim_ns:\n mmax = self.m_max\n mass = mass + 0.48 * quad(imf_func, mmax, mlim_ns)[0] / norm\n mass = mass + 0.077 * quad(m_imf_func, mmax, mlim_ns)[0] / norm\n\n return mass\n\n\ndef fetch_mist_iso_cmd(log_age, feh, phot_system, mist_path=MIST_PATH,\n v_over_vcrit=0.4):\n \"\"\"\n Fetch MIST isochrone grid.\n\n Parameters\n ----------\n log_age : float\n Logarithm base 10 of the simple stellar population age in years.\n feh : float\n Metallicity [Fe/H] of the simple stellar population.\n phot_system : str\n Name of the photometric system.\n mist_path : str, optional\n Path to MIST isochrone grids. Use this if you want to use a different\n path from the `MIST_PATH` environment variable.\n v_over_vcrit : float, optional\n Rotation rate divided by the critical surface linear velocity. Current\n options are 0.4 (default) and 0.0.\n\n Returns\n -------\n iso_cmd : `~numpy.ndarray`\n Structured ``numpy`` array with isochrones and stellar magnitudes.\n \"\"\"\n\n # fetch the mist grid if necessary\n fetch_mist_grid_if_needed(phot_system, v_over_vcrit, mist_path)\n\n v = f'{v_over_vcrit:.1f}'\n ver = 'v1.2'\n p = phot_str_helper[phot_system.lower()]\n path = os.path.join(mist_path, 'MIST_' + ver + f'_vvcrit{v}_' + p)\n sign = 'm' if feh < 0 else 'p'\n fn = f'MIST_{ver}_feh_{sign}{abs(feh):.2f}_afe_p0.0_vvcrit{v}_{p}.iso.cmd'\n fn = os.path.join(path, fn)\n iso_cmd = IsoCmdReader(fn, verbose=False)\n iso_cmd = iso_cmd.isocmds[iso_cmd.age_index(log_age)]\n return iso_cmd\n\n\nclass MISTIsochrone(Isochrone):\n \"\"\"\n Class for fetching and storing MIST isochrones. It also has several methods\n for calculating IMF-weighted photometric properties of a stellar population\n with the given age an metallicity.\n\n .. note::\n Currently, the models are interpolated in metallicity but not in age.\n Ages are therefore limited to the age grid of the MIST models. The\n [Fe/H] and log(Age/yr) grids are stored as the private class attributes\n ``_feh_grid`` and ``_log_age_grid``.\n\n Parameters\n ----------\n log_age : float\n Logarithm base 10 of the simple stellar population age in years.\n feh : float\n Metallicity [Fe/H] of the simple stellar population.\n phot_system : str or list-like\n Name of the photometric system(s).\n mist_path : str, optional\n Path to MIST isochrone grids. Use this if you want to use a different\n path from the ``MIST_PATH`` environment variable.\n ab_or_vega : str, optional\n Magnitudes will be in the AB (default) or Vega magnitude system.\n v_over_vcrit : float, optional\n Rotation rate divided by the critical surface linear velocity. Current\n options are 0.4 (default) and 0.0.\n \"\"\"\n\n # the age grid\n _log_age_grid = np.arange(5.0, 10.3, 0.05)\n _log_age_min = _log_age_grid.min()\n _log_age_max = _log_age_grid.max()\n\n # the [Fe/H] metallicity grid\n # mist has feh <= -4, but using <=-3 due to interpolation issues\n _feh_grid = np.concatenate([np.arange(-3.0, -2., 0.5),\n np.arange(-2.0, 0.75, 0.25)])\n _feh_min = _feh_grid.min()\n _feh_max = _feh_grid.max()\n\n def __init__(self, log_age, feh, phot_system, mist_path=MIST_PATH,\n ab_or_vega='ab', v_over_vcrit=0.4):\n\n # verify age are metallicity are within model grids\n if log_age < self._log_age_min or log_age > self._log_age_max:\n raise Exception(f'log_age = {log_age} not in range of age grid')\n if feh < self._feh_min or feh > self._feh_max:\n raise Exception(f'feh = {feh} not in range of feh grid')\n\n self.feh = feh\n self.mist_path = mist_path\n self.phot_system = phot_system\n self.ab_or_vega = ab_or_vega\n self.v_over_vcrit = v_over_vcrit\n\n # use nearest age (currently not interpolating on age)\n age_diff = np.abs(self._log_age_grid - log_age)\n self.log_age = self._log_age_grid[age_diff.argmin()]\n if age_diff.min() > 1e-6:\n logger.debug('Using nearest log_age = {:.2f}'.format(self.log_age))\n\n # store phot_system as list to allow multiple photometric systems\n if type(phot_system) == str:\n phot_system = [phot_system]\n\n # fetch first isochrone grid, interpolating on [Fe/H] if necessary\n self._iso_full = self._fetch_iso(phot_system[0])\n\n # iterate over photometric systems and fetch remaining isochrones\n filter_dict = get_filter_names()\n filters = filter_dict[phot_system[0]].copy()\n for p in phot_system[1:]:\n filt = filter_dict[p].copy()\n filters.extend(filt)\n _iso = self._fetch_iso(p)\n mags = [_iso[f].data for f in filt]\n self._iso_full = append_fields(self._iso_full, filt, mags)\n\n # covert magnitudes to ab or vega as necessary\n self.zpt_convert = load_zero_point_converter()\n for filt in filters:\n converter = getattr(self.zpt_convert, f'to_{ab_or_vega.lower()}')\n try:\n m_convert = converter(filt)\n except AttributeError:\n m_convert = 0.0\n logger.warning(f'No AB / Vega conversion found for {filt}.')\n self._iso_full[filt] = self._iso_full[filt] + m_convert\n\n super(MISTIsochrone, self).__init__(\n mini = self._iso_full['initial_mass'],\n mact = self._iso_full['star_mass'],\n mags = Table(self._iso_full[filters]),\n eep = self._iso_full['EEP'],\n log_L = self._iso_full['log_L'],\n log_Teff = self._iso_full['log_Teff'],\n )\n\n @property\n def isochrone_full(self):\n \"\"\"MIST entire isochrone in a structured `~numpy.ndarray`.\"\"\"\n return self._iso_full\n\n @staticmethod\n def from_parsec(fn, **kwargs):\n msg = 'PARSEC isochrones do not with MISTIsochrone.'\n raise Exception(msg + ' Use artpop.Isochrone instead.')\n\n def _fetch_iso(self, phot_system):\n \"\"\"Fetch MIST isochrone grid, interpolating on [Fe/H] if necessary.\"\"\"\n if self.feh in self._feh_grid:\n args = [self.log_age, self.feh, phot_system, self.mist_path,\n self.v_over_vcrit]\n iso = fetch_mist_iso_cmd(*args)\n else:\n iso = self._interp_on_feh(phot_system)\n return iso\n\n def _interp_on_feh(self, phot_system):\n \"\"\"Interpolate isochrones between two [Fe/H] grid points.\"\"\"\n i_feh = self._feh_grid.searchsorted(self.feh)\n feh_lo, feh_hi = self._feh_grid[i_feh - 1: i_feh + 1]\n\n logger.debug('Interpolating to [Fe/H] = {:.2f} '\\\n 'using [Fe/H] = {} and {}'.\\\n format(self.feh, feh_lo, feh_hi))\n\n mist_0 = fetch_mist_iso_cmd(\n self.log_age, feh_lo, phot_system, self.mist_path)\n mist_1 = fetch_mist_iso_cmd(\n self.log_age, feh_hi, phot_system, self.mist_path)\n\n y0, y1 = np.array(mist_0.tolist()), np.array(mist_1.tolist())\n\n x = self.feh\n x0, x1 = feh_lo, feh_hi\n weight = (x - x0) / (x1 - x0)\n\n len_0, len_1 = len(y0), len(y1)\n\n # if necessary, extrapolate using trend of the longer array\n if (len_0 < len_1):\n delta = y1[len_0:] - y1[len_0 - 1]\n y0 = np.append(y0, y0[-1] + delta, axis=0)\n elif (len_0 > len_1):\n delta = y0[len_1:] - y0[len_1 - 1]\n y1 = np.append(y1, y1[-1] + delta, axis=0)\n\n y = y0 * (1 - weight) + y1 * weight\n iso = np.core.records.fromarrays(y.transpose(), dtype=mist_0.dtype)\n\n return iso\n", "meta": {"hexsha": "96ba38751463aa5c27d0ce141eaaa0a1c74f1e08", "size": 25534, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/artpop/stars/isochrones.py", "max_stars_repo_name": "eteq/ArtPop", "max_stars_repo_head_hexsha": "c510d409196c4296024214c2e01766d1ca97b3dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2021-09-22T21:28:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T02:52:46.000Z", "max_issues_repo_path": "src/artpop/stars/isochrones.py", "max_issues_repo_name": "eteq/ArtPop", "max_issues_repo_head_hexsha": "c510d409196c4296024214c2e01766d1ca97b3dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-12-16T17:43:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-07T20:12:13.000Z", "max_forks_repo_path": "src/artpop/stars/isochrones.py", "max_forks_repo_name": "eteq/ArtPop", "max_forks_repo_head_hexsha": "c510d409196c4296024214c2e01766d1ca97b3dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-12-17T03:50:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T16:58:57.000Z", "avg_line_length": 37.0595065312, "max_line_length": 79, "alphanum_fraction": 0.581538341, "include": true, "reason": "import numpy,from numpy,from scipy,from astropy", "num_tokens": 6376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.25386101261427363, "lm_q1q2_score": 0.12990489544173736}} {"text": "\"\"\"\nModule with reading functionalities for isochrones.\n\"\"\"\n\nimport configparser\nimport os\nimport warnings\n\nfrom typing import Optional, Tuple\n\nimport h5py\nimport numpy as np\n\nfrom scipy.interpolate import griddata\nfrom typeguard import typechecked\n\nfrom species.core import box\nfrom species.read import read_model\nfrom species.util import read_util\n\n\nclass ReadIsochrone:\n \"\"\"\n Class for reading isochrone data from the database.\n \"\"\"\n\n @typechecked\n def __init__(self, tag: str) -> None:\n \"\"\"\n Parameters\n ----------\n tag : str\n Database tag of the isochrone data.\n\n Returns\n -------\n NoneType\n None\n \"\"\"\n\n self.tag = tag\n\n config_file = os.path.join(os.getcwd(), \"species_config.ini\")\n\n config = configparser.ConfigParser()\n config.read(config_file)\n\n self.database = config[\"species\"][\"database\"]\n\n with h5py.File(self.database, \"r\") as h5_file:\n if f\"isochrones/{self.tag}\" not in h5_file:\n raise ValueError(f\"There is no isochrone data stored \"\n f\"with the selected tag \\'{tag}\\'.\")\n\n @typechecked\n def get_isochrone(\n self,\n age: float,\n masses: np.ndarray,\n filters_color: Optional[Tuple[str, str]] = None,\n filter_mag: Optional[str] = None,\n ) -> box.IsochroneBox:\n \"\"\"\n Function for selecting an isochrone.\n\n Parameters\n ----------\n age : float\n Age (Myr) at which the isochrone data is interpolated.\n masses : np.ndarray\n Masses (:math:`M_\\\\mathrm{J}`) at which the isochrone\n data is interpolated.\n filters_color : tuple(str, str), None\n Filter names for the color as listed in the file with the\n isochrone data. Not selected if set to ``None`` or if only\n evolutionary tracks are available.\n filter_mag : str, None\n Filter name for the absolute magnitude as listed in the\n file with the isochrone data. Not selected if set to\n ``None`` or if only evolutionary tracks are available.\n\n Returns\n -------\n species.core.box.IsochroneBox\n Box with the isochrone.\n \"\"\"\n\n age_points = np.full(masses.shape[0], age) # (Myr)\n\n color = None\n mag_abs = None\n\n index_teff = 2\n index_logg = 4\n\n # Read isochrone data\n\n with h5py.File(self.database, \"r\") as h5_file:\n model = h5_file[f\"isochrones/{self.tag}/evolution\"].attrs[\"model\"]\n evolution = np.asarray(h5_file[f\"isochrones/{self.tag}/evolution\"])\n\n if model == \"baraffe\":\n filters = list(h5_file[f\"isochrones/{self.tag}/filters\"])\n magnitudes = np.asarray(h5_file[f\"isochrones/{self.tag}/magnitudes\"])\n\n # Convert the h5py list of filters from bytes to strings\n for i, item in enumerate(filters):\n if isinstance(item, bytes):\n filters[i] = item.decode(\"utf-8\")\n\n if model == \"baraffe\":\n if filters_color is not None:\n index_color_1 = filters.index(filters_color[0])\n index_color_2 = filters.index(filters_color[1])\n\n if filter_mag is not None:\n index_mag = filters.index(filter_mag)\n\n if filters_color is not None:\n mag_color_1 = griddata(\n points=evolution[:, 0:2],\n values=magnitudes[:, index_color_1],\n xi=np.stack((age_points, masses), axis=1),\n method=\"linear\",\n fill_value=\"nan\",\n rescale=False,\n )\n\n mag_color_2 = griddata(\n points=evolution[:, 0:2],\n values=magnitudes[:, index_color_2],\n xi=np.stack((age_points, masses), axis=1),\n method=\"linear\",\n fill_value=\"nan\",\n rescale=False,\n )\n\n color = mag_color_1 - mag_color_2\n\n if filter_mag is not None:\n mag_abs = griddata(\n points=evolution[:, 0:2],\n values=magnitudes[:, index_mag],\n xi=np.stack((age_points, masses), axis=1),\n method=\"linear\",\n fill_value=\"nan\",\n rescale=False,\n )\n\n teff = griddata(\n points=evolution[:, 0:2],\n values=evolution[:, index_teff],\n xi=np.stack((age_points, masses), axis=1),\n method=\"linear\",\n fill_value=\"nan\",\n rescale=False,\n )\n\n logg = griddata(\n points=evolution[:, 0:2],\n values=evolution[:, index_logg],\n xi=np.stack((age_points, masses), axis=1),\n method=\"linear\",\n fill_value=\"nan\",\n rescale=False,\n )\n\n return box.create_box(\n boxtype=\"isochrone\",\n model=self.tag,\n filters_color=filters_color,\n filter_mag=filter_mag,\n color=color,\n magnitude=mag_abs,\n teff=teff,\n logg=logg,\n masses=masses,\n )\n\n @typechecked\n def get_color_magnitude(\n self,\n age: float,\n masses: np.ndarray,\n model: str,\n filters_color: Tuple[str, str],\n filter_mag: str,\n adapt_logg: bool = False,\n ) -> box.ColorMagBox:\n \"\"\"\n Function for calculating color-magnitude\n combinations from a selected isochrone.\n\n Parameters\n ----------\n age : float\n Age (Myr) at which the isochrone data is interpolated.\n masses : np.ndarray\n Masses (:math:`M_\\\\mathrm{J}`) at which the isochrone\n data is interpolated.\n model : str\n Atmospheric model used to compute the synthetic photometry.\n filters_color : tuple(str, str)\n Filter names for the color as listed in the file with the\n isochrone data. The filter names should be provided in the\n format of the SVO Filter Profile Service.\n filter_mag : str\n Filter name for the absolute magnitude as listed in the\n file with the isochrone data. The value should be equal\n to one of the ``filters_color`` values.\n adapt_logg : bool\n Adapt :math:`\\\\log(g)` to the upper or lower boundary of\n the atmospheric model grid whenever the :math:`\\\\log(g)`\n that has been calculated from the isochrone mass and\n radius lies outside the available range of the synthetic\n spectra. Typically :math:`\\\\log(g)` has only a minor\n impact on the broadband magnitudes and colors.\n\n Returns\n -------\n species.core.box.ColorMagBox\n Box with the color-magnitude data.\n \"\"\"\n\n isochrone = self.get_isochrone(\n age=age, masses=masses, filters_color=None, filter_mag=None\n )\n\n model1 = read_model.ReadModel(model=model, filter_name=filters_color[0])\n model2 = read_model.ReadModel(model=model, filter_name=filters_color[1])\n\n param_bounds = model1.get_bounds()\n\n if model1.get_parameters() == [\"teff\", \"logg\", \"feh\"]:\n if model == \"sonora-bobcat\":\n iso_feh = float(self.tag[-4:])\n else:\n iso_feh = 0.0\n\n elif model1.get_parameters() != [\"teff\", \"logg\"]:\n raise ValueError(\n \"Creating synthetic colors and magnitudes from \"\n \"isochrones is currently only implemented for \"\n \"models with only Teff and log(g) as free parameters. \"\n \"Please contact Tomas Stolker if additional \"\n \"functionalities are required.\"\n )\n\n else:\n iso_feh = None\n\n mag1 = np.zeros(isochrone.masses.shape[0])\n mag2 = np.zeros(isochrone.masses.shape[0])\n radius = np.zeros(isochrone.masses.shape[0])\n\n for i, mass_item in enumerate(isochrone.masses):\n model_param = {\n \"teff\": isochrone.teff[i],\n \"logg\": isochrone.logg[i],\n \"mass\": mass_item,\n \"distance\": 10.0,\n }\n\n if iso_feh is not None:\n model_param['feh'] = iso_feh\n\n radius[i] = read_util.get_radius(\n model_param[\"logg\"], model_param[\"mass\"]\n ) # (Rjup)\n\n if np.isnan(isochrone.teff[i]):\n mag1[i] = np.nan\n mag2[i] = np.nan\n\n warnings.warn(\n f\"The value of Teff is NaN for the following \"\n f\"isochrone sample: {model_param}. Setting \"\n f\"the magnitudes to NaN.\"\n )\n\n else:\n for item_bounds in param_bounds:\n if model_param[item_bounds] < param_bounds[item_bounds][0]:\n if adapt_logg and item_bounds == \"logg\":\n warnings.warn(\n f\"The log(g) is {model_param[item_bounds]} but the \"\n f\"lower boundary of the model grid is \"\n f\"{param_bounds[item_bounds][0]}. Adapting \"\n f\"log(g) to {param_bounds[item_bounds][0]} since \"\n f\"adapt_logg=True.\"\n )\n\n model_param[\"logg\"] = param_bounds[\"logg\"][0]\n\n else:\n mag1[i] = np.nan\n mag2[i] = np.nan\n\n warnings.warn(\n f\"The value of {item_bounds} is \"\n f\"{model_param[item_bounds]}, which is below \"\n f\"the lower bound of the model grid \"\n f\"({param_bounds[item_bounds][0]}). Setting the \"\n f\"magnitudes to NaN for the following isochrone \"\n f\"sample: {model_param}.\"\n )\n\n elif model_param[item_bounds] > param_bounds[item_bounds][1]:\n if adapt_logg and item_bounds == \"logg\":\n warnings.warn(\n f\"The log(g) is {model_param[item_bounds]} but \"\n f\"the upper boundary of the model grid is \"\n f\"{param_bounds[item_bounds][1]}. Adapting \"\n f\"log(g) to {param_bounds[item_bounds][1]} \"\n f\"since adapt_logg=True.\"\n )\n\n model_param[\"logg\"] = param_bounds[\"logg\"][1]\n\n else:\n mag1[i] = np.nan\n mag2[i] = np.nan\n\n warnings.warn(\n f\"The value of {item_bounds} is \"\n f\"{model_param[item_bounds]}, which is above \"\n f\"the upper bound of the model grid \"\n f\"({param_bounds[item_bounds][1]}). Setting the \"\n f\"magnitudes to NaN for the following isochrone \"\n f\"sample: {model_param}.\"\n )\n\n if not np.isnan(mag1[i]):\n mag1[i], _ = model1.get_magnitude(model_param)\n mag2[i], _ = model2.get_magnitude(model_param)\n\n if filter_mag == filters_color[0]:\n abs_mag = mag1\n\n elif filter_mag == filters_color[1]:\n abs_mag = mag2\n\n else:\n raise ValueError(\n \"The argument of filter_mag should be equal to \"\n \"one of the two filter values of filters_color.\"\n )\n\n return box.create_box(\n boxtype=\"colormag\",\n library=model,\n object_type=\"model\",\n filters_color=filters_color,\n filter_mag=filter_mag,\n color=mag1 - mag2,\n magnitude=abs_mag,\n names=None,\n sptype=masses,\n mass=masses,\n radius=radius,\n iso_tag=self.tag,\n )\n\n @typechecked\n def get_color_color(\n self,\n age: float,\n masses: np.ndarray,\n model: str,\n filters_colors: Tuple[Tuple[str, str], Tuple[str, str]],\n ) -> box.ColorColorBox:\n \"\"\"\n Function for calculating color-magnitude combinations from a\n selected isochrone.\n\n Parameters\n ----------\n age : float\n Age (Myr) at which the isochrone data is interpolated.\n masses : np.ndarray\n Masses (:math:`M_\\\\mathrm{J}`) at which the isochrone\n data is interpolated.\n model : str\n Atmospheric model used to compute the synthetic photometry.\n filters_colors : tuple(tuple(str, str), tuple(str, str))\n Filter names for the colors as listed in the file with the\n isochrone data. The filter names should be provided in the\n format of the SVO Filter Profile Service.\n\n Returns\n -------\n species.core.box.ColorColorBox\n Box with the color-color data.\n \"\"\"\n\n isochrone = self.get_isochrone(\n age=age, masses=masses, filters_color=None, filter_mag=None\n )\n\n model1 = read_model.ReadModel(model=model, filter_name=filters_colors[0][0])\n model2 = read_model.ReadModel(model=model, filter_name=filters_colors[0][1])\n model3 = read_model.ReadModel(model=model, filter_name=filters_colors[1][0])\n model4 = read_model.ReadModel(model=model, filter_name=filters_colors[1][1])\n\n if model1.get_parameters() == [\"teff\", \"logg\", \"feh\"]:\n if model == \"sonora-bobcat\":\n iso_feh = float(self.tag[-4:])\n else:\n iso_feh = 0.0\n\n elif model1.get_parameters() != [\"teff\", \"logg\"]:\n raise ValueError(\n \"Creating synthetic colors and magnitudes from \"\n \"isochrones is currently only implemented for \"\n \"models with only Teff and log(g) as free parameters. \"\n \"Please contact Tomas Stolker if additional \"\n \"functionalities are required.\"\n )\n\n else:\n iso_feh = None\n\n mag1 = np.zeros(isochrone.masses.shape[0])\n mag2 = np.zeros(isochrone.masses.shape[0])\n mag3 = np.zeros(isochrone.masses.shape[0])\n mag4 = np.zeros(isochrone.masses.shape[0])\n radius = np.zeros(isochrone.masses.shape[0])\n\n for i, mass_item in enumerate(isochrone.masses):\n model_param = {\n \"teff\": isochrone.teff[i],\n \"logg\": isochrone.logg[i],\n \"mass\": mass_item,\n \"distance\": 10.0,\n }\n\n if iso_feh is not None:\n model_param['feh'] = iso_feh\n\n radius[i] = read_util.get_radius(\n model_param[\"logg\"], model_param[\"mass\"]\n ) # (Rjup)\n\n if np.isnan(isochrone.teff[i]):\n mag1[i] = np.nan\n mag2[i] = np.nan\n mag3[i] = np.nan\n mag4[i] = np.nan\n\n warnings.warn(\n f\"The value of Teff is NaN for the following isochrone \"\n f\"sample: {model_param}. Setting the magnitudes to NaN.\"\n )\n\n else:\n for item_bounds in model1.get_bounds():\n if model_param[item_bounds] < model1.get_bounds()[item_bounds][0]:\n mag1[i] = np.nan\n mag2[i] = np.nan\n mag3[i] = np.nan\n mag4[i] = np.nan\n\n warnings.warn(\n f\"The value of {item_bounds} is \"\n f\"{model_param[item_bounds]}, which is \"\n f\"below the lower bound of the model grid \"\n f\" ({model1.get_bounds()[item_bounds][0]}). \"\n f\"Setting the magnitudes to NaN for the \"\n f\"following isochrone sample: {model_param}.\"\n )\n\n elif (\n model_param[item_bounds] > model1.get_bounds()[item_bounds][1]\n ):\n mag1[i] = np.nan\n mag2[i] = np.nan\n mag3[i] = np.nan\n mag4[i] = np.nan\n\n warnings.warn(\n f\"The value of {item_bounds} is \"\n f\"{model_param[item_bounds]}, which is above \"\n f\"the upper bound of the model grid \"\n f\"({model1.get_bounds()[item_bounds][1]}). \"\n f\"Setting the magnitudes to NaN for the \"\n f\"following isochrone sample: {model_param}.\"\n )\n\n if (\n not np.isnan(mag1[i])\n and not np.isnan(mag2[i])\n and not np.isnan(mag3[i])\n and not np.isnan(mag4[i])\n ):\n mag1[i], _ = model1.get_magnitude(model_param)\n mag2[i], _ = model2.get_magnitude(model_param)\n mag3[i], _ = model3.get_magnitude(model_param)\n mag4[i], _ = model4.get_magnitude(model_param)\n\n return box.create_box(\n boxtype=\"colorcolor\",\n library=model,\n object_type=\"model\",\n filters=filters_colors,\n color1=mag1 - mag2,\n color2=mag3 - mag4,\n names=None,\n sptype=masses,\n mass=masses,\n radius=radius,\n iso_tag=self.tag,\n )\n", "meta": {"hexsha": "8edc53f5a6ef11d6b2e1c91f683c5e1205d1d6bf", "size": 18357, "ext": "py", "lang": "Python", "max_stars_repo_path": "species/read/read_isochrone.py", "max_stars_repo_name": "tomasstolker/SPECIES", "max_stars_repo_head_hexsha": "f74483a334f36cbeafeaf372446ae1ea9f278d95", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "species/read/read_isochrone.py", "max_issues_repo_name": "tomasstolker/SPECIES", "max_issues_repo_head_hexsha": "f74483a334f36cbeafeaf372446ae1ea9f278d95", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "species/read/read_isochrone.py", "max_forks_repo_name": "tomasstolker/SPECIES", "max_forks_repo_head_hexsha": "f74483a334f36cbeafeaf372446ae1ea9f278d95", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.783625731, "max_line_length": 86, "alphanum_fraction": 0.4959416027, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.25683199707586785, "lm_q1q2_score": 0.12941922811583656}} {"text": "import os\n\nimport numpy as np\nfrom scipy.interpolate import RectBivariateSpline\n\nfrom adf11 import Adf11\n\n\nargon_data = {\n 'ionisation' : 'scd89_ar.dat',\n 'recombination' : 'acd89_ar.dat',\n 'continuum_power' : 'prb89_ar.dat',\n 'line_power' : 'plt89_ar.dat',\n 'cx_power' : 'prc89_ar.dat',\n}\n\ncarbon_data = {\n 'ionisation' : 'scd96_c.dat',\n 'recombination' : 'acd96_c.dat',\n 'continuum_power' : 'prb96_c.dat',\n 'line_power' : 'plt96_c.dat',\n 'cx_power' : 'prc96_c.dat',\n}\n\nneon_data = {\n 'ionisation' : 'scd96_ne.dat',\n 'recombination' : 'acd96_ne.dat',\n 'continuum_power' : 'prb96_ne.dat',\n 'line_power' : 'plt96_ne.dat',\n}\n\ndef _element_data(element):\n e = element.lower()\n if e in ['ar', 'argon']:\n return argon_data\n elif e in ['c', 'carbon']:\n return carbon_data\n elif e in ['ne', 'neon']:\n return neon_data\n else:\n raise NotImplementedError('unknown element: %s' % element)\n\n\ndef _full_path(file_):\n \"\"\" Figure out the location of the atomic datafiles. \"\"\"\n module_path = os.path.dirname(os.path.realpath( __file__ ))\n return os.path.join(module_path, '..', 'adas_data', file_)\n\n\nclass AtomicData(object):\n def __init__(self, coefficients):\n \"\"\"\n Parameters\n ----------\n element : string\n Name of the element.\n coefficients : dict\n Map of the different rate coefficients.\n \"\"\"\n self.coeffs = coefficients\n self._check_consistency()\n self._make_element_initial_uppercase()\n\n def copy(self):\n new_coeffs = {}\n for key, value in self.coeffs.iteritems():\n new_coeffs[key] = value.copy()\n\n return self.__class__(new_coeffs)\n\n def _check_consistency(self):\n nuclear_charge = set()\n element = set()\n for coeff in self.coeffs.values():\n nuclear_charge.add(coeff.nuclear_charge)\n element.add(coeff.element.lower())\n\n assert len(nuclear_charge) == 1, 'inconsistent nuclear charge.'\n assert len(element) == 1, 'inconsistent element name.'\n\n self.nuclear_charge = nuclear_charge.pop()\n self.element = element.pop()\n\n @classmethod\n def from_element(cls, element):\n element_data = _element_data(element)\n\n coefficients = {}\n for key in element_data.keys():\n name = _full_path(element_data[key])\n coefficients[key] = RateCoefficient.from_adf11(name)\n\n return cls(coefficients)\n\n def _make_element_initial_uppercase(self):\n e = self.element\n self.element = e[0].upper() + e[1:]\n\n\nclass RateCoefficient(object):\n def __init__(self, nuclear_charge, element, log_temperature, log_density,\n log_coeff, name=None):\n self.nuclear_charge = nuclear_charge\n self.element = element\n self.adf11_file = name\n\n self.log_temperature = log_temperature\n self.log_density = log_density\n self.log_coeff = log_coeff\n\n self._compute_interpolating_splines()\n\n @classmethod\n def from_adf11(cls, name):\n adf11_data = Adf11(name).read()\n nuclear_charge = adf11_data['charge']\n element = adf11_data['element']\n filename = adf11_data['name']\n\n log_temperature = adf11_data['log_temperature']\n log_density = adf11_data['log_density']\n log_coeff = adf11_data['log_coeff']\n\n return cls(nuclear_charge, element, log_temperature, log_density,\n log_coeff, name=filename)\n\n def copy(self):\n log_temperature = self.log_temperature.copy()\n log_density = self.log_density.copy()\n log_coeff = self.log_coeff.copy()\n cls = self.__class__(self.nuclear_charge, self.element, log_temperature,\n log_density, log_coeff, self.adf11_file)\n return cls\n\n def _compute_interpolating_splines(self):\n self.splines = []\n for k in xrange(self.nuclear_charge):\n x = self.log_temperature\n y = self.log_density\n z = self.log_coeff[k]\n self.splines.append(RectBivariateSpline(x, y, z))\n\n def __call__(self, k, Te, ne):\n \"\"\"\n Evaulate the ionisation/recombination coefficients of k'th atomic state\n at a given temperature and density.\n\n Parameters\n ----------\n k : int\n Ionisation stage. k=0 is the neutral atom, k=Z is the fully\n stripped ion, where Z is the atomic number.\n Te : array_like\n Temperature in [eV].\n ne : array_like\n Density in [m-3].\n\n Returns\n -------\n c : array_like\n Rate coefficent in [m3/s].\n \"\"\"\n c = self.log10(k, Te, ne)\n return np.power(10, c)\n\n def log10(self, k, Te, ne):\n \"\"\"\n Evaulate the logarithm of ionisation/recombination coefficients of\n k'th atomic state at a given temperature and density.\n\n Parameters\n ----------\n k : int\n Ionisation stage. k=0 is the neutral atom, k=Z is the fully\n stripped ion, where Z is the atomic number.\n Te : array_like\n Temperature in [eV].\n ne : array_like\n Density in [m-3].\n\n Returns\n -------\n c : array_like\n log10(rate coefficent in [m3/s])\n \"\"\"\n\n Te, ne = np.broadcast_arrays(Te, ne)\n log_temperature = np.log10(Te)\n log_density = np.log10(ne)\n\n c = self.splines[k](log_temperature, log_density)\n return c.diagonal()\n\n @property\n def temperature_grid(self):\n return 10**(self.log_temperature)\n\n @property\n def density_grid(self):\n return 10**(self.log_density)\n\nfrom sys import float_info\nclass ZeroCoefficient(RateCoefficient):\n def __init__(self):\n pass\n\n def __call__(self, k, Te, ne):\n Te, ne = np.broadcast_arrays(Te, ne)\n return float_info.min * np.ones_like(Te)\n", "meta": {"hexsha": "946d671aeb9a12600c08b5ec190cafa28d3a26ab", "size": 5977, "ext": "py", "lang": "Python", "max_stars_repo_path": "atomic/atomic_data.py", "max_stars_repo_name": "wagdav/atomic", "max_stars_repo_head_hexsha": "c54225abdb607c53a9d35658d381635403c751fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-03-05T21:20:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T06:49:15.000Z", "max_issues_repo_path": "atomic/atomic_data.py", "max_issues_repo_name": "wagdav/atomic", "max_issues_repo_head_hexsha": "c54225abdb607c53a9d35658d381635403c751fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "atomic/atomic_data.py", "max_forks_repo_name": "wagdav/atomic", "max_forks_repo_head_hexsha": "c54225abdb607c53a9d35658d381635403c751fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2016-09-16T17:23:06.000Z", "max_forks_repo_forks_event_max_datetime": "2017-03-03T15:38:29.000Z", "avg_line_length": 28.4619047619, "max_line_length": 80, "alphanum_fraction": 0.6028107746, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.2568319856991699, "lm_q1q2_score": 0.12941922238304826}} {"text": "\"\"\"Markov Chain Monte Carlo for trDesign.\"\"\"\n\n# native\nfrom datetime import datetime\nimport time\n\n# lib\nimport numpy as np\nfrom numpy.random import choice\nimport torch\nfrom torch.cuda.amp import autocast\nimport math\nimport random\nimport time\n\n# pkg\nfrom losses import * # pylint: disable=wildcard-import, unused-wildcard-import\nfrom tr_Rosetta_model import trRosettaEnsemble, prep_seq\nfrom utils import aa2idx, distogram_distribution_to_distogram, idx2aa, plot_progress\nimport config as cfg\nfrom utils import definegroupbydist, plot_muts\n\n\ndef v(torch_value):\n \"\"\"Return a detached value, if possible.\"\"\"\n try:\n return torch_value.cpu().detach().item()\n except Exception:\n return torch_value\n\ndef motifsort(elem):\n return elem[4]\n\ndef placemotifs(motifs, seq_L, sequence, mode = 0):\n \"\"\"Randomly position discontinous motifs and check if valid. motif = [start, end, length, restraints, group, newstart, newend]\"\"\"\n print(\"Placing motifs...\")\n valid = False\n i = 0\n sum = 0\n\n for m in motifs:\n sum += m[2]\n if (sum > seq_L):\n print(\"Sequence too short\")\n return placemotifs(motifs[:-1], seq_L, sequence, mode)\n elif sum == seq_L:\n pos = 0\n mode = -3\n for m in motifs:\n m[5] = pos\n m[6] = m[5] + m[2] - 1\n pos = pos + m[2]\n\n while not valid:\n if mode == 0 or mode == 1:\n for m in motifs[:]:\n m[5] = np.random.randint(0,seq_L-m[2]+1)\n m[6] = m[5]+m[2]-1\n elif mode == -2:\n print(\"predefined motifs\")\n seq_con = \"\"\n for i in range(0,seq_L):\n restraint = \"-\"\n for m in motifs:\n if i >= m[5] and i <= m[6]:\n mi = i - m[5] #local index\n c = m[3][mi] #con type\n if c in cfg.sequence_restraint_letters:\n restraint = sequence[i]\n continue\n\n seq_con = seq_con + restraint\n\n return motifs, seq_con\n elif mode == -3:\n break;\n elif mode == 2:\n spacing = (seq_L-sum)/(1+len(motifs))\n pos = int(spacing)\n for m in motifs[:]:\n buffer = int(abs(np.random.normal(spacing,spacing)))\n m[5] = pos\n m[6] = m[5]+m[2]-1\n pos = m[6] + buffer\n\n elif mode == 2.1:\n spacing = int((seq_L-sum-6)/(len(motifs)-1)) #calculate spacing for even placement with short unrestrained tails\n pos = int(seq_L-sum-((len(motifs)-1)*spacing)) #center the motifs\n for m in motifs[:]:\n m[5] = pos\n m[6] = m[5]+m[2]-1\n pos = m[6]+spacing\n elif mode == 2.2:\n motifs[0][5] = 0\n motifs[0][6] = motifs[0][2]-1\n motifs[-1][6] = seq_L - 1\n motifs[-1][5] = seq_L - motifs[-1][2]\n last = motifs[-1]\n spacing = int((seq_L-sum)/(len(motifs)-1))\n pos = motifs[0][6]\n for m in motifs[1:-1]:\n buffer = int(abs(np.random.normal(spacing,spacing)))\n pos += 1 + buffer\n m[5] = pos\n m[6] = m[5] + m[2] - 1\n pos = m[6]\n\n elif mode == 3:\n motifs.sort(key=motifsort)\n for m in motifs[:]: #set all same group\n m[4] = 0\n return placemotifs(motifs, seq_L, sequence, mode = 2)\n elif mode == 4 or mode == 5:\n motifs = definegroupbydist(motifs,cfg.target_motif_path, mode)\n return placemotifs(motifs, seq_L, sequence, mode = 3)\n else: return placemotifs(motifs, seq_L, sequence, mode = 1)\n\n #check if motifs are valid\n valid = True\n i = i + 1\n for m1 in motifs[:]:\n if m1[6] > seq_L - 1:\n print(\"ends outside\")\n valid = False\n continue\n for m2 in motifs[:]:\n if m1 == m2: continue\n if (m1[5] >= m2[5]) and (m1[5] <= m2[6]):\n valid = False\n break\n elif m1[6] >= m2[5] and m1[6] <= m2[6]:\n valid = False\n break\n\n if i > 20000: #if not valid, place motifs manually\n print(\"No valid motif placements found, attempting sequential positions\")\n random.shuffle(motifs)\n rest = seq_L - sum\n buffer = math.floor(rest/(len(motifs)+1))\n pos = buffer\n for m in motifs:\n m[5] = pos\n m[6] = m[5] + m[2]-1\n pos += m[2] + buffer\n break\n\n seq_con = \"\"\n\n constrain_seq = False\n if sequence is not None:\n for i in range(0,seq_L):\n restraint = \"-\"\n for m in motifs:\n if i >= m[5] and i <= m[6]:\n mi = i - m[5] #local index\n c = m[3][mi] #con type\n if c in cfg.sequence_restraint_letters:\n si = m[0]+mi #template index\n restraint = sequence[si]\n constrain_seq = True\n continue\n\n if i == 0 and cfg.first_residue_met:\n restraint = \"M\"\n\n seq_con = seq_con + restraint\n\n if not constrain_seq:\n seq_con = None\n\n return motifs, seq_con\n\n\ndef createmask(motifs, seq_L, save_dir, is_site_mask = False):\n \"\"\"Create mask for discontinous motifs\"\"\"\n\n #setup mask size\n motif_mask_g = np.zeros((seq_L, seq_L))\n motif_mask = np.zeros((seq_L, seq_L))\n\n for m1 in motifs[:]:\n for i in range(m1[5],m1[6]+1):\n c1 = m1[3][i-m1[5]]\n if c1 in cfg.structure_restraint_letters: #contraint is structural?\n for m2 in motifs[:]:\n if math.fabs(m2[4]-m1[4]) > 1: #motifs are not in restrained groups?\n continue\n for j in range(m2[5],m2[6]+1):\n c2 = m2[3][j-m2[5]]\n if c2 in cfg.structure_restraint_letters:\n v1 = cfg.structure_restraint_mask_values[c1]\n v2 = cfg.structure_restraint_mask_values[c2]\n value = np.clip(v1*v2, 1, 100)\n motif_mask[i,j] = value\n motif_mask_g[i,j] = value**0.5\n\n if not is_site_mask:\n plot_values = motif_mask_g.copy()\n plot_distogram(\n plot_values,\n save_dir / f\"motif_mask_groups.jpg\",\n )\n\n return motif_mask\n\nclass MCMC_Optimizer(torch.nn.Module):\n \"\"\"Markov Chain Monte Carlo optimizer.\"\"\"\n\n # We don't define `.forward()`, but it's nn-based.\n # pylint: disable=too-many-instance-attributes, abstract-method\n\n DEFAULT_ROOT_PATH = Path(__file__).parent.parent\n DEFAULT_MODEL_PATH = DEFAULT_ROOT_PATH / \"models\" / \"trRosetta_models\"\n DEFAULT_BGND_PATH = DEFAULT_ROOT_PATH / \"backgrounds\"\n DEFAULT_RESULTS_PATH = DEFAULT_ROOT_PATH / \"results\"\n\n def __init__(\n self,\n L,\n aa_weight,\n MCMC,\n native_frequencies,\n experiment_name,\n aa_valid,\n max_aa_index=20,\n sequence_constraint=None,\n target_motif_path=None,\n trRosetta_model_dir=\"models/trRosetta_models\",\n background_distribution_dir=\"backgrounds\",\n motifs=None,\n motifmode = 0,\n motif_weight = 1,\n bkg_weight = 1\n ):\n \"\"\"Construct the optimizer.\"\"\"\n super().__init__()\n self.results_dir = self.setup_results_dir(experiment_name)\n self.bkg_dir = background_distribution_dir\n self.structure_models = trRosettaEnsemble(\n trRosetta_model_dir\n ) # .share_memory()\n print(\n f\"{self.structure_models.n_models} structure prediction models loaded to {d()}\"\n )\n\n # General params:\n self.eps = 1e-7\n self.seq_L = L\n self.motifs = None\n self.motifmode = motifmode\n self.use_sites = cfg.use_sites\n print(\"Sequence Length: \" + str(self.seq_L))\n if motifs is not None:\n _motifs,_seq_con = placemotifs(motifs, self.seq_L, sequence_constraint, mode=self.motifmode)\n self.motifs = _motifs\n if _seq_con is not None: sequence_constraint = _seq_con\n\n for m in self.motifs: print(m)\n print(sequence_constraint)\n\n # Setup MCMC params:\n self.beta, self.N, self.coef, self.M, self.MaxM = (\n MCMC[\"BETA_START\"],\n MCMC[\"N_STEPS\"],\n MCMC[\"COEF\"],\n MCMC[\"M\"],\n MCMC[\"MAX\"],\n )\n self.aa_weight = aa_weight\n\n # Setup sequence constraints:\n self.aa_valid = aa_valid\n self.native_frequencies = native_frequencies\n\n self.seq_constraint = sequence_constraint\n if self.seq_constraint is not None:\n assert len(self.seq_constraint) == self.seq_L, \\\n \"Constraint length (%d) must == Seq_L (%d)\" %(len(self.seq_constraint), self.seq_L)\n\n self.seq_constraint = (\n aa2idx(self.seq_constraint).copy().reshape([1, self.seq_L])\n )\n self.seq_constraint_indices = np.where(\n self.seq_constraint != max_aa_index, 1, 0\n )\n\n self.target_motif_path = target_motif_path\n self.setup_losses()\n\n # stats\n self.bad_accepts = []\n self.n_accepted_mutations = 0\n self.n_accepted_bad_mutations = 0\n self.best_metrics = {}\n self.best_step = 0\n self.best_sequence = None\n self.best_E = None\n self.step = 0\n self.motif_weight = motif_weight\n self.bkg_weight = bkg_weight\n\n self.matrix_setup()\n\n def matrix_setup(self):\n self.substitution_matrix = {}\n with open(\"src/\" + cfg.MATRIXFILE) as reader:\n columns = reader.readline().strip().split()\n lines = reader.readlines()\n for aa in columns:\n if aa in cfg.RM_AA: continue\n if aa not in cfg.ALPHABET_core_str: continue\n self.substitution_matrix[aa] = {}\n\n\n for line in lines:\n data = line.strip().split()\n aa1 = data[0]\n if aa1 not in cfg.ALPHABET_core_str: continue\n sub = {}\n for i in range(0,len(columns)):\n aa2 = columns[i]\n if aa2 in cfg.RM_AA: continue\n if aa2 not in cfg.ALPHABET_core_str: continue\n value = data[i+1]\n try: sub[aa2] = float(value)\n except: sub[aa2] = 0\n\n self.substitution_matrix[aa1] = dict(sorted(sub.items(), key=lambda x: x[1]))\n\n if True: #convert to non negative values\n min_value = 1\n\n for a in self.substitution_matrix.items():\n for b in a[1].items():\n if b[1] < min_value: min_value = b[1]\n\n if min_value < 0:\n offset = -min_value + 1\n\n for a in self.substitution_matrix.items():\n for b in a[1].items():\n self.substitution_matrix[a[0]][b[0]] += offset\n\n #for a in self.substitution_matrix.items():\n # for b in a[1].items():\n # self.substitution_matrix[a[0]][b[0]] = self.substitution_matrix[a[0]][b[0]]*self.substitution_matrix[a[0]][b[0]]\n\n\n\n def setup_results_dir(self, experiment_name):\n \"\"\"Create the directories for the results.\"\"\"\n results_dir = (\n self.DEFAULT_RESULTS_PATH\n / experiment_name\n / datetime.now().strftime(\"%Y-%m-%d_%H%M%S\")\n )\n results_dir.mkdir(parents=True, exist_ok=True)\n (results_dir / \"distogram_evolution\").mkdir(parents=True, exist_ok=True)\n print(f\"Writing results to {results_dir}\")\n return results_dir\n\n def setup_losses(self):\n \"\"\"Prepare the loss functions.\"\"\"\n\n # Initialize protein background distributions:\n if cfg.BACKGROUND: self.bkg_loss = Structural_Background_Loss(self.seq_L, self.bkg_dir)\n self.aa_bkgr_distribution = torch.from_numpy(self.native_frequencies).to(d())\n\n # Motif-Loss:\n self.motif_weight = 1.00 #Multiplier for the loss contribution\n self.motif_mask = np.zeros((self.seq_L, self.seq_L)) #LxL tensor, int64, L currently specified in config.py. Cotains only zeros\n self.motif_mask = torch.from_numpy(self.motif_mask).long().to(d())\n\n #If motif target is specified. Motif target file is .npz LxL. L is overall protein length\n #Overrides previous motif_mask\n #New mask will be ones with a diagonal zero line\n if self.target_motif_path is not None:\n self.motif_mask = np.ones((self.seq_L, self.seq_L))\n\n if self.motifs is not None:\n self.motif_mask = createmask(self.motifs, self.seq_L, self.results_dir)\n\n self.motif_mask = torch.from_numpy(self.motif_mask).long().to(d())\n self.motif_mask.fill_diagonal_(0)\n self.motif_sat_loss = Motif_Satisfaction(\n self.target_motif_path, mask=self.motif_mask, save_dir=self.results_dir, motifs = self.motifs\n )\n\n self.site_weight = 0\n if self.use_sites:\n self.site_mask = createmask(self.motifs, self.seq_L, self.results_dir, is_site_mask = True)\n self.site_mask = torch.from_numpy(self.site_mask).long().to(d())\n self.site_mask.fill_diagonal_(0)\n\n self.site_sat_loss = Site_Satisfaction(\n self.target_motif_path, mask=self.site_mask, motifs = self.motifs\n )\n\n\n # Apply the background KL-loss only under the hallucination_mask == 1 region\n self.hallucination_mask = 1 - torch.clip(self.motif_mask, 0, 1)\n self.hallucination_mask.fill_diagonal_(0)\n\n def loss(self, sequence, structure_predictions, msa1hot, track=False):\n \"\"\"Compute the loss function.\"\"\"\n\n # Top-prob: extremily expensive operation\n #TM_score_proxy = top_prob(structure_predictions['dist'], verbose=False)\n #TM_score_proxy = TM_score_proxy[0] # We're running with batch_size = 1\n\n # Background KL-loss:\n if cfg.BACKGROUND:\n background_loss = self.bkg_loss(\n structure_predictions, hallucination_mask=self.hallucination_mask\n )\n else:\n background_loss = torch.tensor(0)\n\n # aa composition loss\n aa_samp = (\n msa1hot[0, :, :20].sum(axis=0) / self.seq_L + self.eps #take entire first sequence, all 1hot chars, and sum across length?\n ) # Get relative frequency for each AA\n aa_samp = (\n aa_samp / aa_samp.sum()\n ) # Normalize to turn into distributions (possibly redundant)\n loss_aa = (\n aa_samp\n * torch.log(aa_samp / (self.aa_bkgr_distribution + self.eps) + self.eps)\n ).sum()\n\n # Motif Loss:\n if self.target_motif_path is not None: #check if target motif has been specified\n motif_loss, motif_loss_pos = self.motif_sat_loss(structure_predictions) #motif_sat_loss = MotifSatisfaction object (nn object)\n else:\n motif_loss = 0 #no target motif = no loss\n\n if self.use_sites:\n site_loss = self.site_sat_loss(structure_predictions)\n else:\n site_loss = torch.tensor(0)\n\n # total loss\n loss_v = (\n self.bkg_weight * background_loss + self.aa_weight * loss_aa + self.motif_weight * motif_loss + self.site_weight * site_loss\n )\n\n metrics = {}\n if track:\n metrics[\"aa_weight\"] = self.aa_weight\n metrics[\"background_loss\"] = background_loss\n metrics[\"motif_loss\"] = motif_loss\n metrics[\"site_loss\"] = site_loss\n metrics[\"total_loss\"] = loss_v\n #metrics[\"TM_score_proxy\"] = TM_score_proxy\n\n return loss_v, metrics\n\n def metropolis(self, seq, seq_curr, E_curr, E):\n \"\"\"Compute the Metropolis criterion.\"\"\"\n accepted = True\n deltaE = E_curr - E\n\n # Metropolis criterion\n if E_curr < E: # Lower energy, replace!\n seq = np.copy(seq_curr)\n E = E_curr\n else: # Higher energy, maybe replace..\n if torch.exp((E - E_curr) * self.beta) > np.random.uniform():\n seq = np.copy(seq_curr)\n E = E_curr\n self.bad_accepts.append(1)\n self.n_accepted_bad_mutations += 1\n else:\n accepted = False\n self.bad_accepts.append(0)\n\n self.register_mutation_fitness(accepted, deltaE)\n\n # Update the best sequence:\n if E_curr < self.best_E:\n self.best_E = E_curr\n self.best_sequence = idx2aa(seq_curr[0])\n self.best_step = self.step\n\n return seq, E\n\n def mutate(self, seq):\n \"\"\"Return a mutated version of the sequence.\"\"\"\n seq_curr = np.copy(seq)\n\n # Introduce a random mutation using the allowed aa_types:\n if cfg.GRADIENT: idx = random.choices(range(self.seq_L), self.gradient, k=1)[0]\n else: idx = np.random.randint(self.seq_L)\n\n from_aa = idx2aa(seq_curr[0])[idx]\n\n #Perform mutation\n mutation_list = self.mutation_score[idx]\n\n if cfg.MATRIX:\n if len(mutation_list) == 0: mutation_list.append([from_aa, from_aa, 0, True, 0]) #Adds accepted dummy mutation\n\n #mut = self.mutation_score[idx]\n #mut_score = mut[2]\n #accepted = mut[3]\n #mins = min(self.mutation_score, key=lambda x: x[2])[2]\n #maxs = max(self.mutation_score, key=lambda x: x[2])[2]\n\n ################################\n ### SUBSTITUTION MATRIX MODE ###\n if cfg.MATRIX_MODE == 'probability':\n last_accepted = None\n verybad = \"\"\n\n for m in reversed(mutation_list):\n if m[2] > 0.1:\n verybad += m[1]\n if m[3]:\n last_accepted = m\n break\n\n if last_accepted[2] < 0.005: p = 1\n else: p = 0\n\n for i in range(10):\n list_of_candidates = [k for k,v in self.substitution_matrix[last_accepted[p]].items()]\n probability_distribution = [v for k,v in self.substitution_matrix[last_accepted[p]].items()]\n mutation = random.choices(list_of_candidates, probability_distribution, k=1)[0]\n if mutation not in verybad: break\n\n seq_curr[0, idx] = aa2idx(mutation)\n\n #############################################\n ### AMINO ACID PROPERTY GROUP MATRIX MODE ###\n elif cfg.MATRIX_MODE == 'groups':\n recent_mutations = []\n\n for m in reversed(mutation_list):\n if self.step - m[4] > self.seq_L * 10: break\n recent_mutations.append(m)\n\n if len(recent_mutations) == 0:\n seq_curr[0, idx] = np.random.choice(self.aa_valid)\n else:\n group_scores = [[0,0,None]] * len(cfg.AA_PROPERTY_GROUPS)\n i = 0\n for k,v in cfg.AA_PROPERTY_GROUPS.items():\n group_scores[i][2] = v\n for m in recent_mutations:\n if m[1] in v:\n group_scores[i][1] += m[2]\n group_scores[i][0] += 1\n i += 1\n\n best = \"\"\n best_s = 1000\n\n for i in range(len(group_scores)):\n g = group_scores[i]\n avg = g[1]/(g[0]+1)\n if avg < best_s:\n best = g[2]\n best_s = avg\n elif avg == best_s:\n best += g[2]\n\n options = []\n for aa in best:\n if aa in cfg.RM_AA: continue\n options.append(aa)\n\n seq_curr[0, idx] = aa2idx(np.random.choice(options))\n\n ################################\n ### MSA MUTATION MATRIX MODE ###\n elif cfg.MATRIX_MODE == 'msa':\n group = cfg.TEMPLATE_AA_PROPERTIES[idx]\n seq_curr[0, idx] = aa2idx(np.random.choice(group))\n\n ###########################\n ### MODE NOT RECOGNIZED ###\n else: seq_curr[0, idx] = np.random.choice(self.aa_valid)\n\n #######################\n ### NON MATRIX MODE ###\n else: seq_curr[0, idx] = np.random.choice(self.aa_valid)\n\n to_aa = idx2aa(seq_curr[0])[idx]\n\n if self.seq_constraint is not None: # Fix the constraint:\n seq_curr = np.where(\n self.seq_constraint_indices, self.seq_constraint, seq_curr\n )\n\n if np.equal(seq_curr, seq).all(): # If the mutation did not change anything, retry\n self.reverse_log = False\n return self.mutate(seq)\n\n # Store mutation information\n self.current_mutations.append([idx, from_aa, to_aa])\n\n return seq_curr\n\n def select_mutation_options(self, matrix, threshold = 0, above = True):\n if above:\n return [k for k,v in matrix.items() if v >= threshold]\n else:\n return [k for k,v in matrix.items() if v <= threshold]\n\n def diff_to_weight(self, diff, increase = True):\n if increase:\n if diff == 0: return 1.25\n else: return 1.5 - 0.025*diff\n else: return 0.8 + 0.02 * diff\n\n def register_mutation_fitness(self, accepted, deltaE):\n if deltaE < -1: deltaE = 0\n else: deltaE = float(deltaE.cpu().detach().numpy())\n\n good = deltaE < 0\n\n for mut in self.current_mutations:\n self.good_mutations[mut[0]] += 1\n\n if good:\n self.good_accepts.append(1)\n for i in range(mut[0]-20,mut[0]+21):\n if i >= 0 and i < self.seq_L:\n self.gradient[i] *= self.diff_to_weight(abs(mut[0]-i))\n else:\n self.good_accepts.append(0)\n for i in range(mut[0]-10,mut[0]+11):\n if i >= 0 and i < self.seq_L:\n self.gradient[i] *= self.diff_to_weight(abs(mut[0]-i), increase = False)\n\n self.mutation_log.append([mut[0], mut[1], mut[2], self.substitution_matrix[mut[1]][mut[2]], deltaE, accepted])\n\n if accepted: self.n_accepted_mutations += 1\n\n self.mutation_score[mut[0]].append([mut[1], mut[2], deltaE, accepted, self.step]) #from, to, result, accepted, when\n\n if self.reverse_log:\n print(\"result: \" + str(mut) + \" \" + str(deltaE) + \" | \" + str(accepted))\n\n self.gradient = np.clip([i+0.01*(1-i) for i in self.gradient], 0.2, 20)\n self.current_mutations = []\n self.reverse_log = False\n\n def fixup_MCMC(self, seq):\n \"\"\"Dynamically adjust the metropolis beta parameter to improve performance.\"\"\"\n if self.step - self.best_step > min(self.N // 4,1000):\n # No improvement for a long time, reload the best_sequence and decrease beta:\n print(\"reload best seq\")\n self.best_step = self.step\n self.beta = self.beta / (self.coef ** 2)\n seq = torch.from_numpy(\n aa2idx(self.best_sequence).reshape([1, self.seq_L])\n ).long()\n self.mutation_score = [[]] * self.seq_L\n\n elif np.mean(self.bad_accepts[-100:]) < 0.02:\n # There has been some progress recently, but we're no longer accepting any bad mutations...\n self.beta = self.beta / self.coef\n else:\n self.beta = self.beta * self.coef\n\n self.beta = np.clip(self.beta, 5, self.MaxM)\n\n #FIX DYNAMIC MATRIX\n if cfg.MATRIX_DYNAMIC: cfg.MATRIX_MODE = random.choice(['msa', 'probability', 'groups', 'none'])\n\n return seq\n\n @torch.no_grad()\n def run(self, start_seq):\n \"\"\"Run the MCMC loop.\"\"\"\n # pylint: disable=too-many-locals\n\n start_time = time.time()\n muttime = 0\n nntime = 0\n losstime = 0\n scoretime = 0\n misctime = 0\n\n # initialize with given input sequence\n print(\"Initial seq: \", start_seq)\n seq = aa2idx(start_seq).copy().reshape([1, self.seq_L])\n\n nsave = min(max(1, self.N // 20),50)\n E, E_tracker = np.inf, []\n self.bad_accepts = []\n self.good_accepts = []\n self.n_accepted_mutations = 0\n self.n_accepted_bad_mutations = 0\n self.best_metrics = {}\n self.best_step = 0\n self.best_sequence = start_seq\n self.best_E = E\n self.best_bkg = 0\n self.best_mtf = 0\n self.best_distogram_distribution = None\n self.gradient = [1] * self.seq_L\n self.good_mutations = [0] * self.seq_L\n self.mutation_score = [[]] * self.seq_L\n self.reverse_log = False\n self.current_mutations = []\n self.mutation_log = []\n self.last_update = time.time()\n self.last_graph = time.time()\n\n # Main loop:\n for self.step in range(self.N + 1):\n\n # random mutation at random position, also fix sequence constraint\n mut_start = time.time()\n if self.step != 0:\n seq_curr = self.mutate(seq)\n #if cfg.MATRIX_MODE == 'msa':\n # for i in range(10): seq_curr = self.mutate(seq_curr)\n else: seq_curr = seq\n\n\n # Preprocess the sequence, relatively expensive operations (0.04s per pass)\n seq_curr = torch.from_numpy(seq_curr).long()\n model_input, msa1hot = prep_seq(seq_curr)\n muttime += time.time() - mut_start\n\n\n # probe effect of mutation\n nn_start = time.time()\n structure_predictions = self.structure_models( #run trRosettaEnsemble -> runs trrosetta n times\n model_input, use_n_models=cfg.n_models\n )\n nntime += time.time() - nn_start\n\n\n #loss functions\n loss_start = time.time()\n E_curr, metrics = self.loss(\n seq_curr, structure_predictions, msa1hot, track=True\n )\n losstime += time.time() - loss_start\n\n\n #scoring evaluation\n score_start = time.time()\n if E_curr < self.best_E:\n self.best_bkg = metrics[\"background_loss\"]\n self.best_mtf = metrics[\"motif_loss\"]\n self.best_site = metrics[\"site_loss\"]\n self.best_distogram_distribution = structure_predictions['dist']\n\n\n seq, E = self.metropolis(seq, seq_curr, E_curr, E)\n\n E_tracker.append(v(E))\n delta_step_best = self.step - self.best_step\n scoretime += time.time() - score_start\n\n misc_start = time.time()\n if time.time() - self.last_update > cfg.report_interval or self.step == 0:\n fps = self.step / (time.time() - start_time)\n background_loss = metrics[\"background_loss\"].cpu().detach().numpy()\n mtf_loss = metrics[\"motif_loss\"].cpu().detach().numpy()\n site_loss = metrics[\"site_loss\"].cpu().detach().numpy()\n\n b_bkg = self.best_bkg.cpu().detach().numpy()\n b_mtf = self.best_mtf.cpu().detach().numpy()\n b_site = self.best_site.cpu().detach().numpy()\n\n self.last_update = time.time()\n\n print(\n f\"Step {self.step:4d} / {self.N:4d} ({delta_step_best}) || \"\n f\"beta: {self.beta:.1f}, \"\n f\"mutations/s: {fps:.2f}, \"\n f\"bad/good_accepts: {np.sum(self.bad_accepts[-100:])}/{np.sum(self.good_accepts[-100:])}\",\n flush=True,\n )\n print(f\"STATS || loss: {E_curr:.3f}, bkg: {background_loss:.3f}, mtf: {mtf_loss:.3f}, site: {site_loss:.3f}\")\n print(f\"BEST STATS || loss: {self.best_E:.3f}, bkg: {b_bkg:.3f}, mtf: {b_mtf:.3f}, site: {b_site:.3f}\")\n\n #timings\n total_time = time.time() - start_time\n print(f\"total time: {total_time:.1f}\")\n print(f\"mut time: {muttime:.2f}\\t| {100*muttime/total_time:.2f}%\")\n print(f\"nn time: {nntime:.1f}\\t| {100*nntime/total_time:.2f}%\")\n print(f\"loss time: {losstime:.2f}\\t| {100*losstime/total_time:.2f}%\")\n print(f\"score time: {scoretime:.1f}\\t| {100*scoretime/total_time:.2f}%\")\n print(f\"misc time: {misctime:.2f}\\t| {100*misctime/total_time:.2f}%\")\n\n plot_muts(self.gradient, self.results_dir / \"gradient.jpg\")\n plot_muts(self.good_mutations, self.results_dir / \"mutations.jpg\")\n\n if time.time() - self.last_graph > 1.8*cfg.report_interval or self.step == 0:\n self.last_graph = time.time()\n\n distogram = distogram_distribution_to_distogram(\n self.best_distogram_distribution.cpu().detach().numpy()\n )\n plot_distogram(\n distogram,\n self.results_dir\n / \"distogram_evolution\"\n / f\"{self.step:06d}_{self.best_E:.4f}.jpg\",\n clim=cfg.limits[\"dist\"],\n )\n\n plot_progress(\n E_tracker,\n self.results_dir / \"progress.jpg\",\n title=f\"Optimization curve after {self.step} steps\",\n )\n print(f\"\\n--- Current best: {self.best_sequence}\")\n\n if (1 + self.step) % (cfg.report_interval//2) == 0:\n with open('control.txt', 'r') as reader:\n lines = reader.readlines()\n line = lines[0].strip()\n if line == \"eval\":\n cmd = lines[1].strip()\n print(\"EVALUATE\")\n print(\"cmd: \" + cmd)\n try:\n eval(cmd.strip())\n except:\n print(\"ERROR\")\n if line == \"exit\" or line == \"break\":\n print(\"ending due to command\")\n break\n elif line == 'matrix':\n if lines[1].strip() == 'n': cfg.MATRIX = False\n else: cfg.MATRIX = True\n print(\"MATRIX: \" + str(cfg.MATRIX))\n elif line == 'gradient':\n if lines[1].strip() == 'n': cfg.GRADIENT = False\n else: cfg.GRADIENT = True\n elif line == \"beta\":\n try:\n value = float(lines[1].strip())\n self.beta = value\n except: print(\"input error\")\n elif line == \"bkw\":\n try:\n value = float(lines[1].strip())\n self.bkg_weight = value\n except: print(\"input error\")\n elif line == \"aaw\":\n try:\n value = float(lines[1].strip())\n self.aa_weight = value\n except: print(\"input error\")\n elif line == \"mw\":\n try:\n value = float(lines[1].strip())\n self.motif_weight = value\n except: print(\"input error\")\n elif line == \"pause\":\n while True:\n with open('control.txt', 'r') as reader:\n line = reader.readlines()[0].strip()\n if line != \"pause\":\n break\n else:\n print(\"pause...\")\n time.sleep(30)\n\n if (delta_step_best > 300 and self.step > 1500 and self.step % 100 == 0) or (cfg.FAST and self.step > 499 and self.step % 50 == 0):\n std = np.std(np.array(E_tracker)[-1000:])\n n_std = std / np.array(E_tracker)[-1000:].mean()\n print(\"sd: \" + str(std))\n if abs(std) < 0.005 or (cfg.FAST and abs(std) < 0.02):\n break\n\n if self.step % self.M == 0 and self.step != 0:\n seq = self.fixup_MCMC(seq)\n\n misctime += time.time() - misc_start\n\n ########################################\n\n # Save final results before exiting:\n seq_curr = torch.from_numpy(\n aa2idx(self.best_sequence).reshape([1, self.seq_L])\n ).long()\n model_input, msa1hot = prep_seq(seq_curr)\n structure_predictions = self.structure_models(model_input)\n E_curr, self.best_metrics = self.loss(\n seq_curr, structure_predictions, msa1hot, track=True\n )\n\n #for key in self.best_metrics.keys():\n # self.best_metrics[key] = v(metrics[key])\n\n TM_score_proxy = top_prob(structure_predictions['dist'], verbose=False)\n TM_score_proxy = TM_score_proxy[0] # We're running with batch_size = 1\n\n self.best_metrics[\"TM_score_proxy\"] = TM_score_proxy\n self.best_metrics[\"sequence\"] = self.best_sequence\n self.best_metrics[\"motifweight\"] = self.motif_weight\n self.best_metrics[\"motifmode\"] = self.motifmode\n self.best_metrics[\"steps\"] = self.step\n self.best_metrics[\"motifs\"] = \"\\\"\" + str(self.motifs.copy()) + \"\\\"\"\n\n # Dump distogram:\n best_distogram_distribution = structure_predictions['dist'].detach().cpu().numpy()\n distogram = distogram_distribution_to_distogram(best_distogram_distribution)\n plot_distogram(\n distogram,\n self.results_dir / f\"result.jpg\",\n clim=cfg.limits[\"dist\"],\n )\n plot_progress(\n E_tracker,\n self.results_dir / \"progress.jpg\",\n title=f\"Optimization curve after {self.step} steps\",\n )\n\n # Write results to csv:\n with (self.results_dir / \"result.csv\").open(\"w\") as f:\n for key, val in self.best_metrics.items():\n f.write(f\"{key},{val}\\n\")\n\n with (self.results_dir / \"mutation_log.csv\").open(\"w\") as f:\n for mut in self.mutation_log:\n f.write(f\"{mut}\\n\")\n\n\n return self.best_metrics\n", "meta": {"hexsha": "dff9257bde0e343878a91ea1299c9eca69d267bf", "size": 35208, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/mcmc.py", "max_stars_repo_name": "FrederikTheisen/trDesignFFT", "max_stars_repo_head_hexsha": "3dfed36e719f8031d3abb6fa7ad5642785a4fbad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-17T02:02:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T02:02:56.000Z", "max_issues_repo_path": "src/mcmc.py", "max_issues_repo_name": "FrederikTheisen/trDesignFFT", "max_issues_repo_head_hexsha": "3dfed36e719f8031d3abb6fa7ad5642785a4fbad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mcmc.py", "max_forks_repo_name": "FrederikTheisen/trDesignFFT", "max_forks_repo_head_hexsha": "3dfed36e719f8031d3abb6fa7ad5642785a4fbad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8174006445, "max_line_length": 143, "alphanum_fraction": 0.5213587821, "include": true, "reason": "import numpy,from numpy", "num_tokens": 8254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.22541662624228417, "lm_q1q2_score": 0.1293166544420239}} {"text": "#Main file for namsless should splinter later in development\n \n#UNITS\n#time:s\n#weight:g\n#length:cm\n#density: g/cm^3\n \nimport numpy as np\nimport scipy.signal\nimport scipy.optimize\nimport matplotlib.pyplot as plt\nfrom collections import OrderedDict\nimport os\nimport datetime\nimport sys\n\n \nSMALL_SIZE = 16\nMEDIUM_SIZE = 18\nBIGGER_SIZE = 24\n \nplt.rc('font', size=SMALL_SIZE) # controls default text sizes\nplt.rc('axes', titlesize=SMALL_SIZE) # fontsize of the axes title\nplt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels\nplt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels\nplt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels\nplt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize\nplt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title\n \n \ndef pull_spectrum(spec_file):\n \"\"\"\n Function to extract the spectrum from a *.Spe file\n Parameters:\n spec_file - file name of *.Spe file\n Returns:\n spectrum - numpy array of the number of counts per bin \n \"\"\"\n with open(spec_file) as data:\n spectrum = np.array([float(i.strip()) for i in data.readlines()[12:2060]])\n return spectrum\n \ndef smooth(y, box_pts):\n \"\"\"\n Simple 1-D convolution function\n Parameters:\n y - 1-D numpy array to be smoothed\n box_pts - width of kernel\n Returns:\n y_smooth - smoothed version of y\n \"\"\"\n box = np.ones(box_pts)/box_pts\n y_smooth = np.convolve(y, box, mode='same')\n return y_smooth\n \n \nclass ATen:\n def __init__(self,input_filepath):\n self.banner = \"\"\" _______ _________ _______ _ \n ( ___ ) \\__ __/( ____ \\( ( /|\n | ( ) | ) ( | ( \\/| \\ ( |\n | (___) | _____ | | | (__ | \\ | |\n | ___ |(_____)| | | __) | (\\ \\) |\n | ( ) | | | | ( | | \\ |\n | ) ( | | | | (____/\\| ) \\ |\n |/ \\| )_( (_______/|/ )_)\n \n \"The People's 1D Continuous Energy Attenuation Code\" \n \n ................... \n .. . .............. \n ......................,.,~$OOZ7O+..................... \n .....................Z$ZOO8OOZDMZ~.................... \n .....................I8DDD8O88D888I................... \n ......................MNMNDDD888888:.................. \n .......................$MMMMMNN888O8.................. \n ........................=MNNNDDDDOOOI................. \n .........................=DDDDD88OZ88................. \n .........................ID88DD88OO88$................ \n ......................,.$8DD8DDDD8OO88I............... \n ....................~OD88DN8DDD8DDDOO88............... \n ...............,IOOZ8888M=+DD88O888DOO8Z.. ......... \n ............?O$OO8DNNMZ,..$DD8OO8888D8OZZZ ......... \n .........:ZO8DDMM8........DD888O8888OOZM.... ......... \n ....,=8MNNNM...... .......ND888888D8ZD8D.............. \n ... ...?I?7,,.............DD8D8888D8D88N.............. \n ... .... . ..........+DDDDDDDDDD8Z8:............. \n ..........................DDDDDDDDDDDD8O8,............ \n .........................88DDNDNDDDNNN8O88+........... \n ........................O8D8DDNNNNNNNNDO88D........... \n .......................+8DDDNNNMNMNNNNDOO887.......... \n ......................,NDDNNNM.MMNNODNNOO88D.......... \n .....................=8DNMN=:8NNDOO8NMMDOO8N:......... \n ....................:8DN~.......?:.....NO88D,......... \n ....................Z88ND.... ..+......,NO8D.......... \n ................... .D888M. ....7.......Z888.......... \n ......................OD8DM,....7......7OO8:.......... \n ........................DDOM...$8$:....OOO8:.......... \n ................... ......IODMMMDIM7..+OO88........... \n .........................~N8NNN8M7DMNMOOODN........... \n ........................D8M$N=DD:Z$NNM8OODO........... \n ................... .,NDONDDD$8:ZM..M888N:........... \n .................... D8ZM..8.$O,8I.ZDOO8D............ \n ................... .?DDO7..?D$8+D.INDO888............ \n ....................,DNO.MI~.IID==.=.8O8DN+. ......... \n ................ ..O8$7..,D,.DM?~M.+OODMN8........... \n ................ ..DND.D$...N$$ON.Z:O8=8DM ......... \n ................... 8NN .:$DDIZDON,~8ZD$D8M .......... \n ....................8DI. , =DND$$$,88I.O8M........... \n ....................DDO $8?..N8DNZ.8ZDNID8D .......... \n ....................8N8 ...M+?=DM$.OO?.8DD$ .......... \n ....................MNN,7ZD $N$+N8ZZO:.DDM.. ......... \n ....................ODO8D..=D.M.8+DON.Z8O+ ........... \n ................... .MN$=.ZI..O,N?8D~~NOM............. \n ................... :DDDZ~I.8$:D,D$8NDM.............. \n ..................... 7ND8D.,7..ODDDNNMO.............. \n ................... . ..MDN8NM8MMMDDD7................ \n ........................ :MNDDDDMNMI ................. \n ...................... .... ~$,:.... ................ \n ................ \n\n\"\"\"\n \n self.input_filepath = input_filepath\n self.casename = self.input_filepath.split(\"/\")[-1][:-3]\n self.working_directory = \"./\" + \"/\".join(self.input_filepath.split(\"/\")[:-1]) + \"/\"\n self.script_dir = \"/\".join(os.path.realpath(__file__).split(\"/\")[:-1]) + \"/\"\n \n os.chdir(self.working_directory)\n \n #Reading contecnts of input file\n with open(input_filepath) as input_file:\n self.raw_input = input_file.readlines()\n input_data = [line.strip() for line in self.raw_input if not (line[0] == \"#\" or line == \"\\n\")]\n \n #Read raw input text into cards\n self.material_card = input_data[input_data.index('READ MATERIAL')+1:input_data.index('END MATERIAL')]\n self.geometry_card = input_data[input_data.index('READ GEOMETRY')+1:input_data.index('END GEOMETRY')]\n self.parameters_card = input_data[input_data.index('READ PARAMETERS')+1:input_data.index('END PARAMETERS')]\n self.paths_card = input_data[input_data.index('READ PATHS')+1:input_data.index('END PATHS')]\n \n #initializing material card\n self.material_process()\n \n \n #parsing geometry related inputs\n self.layer_materials = [a for a in self.geometry_card if a.split()[0] == \"layer_material\"][0].split()[2:] \n self.layer_thicknesses = np.array([a for a in self.geometry_card if a.split()[0] == \"layer_thicknesses\"][0].split()[2:]).astype(np.float32)\n \n #parsing parameter related inputs\n self.parameters = {x[0] : x[1] for x in [parameter.replace(\" \", \"\").split(\"=\") for parameter in self.parameters_card]}\n \n #parsing path related inputs\n self.paths = {x[0] : self.working_directory + x[1] for x in [parameter.replace(\" \", \"\").split(\"=\") for parameter in self.paths_card]}\n \n self.bin_calibration(self.paths[\"cs137spec_filepath\"])\n \n self.source_spec = pull_spectrum(self.paths[\"source_filepath\"])/float(self.parameters[\"source_time\"])\n \n if \"background_filepath\" in self.paths:\n self.source_spec -= pull_spectrum(self.paths[\"background_filepath\"])/float(self.parameters[\"background_time\"])\n \n #identigy groups and strengths and assign \"cross sections\"\n self.id_groups(plot_spec_peaks = True, plot_norm_peaks = True)\n self.ac_process()\n \n \n \n def bin_calibration(self,cs137spec_filepath):\n \"\"\"\n Function to set energy values to each bin. Must be based on cs137 spectrum.\n Parameters:\n self - does not pull any attributes from self\n cs137spec_filepath - file name of a *.Spe file containing unattenuated spectrum from a Cs-137 source \n Returns:\n self.bin_energies - numpy array containing the estimated energies associated with each bin\n \"\"\"\n def how_much_gaussian(n, x, y):\n def gaus(x,a0,mu,sigma):\n return a0*(sigma*np.sqrt(2*np.pi))**-1*np.exp(-(x-mu)**2/(2*sigma**2)) \n \n a0 = np.trapz(y) \n mean0 = x[y.argmax()] \n sigma0 = sum(y*(x-mean0)**2)/n \n \n popt,pcov = scipy.optimize.curve_fit(gaus,x,y,p0=[a0,mean0,sigma0],maxfev=1000000)\n perr = np.sqrt(np.diag(pcov)).sum()\n \n if perr > 500:\n return False\n else:\n return True\n\n\n \n cs137_peak = 661.6 #keV\n \n #Smooth the spectrum and extract energy local maxima\n cs137_spec = pull_spectrum(cs137spec_filepath) \n plt.show()\n \n cs137_spec = smooth(cs137_spec,30)\n peaks, empty_dict = scipy.signal.find_peaks(cs137_spec)\n \n #calculate the prominence associated with each maxima and find the bin with the largest prominence\n prominences, left_bases, right_bases = scipy.signal.peak_prominences(cs137_spec, peaks)\n peaks = np.compress(prominences > prominences.mean(), peaks)\n left_bases = np.compress(prominences > prominences.mean(), left_bases)\n right_bases = np.compress(prominences > prominences.mean(), right_bases)\n \n gauss_errors = np.array([])\n for i in range(peaks.size):\n n = right_bases[i]-left_bases[i]\n x = np.linspace(left_bases[i],right_bases[i],n)\n y = cs137_spec[left_bases[i]:right_bases[i]]\n gauss_errors = np.append(gauss_errors, how_much_gaussian(n,x,y))\n \n peaks = np.compress(gauss_errors, peaks)\n prominences, left_bases, right_bases = scipy.signal.peak_prominences(cs137_spec, peaks)\n \n \n \n #Find bin of maximum energy\n maxEbin = peaks[prominences.argmax()]\n self.maxEbin = maxEbin\n self.cs137_spec = cs137_spec\n delE = cs137_peak/maxEbin\n \n #Create bin energy array\n self.bin_energies = np.arange(0, cs137_spec.size * delE, delE)\n \n return 1\n \n def id_groups(self, plot_spec_peaks = False, plot_norm_peaks = False, width_threshold = [30, 170], width_rel_height = 0.7):\n \"\"\"\n Function to identify energy group and count rate of each energy group.\n Parameters:\n self - both bin_energies and source_spec must be defined\n plot_spec_peaks - boolean to plot full source spectrum with e group identified\n plot_norm_peaks = boolean to plot norm fits as well. Should only be true if plot_spec_peaks is true\n width_threshold - tuning parameter for acceptable peak width\n Returns:\n self.group_counts - count rate associated with each group\n self.group_energies - energy value associated with each group\n \"\"\"\n #Define gaussian checker for later in function \n def is_gaussian(n, x, y, width_rel_height,be,plot_norm_peaks):\n def gaus(x,a0,mu,sigma):\n return a0*(sigma*np.sqrt(2*np.pi))**-1*np.exp(-(x-mu)**2/(2*sigma**2)) \n \n a0 = np.trapz(y) #4253\n mean0 = x[y.argmax()] #sum(x*y)/n #377.977\n sigma0 = sum(y*(x-mean0)**2)/n # 114.967\n \n \n popt,pcov = scipy.optimize.curve_fit(gaus,x,y,p0=[a0,mean0,sigma0],maxfev=100000)\n perr = np.sqrt(np.diag(pcov)).sum()\n \n if perr > 30 or perr is np.nan:\n return (False, 0)\n else:\n if plot_norm_peaks:\n plt.plot(be,gaus(x,*popt),'o', c = \"mediumseagreen\", MarkerSize=5, label = \"Gaussian Approximation\")\n return (True, popt[0])\n \n #initializing figure if necessary\n if plot_spec_peaks or plot_norm_peaks:\n plt.figure(figsize=[15,8])\n \n #Smooth signal to and easily identify spectrum peaks\n smoothed_spec = self.source_spec \n peaks, empty_dict = scipy.signal.find_peaks(smoothed_spec)\n \n \n #Apply criteria that prominences must be greater than the average promenance\n prominences, left_bases, right_bases = scipy.signal.peak_prominences(smoothed_spec, peaks)\n peaks = np.compress(prominences > prominences.mean(), peaks)\n \n #Apply criteria that widths must be greater than width_threshold\n widths, width_heights, leftips, rightips = scipy.signal.peak_widths(x = smoothed_spec, peaks = peaks, rel_height = width_rel_height)\n peaks = np.compress((widths > width_threshold[0]) * (widths < width_threshold[1]), peaks)\n leftips = np.floor(np.compress((widths > width_threshold[0]) * (widths < width_threshold[1]), leftips)).astype(np.int32)\n rightips = np.ceil(np.compress((widths > width_threshold[0]) * (widths < width_threshold[1]), rightips)).astype(np.int32) \n widths = np.compress((widths > width_threshold[0]) * (widths < width_threshold[1]), widths)\n \n \n #Apply criteria that shape must be appropriately gaussian\n #Hiding in here is getting the count rate under each peak as a return from the is_gaussian\n remove_i = np.array([]).astype(int)\n group_counts = np.array([])\n for i in range(peaks.size):\n n = rightips[i]-leftips[i]\n x = np.linspace(leftips[i],rightips[i],n)\n y = self.source_spec[leftips[i]:rightips[i]]\n gaussianality, group_count = is_gaussian(n,x,y, width_rel_height,self.bin_energies[leftips[i]:rightips[i]],plot_norm_peaks = plot_norm_peaks)\n if not gaussianality:\n remove_i = np.append(remove_i, i)\n else:\n group_counts = np.append(group_counts, group_count)\n \n peaks = np.delete(peaks,remove_i)\n leftips = np.delete(leftips,remove_i)\n rightips = np.delete(rightips,remove_i)\n \n #Add optional peak plotted to make sure peaks were done correctly\n if plot_spec_peaks:\n plt.plot(self.bin_energies,self.source_spec, c = \"royalblue\",label = \"Source Spectrum\")\n \n for i in range(leftips.size):\n plt.axvline(self.bin_energies[peaks[i]], c = \"crimson\", label = \"Group Energy Value\")\n \n \n plt.ylabel(\"Counts [#/s]\")\n plt.xlabel(\"Energy [keV]\")\n handles, labels = plt.gca().get_legend_handles_labels()\n by_label = OrderedDict(zip(labels, handles))\n plt.legend(by_label.values(), by_label.keys())\n plt.tight_layout()\n \n \n self.group_counts = group_counts\n self.group_energies = self.bin_energies[peaks]\n return 1\n \n def material_process(self):\n \"\"\"\n Function to decompose entries in MATERIAL CARD from text into data structs\n Parameters:\n self - must have material_card specified\n Returns:\n self.materials - dictionary-containing two items, a density and a \n material composition list\n \"\"\"\n self.materials = {}\n for entry in self.material_card:\n entry = entry.split()\n material = entry.pop(0)\n density = float(entry.pop(0))\n composition = [[int(entry[2*i]), float(entry[2*i-1])] for i in range(int(len(entry)/2))]\n self.materials[material] = [density, composition]\n \n return 1\n \n def ac_process(self):\n \"\"\"\n Function to assign cross sections to each energy group for each material\n Parameters:\n self - must have self.materials defined\n Returns:\n self.ac - dictionary with keys of each material ID and values of list representing energies\n - energy list as follows \n - each row is a separate nuclide\n - each column is an energy group\n - sum each row for total ac for an energy group\n \"\"\"\n def pull_ac(filename):\n #function to pull cross sections from libraries in workable form\n with open(filename, \"r\") as f:\n lib = np.array([s[3:].split() for s in f.readlines()])[:,:2].astype(np.float32)\n return lib\n\n self.ac = {}\n for key, value in self.materials.items():\n density = value[0]\n group_ac = np.empty((len(value[1])))\n for energy in self.group_energies:\n ac = np.array([])\n for znum, mass_frac in value[1]:\n library = self.script_dir + \"alib/\" + [i for i in os.listdir(self.script_dir + \"alib/\") if \"alib_\" + str(znum) in i][0]\n temp_ac = pull_ac(library)\n ac = np.append(ac, np.interp(energy/1000,temp_ac[:,0],temp_ac[:,1])*mass_frac)\n \n group_ac = np.vstack((group_ac, ac*density))\n self.ac[key] = group_ac[1:,:] #some adjustment that needs to be made because of array initialization\n return 1\n \n \n def compute(self):\n def solve_master(master_ara, div_rows):\n for i in range(master_ara.shape[0]):\n if np.isclose(master_ara[i,1],0):\n thickness = master_ara[i,2] - master_ara[i-1,2] \n master_ara[i,1] = master_ara[i-1,1]*np.exp(-master_ara[i-1,3]*thickness)\n\n \n #setting up depth vector and n depending on \"layer_mesh_divs\"\n if \"layer_mesh_divs\" in self.parameters.keys():\n depth = np.array([0])\n material_list = []\n \n n = int(self.parameters[\"layer_mesh_divs\"])\n \n for thickness, material in zip(self.layer_thicknesses,self.layer_materials):\n material_list += n*[material]\n start = depth[-1]\n stop = depth[-1]+thickness\n depth = np.append(depth, np.linspace(start + (stop-start)/(n+1) ,depth[-1]+thickness,n))\n else:\n n = 1\n depth = np.append(0,np.cumsum(self.layer_thicknesses))\n material_list = self.layer_materials\n \n \n #set up master array with columns energy, strength, depth, and atten coeff\n master_ara = np.zeros((depth.size*self.group_energies.size, 4))\n \n #create array with enery group repeated the same number of times as the length of depth vec\n working_grp = np.array([])\n for i in reversed(range(self.group_energies.size)):\n working_grp = np.append(working_grp, np.tile(self.group_energies[i],depth.size))\n \n #set up attenuation coeff vector\n ac_vec = np.array([])\n \n self.material_divisions = []\n \n for i in range(self.group_energies.size):\n ac_vec = np.append(0,ac_vec)\n for mat in material_list:\n ac_vec = np.append( self.ac[mat][i,:].sum(), ac_vec)\n self.material_divisions.append(mat)\n \n\n #place these vectors in master_ara\n master_ara[:,0] = working_grp\n master_ara[:,2] = np.tile(depth, self.group_energies.size)\n master_ara[:,3] = ac_vec\n \n #finding rows that start each energy group\n div_rows = np.array([0])\n for i in range(master_ara.shape[0]-1):\n if master_ara[i,3]==0:\n div_rows = np.append(div_rows, i+1)\n \n #initializing count rate for each energy group\n master_ara[div_rows,1] = self.group_counts\n \n #Fill in counts to each division in master_ara\n solve_master(master_ara, div_rows)\n \n self.master_ara = [master_ara,div_rows]\n \n return 1\n \n def print_output(self):\n def heading(string):\n return(\"\\n\" + 80*\"-\" + \"\\n\" + string + \"\\n\" + 80*\"-\" + \"\\n\")\n \n \n #set up output and banner\n output = open(self.working_directory + self.casename + \".out\", \"w\")\n output.write(self.banner + \"\\n\" + str(datetime.datetime.now()) + \"\\n\\n\")\n \n #printing raw input\n output.write(heading(\"Raw Input\"))\n output.write(\"\".join(self.raw_input))\n \n #printing cards\n output.write(heading(\"Material Card\"))\n output.write(\"\\n\".join(self.material_card) + \"\\n\")\n output.write(heading(\"Geometry Card\"))\n output.write(\"\\n\".join(self.geometry_card) + \"\\n\")\n output.write(heading(\"Parameters Card\"))\n output.write(\"\\n\".join(self.parameters_card) + \"\\n\") \n output.write(heading(\"Paths Card\"))\n output.write(\"\\n\".join(self.paths_card) + \"\\n\") \n\n #printing materials\n output.write(heading(\"Materials\"))\n for key, item in self.materials.items():\n #print(key,item[)\n output.write(\"Material: %s Density: %.4f [g/cm^3]\\n\" % (key.ljust(15), item[0]))\n output.write(\"Atomic Number Mass Fraction\\n\")\n for z,p in item[1]:\n output.write(\"%i %.5f\\n\"%(z,p))\n output.write(\"\\n\")\n \n #printing geomety\n output.write(heading(\"Geometry\"))\n output.write(\"Material Layer Thickness [cm] Cumulative Thickness [cm]\\n\")\n accum = 0\n for i in range(len(self.layer_materials)):\n accum += self.layer_thicknesses[i]\n output.write(\"{:<17}\".format(self.layer_materials[i]) + \" %.5f\"%self.layer_thicknesses[i] + \" \"*17 + \"%.5f\"%(accum) + \"\\n\")\n \n #printing group energy and strength\n output.write(heading(\"Energy Group Identification\"))\n output.write(\"Group Energy [keV] Group Count Rate [#/s]\\n\")\n for i in range(len(self.group_counts)):\n grp = \"%.5f\"%(self.group_energies[i])\n output.write(grp + (34 - len(grp))*\" \" + \"%.5f\\n\"%(self.group_counts[i]))\n \n #printing master array\n output.write(heading(\"Master Array\"))\n output.write(\"Grp Energy [keV] Count Rate [#/s] Depth [cm] Atten Coeff [cm^2] Material\\n\")\n \n i = 0\n for j, row in enumerate(self.master_ara[0]):\n e = \"%.3f\"%row[0]\n s = \"%.3f\"%row[1]\n d = \"%.3f\"%row[2]\n c = \"%.5f\"%row[3]\n \n if np.isclose(row[3],0):\n m = \"\"\n else:\n m = self.material_divisions[i]\n i += 1\n \n output.write(e + \" \"*(19-len(e)) + s + \" \"*(19-len(s)) + d + \" \"*(13-len(d))+ c + (21-len(c))*\" \" + m + \"\\n\")\n \n if m == \"\":\n output.write(26*\" - \" + \"\\n\")\n \n #attenuation coefficient libraries\n output.write(heading(\"Attenuation Coefficient Values\"))\n for key, item in self.ac.items():\n output.write(\"Material = {mat}\\n\".format(mat = key))\n output.write(\"Atomic Number Mass Fraction \")\n for i, e in enumerate(self.group_energies):\n a = \"E%i:%.2f\"%(i,e)\n output.write(a + \" \"*(15-len(a)))\n output.write(\"\\n\") \n for i in range(item.T.shape[0]):\n anum = str(self.materials[key][1][i][0])\n frac = \"%.4f\"%self.materials[key][1][i][1]\n output.write(anum + \" \"*(16-len(anum)) + frac + \" \"*11 ) \n for j in range(item.T.shape[1]):\n const = \"%.4f\"%item.T[i,j]\n output.write(const + \" \"*(15-len(const)))\n output.write(\"\\n\")\n output.write(\"\\n\")\n \n \n #printing calibration spectra with peak identified\n output.write(heading(\"Cs-137 Calibration Spectrum\"))\n output.write(\"Bin Number Count Number\\n\")\n for i in range(self.cs137_spec.size):\n output.write(\"{:<21}\".format(str(i)) + str(self.cs137_spec[i]))\n \n if i == self.maxEbin:\n output.write(\" *661.5 keV peak, used for calibration\")\n \n output.write(\"\\n\")\n \n #printing source spectra\n output.write(heading(\"Unattenuated Spectra\"))\n output.write(\"Bin Energy [keV] Count Rate [#/s]\\n\")\n for i in range(self.source_spec.size):\n e = \"%.5f\"%self.bin_energies[i]\n s = \"%.5f\\n\"%np.abs(self.source_spec[i])\n output.write(e +(30-len(e))*\" \" + s)\n \n \n output.close()\n \nif __name__ == '__main__':\n ms_input = sys.argv[2] \n \n test = ATen(ms_input) \n test.compute()\n test.print_output()\n \n plt.show()\n", "meta": {"hexsha": "d76d6777460197f149cfabaac56a5b27e2b84a9c", "size": 26301, "ext": "py", "lang": "Python", "max_stars_repo_path": "ATen.py", "max_stars_repo_name": "deanrp2/nameless", "max_stars_repo_head_hexsha": "d785e04a3c20438feea4abcb61eb141763043909", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ATen.py", "max_issues_repo_name": "deanrp2/nameless", "max_issues_repo_head_hexsha": "d785e04a3c20438feea4abcb61eb141763043909", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ATen.py", "max_forks_repo_name": "deanrp2/nameless", "max_forks_repo_head_hexsha": "d785e04a3c20438feea4abcb61eb141763043909", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-01T07:16:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T07:16:51.000Z", "avg_line_length": 46.4681978799, "max_line_length": 153, "alphanum_fraction": 0.4923386943, "include": true, "reason": "import numpy,import scipy", "num_tokens": 6049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.24508501313237172, "lm_q1q2_score": 0.12923737341624705}} {"text": "\"\"\"MCEq Flux Models\n\nThis script implements the use of MCEq flux models via the IceCube standard\nmethod of getFlux(ptype, energy, costheta). As such it may be used as a\ndrop-in replacement for other fluxes. Weighting in IceCube is performed\nby multiplying the flux by the normalized one weight:\n\nNuGen:\n (with generator)\n weight = p_int * (flux_val / unit) * generator(energy, ptype, costheta)\n (without generator)\n weight = flux_val * one_weight / (type_weight * n_events * n_files)\n\n with flux_val = flux_object.getFlux(ptype, energy, costheta)\n\nIt is recommended to cache the results of MCEq because these take a while\nto produce. By default, the cache file is chosen\nto be located in the 'resources' directory relative to the location of this\nscript. You may also set the environment variable 'MCEQ_CACHE_DIR' in order\nto choose a different location for the cache file, or pass in an explicit\ncache file when initializing the MCEQFlux object.\n\nEnvironment Variables:\n\n 'MCEQ_CACHE_DIR':\n If provided, the MCEq cache file will be written to this directory.\n\n 'MKL_PATH':\n Path to the MKL libraries. If provided, these are passed on to MCEq.\n Note: the python package can be installed directly with MKL support\n via 'pip install MCEq[MKL]'.\n\nCredit for the vast majority of code in this file goes to Mathis Boerner.\n\"\"\"\nimport os\nimport logging\nfrom copy import deepcopy\nimport os\nimport numpy as np\nfrom scipy.interpolate import RectBivariateSpline\n\nimport ic3_labels\n\nlog = logging.getLogger('MCEqFlux')\n\n\n# If cashier is available, set up directory for caching of MCEq results\ntry:\n from ic3_labels.weights.resources.cashier import cache\n got_cashier = True\n\n if 'MCEQ_CACHE_DIR' in os.environ:\n cache_dir = os.environ['MCEQ_CACHE_DIR']\n log.info(\"Found 'MCEQ_CACHE_DIR' in environment variables: {}\".format(\n cache_dir))\n\n if not os.path.exists(cache_dir):\n log.info('Creating cache directory: {}'.format(cache_dir))\n os.makedirs(cache_dir)\n\n CACHE_FILE = os.path.join(cache_dir, 'mceq.cache')\n\n else:\n script_dir = os.path.dirname(os.path.abspath(__file__))\n CACHE_FILE = os.path.join(script_dir, 'resources', 'mceq.cache')\n\n log.info('Using MCEq cache file: {}'.format(CACHE_FILE))\n\nexcept ImportError:\n got_cashier = False\n CACHE_FILE = None\n log.info(\"Could not import 'cashier'. MCEq results will not be cached!\")\n\n\n# Dictionary that converts ptype -> MCEq type string\nPTYPE_CONVERTER = {\n 12: 'nue',\n -12: 'antinue',\n 14: 'numu',\n -14: 'antinumu',\n 16: 'nutau',\n -16: 'antinutau',\n}\n\n\ndef get_spline(\n interaction_model,\n primary_model,\n months,\n theta_grid,\n theta_grid_cos,\n cached=True,\n cache_file=CACHE_FILE,\n cache_read_only=False):\n \"\"\"Get MCEq spline\n\n Solves the MCEq cascade equations for the given parameters. The equations\n are solved on the provided grid and interpolated.\n\n Parameters\n ----------\n interaction_model : str\n The interaction model. This is passed on to `MCEqRun`.\n primary_model : str\n The primary model to use. Must be one of:\n GST_3-gen, GST_4-gen, H3a, H4a, poly-gonato, TIG, ZS, ZSP, GH\n months : list of str\n The months for which to solve the cascade equations. These must be\n provided as a list of month names, e.g. ['January', 'August']. A list\n of splines will be returned of the same length as `months`.\n theta_grid : array_like\n The grid points in theta to evaluate on in degrees. If `theta_grid_cos`\n is True, this is instead cos(theta).\n theta_grid_cos : bool\n If True, `theta_grid` is interpreted as cos(theta), i.e. arccos() is\n applied first.\n cached : bool, optional\n If True, the result will be cached, or taken from cache if previously\n already computed. This is recommended, as MCEq takes a while to run.\n cache_file : str, optional\n The path to the cache file to use.\n cache_read_only : bool, optional\n If True, the cache is read only.\n\n Returns\n -------\n dict\n The result of MCEq together with the fitted splines. The structure is\n as follows:\n {\n # first month provided via `months`\n 0: {\n 'total_spline_dict': dict of RectBivariateSpline\n A dictionary with the fitted splines for each particle\n type for the 'total' flux. The dictionary keys are the\n PDG particle encodings.\n 'conv_spline_dict': dict of RectBivariateSpline\n A dictionary with the fitted splines for each particle\n type for the 'conv' flux. The dictionary keys are the\n PDG particle encodings.\n 'pr_spline_dict': dict of RectBivariateSpline\n A dictionary with the fitted splines for each particle\n type for the 'pr' flux. The dictionary keys are the\n PDG particle encodings.\n 'total_flux_dict': dict of array_like\n A dictionary with the total flux for each grid point.\n This is the result obtained from MCEq for the 'total' flux.\n 'conv_flux_dict': dict of array_like\n A dictionary with the conv flux for each grid point.\n This is the result obtained from MCEq for the 'conv' flux.\n 'pr_flux_dict': dict of array_like\n A dictionary with the prompt flux for each grid point.\n This is the result obtained from MCEq for the 'pr' flux.\n 'config_updates': dict\n A dictionary of config updates that were applied to\n mceq_config prior to solving the equations.\n 'mceq_version' : str\n The MCEq version that was used to create the splines.\n 'ic3_labels_version' : str\n The version of the ic3-labels package that was used to\n create the splines.\n 'e_grid' : array_like\n The grid of energy points in log10.\n 'theta_grid' : array_like\n The grid of thetas.\n }\n\n # second month provided via `months`\n 1: {\n ...\n }\n\n ...\n }\n \"\"\"\n log.info('Getting Spline for {}; {} (cached={})'.format(\n interaction_model,\n primary_model,\n cached))\n\n def __solve_month__(\n mceq_run, e_grid, theta_grid, theta_grid_cos,\n ptype_converter=PTYPE_CONVERTER,\n eps=1e-128,\n ):\n \"\"\"Solve MCEq equations for the provided mceq_run instance.\n\n Parameters\n ----------\n mceq_run : MCEqRun instance\n The MCEqRun instance. This instance must be configured to use\n the desired geometry and season.\n e_grid : array_like\n The grid of energy points in log10.\n theta_grid : array_like\n The grid points in theta to evaluate on in degrees.\n If `theta_grid_cos` is True, this is instead cos(theta).\n theta_grid_cos : bool\n If True, `theta_grid` is interpreted as cos(theta),\n i.e. arccos() is applied first.\n ptype_converter : dict, optional\n A dictionary that converts PDG encoding to MCEq type string.\n eps : float, optional\n A small float value > 0 that is used to clip the total flux\n prior to applying log10 for the spline fitting.\n\n Returns\n -------\n list of dict of RectBivariateSpline\n A list of dictionaries with the fitted splines for each particle\n type. The dictionary keys are the PDG particle encodings.\n The order of the dictionaries are: 'total', 'conv', 'pr'\n list of dict of array_like\n A list of dictionaries with the total flux for each grid point.\n This is the result obtained from MCEq.\n The order of the dictionaries are: 'total', 'conv', 'pr'\n \"\"\"\n total_flux_dict = {}\n conv_flux_dict = {}\n pr_flux_dict = {}\n total_spline_dict = {}\n conv_spline_dict = {}\n pr_spline_dict = {}\n for key, value in ptype_converter.items():\n total_flux_dict[key] = np.ones((len(e_grid), len(theta_grid)))\n conv_flux_dict[key] = np.ones((len(e_grid), len(theta_grid)))\n pr_flux_dict[key] = np.ones((len(e_grid), len(theta_grid)))\n\n for i, theta_i in enumerate(theta_grid):\n if theta_grid_cos:\n theta_i = np.rad2deg(np.arccos(theta_i))\n mceq_run.set_theta_deg(theta_i)\n mceq_run.solve()\n\n # fill in flux totals\n for key, value in ptype_converter.items():\n total_flux_dict[key][:, i] = mceq_run.get_solution(\n 'total_{}'.format(value))\n conv_flux_dict[key][:, i] = mceq_run.get_solution(\n 'conv_{}'.format(value))\n pr_flux_dict[key][:, i] = mceq_run.get_solution(\n 'pr_{}'.format(value))\n\n # create splines\n for key, value in ptype_converter.items():\n total_spline_dict[key] = RectBivariateSpline(\n e_grid,\n theta_grid,\n np.log10(np.clip(total_flux_dict[key], eps, float('inf'))),\n s=0,\n )\n conv_spline_dict[key] = RectBivariateSpline(\n e_grid,\n theta_grid,\n np.log10(np.clip(conv_flux_dict[key], eps, float('inf'))),\n s=0,\n )\n pr_spline_dict[key] = RectBivariateSpline(\n e_grid,\n theta_grid,\n np.log10(np.clip(pr_flux_dict[key], eps, float('inf'))),\n s=0,\n )\n\n spline_dicts = [\n total_spline_dict, conv_spline_dict, pr_spline_dict\n ]\n\n flux_dicts = [\n total_flux_dict, conv_flux_dict, pr_flux_dict\n ]\n\n return spline_dicts, flux_dicts\n\n def __get_spline__(\n interaction_model,\n primary_model,\n months,\n theta_grid,\n theta_grid_cos,\n ):\n \"\"\"Get MCEq spline for the provided settings\n\n Parameters\n ----------\n interaction_model : str\n The interaction model. This is passed on to `MCEqRun`.\n primary_model : str\n The primary model to use. Must be one of:\n GST_3-gen, GST_4-gen, H3a, H4a, poly-gonato, TIG, ZS, ZSP, GH\n months : list of str\n The months for which to solve the cascade equations. These must be\n provided as a list of month names, e.g. ['January', 'August']. A\n list of splines will be returned of the same length as `months`.\n theta_grid : array_like\n The grid points in theta to evaluate on in degrees.\n If `theta_grid_cos` is True, this is instead cos(theta).\n theta_grid_cos : bool\n If True, `theta_grid` is interpreted as cos(theta),\n i.e. arccos() is applied first.\n\n Returns\n -------\n dict\n The result of MCEq together with the fitted splines.\n See documentation of `get_spline()` for more details.\n\n Raises\n ------\n AttributeError\n If the provided `primary_model` is unknown.\n \"\"\"\n log.info('\\tCalculating \\'{}\\' \\'{}\\''.format(\n interaction_model, primary_model))\n\n import mceq_config\n from MCEq import version\n from MCEq.core import MCEqRun\n import crflux.models as pm\n\n config_updates = {\n 'h_obs': 1000.,\n 'debug_level': 1,\n }\n if 'MKL_PATH' in os.environ:\n config_updates['MKL_path'] = os.environ['MKL_PATH']\n\n splines = {}\n pmodels = {\n \"GST_3-gen\": (pm.GaisserStanevTilav, \"3-gen\"),\n \"GST_4-gen\": (pm.GaisserStanevTilav, \"4-gen\"),\n \"H3a\": (pm.HillasGaisser2012, \"H3a\"),\n \"H4a\": (pm.HillasGaisser2012, \"H4a\"),\n \"poly-gonato\": (pm.PolyGonato, False),\n \"TIG\": (pm.Thunman, None),\n \"ZS\": (pm.ZatsepinSokolskaya, 'default'),\n \"ZSP\": (pm.ZatsepinSokolskaya, 'pamela'),\n \"GH\": (pm.GaisserHonda, None),\n }\n\n for i, month in enumerate(months):\n config_updates['density_model'] = (\n 'MSIS00_IC', ('SouthPole', month))\n\n # update settings in mceq_config\n # Previous method mceq_config.config is deprecated and resulted\n # in pickle errors for deepcopy.\n for name, value in config_updates.items():\n setattr(mceq_config, name, value)\n\n try:\n pmodel = pmodels[primary_model]\n except KeyError:\n raise AttributeError(\n 'primary_model {} unknown. options: {}'.format(\n primary_model, pmodels.keys()))\n mceq_run = MCEqRun(\n interaction_model=interaction_model,\n primary_model=pmodel,\n theta_deg=0.0,\n **config_updates)\n e_grid = np.log10(deepcopy(mceq_run.e_grid))\n spline_dicts, flux_dicts = __solve_month__(\n mceq_run,\n e_grid,\n theta_grid,\n theta_grid_cos)\n\n splines[i] = {}\n splines[i]['total_spline_dict'] = spline_dicts[0]\n splines[i]['conv_spline_dict'] = spline_dicts[1]\n splines[i]['pr_spline_dict'] = spline_dicts[2]\n splines[i]['total_flux_dict'] = flux_dicts[0]\n splines[i]['conv_flux_dict'] = flux_dicts[1]\n splines[i]['pr_flux_dict'] = flux_dicts[2]\n splines[i]['config_updates'] = deepcopy(config_updates)\n splines[i]['mceq_version'] = version.__version__\n splines[i]['ic3_labels_version'] = ic3_labels.__version__\n splines[i]['e_grid'] = e_grid\n splines[i]['theta_grid'] = theta_grid\n return splines\n\n if got_cashier and cached:\n if cache_file is None:\n cache_f = 'mceq.cache'\n else:\n cache_f = cache_file\n log.info('\\tUsing cache \\'{}\\''.format(cache_f))\n\n @cache(cache_file=cache_f, read_only=cache_read_only)\n def wrapped_get_spline(\n interaction_model,\n primary_model,\n months,\n theta_grid,\n theta_grid_cos,\n ):\n return __get_spline__(\n interaction_model=interaction_model,\n primary_model=primary_model,\n months=months,\n theta_grid=theta_grid,\n theta_grid_cos=theta_grid_cos,\n )\n\n return wrapped_get_spline(\n interaction_model,\n primary_model,\n months,\n theta_grid,\n theta_grid_cos,\n )\n else:\n return __get_spline__(\n interaction_model=interaction_model,\n primary_model=primary_model,\n months=months,\n theta_grid=theta_grid,\n theta_grid_cos=theta_grid_cos,\n )\n\n\nclass MCEQFlux(object):\n\n \"\"\"MCQe Flux Wrapper\n\n Attributes\n ----------\n min_theta_deg : float, optional\n The minimum value of the theta grid in degrees.\n If `theta_grid_cos` is True, this is instead cos(theta).\n max_theta_deg : float, optional\n The maximum value of the theta grid in degrees.\n If `theta_grid_cos` is True, this is instead cos(theta).\n month_weights : array_like\n A list of probabilities for each month. These are used as weights\n to sample the corresponding month for each MC events.\n These weights can, for instance, be set to the relative livetime in\n each month of the year. This will then account for seasonal variations.\n months : list of str\n A list of months for which the interpolation splines are created.\n random_state : np.random.RandomState\n The random state that is used to draw the month for each MC event.\n splines : dict\n A dictionary containing the MCEq result and fitted splines.\n See documentation of `get_splines()` for more details.\n theta_grid : array_like\n The grid points in theta to evaluate on in degrees.\n If `theta_grid_cos` is True, this is instead cos(theta).\n theta_grid_cos : bool\n If True, `min_theta_deg` and `max_theta_deg` are interpreted as\n cos(theta), i.e. arccos() is applied first.\n \"\"\"\n\n def __init__(\n self,\n min_theta_deg=0.,\n max_theta_deg=180.,\n theta_grid_cos=False,\n theta_steps=181,\n season='full_year',\n flux_type='total',\n random_state=None,\n **kwargs):\n \"\"\"Initialize MCEQFlux Instance\n\n Parameters\n ----------\n min_theta_deg : float, optional\n The minimum value of the theta grid in degrees.\n If `theta_grid_cos` is True, this is instead cos(theta).\n max_theta_deg : float, optional\n The maximum value of the theta grid in degrees.\n If `theta_grid_cos` is True, this is instead cos(theta).\n theta_grid_cos : bool\n If True, `min_theta_deg` and `max_theta_deg` are interpreted as\n cos(theta), i.e. arccos() is applied first.\n theta_steps : int, optional\n The number of grid points between the specified min and max values.\n season : str, optional\n What season to use. This may either be a single month ,\n for example 'January', or 'full_year' may be used to run MCEq\n for every month of the year.\n flux_type : str, optional\n The flux type to compute. This must be one of\n 'total': combined prompt and conv flux\n 'pr': prompt neutrino flux\n 'conv': conventional neutrino flux\n This will set the default flux type when calling `getFlux()`.\n You may, however, overwrite this defaul by passing an alternative\n flux type to `getFlux()`. Setting this default value allows for\n drop in replacement of other flux implementations in IceCube.\n random_state : np.random.Randomstate or int, optional\n An int or random state to set the seed.\n **kwargs\n Additional keyword arguments. (Not used!)\n \"\"\"\n if not isinstance(random_state, np.random.RandomState):\n random_state = np.random.RandomState(random_state)\n self.random_state = random_state\n if season.lower() == 'full_year':\n self.months = [\n 'January',\n 'February',\n 'March',\n 'April',\n 'May',\n 'June',\n 'July',\n 'August',\n 'September',\n 'October',\n 'November',\n 'December',\n ]\n else:\n self.months = [season]\n\n if flux_type.lower() not in ['total', 'conv', 'pr']:\n raise ValueError('Flux type: {} must be on of {}'.format(\n flux_type.lower(), ['total', 'conv', 'pr']))\n\n self.flux_type = flux_type\n self.set_month_weights(np.ones_like(self.months, dtype=float))\n self.min_theta = min_theta_deg\n self.max_theta = max_theta_deg\n if theta_grid_cos:\n self.min_theta = np.cos(np.deg2rad(min_theta_deg))\n self.max_theta = np.cos(np.deg2rad(max_theta_deg))\n self.theta_grid_cos = theta_grid_cos\n self.theta_grid = np.linspace(\n self.min_theta, self.max_theta, theta_steps)\n\n self.splines = None\n\n def initialize(\n self,\n interaction_model='SIBYLL2.3c',\n primary_model='H3a',\n cached=True,\n cache_file=CACHE_FILE,\n cache_read_only=False,\n ):\n \"\"\"Initialize MCEQFlux instance\n\n This will compute the splines or retrieve these from the cache\n if `cached` is True and if these have been previously computed.\n This method must be called prior to calls to `getFlux()`.\n\n Parameters\n ----------\n interaction_model : str\n The interaction model. This is passed on to `MCEqRun`.\n primary_model : str\n The primary model to use. Must be one of:\n GST_3-gen, GST_4-gen, H3a, H4a, poly-gonato, TIG, ZS, ZSP, GH\n cached : bool, optional\n If True, the result will be cached and if already computed, it will\n be retrieved from cache. This avoids recomputation of MCEq, which\n is recommended in order to reduce computation time.\n cache_file : str, optional\n The path to the cache file to use.\n cache_read_only : bool, optional\n If True, the cache is read only.\n \"\"\"\n if cache_file is None:\n cache_file = CACHE_FILE\n\n self.splines = get_spline(\n interaction_model,\n primary_model,\n self.months,\n self.theta_grid,\n self.theta_grid_cos,\n cached=cached,\n cache_file=cache_file,\n cache_read_only=cache_read_only,\n )\n\n from MCEq import version\n\n # throw warning if there is a version mis-match.\n for key, spline in self.splines.items():\n msg = (\n 'Cached file was created with {} version {}, '\n 'but this is version {}!'\n )\n if version.__version__ != spline['mceq_version']:\n log.warning(msg.format(\n 'MCEq', spline['mceq_version'], version.__version__))\n\n if ic3_labels.__version__ != spline['ic3_labels_version']:\n log.warning(msg.format(\n 'ic3_labels',\n spline['ic3_labels_version'],\n ic3_labels.__version__,\n ))\n\n def set_month_weights(self, month_weights):\n \"\"\"Summary\n\n Parameters\n ----------\n month_weights : array_like\n A list of probabilities for each month (these will be normalized\n internally). These are used as weights to sample the corresponding\n month for each MC events. These weights can, for instance, be set\n to the relative livetime in each month of the year.\n This will then account for seasonal variations.\n\n Raises\n ------\n AttributeError\n If the length of the provided `muon_weights` does not match the\n length of the specified months.\n \"\"\"\n if len(month_weights) != len(self.months):\n raise AttributeError(\n 'month_weights needs to be of the same '\n 'length like self.months.'\n )\n self.month_weights = month_weights / np.sum(month_weights)\n\n def getFlux(\n self,\n ptype,\n energy,\n costheta,\n selected_month=None,\n random_state=None,\n flux_type=None,\n ):\n \"\"\"Get flux for provided particle\n\n The flux is given in GeV^-1 cm^-2 s^-1 sr^-1 and may be used to\n weight NuGen events via the normalized `one_weight`:\n weight = flux * one_weight / (type_weight * n_events * n_files)\n\n Parameters\n ----------\n ptype : array_like or int\n The PDG encoding.\n For instance: I3MCWeightDict -> PrimaryNeutrinoType\n energy : array_like or float\n The energy of the primary particle.\n For instance: I3MCWeightDict -> PrimaryNeutrinoEnergy\n costheta : array_like or float\n The cos(zenith) angle of the primary particle.\n For instance: cos(I3MCWeightDict -> PrimaryNeutrinoZenith)\n selected_month : array_like, optional\n The month in which each event occurred. This must be given as\n an array of integer values between [0, 11] if `season` is\n 'full_year'. If the `MCEQFlux` instance is initialized with only\n one month as the season, then `selected_month` must not be set.\n If None provided, the corresponding month of each event will be\n sampled via the defined `month_weights`.\n random_state : np.random.Randomstate or int, optional\n An int or random state to set the seed.\n If None provided, the random state will be used that was\n reated during initialization.\n flux_type : str, optional\n The flux type to compute. This must be one of\n 'total': combined prompt and conv flux\n 'pr': prompt neutrino flux\n 'conv': conventional neutrino flux\n If None is provided, the specified default value at\n object instantiation time (__init__()) will be used.\n\n Returns\n -------\n array_like\n The flux for the given particle in GeV^-1 cm^-2 s^-1 sr^-1.\n\n Raises\n ------\n RuntimeError\n If MCEQFlux has not been initialized yet.\n ValueError\n If wrong `flux_type` is provided.\n \"\"\"\n if self.splines is None:\n raise RuntimeError(\n 'No splines calculated! Run \\'initialize\\' first')\n\n if len(self.months) == 1 and selected_month is not None:\n raise ValueError(\n 'The months may not be set, since the MCEQFlux instance is '\n + 'initialized with only one month: {}'.format(self.months)\n )\n\n if flux_type is None:\n flux_type = self.flux_type\n elif flux_type.lower() not in ['total', 'conv', 'pr']:\n raise ValueError('Flux type: \"{}\" must be on of {}'.format(\n flux_type.lower(), ['total', 'conv', 'pr']))\n flux_type = flux_type.lower()\n\n if random_state is None:\n random_state = self.random_state\n elif not isinstance(random_state, np.random.RandomState):\n random_state = np.random.RandomState(random_state)\n\n # convert to numpy arrays and make sure these are at least 1D\n ptype = np.atleast_1d(ptype)\n energy = np.atleast_1d(energy)\n costheta = np.atleast_1d(costheta)\n\n if len(self.splines) > 1:\n if selected_month is None:\n int_months = np.arange(len(self.splines), dtype=int)\n selected_month = random_state.choice(\n int_months,\n replace=True,\n size=len(energy),\n p=self.month_weights,\n )\n else:\n selected_month = np.asarray(selected_month, dtype=int)\n else:\n selected_month = list(self.splines.keys())[0]\n flux = np.ones_like(energy)\n flux[:] = float('NaN')\n log10_energy = np.log10(energy)\n theta = np.rad2deg(np.arccos(costheta))\n\n for ptype_i in np.unique(ptype):\n mask_ptype = ptype == ptype_i\n for i in self.splines.keys():\n if isinstance(selected_month, int):\n idx_ptype = mask_ptype\n else:\n is_in_month = selected_month == i\n idx_ptype = np.logical_and(mask_ptype, is_in_month)\n flux[idx_ptype] = self.splines[i][\n flux_type + '_spline_dict'][ptype_i](\n log10_energy[idx_ptype],\n theta[idx_ptype],\n grid=False)\n return np.power(10., flux)\n", "meta": {"hexsha": "7510b2e855983a51cfd89ee8bf17833c9ed74428", "size": 28190, "ext": "py", "lang": "Python", "max_stars_repo_path": "ic3_labels/weights/mceq_models.py", "max_stars_repo_name": "IceCubeOpenSource/ic3-labels", "max_stars_repo_head_hexsha": "049565e1dd423115020484fca5b891afdd1f97bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-21T09:06:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-21T09:06:12.000Z", "max_issues_repo_path": "ic3_labels/weights/mceq_models.py", "max_issues_repo_name": "icecube/ic3-labels", "max_issues_repo_head_hexsha": "049565e1dd423115020484fca5b891afdd1f97bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ic3_labels/weights/mceq_models.py", "max_forks_repo_name": "icecube/ic3-labels", "max_forks_repo_head_hexsha": "049565e1dd423115020484fca5b891afdd1f97bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-06-10T13:37:17.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-21T06:16:35.000Z", "avg_line_length": 38.0945945946, "max_line_length": 79, "alphanum_fraction": 0.5759843916, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2538610126142736, "lm_q1q2_score": 0.1289136340834609}} {"text": "#!/search/odin/liyaozong/tools/python3/bin/python3\n# coding: utf8\n\nimport random\nimport numpy as np\nfrom collections import defaultdict, deque\nfrom game import Board, Game\nfrom mcts_pure import MCTSPlayer as MCTS_Pure\nfrom mcts_alphaZero import MCTSPlayer\nimport multiprocessing\nfrom multiprocessing import Manager, Pool\nimport time\nimport logging\nfrom tensorflow.python.platform import gfile\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\nmodel_dir='./multi_3'\nlog_name = model_dir + '/logs'\ncurrent_model_name = model_dir + '/current_policy_model'\ntemp_current_model_name = model_dir + '/temp_current_policy_model'\nbest_model_name = model_dir + '/best_policy_model'\n\n\nclass TrainPipeline():\n\n def __init__(self, init_model=None):\n # params of the board and the game\n self.board_width = 8\n self.board_height = 8\n self.n_in_row = 5\n # training params\n self.learn_rate = 2e-3\n # self.lr_multiplier = 1.0\n self.temp = 1.0 # the temperature param\n self.n_playout = 400 # num of simulations for each move\n self.c_puct = 5\n self.batch_size = 512 # mini-batch size for training\n self.buffer_num = self.batch_size * 10\n self.epochs = 5 # num of train_steps for each update\n self.kl_targ = 0.02\n self.check_freq = 60\n self.game_batch_num = 1000000000\n self.process_num = 12\n self.summary_record_freq = 5\n # self.global_update_step = 0\n\n def collect_selfplay_data_thread(self, thread_id, shared_queue, net_lock, data_lock):\n logging.info('selfpaly process start: {}'.format(thread_id))\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(thread_id % 6 + 2)\n from policy_value_net_tensorflow import PolicyValueNet\n # 读取模型文件,加锁\n with net_lock:\n current_policy = PolicyValueNet(self.board_width, self.board_height, model_file=current_model_name)\n local_board = Board(width=self.board_width,\n height=self.board_height,\n n_in_row=self.n_in_row)\n local_game = Game(local_board)\n local_mcts_player = MCTSPlayer(current_policy.policy_value_fn,\n c_puct=self.c_puct,\n n_playout=self.n_playout,\n is_selfplay=1)\n winner, play_data = local_game.start_self_play(local_mcts_player,\n temp=self.temp)\n play_data = list(play_data)\n play_data = self.get_equi_data(play_data)\n # 添加对弈数据,加锁\n with data_lock:\n shared_queue.extend(play_data)\n while len(shared_queue) > self.buffer_num:\n shared_queue.pop(0)\n logging.info('selfpaly process finished: {}'.format(thread_id))\n\n def get_equi_data(self, play_data):\n \"\"\"augment the data set by rotation and flipping\n play_data: [(state, mcts_prob, winner_z), ..., ...]\n \"\"\"\n extend_data = []\n for state, mcts_porb, winner in play_data:\n for i in [1, 2, 3, 4]:\n # rotate counterclockwise\n equi_state = np.array([np.rot90(s, i) for s in state])\n equi_mcts_prob = np.rot90(np.flipud(\n mcts_porb.reshape(self.board_height, self.board_width)), i)\n extend_data.append((equi_state,\n np.flipud(equi_mcts_prob).flatten(),\n winner))\n # flip horizontally\n equi_state = np.array([np.fliplr(s) for s in equi_state])\n equi_mcts_prob = np.fliplr(equi_mcts_prob)\n extend_data.append((equi_state,\n np.flipud(equi_mcts_prob).flatten(),\n winner))\n return extend_data\n\n def policy_update(self, current_policy_value_net, shared_queue, net_lock, global_update_step, lr_multiplier):\n \"\"\"update the policy-value net\"\"\"\n random_index = list(range(len(shared_queue)))\n random.shuffle(random_index)\n mini_batch = []\n for i in range(self.batch_size):\n mini_batch.append(shared_queue[random_index[i]])\n state_batch = [data[0] for data in mini_batch]\n mcts_probs_batch = [data[1] for data in mini_batch]\n winner_batch = [data[2] for data in mini_batch]\n old_probs, old_v = current_policy_value_net.policy_value(state_batch)\n loss, entropy = current_policy_value_net.train_step(\n state_batch,\n mcts_probs_batch,\n winner_batch,\n self.learn_rate * lr_multiplier.value)\n new_probs, new_v = current_policy_value_net.policy_value(state_batch)\n kl = np.mean(np.sum(old_probs * (\n np.log(old_probs + 1e-10) - np.log(new_probs + 1e-10)),\n axis=1)\n )\n # adaptively adjust the learning rate\n if kl > self.kl_targ * 2 and lr_multiplier.value > 0.1:\n lr_multiplier.value /= 1.5\n elif kl < self.kl_targ / 2 and lr_multiplier.value < 10:\n lr_multiplier.value *= 1.5\n\n explained_var_old = (1 -\n np.var(np.array(winner_batch) - old_v.flatten()) /\n np.var(np.array(winner_batch)))\n explained_var_new = (1 -\n np.var(np.array(winner_batch) - new_v.flatten()) /\n np.var(np.array(winner_batch)))\n logging.info(\"update current model process kl:{:.5f},lr_multiplier:{:.3f},loss:{},entropy:{},explained_var_old:{:.3f},explained_var_new:{:.3f}\".format(\n kl,\n lr_multiplier.value,\n loss,\n entropy,\n explained_var_old,\n explained_var_new))\n # summary for tensorboard\n if global_update_step.value % self.summary_record_freq == 0:\n current_policy_value_net.summary_record(\n state_batch,\n mcts_probs_batch,\n winner_batch,\n global_update_step.value,\n )\n\n def update_net(self, shared_queue, net_lock, update_best_model, global_update_step, lr_multiplier, stop_update_process, update_or_selfplay):\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n from policy_value_net_tensorflow import PolicyValueNet\n current_policy_value_net = PolicyValueNet(self.board_width, self.board_height, model_dir)\n current_policy_value_net.save_model(current_model_name)\n current_policy_value_net.save_model(best_model_name)\n while global_update_step.value <= self.game_batch_num:\n if update_or_selfplay.value == 0:\n if len(shared_queue) >= self.batch_size:\n for _ in range(self.epochs):\n global_update_step.value += 1\n logging.info('update current model process start self train: {}'.format(global_update_step.value))\n self.policy_update(current_policy_value_net, shared_queue, net_lock, global_update_step, lr_multiplier)\n if (global_update_step.value) % self.check_freq == 0:\n update_best_model.value = 1\n # 这里更新最新模型文件\n with net_lock:\n logging.info('update process update current model')\n current_policy_value_net.save_model(current_model_name)\n update_or_selfplay.value = 1\n else:\n time.sleep(1)\n stop_update_process.value = 1\n\n\n def update_best_model_thread(self, current_model_name, best_model_name, net_lock, update_best_model, stop_update_process):\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n def update_best_model_local_process_func(name1, name2):\n from policy_value_net_tensorflow import PolicyValueNet\n PolicyValueNet(self.board_width, self.board_height, model_file=name1).save_model(name2)\n update_best_model_global_num = 0\n update_best_model_time = 0\n logging.info('update best model process start!')\n while stop_update_process.value == 0:\n time.sleep(1)\n if update_best_model.value == 1:\n update_best_model.value = 0\n update_best_model_global_num += 1\n logging.info('update best model process global_num:{}'.format(update_best_model_global_num))\n win_num = 0\n start_player = 0\n with net_lock:\n p = multiprocessing.Process(target=update_best_model_local_process_func, args=(current_model_name, temp_current_model_name))\n p.start()\n p.join()\n for i in range(30):\n board = Board(width=self.board_width, height=self.board_height, n_in_row=self.n_in_row)\n game = Game(board)\n win_player = game.two_net_play(temp_current_model_name, best_model_name, net_lock, start_player=start_player, is_shown=0)\n start_player = 1 - start_player # play first in turn\n if win_player == 0:\n win_num += 1\n logging.info('update best model process global_num:{} finished, current model win total {}'.format(update_best_model_global_num, win_num))\n if win_num >= 16:\n update_best_model_time += 1\n logging.info('update best model process get new best model:{}'.format(update_best_model_time))\n p = multiprocessing.Process(target=update_best_model_local_process_func, args=(temp_current_model_name, best_model_name))\n p.start()\n p.join()\n\n def run(self):\n \"\"\"run the training pipeline\"\"\"\n try:\n # 必须在一个线程中引入tensorflow,否则会造成其他线程由于错误阻塞。\n # ERROR: could not retrieve CUDA device count: CUDA_ERROR_NOT_INITIALIZED\n m = Manager()\n shared_queue = m.list()\n net_lock = m.Lock()\n data_lock = m.Lock()\n stop_update_process = multiprocessing.Value('i', 0)\n update_best_model = multiprocessing.Value('i', 0)\n global_update_step = multiprocessing.Value('i', 0)\n lr_multiplier = multiprocessing.Value('d', 1.0)\n update_or_selfplay = multiprocessing.Value('i', 0)\n update_best_model_process = multiprocessing.Process(target=self.update_best_model_thread,\n args=(current_model_name, best_model_name, net_lock, update_best_model, stop_update_process))\n update_best_model_process.start()\n update_current_model_process = multiprocessing.Process(target=self.update_net,\n args=(shared_queue, net_lock, update_best_model, global_update_step, lr_multiplier, stop_update_process, update_or_selfplay))\n update_current_model_process.start()\n while stop_update_process.value == 0:\n if update_or_selfplay.value == 1:\n # 产生训练数据\n pro_list = []\n for i in range(self.process_num):\n pro = multiprocessing.Process(target=self.collect_selfplay_data_thread, args=(i, shared_queue, net_lock, data_lock))\n pro_list.append(pro)\n pro.start()\n for pro in pro_list:\n pro.join()\n update_or_selfplay.value = 0\n else:\n time.sleep(0.1)\n # 等待更新最有模型的进程结束,再结束主程序\n stop_update_process.value = 1\n while update_best_model_process.is_alive():\n time.sleep(5)\n except Exception as e:\n logging.error(e)\n\nif __name__ == '__main__':\n if gfile.Exists(model_dir):\n gfile.DeleteRecursively(model_dir)\n gfile.MakeDirs(model_dir)\n # log 配置\n logging.basicConfig(filename=log_name, level=logging.INFO, format=\"[%(levelname)s]\\t%(asctime)s\\tLINENO:%(lineno)d\\t%(message)s\", datefmt=\"%Y-%m-%d %H:%M:%S\")\n training_pipeline = TrainPipeline()\n logging.info('start training')\n training_pipeline.run()\n logging.info('all finished')\n\n", "meta": {"hexsha": "84a31b238c88252bfbdf9e582d5c5e8c7f1dfafd", "size": 12361, "ext": "py", "lang": "Python", "max_stars_repo_path": "train_multi_3.0.py", "max_stars_repo_name": "liyaozong1991/Gomoku-AI", "max_stars_repo_head_hexsha": "40670d0b621475a7caa3a3e9ef51644da1b352f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "train_multi_3.0.py", "max_issues_repo_name": "liyaozong1991/Gomoku-AI", "max_issues_repo_head_hexsha": "40670d0b621475a7caa3a3e9ef51644da1b352f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "train_multi_3.0.py", "max_forks_repo_name": "liyaozong1991/Gomoku-AI", "max_forks_repo_head_hexsha": "40670d0b621475a7caa3a3e9ef51644da1b352f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.28515625, "max_line_length": 162, "alphanum_fraction": 0.6044009384, "include": true, "reason": "import numpy", "num_tokens": 2620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.25386099567919973, "lm_q1q2_score": 0.12891362548362947}} {"text": "#!/usr/bin/env python\n\nimport os\nimport time\nimport numpy as np\nimport socket\nimport logging\nimport tempfile\nimport shutil\nfrom glob import glob\nfrom datetime import datetime\nfrom dlnpyutils import utils as dln, coords\nimport photred\nfrom photred import io,daomatch\nfrom photred import allframe as alf\nimport dill as pickle\nfrom astropy.io import fits\nfrom astropy.wcs import WCS\nfrom astropy.table import Table\nfrom astropy.coordinates import SkyCoord\nfrom dustmaps.sfd import SFDQuery\nimport subprocess\n\ndef make_brick_wcs(brickstr):\n \"\"\"\n This creates a brick WCS given the brick structure\n \n Each brick covers 0.25 x 0.25 deg at a pixel scale of 0.262\"/pix\n with 3600x3600 pixels that gives us an overlap of ~82 pixels on\n each side. The *UNIQUE* brick area (0.25x0.25 deg) is defined by\n the BRAMIN/MAX and BDECMIN/MAX keywords.\n \"\"\"\n\n # Make the tiling file\n #---------------------\n nx = 3600\n ny = 3600\n step = 0.262 / 3600 # 0.262\" per pixel, DECam pixel scale\n xref = nx/2\n yref = ny/2\n\n # Make the header as well\n tilehead = fits.Header()\n tilehead['NAXIS1'] = nx\n tilehead['CDELT1'] = step\n tilehead['CRPIX1'] = xref+1\n tilehead['CRVAL1'] = brickstr['ra']\n tilehead['CTYPE1'] = 'RA---TAN'\n tilehead['NAXIS2'] = ny\n tilehead['CDELT2'] = step\n tilehead['CRPIX2'] = yref+1\n tilehead['CRVAL2'] = brickstr['dec']\n tilehead['CTYPE2'] = 'DEC--TAN'\n tilehead['BRAMIN'] = brickstr['ra1'],'RA min of unique brick area'\n tilehead['BRAMAX'] = brickstr['ra2'],'RA max of unique brick area'\n tilehead['BDECMIN'] = brickstr['dec1'],'DEC min of unique brick area'\n tilehead['BDECMAX'] = brickstr['dec2'],'DEC max of unique brick area'\n wcs = WCS(tilehead)\n \n # Create the TILE structure\n tile = {'type':'WCS','naxis':np.array([nx,ny]),'cdelt':np.array([step,step]).astype(float),\n 'crpix':np.array([xref+1,yref+1]).astype(float),\n 'crval':np.array([brickstr['ra'],brickstr['dec']]).astype(float),'ctype':['RA--TAN','DEC--TAN'],\n 'head':tilehead,'wcs':wcs,'xrange':[0,nx],'yrange':[0,ny],'nx':nx,'ny':ny}\n\n return tile\n\ndef forcebrick(brick,scriptsdir=None,irafdir=None,workdir=None,redo=False,\n update=False,logfile=None,delvedir=None,delvereddir=None):\n \"\"\"\n Process a single DELVE brick and perform ALLFRAME FORCED photometry \n \n Parameters\n ----------\n brick : str\n The DELVE brick name, e.g. 1234m045 \n \n By D. Nidever August 2019 \n Translated to Python by D. Nidever, April 2022\n \"\"\"\n \n # Limit the number of threads \n #CPU,tpool_nthreads=4 \n \n # This bricks pre-processing script gets DELVE and community MC data ready \n # to run PHOTRED ALLFRAME on it. \n \n t0 = time.time()\n curdir = os.path.abspath(os.curdir) \n \n # Defaults\n if delvedir is not None:\n if delvedir.endswith('/')==False:\n delvedir += '/' \n else: \n delvedir = '/net/dl2/dnidever/delve/' \n if os.path.exists(delvedir)==False:\n os.makedirs(delvedir)\n if delvereddir is not None:\n if delvereddir.endswith('/')==False:\n delvereddir += '/'\n else: \n delvereddir = '/'.join(os.path.abspath(__file__).split('/')[:-3])+'/'\n if scriptsdir is not None:\n if scriptsdir.endswith('/')==False:\n scriptsdir += '/'\n else: \n scriptsdir = '/'.join(photred.__file__.split('/')[:-3])+'/scripts/'\n if irafdir is not None:\n if irafdir.endswith('/')==False:\n irafdir += '/'\n else: \n irafdir = os.path.expanduser('~/iraf/')\n tempdir = '/tmp/'\n if workdir is None:\n host = socket.gethostname()\n hostname = host.split('.')[0]\n workdir = '/data0/dnidever/delve/' \n if os.path.exists(workdir)==False:\n os.makedirs(workdir)\n # Exposures directory\n expdir = delvedir+'exposures/'\n # Bricks directory\n brickdir = delvedir+'bricks/' \n if os.path.exists(brickdir)==False:\n os.makedirs(brickdir)\n logsdir = brickdir+'logs/' \n if os.path.exists(logsdir)==False:\n os.makedirs(logsdir)\n \n # Start the logfile \n #------------------ \n # format is delvered_forcebrick.brick.host.DATETIME.log\n host = socket.gethostname()\n hostname = host.split('.')[0]\n logtime = datetime.now().strftime(\"%Y%m%d%H%M%S\") \n # Set up logging to screen and logfile\n logFormatter = logging.Formatter(\"%(asctime)s [%(levelname)-5.5s] %(message)s\")\n logger = logging.getLogger() \n while logger.hasHandlers(): # some existing loggers, remove them \n logger.removeHandler(logger.handlers[0]) \n logger = logging.getLogger()\n logtime = datetime.now().strftime(\"%Y%m%d%H%M%S\")\n if logfile is None:\n logfile = logsdir+'delvered_brick.'+brick+'.'+hostname+'.'+logtime+'.log' \n if os.path.exists(logfile): os.remove(logfile)\n fileHandler = logging.FileHandler(logfile)\n fileHandler.setFormatter(logFormatter)\n logger.addHandler(fileHandler)\n consoleHandler = logging.StreamHandler()\n consoleHandler.setFormatter(logFormatter)\n logger.addHandler(consoleHandler)\n logger.setLevel(logging.NOTSET)\n \n # Chip name and CCDNUM relations\n decam = Table.read(delvereddir+'data/decam.txt',format='ascii')\n for n in decam.colnames: decam[n].name = n.lower() # lowercase column names\n \n # Load the brick information\n brickstr = Table.read(delvereddir+'data/delvemc_bricks_0.25deg.fits.gz')\n for n in brickstr.colnames: brickstr[n].name = n.lower() # lowercase column names\n\n # Get the brick information \n bind, = np.where(brickstr['brickname'] == brick) \n if len(bind) == 0: \n logger.info(brick+' not in DELVE-MC brick list')\n return \n brickstr1 = brickstr[bind[0]]\n \n # Subdirectory is the first 4 digits of the brickname, e.g., 0952 of 0952m462, the RA portion of the name \n subdir = brickdir+brick[0:4]+'/' \n if os.path.exists(subdir)==False:\n os.makedirs(subdir)\n # Create brick directory if it doesn't exist yet \n bdir = subdir+brick+'/' \n if os.path.exists(bdir)==False:\n os.makedirs(bdir)\n logfile = bdir+brick+'.'+logtime+'.log' \n \n # Check the output file \n photfile = bdir+brick+'.fits'\n if os.path.exists(photfile+'.gz') and redo==False and update==False:\n logger.info(photfile+'.gz EXISTS and redo or update NOT set')\n return \n \n # DECam imager \n thisimager = {'telescope':'BLANCO','instrument':'DECam','namps':62,'separator':'_'} \n \n # Print information \n logger.info('--------------------------------------------------------------------')\n logger.info(' Run ALLFRAME forced photometry on DELVE Brick = '+brick)\n logger.info('--------------------------------------------------------------------')\n logger.info('DELVEDIR = '+delvedir)\n logger.info('SCRIPTSDIR = '+scriptsdir)\n logger.info('IRAFDIR = '+irafdir)\n logger.info('EXPOSUREDIR = '+expdir)\n logger.info('WORKINGDIR = '+workdir)\n logger.info('HOST = '+host)\n logger.info(datetime.now().strftime(\"%a %b %d %H:%M:%S %Y\")) \n \n # The photed.setup file \n setup = ['##### REQUIRED #####',\n 'scriptsdir '+scriptsdir,\n 'irafdir '+irafdir,\n 'telescope Blanco',\n 'instrument DECAM',\n 'observatory CTIO',\n 'nmulti 10',\n 'nmulti_wcs 40',\n 'nmulti_daophot 30',\n 'nmulti_allframe 10',\n 'filtref g,i,r,z,u',\n 'trans delve.trans',\n '##### OPTIONAL #####',\n 'sepfielddir 1',\n 'sepchipdir 1',\n 'keepmef 0',\n 'catformat FITS',\n 'workdir '+workdir,\n 'clean 1',\n 'skipcheck 1',\n 'redo 0',\n 'wcsrefname GAIADR2',\n 'searchdist 20',\n '#wcsrmslim 1.0',\n 'hyperthread 1',\n 'daopsfva 1',\n 'daofitradfwhm 1.0',\n 'psfcomsrc 0',\n 'psfcomglobal 0',\n 'psfcomgauss 0',\n '#mchmaxshift 50.0',\n 'finditer 1', # 2->1 on 7/22/20 \n 'alfdetprog sextractor',\n '#alfnocmbimscale 0',\n 'alftrimcomb 0',\n '#ddo51radoffset 1',\n 'cmbforce 1',\n 'keepinstr 1',\n 'avgmag 1',\n 'avgonlymag 0',\n 'todered u,g,r,i,z,g-i',\n '##### STAGES #####',\n '#rename',\n '#split',\n '#wcs',\n '#daophot',\n '#zeropoint',\n '#match',\n ' allframe',\n '#apcor',\n '#astrom',\n '#calib',\n '#combine',\n '#deredden',\n '#save',\n '#html']\n dln.writelines(bdir+'photred.setup',setup)\n setup = io.readsetup(setupdir=bdir)\n \n # Print out some information about the brick \n logger.info('RA = %.5f' % brickstr1['ra'])\n logger.info('DEC = %.3f' % brickstr1['dec'])\n logger.info('RA range = [ %.5f,%.5f ]' % (brickstr1['ra1'],brickstr1['ra2']))\n logger.info('DEC range = [ %.5f,%.5f ]' % (brickstr1['dec1'],brickstr1['dec2'])) \n \n # Get the Brick WCS information \n tile = make_brick_wcs(brickstr1)\n \n # Step 1: Get the list of exposures/chips that overlap this brick \n #---------------------------------------------------------------- \n logger.info('Step 1: Get list of chip files that overlap this brick')\n #logger.info('Getting chips that overlap this brick' \n cenra = brickstr1['ra']\n cendec = brickstr1['dec']\n tid,tmpfile = tempfile.mkstemp(prefix=\"tmp\",suffix='.fits',dir=tempdir)\n dln.touch(tmpfile)\n for f in [tmpfile]:\n if os.path.exists(f): os.remove(f)\n # /noshell causes problems on gp09 because it gives python2 instead of python3\n out = subprocess.check_output(delvereddir+'bin/query_delvered_summary_table '+str(cenra)+' '+str(cendec)+' '+tmpfile+' --lim 0.5',shell=True)\n exists = os.path.exists(tmpfile)\n size = os.path.getsize(tmpfile)\n if size == 0: \n logger.info('No overlapping chips found')\n if os.path.exists(tmpfile): os.remove(tmpfile)\n return\n chstr = Table.read(tmpfile)\n if os.path.exists(tmpfile): os.remove(tmpfile)\n nchstr = len(chstr) \n logger.info('Found '+str(nchstr)+' overlapping chips within 0.5 deg of brick center')\n logger.info(datetime.now().strftime(\"%a %b %d %H:%M:%S %Y\")) \n \n # Make sure the chips are unique, some were duplicated on SMASH nights \n chid = np.char.array(chstr['expnum'].astype(str))+'-'+np.char.array(chstr['chip'].astype(str))\n uchstr,ui = np.unique(chid,return_index=True)\n chstr = chstr[ui] \n nchstr = len(chstr) \n \n # Do more rigorous overlap checking \n # the brick region with overlap \n print('Performing more rigorous overlap checking')\n\n bcoo = tile['wcs'].pixel_to_world([0,tile['nx']-1,tile['nx']-1,0],[0,0,tile['ny']-1,tile['ny']-1])\n bvra = bcoo.ra.deg\n bvdec = bcoo.dec.deg\n #HEAD_XYAD,tile.head,[0,tile.nx-1,tile.nx-1,0],[0,0,tile.ny-1,tile.ny-1],bvra,bvdec,/deg\n olap = np.zeros(nchstr,bool)\n vxarr = np.zeros((nchstr,4),float)\n vyarr = np.zeros((nchstr,4),float) \n for i in range(nchstr): \n if (i % 100 == 0) and (i > 0): \n print(i)\n hd1 = io.readfile(chstr['file'][i],header=True)\n nx = hd1['naxis1']\n ny = hd1['naxis2']\n w1 = WCS(hd1)\n vcoo = w1.pixel_to_world([0,nx-1,nx-1,0],[0,0,ny-1,ny-1])\n vra = vcoo.ra.deg\n vdec = vcoo.dec.deg\n olap[i] = coords.doPolygonsOverlap(bvra,bvdec,vra,vdec) \n vx,vy = tile['wcs'].world_to_pixel(vcoo)\n vxarr[i,:] = vx \n vyarr[i,:] = vy \n # Require at least a 2 pixel overlap in X and Y \n g, = np.where((olap==True) & (np.max(vxarr,axis=1) >= 2) & (np.max(vyarr,axis=1) >= 2) &\n (np.min(vxarr,axis=1) <= tile['nx']-3) & (np.min(vyarr,axis=1) <= tile['ny']-3))\n if len(g) == 0: \n logger.info('No chips overlap this brick')\n return \n logger.info(str(len(g))+' chips overlap this brick')\n chstr = chstr[g] \n nchstr = len(chstr)\n \n # APPLY cuts on the exposures \n #----------------------------- \n logger.info('Applying quality, zero-point, filter and exptime cuts')\n \n # Zero-point structure, from NSC\n zpstr = np.zeros(7,dtype=np.dtype([('instrument',np.str,10),('filter',np.str,10),('amcoef',(float,2)),('thresh',float)]))\n #zpstr = replicate({instrument:'',filter:'',amcoef:fltarr(2),thresh:0.5},7)\n zpstr['instrument'] = 'c4d'\n zpstr['filter'] = ['u','g','r','i','z','Y','VR'] \n zpstr['amcoef'][0] = [-1.60273, -0.375253] # c4d-u \n zpstr['amcoef'][1] = [0.277124, -0.198037] # c4d-g \n zpstr['amcoef'][2] = [0.516382, -0.115443] # c4d-r \n zpstr['amcoef'][3] = [0.380338, -0.067439] # c4d-i \n zpstr['amcoef'][4] = [0.074517, -0.067031] # c4d-z \n zpstr['amcoef'][5] = [-1.07800, -0.060014] # c4d-Y \n zpstr['amcoef'][6] = [1.111859, -0.083630] # c4d-VR \n \n # Convert to additive zero-point as used in NSC \n zpterm = -chstr['calib_zpterm']\n # Fix early DES exposures that used different units/gain \n gdes, = np.where(chstr['gain'] < 2)\n if len(gdes) > 0: \n zpterm[gdes] -= 1.55 \n # global zpterm and airmass correction \n for i in range(len(zpstr)): \n ind, = np.where(chstr['filter']==zpstr['filter'][i])\n if len(ind)>0: \n zpterm[ind] -= np.polyval(np.flip(zpstr['amcoef'][i]),chstr['airmass'][ind])\n \n fwhmthresh = 2.0 # seeing 2.0\" threshold \n filt = np.char.array(chstr['filter'].astype(str)).ljust(1) # first characater\n gdch, = np.where((chstr['fwhm']*chstr['pixscale'] <= fwhmthresh) & (chstr['exptime'] >= 90.) & (zpterm >= -0.5) &\n np.isfinite(zpterm) & np.isfinite(chstr['apcor']) &\n ((filt== 'u') | (filt=='g') | (filt=='r') | (filt=='i') | (filt=='z') | (filt=='Y')))\n if len(gdch) == 0: \n logger.info('No chips passed the cuts')\n return \n logger.info(str(len(gdch))+' chips passed the cuts')\n chstr = chstr[gdch] \n nchstr = len(chstr)\n chstr['file'] = np.char.array(chstr['file'].astype(str)).strip()\n chstr['base'] = np.char.array(chstr['base'].astype(str)).strip()\n \n # Check if we need to update\n if update and redo==False:\n # Load previous meta \n metafile = bdir+brick+'_meta.fits'\n if os.path.exists(metafile):\n meta0 = Table.read(metafile,1)\n meta0['base'] = str(meta0['base'])\n ind1,ind2 = dln.match(meta0['base'],chstr['base'])\n if nchstr == len(meta0) and nchstr == nmatch: \n logger.info('Nothing to UPDATE') \n return \n # Moving previous catalogs to a backup\n oldfiles = glob(bdir+brick+'*fits*')\n oldfiles += glob(bdir+brick+'allframe.opt')\n oldfiles += glob(bdir+brick+'default.*')\n if len(oldfiles)>0: \n bakdir = bdir+'bak'+logtime\n logger.info('Backing up old files to '+bakdir)\n os.makedirs(bakdir)\n for f in oldfiles:\n shutil.move(f,bakdir)\n else:\n logger.info('No old files to backup')\n logger.info('There are new exposures to include. UPDATING')\n \n \n # Create temporary local directory to perform the work/processing \n # copy everything to it \n if os.path.exists(workdir)==False:\n os.makedirs(workdir)\n \n procdir = tempfile.mkdtemp(prefix=\"brk\",dir=workdir)\n procdir += '/'\n os.chmod(procdir,0o755)\n logger.info('Working in temporary directory '+procdir)\n logger.info(datetime.now().strftime(\"%a %b %d %H:%M:%S %Y\")) \n \n # Copy the files \n #---------------- \n logger.info('Copying over the necessary files to '+procdir)\n # Chip loop \n for i in range(nchstr): \n logger.info('Copying over files for '+chstr['file'][i])\n # New filename \n #chstr[i].newbase = chstr[i].base \n odir = os.path.dirname(chstr['file'][i])+'/'\n obase = photred.utils.fitsext(chstr['file'][i],basename=True)\n # Need symlinks to .psf, .als \n if os.path.exists(odir+obase+'.psf') == False: \n logger.info(odir+obase+'.psf NOT FOUND. Skipping this chip') \n continue\n if os.path.exists(odir+obase+'.als') == False: \n logger.info(odir+obase+'.als NOT FOUND. Skipping this chip')\n continue\n for e in ['.psf','.als','.ap','.opt','.als.opt','.log']:\n dln.remove(procdir+str(chstr['base'][i])+e,allow=True)\n for e in ['.psf','.als','.ap','.opt','.als.opt','.log']:\n dln.remove(procdir+'/'+obase+e,allow=True)\n shutil.copyfile(odir+obase+e,procdir+obase+e)\n os.chmod(procdir+chstr['base'][i]+e,0o755) # make sure they are writable \n # Copy the fits, fits resource file and header files locally \n if os.path.exists(odir+obase+'.fits') == False: \n logger.info(odir+obase+'.fits NOT FOUND. Skipping this chip')\n continue\n dln.remove(procdir+obase+'.fits',allow=True)\n shutil.copyfile(odir+obase+'.fits',procdir+obase+'.fits')\n if os.path.exists(odir+'.'+obase+'.fits'):\n dln.remove(procdir+'.'+obase+'.fits',allow=True)\n shutil.copyfile(odir+'.'+obase+'.fits',procdir+'.'+obase+'.fits')\n if os.path.exists(odir+obase+'.fits.head'):\n dln.remove(procdir+obase+'.fits.head',allow=True)\n shutil.copyfile(odir+obase+'.fits.head',procdir+obase+'.fits.head')\n os.chmod(procdir+chstr['base'][i]+'.fits',0o755)\n \n # Step 2: Run DAOMATCH_TILE.PRO on the files \n #-------------------------------------------- \n logger.info('Step 2: Matching up objects with DAOMATCH_TILE')\n logger.info(datetime.now().strftime(\"%a %b %d %H:%M:%S %Y\"))\n os.chdir(procdir)\n group = {'x0':0,'y0':0} \n daomatch.daomatch_tile(np.char.array(chstr['base'])+'.als',tile,group)\n\n # Step 3: Run ALLFRAME \n #---------------------- \n logger.info('Step 3: Run ALLFRAME')\n logger.info(datetime.now().strftime(\"%a %b %d %H:%M:%S %Y\")) \n # DO I NEED TO HAVE IT TRIM THE COMBINED IMAGE??? \n mchbase = procdir+chstr['base'][0]\n mchfile = mchbase+'.mch'# allframe needs absolute path \n import pdb; pdb.set_trace()\n alf.allframe(mchfile,tile=tile,setupdir=bdir,scriptsdir=scriptsdir,irafdir=irafdir,\n logfile=logfile,catformat='FITS',imager=thisimager,geocoef=0)\n magfile = chstr['base'][0]+'.mag' \n if os.path.exists(magfile) == False: \n logger.info(magfile+' NOT FOUND')\n return \n \n # Step 4: Calculate coordinates \n #------------------------------- \n logger.info('Step 4: Adding coordinates')\n logger.info(datetime.now().strftime(\"%a %b %d %H:%M:%S %Y\")) \n # Load the MCH file\n alsfiles,trans,magoff = io.readmch(mchfile)\n nalsfiles = len(alsfiles) \n # Load the photometry file \n instphot = io.readfile(magfile) \n ninstphot = len(instphot) \n logger.info('Nstars = '+str(ninstphot)) \n # Converting to IDL X/Y convention, starting at (0,0) \n # DAOPHOT has X/Y start at (1,1)\n ra,dec = tile['wcs'].pixel_to_world(instphot.x-1.0,instphot.y-1.0)\n #HEAD_XYAD,tile.head,instphot.x-1.0,instphot.y-1.0,ra,dec,/degree \n \n # Step 5: Calibrating photometry with zero-points \n #------------------------------------------------- \n logger.info('Step 5: Calibrating photometry with zero-points')\n logger.info(datetime.now().strftime(\"%a %b %d %H:%M:%S %Y\"))\n cmag = np.zeros((ninstphot,nchstr),float)+99.99\n cerr = np.zeros((ninstphot,nchstr),float)+9.99 \n # Chip loop \n for i in range(nchstr): \n # id, x, y, ra, dec, unsolved magnitudes, chi, sharp \n imag = instphot['mag'+str(i+1)] \n ierr = instphot['err'+str(i+1)]\n gdmag, = np.where(imag < 50)\n if len(gdmag) > 0: \n # exptime, aperture correction, zero-point \n # aperture correction is SUBTRACTIVE, makes it brighter \n # ZPTERM is a SUBTRACTIVE constant offset \n cmag[gdmag,i] = imag[gdmag] + 2.5*np.log10(chstr['exptime'][i]) - chstr['apcor'][i] - chstr['calib_zpterm'][i]\n # Add zero-point error in quadrature \n cerr[gdmag,i] = np.sqrt(ierr[gdmag]**2+chstr['calib_zptermsig'][i]**2) \n # Calculate average photometry per filter\n ufilt = np.unique(chstr['filter'])\n nufilt = len(ufilt)\n avgmag = np.zeros((ninstphot,nufilt),float)\n avgerr = np.zeros((ninstphot,nufilt),float) \n ndet = np.zeros((ninstphot,nufilt),int)\n for i in range(nufilt): \n gdf, = np.where(chstr['filter'] == ufilt[i]) \n # Single exposure \n if len(gdf) == 1: \n avgmag[:,i] = cmag[:,gdf[0]] \n avgerr[:,i] = cerr[:,gdf[0]] \n ndet[:,i] = np.sum(cmag[:,gdf[0]] < 50) \n # Multiple exposures \n else: \n # Loop through all of the exposures and add up the flux, totalwt, etc.\n totalwt = np.zeros(ninstphot,float)\n totalfluxwt = np.zeros(ninstphot,float)\n for k in range(ngdf): \n gdmag, = np.where(cmag[:,gdf[k]] < 50) \n if len(gdmag) > 0: \n totalwt[gdmag] += 1.0/cerr[gdmag,gdf[k]]**2 \n totalfluxwt[gdmag] += 2.5118864**cmag[gdmag,gdf[k]] * (1.0/cerr[gdmag,gdf[k]]**2) \n ndet[gdmag,i] += 1\n newflux = totalfluxwt/totalwt \n newmag = 2.5*np.log10(newflux) \n newerr = np.sqrt(1.0/totalwt) \n bdmag, = np.where(~np.isfinite(newmag)) \n if len(bdmag) > 0: \n newmag[bdmag] = 99.99 \n newerr[bdmag] = 9.99 \n avgmag[:,i] = newmag \n avgerr[:,i] = newerr \n # Measure scatter\n scatter = np.zeros((ninstphot,nufilt),float)+99.99\n for i in range(nufilt): \n gdf, = np.where(chstr['filter'] == ufilt[i]) \n if len(gdf) > 1:\n totaldiff = np.zeros(ninstphot,float)\n for k in range(ngdf): \n gdmag, = np.where(cmag[:,gdf[k]] < 50) \n if len(gdmag) > 0: \n totaldiff[gdmag] += (avgmag[gdmag,i]-cmag[gdmag,gdf[k]])**2 \n scatter[:,i] = np.sqrt( totaldiff/np.maximum(ndet[:,i],1) ) \n bd, = np.where(ndet[:,i] <= 1) \n if len(bd) > 0 : \n scatter[bd,i]=99.99 \n # Create final catalog schema\n photdt = [('objid',(np.str,100)),('x',float),('y',float),('ra',float),('dec',float)]\n\n # Add columns for calibrated single-epoch photometry columns \n cmagnames = np.zeros(nchstr,(np.str,100))\n cerrnames = np.zeros(nchstr,(np.str,100)) \n for i in range(nufilt): \n ind, = np.where(chstr['filter'] == ufilt[i]) \n cmagnames[ind] = [ufilt[i].upper()+str(j+1)+'MAG' for j in np.arange(nind)]\n cerrnames[ind] = [ufilt[i].upper()+str(j+1)+'ERR' for j in np.arange(nind)] \n for i in range(nchstr):\n photdt += [(cmagnames[i],np.float32),(cerrnames[i],np.float32)]\n # Add columns for average photometry per filter \n for i in range(nufilt):\n photdt += [(ufilt[i]+'MAG',np.float32),(ufilt[i]+'ERR',np.float32),(ufilt[i]+'SCATTER',np.float32),('NDET'+ufilt[i],int)]\n # Extra columns\n photdt += [('chi',np.float32),('sharp',np.float32),('prob',np.float32),('ebv',np.float32)]\n # other SE columns\n photdt += [('mag_auto',np.float32),('magerr_auto',np.float32),('asemi',np.float32),('bsemi',np.float32),\n ('theta',np.float32),('ellipticity',np.float32),('fwhm',np.float32)]\n # in unique brick area\n dt += [('brickuniq',boolean)]\n # Create final catalog\n phot = np.zeros(ninstphot,dtype=np.dtype(photdt))\n for n in instphot:\n phot[n] = instphot[n]\n phtags = phot.colnames\n # object IDs \n phot['objid'] = brick+'.'+np.char.array(instphot['id'])\n # Stuff in the coordinates calculated above \n phot['ra'] = ra \n phot['dec'] = dec \n # Stuff in the calibrated single-epoch photometry columns \n for i in range(nchstr): \n phot[cmagnames[i]] = cmag[:,i] \n phot[cerrnames[i]] = cerr[:,i] \n # Stuff in the average photometry per filter \n for i in range(nufilt): \n phot[ufilt[i].upper()+'MAG'] = avgmag[:,i] \n phot[ufilt[i].upper()+'ERR'] = avgerr[:,i] \n phot[ufilt[i].upper()+'SCATTER'] = scatter[:,i] \n phot['NDET'+ufilt[i].upper()] = ndet[:,i] \n \n # Calculate SFD E(B-V) \n #GLACTC,phot.ra,phot.dec,2000.0,glon,glat,1,/deg\n coo = SkyCoord(phot['ra'], phot['dec'], unit='deg', frame='icrs')\n coo_gal = coo.transform_to('galactic')\n sfd = SFDQuery()\n phot['ebv'] = sfd(coords_gal)\n \n # THIS IS NOW BEING DONE IN DELVERED_FINALCAT.PRO THAT COMBINES ALL CATALOGS \n # Only include objects that are INSIDE the UNIQUE brick area \n # INCLUSIVE at the lower RA and DEC limit \n # Getting objects that are in the UNIQUE brick area \n if brickstr1.dec == -90: \n # the brick right at the pole does not have any RA limits \n ginside, = np.where(phot['dec'] < brickstr1['dec2']) \n else: \n ginside, = np.where((phot['ra'] >= brickstr1['ra1']) & (phot['ra'] < brickstr1['ra2']) &\n (phot['dec'] >= brickstr1['dec1']) & (phot['dec'] < brickstr1['dec2']))\n if len(ginside)>0: \n phot['brickuniq'][ginside] = True\n \n # Get some meta-data \n for i in range(nchstr): \n alffile = chstr['base'][i]+'.alf' \n if os.path.exists(alffile):\n chstr['alf_nsources'][i] = dln.numlines(alffile)-3 \n \n \n # Make the exposure-level forced photometry catalog \n #-------------------------------------------------- \n # Load the individual ALF files to get chi, sharp \n # Load TFR file to conver ALF IDs to final object ID \n tfrfile = mchbase+'_comb.tfr' \n alffiles,tfrstr = io.readtfr(tfrfile)\n expdt = [('id',(np.str,100)),('objid',(np.str,100)),('exposure',(np.str,100)),('ccdnum',int),('filter',(np.str,10)),\n ('mjd',float),('x',float),('y',float),('ra',float),('dec',float),('imag',float),('ierr',float),\n ('mag',float),('err',float),('sky',float),('chi',float),('sharp',float)]\n expcat = np.zeros(int(np.sum(cmag < 50))+10000,dtype=np.dtype(expdt))\n cnt = 0\n for i in range(nchstr): \n base1 = chstr['base'][i]\n fitsfile = base1+'.fits' \n if os.path.exists(alffiles[i]) and os.path.exists(fitsfile):\n alf = io.readals(alffiles[i])\n if len(alf)==0: \n continue\n # Sometimes the rows are duplicated in the ALF file \n ui = np.uniq(alf.id,np.argsort(alf.id)) \n if len(ui) < nalf: \n alf = alf[ui] \n nalf = len(alf) \n head = io.readfile(fitsfile,header=True) \n \n # Calibrate the photometry \n # exptime, aperture correction, zero-point \n # aperture correction is SUBTRACTIVE, makes it brighter \n # ZPTERM is a SUBTRACTIVE constant offset \n cmag1 = alf['mag'] + 2.5*np.log10(chstr['exptime'][i]) - chstr['apcor'][i] - chstr['calib_zpterm'][i]\n # Add zero-point error in quadrature \n cerr1 = np.sqrt(alf['err']**2+chstr['calib_zptermsig'][i]**2) \n \n # Coordinates\n ra1,dec1 = head.pixel_to_world(alf['x']-1,alf['y']-1)\n #HEAD_XYAD,head,alf.x-1,alf.y-1,ra1,dec1,/deg \n \n # MATCH up ALF IDs to TFR INDEX \n # One row per unique object \n # the INDEX values are 1-based indices into the ALF files\n ind1,ind2 = dln.match(tfrstr.index[i],lindgen(nalf)+1)\n #MATCH,tfrstr.index[i],lindgen(nalf)+1,ind1,ind2,/sort,count=nmatch \n objid = brick+'.'+np.char.array(tfrstr['id'][ind1])\n \n # Create the new catalog\n newcat = np.zeros(nalf,dtype=np.dtype(dt))\n newcat['objid'] = objid \n newcat['id'] = chstr['expnum'][i]+'_'+chstr['chip'][i]+'.'+np.char.array(alf['id'])\n newcat['exposure'] = chstr['base'][i]\n newcat['ccdnum'] = chstr['chip'][i]\n newcat['filter'] = chstr['filter'][i]\n dateobs = chstr['utdate'][i]+'T'+chstr['uttime'][i]\n t = Time(dateobs)\n newcat['mjd'] = t.mjd\n newcat['x'] = alf['x']\n newcat['y'] = alf['y']\n newcat['ra'] = ra1 \n newcat['dec'] = dec1 \n newcat['imag'] = alf['mag']\n newcat['ierr'] = alf['err']\n newcat['mag'] = cmag1 \n newcat['err'] = cerr1 \n newcat['sky'] = alf['sky']\n newcat['chi'] = alf['chi']\n newcat['sharp'] = alf['sharp']\n \n # Add more elements \n if cnt+nalf > len(expcat): \n expcat = add_elements(expcat,100000>nalf) \n \n # Add to global catalog \n expcat[cnt:cnt+nalf-1] = newcat \n cnt += nalf\n \n else:\n logger.info(alffile+' NOT FOUND')\n expcat = expcat[0:cnt] # this should not be needed \n \n # Object catalog \n #---------------\n # do not want all of the individual epoch photometry\n # these are between the DEC and the first unique mean magnitude (e.g. GMAG, and GERR)\n lo = where(phtags=='DEC')[0][0]\n hi = where(np.char.array(phtags).upper() == ufilt[0].upper()+'MAG')[0][0]\n objdt = photdt[0:lo]\n objdt += photdt[hi:]\n obj = np.zeros(ninstphot,dtype=np.dtype(objdt))\n for n in obj.colnames:\n obj[n] = phot[h]\n \n # Saving final catalog \n logger.info(datetime.now().strftime(\"%a %b %d %H:%M:%S %Y\")) \n photfile = bdir+brick+'.fits'\n if len(phot.colnames) <= 999:\n logger.info('Writing photometry to '+photfile+'.gz')\n phot.writeto(photfile,overwrite=True)\n out = subprocess.check_output(['gzip','-f',photfile],shell=False)\n else: \n logger.info('Too many columns for FITS. Saving as pickle file instead. '+bdir+brick+'.pkl')\n with open(bdir+brick+'.pkl','wb') as f:\n pickle.dump(phot,f)\n \n # Saving object photometry catalog \n objfile = bdir+brick+'_object.fits'\n obj.writeto(objfile,overwrite=True)\n out = subprocess.check_output(['gzip','-f',objfile],shell=False) \n \n # Saving exposure-level forced photometry catalog \n expfile = bdir+brick+'_expforced.fits'\n expcat.writeto(expfile,overwrite=True)\n out = subprocess.check_output(['gzip','-f',expfile],shell=False)\n \n # Save metadata \n metafile = bdir+brick+'_meta.fits' \n logger.info('Writing meta-data to '+metafile)\n chstr.writeto(metafile,overwrite=True)\n \n \n # Delete files we don't want to keep \n #----------------------------------- \n # Individual fits files \n alsbase = os.path.basename(alsfiles,'.als') \n # if fits files have resources files then replace the fits file by a \n # dummy file \n for i in range(len(alsbase)):\n exists = os.path.exists(alsbase[i]+'.fits')\n size = os.path.getsize(alsbase[i]+'.fits')\n if exists and size > 1: \n os.remove(alsbase[i]+'.fits')\n if os.path.exists('.'+alsbase[i]+'.fits'):\n dln.writelines(alsbase[i]+'.fits','')\n # Combined files \n # _comb lst, lst1, lst2, lst1.chi, grp, nst, lst2.chi, plst.chi, psfini.ap \n # nei, als.inp, a.fits, cmn.log, cmn.coo, cmn.ap, cmn.lst, \n # _sub.fits, _sub.cat, _sub.als, _all.coo, makemag \n base = os.path.basename(mchfile,'.mch')\n ext = ['.lst','.lst1','.lst2','.lst1.chi','.lst2.chi','.grp','.nst','.plst.chi','.nei',\n '.als.inp','.cmn.log','.cmn.coo','.cmn.ap','.cmn.lst','a.fits','a.fits.fz',\n '_sub.fits','_sub.cat','_sub.als','_all.coo','.makemag']\n for e in ext:\n if os.path.exists(base+e): os.remove(base+e)\n if os.path.exists('check.fits'): os.remove('check.fits')\n \n # fpack _comb.fits and _combs.fits\n for f in [base+'_comb.fits.fz',base+'_combs.fits.fz']:\n if os.path.exists(f): os.remove(f)\n out = subprocess.check_output(['fpack','-D','-Y',base+'_comb.fits'],shell=False)\n out = subprocess.check_output(['fpack','-D','-Y',base+'_combs.fits'],shell=False)\n # gzip _comb.mask.fits and _comb.bpm.fits \n out = subprocess.check_output(['gzip','-f',base+'_comb.mask.fits'],shell=False)\n out = subprocess.check_output(['gzip','-f',base+'_comb.bpm.fits'],shell=False)\n \n # Copy everything left back to the original directory \n logger.info('Copying files back to '+bdir)\n allfiles = glob(procdir+'*')\n allfiles += glob(procdir+'.*.fits')\n nallfiles = len(allfiles)\n for f in allfiles:\n base = os.path.basename(f)\n if os.path.exists(bdir+'/'+base): os.remove(bdir+'/'+base)\n shutil.move(f,bdir)\n os.rmdir(procdir) # delete temporary processing directory \n \n logger.info(datetime.now().strftime(\"%a %b %d %H:%M:%S %Y\")) \n logger.info('DELVERED_FORCEBRICK:ne after '+str(time.time()-t0,2)+' sec.')\n\n os.chdir(curdir) # back to original directory \n \n # Create JOINT catalogs \n logger.info('')\n logger.info('CREATE JOINT CATALOGS')\n logger.info('')\n logger.info(datetime.now().strftime(\"%a %b %d %H:%M:%S %Y\")) \n \n if redo or update:\n jntredo = True \n else: \n jntredo = False\n delvered_jointbrickcats(brick,logfile=logfile,redo=jntredo)\n \n \n \n", "meta": {"hexsha": "ca76a24dcc12f957fcbc9c6f4239fe92414a4531", "size": 34713, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/delvered/forcebrick.py", "max_stars_repo_name": "dnidever/delvered", "max_stars_repo_head_hexsha": "37d96d8943879c278317a8aed321f44a4667a220", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/delvered/forcebrick.py", "max_issues_repo_name": "dnidever/delvered", "max_issues_repo_head_hexsha": "37d96d8943879c278317a8aed321f44a4667a220", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/delvered/forcebrick.py", "max_forks_repo_name": "dnidever/delvered", "max_forks_repo_head_hexsha": "37d96d8943879c278317a8aed321f44a4667a220", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9085290482, "max_line_length": 145, "alphanum_fraction": 0.5498228329, "include": true, "reason": "import numpy,from astropy", "num_tokens": 9998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.20946967639529512, "lm_q1q2_score": 0.12884225700559654}} {"text": "import warnings\nimport numpy as np\nimport copy\n\nfrom astropy.time import Time\nfrom astropy.utils.iers.iers import IERSRangeError\n\n__all__ = [\"ModifiedJulianDate\", \"MJDWarning\", \"UTCtoUT1Warning\"]\n\n\n# Filter out ERFA's complaints that we are simulating dates which\n# are in the future\nwarnings.filterwarnings(\"ignore\",\n message='.*taiutc.*dubious.year.*')\n\n\nclass MJDWarning(Warning):\n \"\"\"\n A sub-class of Warning. All of the warnings raised by ModifiedJulianDate\n will be of this class (or its sub-classes), so that users can filter them\n out by creating a simple filter targeted at category=MJDWarning.\n \"\"\"\n pass\n\n\nclass UTCtoUT1Warning(MJDWarning):\n \"\"\"\n A sub-class of MJDWarning meant for use when astropy.Time cannot interpolate\n UT1-UTC as a function of UTC because UTC is out of bounds of the data.\n This class exists so that users can filter these warnings out by creating\n a simple filter targeted at category=UTCtoUT1Warning.\n \"\"\"\n pass\n\n\nclass ModifiedJulianDate(object):\n\n @classmethod\n def _get_ut1_from_utc(cls, UTC):\n \"\"\"\n Take a numpy array of UTC values and return a numpy array of UT1 and dut1 values\n \"\"\"\n\n time_list = Time(UTC, scale='utc', format='mjd')\n\n try:\n dut1_out = time_list.delta_ut1_utc\n ut1_out = time_list.ut1.mjd\n except IERSRangeError:\n ut1_out = np.copy(UTC)\n dut1_out = np.zeros(len(UTC))\n warnings.warn(\"ModifiedJulianData.get_list() was given date values that are outside \"\n \"astropy's range of interpolation for converting from UTC to UT1. \"\n \"We will treat UT1=UTC for those dates, lacking a better alternative.\",\n category=UTCtoUT1Warning)\n from astropy.utils.iers import TIME_BEFORE_IERS_RANGE, TIME_BEYOND_IERS_RANGE\n dut1_test, status = time_list.get_delta_ut1_utc(return_status=True)\n good_dexes = np.where(np.logical_and(status != TIME_BEFORE_IERS_RANGE,\n status != TIME_BEYOND_IERS_RANGE))\n\n if len(good_dexes[0]) > 0:\n time_good = Time(UTC[good_dexes], scale='utc', format='mjd')\n dut1_good = time_good.delta_ut1_utc\n ut1_good = time_good.ut1.mjd\n\n ut1_out[good_dexes] = ut1_good\n dut1_out[good_dexes] = dut1_good\n\n return ut1_out, dut1_out\n\n @classmethod\n def get_list(cls, TAI=None, UTC=None):\n \"\"\"\n Instantiate a list of ModifiedJulianDates from a numpy array of either TAI\n or UTC values.\n\n @param[in] TAI (optional) a numpy array of MJD' in TAI\n\n @param[in] UTC (optional) a numpy array of MJDs in UTC\n\n @param[out] a list of ModifiedJulianDate instantiations with all of their\n properties already set (so the code does not waste time converting from TAI\n to TT, TDB, etc. when those time scales are called for).\n \"\"\"\n\n if TAI is None and UTC is None:\n return None\n\n if TAI is not None and UTC is not None:\n raise RuntimeError(\"You should not specify both TAI and UTC in ModifiedJulianDate.get_list()\")\n\n if TAI is not None:\n time_list = Time(TAI, scale='tai', format='mjd')\n tai_list = TAI\n utc_list = time_list.utc.mjd\n elif UTC is not None:\n time_list = Time(UTC, scale='utc', format='mjd')\n utc_list = UTC\n tai_list = time_list.tai.mjd\n\n tt_list = time_list.tt.mjd\n tdb_list = time_list.tdb.mjd\n\n ut1_list, dut1_list = cls._get_ut1_from_utc(utc_list)\n\n values = np.array([tai_list, utc_list, tt_list, tdb_list,\n ut1_list, dut1_list]).transpose()\n\n output = []\n for vv in values:\n mjd = ModifiedJulianDate(TAI=40000.0)\n mjd._force_values(vv)\n output.append(mjd)\n\n return output\n\n def __init__(self, TAI=None, UTC=None):\n \"\"\"\n Must specify either:\n\n @param [in] TAI = the International Atomic Time as an MJD\n\n or\n\n @param [in] UTC = Universal Coordinate Time as an MJD\n \"\"\"\n\n if TAI is None and UTC is None:\n raise RuntimeError(\"You must specify either TAI or UTC to \"\n \"instantiate ModifiedJulianDate\")\n\n if TAI is not None:\n self._time = Time(TAI, scale='tai', format='mjd')\n self._tai = TAI\n self._utc = None\n self._initialized_with = 'TAI'\n else:\n self._time = Time(UTC, scale='utc', format='mjd')\n self._utc = UTC\n self._tai = None\n self._initialized_with = 'UTC'\n\n self._tt = None\n self._tdb = None\n self._ut1 = None\n self._dut1 = None\n\n def _force_values(self, values):\n \"\"\"\n Force the properties of this ModifiedJulianDate to have specific values.\n\n values is a list of [TAI, UTC, TT, TDB, UT1, UT1-UTC] values.\n\n This method exists so that, when instantiating lists of ModifiedJulianDates,\n we can use astropy.time.Time's vectorized methods to quickly perform many\n conversions at once. Users should not try to use this method by hand.\n \"\"\"\n self._tai = values[0]\n self._utc = values[1]\n self._tt = values[2]\n self._tdb = values[3]\n self._ut1 = values[4]\n self._dut1 = values[5]\n\n def __eq__(self, other):\n return self._time == other._time\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __deepcopy__(self, memo):\n if self._initialized_with == 'TAI':\n new_mjd = ModifiedJulianDate(TAI=self.TAI)\n else:\n new_mjd = ModifiedJulianDate(UTC=self.UTC)\n\n new_mjd._tai = copy.deepcopy(self._tai, memo)\n new_mjd._utc = copy.deepcopy(self._utc, memo)\n new_mjd._tt = copy.deepcopy(self._tt, memo)\n new_mjd._tdb = copy.deepcopy(self._tdb, memo)\n new_mjd._ut1 = copy.deepcopy(self._ut1, memo)\n new_mjd._dut1 = copy.deepcopy(self._dut1, memo)\n\n return new_mjd\n\n def _warn_utc_out_of_bounds(self, method_name):\n \"\"\"\n Raise a standard warning if UTC is outside of the range that can\n be interpolated on the IERS tables.\n\n method_name is the name of the method that caused this warning.\n \"\"\"\n warnings.warn(\"UTC is outside of IERS table for UT1-UTC.\\n\"\n \"Returning UT1 = UTC for lack of a better idea\\n\"\n \"This warning was caused by calling ModifiedJulianDate.%s\\n\" % method_name,\n category=UTCtoUT1Warning)\n\n @property\n def TAI(self):\n \"\"\"\n International Atomic Time as an MJD\n \"\"\"\n if self._tai is None:\n self._tai = self._time.tai.mjd\n\n return self._tai\n\n @property\n def UTC(self):\n \"\"\"\n Universal Coordinate Time as an MJD\n \"\"\"\n if self._utc is None:\n self._utc = self._time.utc.mjd\n\n return self._utc\n\n @property\n def UT1(self):\n \"\"\"\n Universal Time as an MJD\n \"\"\"\n if self._ut1 is None:\n try:\n self._ut1 = self._time.ut1.mjd\n except IERSRangeError:\n self._warn_utc_out_of_bounds('UT1')\n self._ut1 = self.UTC\n\n return self._ut1\n\n @property\n def dut1(self):\n \"\"\"\n UT1-UTC in seconds\n \"\"\"\n\n if self._dut1 is None:\n try:\n self._dut1 = self._time.delta_ut1_utc\n except IERSRangeError:\n self._warn_utc_out_of_bounds('dut1')\n self._dut1 = 0.0\n\n return self._dut1\n\n @property\n def TT(self):\n \"\"\"\n Terrestrial Time (aka Terrestrial Dynamical Time) as an MJD\n \"\"\"\n if self._tt is None:\n self._tt = self._time.tt.mjd\n\n return self._tt\n\n @property\n def TDB(self):\n \"\"\"\n Barycentric Dynamical Time as an MJD\n \"\"\"\n if self._tdb is None:\n self._tdb = self._time.tdb.mjd\n\n return self._tdb\n", "meta": {"hexsha": "2150ff727fa96ee9d18dda4e7cfab79a4f312619", "size": 8311, "ext": "py", "lang": "Python", "max_stars_repo_path": "rubin_sim/utils/ModifiedJulianDate.py", "max_stars_repo_name": "RileyWClarke/flarubin", "max_stars_repo_head_hexsha": "eb7b1ee21c828523f8a5374fe4510fe6e5ec2a2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rubin_sim/utils/ModifiedJulianDate.py", "max_issues_repo_name": "RileyWClarke/flarubin", "max_issues_repo_head_hexsha": "eb7b1ee21c828523f8a5374fe4510fe6e5ec2a2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rubin_sim/utils/ModifiedJulianDate.py", "max_forks_repo_name": "RileyWClarke/flarubin", "max_forks_repo_head_hexsha": "eb7b1ee21c828523f8a5374fe4510fe6e5ec2a2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2443609023, "max_line_length": 106, "alphanum_fraction": 0.5878955601, "include": true, "reason": "import numpy,from astropy", "num_tokens": 2080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.24508502416032485, "lm_q1q2_score": 0.12828248886506463}} {"text": "import numpy as np\nimport pymc3 as pm\nimport theano as th\nimport theano.tensor as tt\nimport inspect\nimport io\n\nimport logging\nimport time\nimport tqdm\nimport argparse\nfrom .. models.fancy_model import GeneralizedContinuousModel\nfrom typing import List, Callable, Optional, Set, Tuple, Any, Dict\nfrom abc import abstractmethod\nfrom ..inference.convergence_tracker import NoisyELBOConvergenceTracker\nfrom ..inference.param_tracker import VariationalParameterTrackerConfig, VariationalParameterTracker\nfrom ..inference import fancy_optimizers\nfrom ..inference.deterministic_annealing import ADVIDeterministicAnnealing\nfrom .. import types\n\n_logger = logging.getLogger(__name__)\n\n\nclass Sampler:\n \"\"\"Base class for log emission posterior probability samplers to be used in the hybrid ADVI scheme.\"\"\"\n def __init__(self, hybrid_inference_params: 'HybridInferenceParameters'):\n self.hybrid_inference_params = hybrid_inference_params\n\n @abstractmethod\n def update_approximation(self, approx: pm.approximations.MeanField) -> None:\n \"\"\"Take a new mean-field approximation and update the sampler routine accordingly.\n\n Args:\n approx: an instance of PyMC3 mean-field posterior approximation\n\n Returns:\n None\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def draw(self) -> np.ndarray:\n \"\"\"Draw one sample (or average of several samples) from log emission posterior probability.\"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def reset(self):\n \"\"\"Reset the internal state of the sampler (e.g. previously accumulated samples).\"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def increment(self, update: np.ndarray):\n \"\"\"Add an incremental update to the current estimate of the log emission posterior mean.\"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def get_latest_log_emission_posterior_mean_estimator(self) -> np.ndarray:\n \"\"\"Returns the latest estimate of the log emission posterior mean.\"\"\"\n raise NotImplementedError\n\n\nclass Caller:\n \"\"\"Base class for callers, i.e. routines that update the posterior of discrete RVs, to be used in the\n hybrid ADVI scheme.\"\"\"\n @abstractmethod\n def call(self) -> 'CallerUpdateSummary':\n \"\"\"Update the posterior of discrete RVs and return a summary\"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def update_auxiliary_vars(self) -> None:\n \"\"\"Update auxiliary variables in workspaces, if any. This routine is called after one\n (or more) round(s) of invoking `Caller.call`.\"\"\"\n raise NotImplemented\n\n\nclass CallerUpdateSummary:\n \"\"\"Represents a summary of updates made to discrete RV posteriors by a `Caller`.\"\"\"\n @abstractmethod\n def reduce_to_scalar(self) -> float:\n \"\"\"A function that reduces arrays to scalars. It is used to summarize tensor-valued updates.\"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def __repr__(self):\n \"\"\"Represents the caller update summary in a human readable format (used in logging).\"\"\"\n raise NotImplementedError\n\n\nclass LoggerTQDMAdapter(io.StringIO):\n \"\"\"Output stream for `tqdm` which will output to logger module instead of `stderr`.\"\"\"\n logger = None\n level = None\n buf = ''\n\n def __init__(self, logger, level=logging.INFO):\n super().__init__()\n self.logger = logger\n self.level = level\n\n def write(self, buf):\n self.buf = buf.strip('\\r\\n\\t ')\n\n def flush(self):\n self.logger.log(self.level, self.buf)\n\n\nclass InferenceTask:\n \"\"\"Base class of all inference tasks.\"\"\"\n\n # Lay in a course for starbase one two warp nine point five...\n @abstractmethod\n def engage(self):\n \"\"\"Initiate inference algorithm.\"\"\"\n raise NotImplementedError(\"Core breach imminent!\")\n\n @abstractmethod\n def disengage(self):\n \"\"\"Wrap up the inference algorithm (clean up workspaces, etc.)\"\"\"\n raise NotImplementedError\n\n\nclass HybridInferenceTask(InferenceTask):\n \"\"\"The hybrid inference framework is applicable to PGMs with the following general structure:\n\n +--------------+ +----------------+\n | discrete RVs + --------► + continuous RVs |\n +--------------+ +----------------+\n\n Note that discrete RVs do not have any continuous parents. The inference is approximately\n performed by factorizing the true posterior into an uncorrelated product of discrete RVs (DRVs)\n and continuous RVs (CRVs):\n\n p(CRVs, DRVs | observed) ~ q(CRVs) q(DRVs)\n\n q(CRVs) is updated via deterministic annealing mean-field ADVI.\n q(DRV) is updated by the provided \"caller\" and is out the scope of this class.\n\n Usage:\n ------\n\n Preliminaries. Let us decompose the log joint as follows:\n\n -log_P(CRVs, DRVs, observed) = F_c(CRVs, observed)\n + F_d(DRVs, observed)\n + F_cd(CRVs, DRVs, observed)\n\n The last term in the free energy (negative log joint) is the only term with cross terms between\n the discrete and continuous sectors.\n\n The user must supply the following components:\n\n (1) a pm.Model that yields the DRV-posterior-expectation of the free energy,\n\n F_c^{eff}(CRVs, observed) = E_{DRVs ~ q(DRVs)} [-log_P(CRVs, DRVs, observed)]\n = F_c(CRVs, observed)\n + E_{DRVs ~ q(DRVs)} [F_cd(CRVs, DRVs, observed)]\n + E_{DRVs ~ q(DRVs)} [F_d(DRVs, observed)]\n\n Note: the last term is fully determined by q(DRVs) and can be dropped while performing\n ADVI updates in the continuous sector.\n\n (2) a \"sampler\" that provides samples from the cross term, which we call \"log emission\",\n defined as:\n\n log_emission(DRVs) = E_{CRVs ~ q(CRVs)} [-F_cd (CRVs, DRV, observed)]\n\n (3) a \"caller\" that updates q(DRVs) given log_emission(DRV), i.e.:\n\n q(DRVs) \\propto \\exp[log_emission(DRVs) - F_d(DRVs, observed)]\n\n In practice, one does not need the complete joint posterior of DRVs: only sufficient\n statistics, to the extent required for calculating F_c^{eff} is needed. Calculating such\n sufficient statistics could be as simple as using the Bayes rule, or more complicated if\n the DRVs are strongly correlated.\n\n The general implementation motif is:\n\n (a) to store sufficient statistics from q(DRVs) as a shared theano tensor such that the the\n model can access it,\n (b) to store log_emission(DRVs) as a shared theano tensor (or ndarray) such that the caller\n can access it, and:\n (c) let the caller directly update the shared sufficient statistics.\n \"\"\"\n\n # if the temperature is within the following tolerance of 1.0, it is assumed that annealing\n # has finished\n temperature_tolerance = 1e-6\n\n def __init__(self,\n hybrid_inference_params: 'HybridInferenceParameters',\n continuous_model: GeneralizedContinuousModel,\n sampler: Optional[Sampler],\n caller: Optional[Caller],\n **kwargs):\n \"\"\"Initializer.\n\n Args:\n hybrid_inference_params: inference configuration\n continuous_model: a PyMC3 model representing the continuous sector of the PGM\n sampler: log emission probability sampler\n caller: discrete RV posterior updater\n **kwargs: extra keywords\n\n Keyword Args:\n custom_optimizer: a custom stochastic optimizer to be used in place of the default optimizer (adamax\n elbo_normalization_factor: normalization factor of the full model ELBO (for logging)\n advi_task_name: name of the ADVI step (for logging)\n sampling_task_name: name of the sampling step (for logging)\n calling_task_name: name of the calling step (for logging)\n \"\"\"\n assert hybrid_inference_params is not None\n self.hybrid_inference_params = hybrid_inference_params\n\n assert continuous_model is not None\n self.continuous_model = continuous_model\n self.continuous_model.verify_var_registry()\n\n if sampler is None:\n _logger.warning(\"No log emission sampler given; skipping the sampling step\")\n self.sampler = sampler\n\n if caller is None:\n _logger.warning(\"No caller given; skipping the calling step\")\n self.caller = caller\n\n if self.hybrid_inference_params.track_model_params:\n _logger.info(\"Instantiating the parameter tracker...\")\n self.param_tracker = self._create_param_tracker()\n else:\n self.param_tracker = None\n\n _logger.info(\"Instantiating the convergence tracker...\")\n self.advi_convergence_tracker = NoisyELBOConvergenceTracker(\n self.hybrid_inference_params.convergence_snr_averaging_window,\n self.hybrid_inference_params.convergence_snr_trigger_threshold,\n self.hybrid_inference_params.convergence_snr_countdown_window)\n\n _logger.info(\"Setting up DA-ADVI...\")\n with self.continuous_model:\n if not hasattr(self, 'temperature'):\n initial_temperature = self.hybrid_inference_params.initial_temperature\n self.temperature: types.TensorSharedVariable = th.shared(\n np.asarray([initial_temperature], dtype=types.floatX))\n initial_temperature = self.temperature.get_value()[0]\n if (np.abs(initial_temperature - 1.0) < self.temperature_tolerance or\n hybrid_inference_params.disable_annealing):\n # no annealing\n temperature_update = None\n else:\n # linear annealing\n max_thermal_advi_iterations = self.hybrid_inference_params.max_advi_iter_first_epoch\n max_thermal_advi_iterations += ((self.hybrid_inference_params.num_thermal_epochs - 1)\n * self.hybrid_inference_params.max_advi_iter_first_epoch)\n temperature_drop_per_iter = (initial_temperature - 1.0) / max_thermal_advi_iterations\n temperature_update = [(self.temperature,\n tt.maximum(1.0, self.temperature - temperature_drop_per_iter))]\n\n self.continuous_model_advi = ADVIDeterministicAnnealing(\n random_seed=self.hybrid_inference_params.random_seed,\n temperature=self.temperature)\n self.continuous_model_approx: pm.MeanField = self.continuous_model_advi.approx\n\n if 'custom_optimizer' in kwargs.keys():\n opt = kwargs['custom_optimizer']\n assert issubclass(type(opt), fancy_optimizers.FancyStochasticOptimizer)\n self.fancy_opt = opt\n else:\n self.fancy_opt = fancy_optimizers.FancyAdamax(\n learning_rate=hybrid_inference_params.learning_rate,\n beta1=hybrid_inference_params.adamax_beta1,\n beta2=hybrid_inference_params.adamax_beta2,\n sample_specific_only=False)\n\n self.continuous_model_step_func = self.continuous_model_advi.objective.step_function(\n score=True,\n obj_optimizer=self.fancy_opt.get_optimizer(self.continuous_model, self.continuous_model_approx),\n total_grad_norm_constraint=self.hybrid_inference_params.total_grad_norm_constraint,\n obj_n_mc=self.hybrid_inference_params.obj_n_mc,\n more_updates=temperature_update)\n\n if self.sampler is not None:\n self.sampler.update_approximation(self.continuous_model_approx)\n\n if 'elbo_normalization_factor' in kwargs.keys():\n self.elbo_normalization_factor = kwargs['elbo_normalization_factor']\n else:\n self.elbo_normalization_factor = 1.0\n\n if 'advi_task_name' in kwargs.keys():\n self.advi_task_name = kwargs['advi_task_name']\n else:\n self.advi_task_name = \"ADVI\"\n\n if 'sampling_task_name' in kwargs.keys():\n self.sampling_task_name = kwargs['sampling_task_name']\n else:\n self.sampling_task_name = \"sampling\"\n\n if 'calling_task_name' in kwargs.keys():\n self.calling_task_name = kwargs['calling_task_name']\n else:\n self.calling_task_name = \"calling_task_name\"\n\n self._t0 = None\n self._t1 = None\n self.elbo_hist: List[float] = []\n self.rls_elbo_hist: List[float] = []\n self.snr_hist: List[float] = []\n self.i_epoch = 1\n self.i_advi = 1\n self.calling_hist: List[Tuple[int, bool, bool]] = []\n self.previous_sampling_rounds = 0\n self.latest_caller_update_summary: Optional[CallerUpdateSummary] = None\n self.tqdm_out = LoggerTQDMAdapter(_logger)\n\n @abstractmethod\n def disengage(self):\n raise NotImplementedError\n\n def engage(self):\n try:\n all_converged = False\n while self.i_epoch <= self.hybrid_inference_params.max_training_epochs:\n _logger.debug(\"Starting epoch {0}...\".format(self.i_epoch))\n converged_continuous = self._update_continuous_posteriors()\n all_converged = converged_continuous\n if self.sampler is not None:\n converged_sampling = self._update_log_emission_posterior_expectation()\n all_converged = all_converged and converged_sampling\n if self.caller is not None:\n converged_discrete = self._update_discrete_posteriors()\n all_converged = all_converged and converged_discrete\n self.i_epoch += 1\n if all_converged and not self._premature_convergence():\n break\n if all_converged:\n _logger.info(\"Inference task completed successfully and convergence achieved.\")\n else:\n _logger.warning(\"Inference task completed successfully but convergence not achieved.\")\n except KeyboardInterrupt:\n pass\n\n def _log_start(self, task_name: str, i_epoch: int):\n self._t0 = time.time()\n _logger.debug(\"Starting {0} for epoch {1}...\".format(task_name, i_epoch))\n\n def _log_stop(self, task_name: str, i_epoch: int):\n self._t1 = time.time()\n _logger.debug('The {0} for epoch {1} successfully finished in {2:.2f}s'.format(\n task_name, i_epoch, self._t1 - self._t0))\n\n def _log_interrupt(self, task_name: str, i_epoch: int):\n _logger.warning('The {0} for epoch {1} was interrupted'.format(task_name, i_epoch))\n\n def _premature_convergence(self):\n too_few_epochs = self.i_epoch < self.hybrid_inference_params.min_training_epochs\n temperature_still_high = np.abs(self.temperature.get_value()[0] - 1) > self.temperature_tolerance\n still_in_annealing = temperature_still_high and not self.hybrid_inference_params.disable_annealing\n return too_few_epochs or still_in_annealing\n\n def _create_param_tracker(self):\n assert all([param_name in self.continuous_model.vars or\n param_name in self.continuous_model.deterministics\n for param_name in self.hybrid_inference_params.param_tracker_config.var_names]),\\\n \"Some of the parameters chosen to be tracker are not present in the model\"\n return VariationalParameterTracker(self.hybrid_inference_params.param_tracker_config)\n\n def _update_continuous_posteriors(self) -> bool:\n self._log_start(self.advi_task_name, self.i_epoch)\n max_advi_iters = self.hybrid_inference_params.max_advi_iter_subsequent_epochs if self.i_epoch > 1 \\\n else self.hybrid_inference_params.max_advi_iter_first_epoch\n converged = False\n with tqdm.trange(max_advi_iters,\n desc=\"({0}) starting...\".format(self.advi_task_name),\n file=self.tqdm_out) as progress_bar:\n try:\n for _ in progress_bar:\n loss = self.continuous_model_step_func() / self.elbo_normalization_factor\n self.i_advi += 1\n try:\n self.advi_convergence_tracker(self.continuous_model_advi.approx, loss, self.i_advi)\n except StopIteration:\n if not self._premature_convergence(): # suppress signal if deemed premature\n raise StopIteration\n snr = self.advi_convergence_tracker.snr\n elbo_mean = self.advi_convergence_tracker.mean\n elbo_variance = self.advi_convergence_tracker.variance\n if snr is not None:\n self.snr_hist.append(snr)\n self.elbo_hist.append(-loss)\n self.rls_elbo_hist.append(elbo_mean)\n progress_bar.set_description(\"({0} epoch {1}) ELBO: {2}, SNR: {3}, T: {4:.2f}\".format(\n self.advi_task_name,\n self.i_epoch,\n \"{0:.3f} +/- {1:.3f}\".format(-elbo_mean, np.sqrt(elbo_variance))\n if elbo_mean is not None and elbo_variance is not None else \"N/A\",\n \"{0:.1f}\".format(snr) if snr is not None else \"N/A\",\n self.temperature.get_value()[0]),\n refresh=False)\n if self.param_tracker is not None \\\n and self.i_advi % self.hybrid_inference_params.track_model_params_every == 0:\n self.param_tracker(self.continuous_model_advi.approx, loss, self.i_advi)\n\n except StopIteration:\n converged = True\n progress_bar.refresh()\n progress_bar.close()\n self._log_stop(self.advi_task_name, self.i_epoch)\n\n except KeyboardInterrupt:\n progress_bar.refresh()\n progress_bar.close()\n self._log_interrupt(self.advi_task_name, self.i_epoch)\n raise KeyboardInterrupt\n\n return converged\n\n def _update_log_emission_posterior_expectation(self):\n self._log_start(self.sampling_task_name, self.i_epoch)\n if self.i_epoch == 1:\n self.sampler.reset() # clear out log emission\n lag = min(self.previous_sampling_rounds, self.hybrid_inference_params.sampler_smoothing_window)\n converged = False\n median_rel_err = np.nan\n with tqdm.trange(self.hybrid_inference_params.log_emission_sampling_rounds,\n desc=\"({0} epoch {1})\".format(self.sampling_task_name, self.i_epoch),\n file=self.tqdm_out) as progress_bar:\n try:\n for i_round in progress_bar:\n update_to_estimator = self.sampler.draw()\n latest_estimator = self.sampler.get_latest_log_emission_posterior_mean_estimator()\n update_to_estimator = (update_to_estimator - latest_estimator) / (i_round + 1 + lag)\n self.sampler.increment(update_to_estimator)\n latest_estimator = self.sampler.get_latest_log_emission_posterior_mean_estimator()\n median_rel_err = np.median(np.abs(update_to_estimator / latest_estimator).flatten())\n std_rel_err = np.std(np.abs(update_to_estimator / latest_estimator).flatten())\n del update_to_estimator\n progress_bar.set_description(\"({0} epoch {1}) relative error: {2:2.4f} +/- {3:2.4f}\".format(\n self.sampling_task_name, self.i_epoch, median_rel_err, std_rel_err),\n refresh=False)\n if median_rel_err < self.hybrid_inference_params.log_emission_sampling_median_rel_error:\n _logger.debug('{0} converged after {1} rounds with final '\n 'median relative error {2:.3}.'.format(self.sampling_task_name, i_round + 1,\n median_rel_err))\n raise StopIteration\n\n except StopIteration:\n converged = True\n progress_bar.refresh()\n progress_bar.close()\n self._log_stop(self.sampling_task_name, self.i_epoch)\n\n except KeyboardInterrupt:\n progress_bar.refresh()\n progress_bar.close()\n raise KeyboardInterrupt\n\n finally:\n self.previous_sampling_rounds = i_round + 1\n if not converged:\n _logger.warning('{0} did not converge (median relative error '\n '= {1:.3}). Increase sampling rounds (current: {2}) if this behavior persists.'\n .format(self.sampling_task_name, median_rel_err,\n self.hybrid_inference_params.log_emission_sampling_rounds))\n\n return converged\n\n def _update_discrete_posteriors(self):\n self._log_start(self.calling_task_name, self.i_epoch)\n first_call_converged = False # if convergence is achieved on the first call (stronger)\n iters_converged = False # if internal loop is converged (weaker, does not imply global convergence)\n with tqdm.trange(self.hybrid_inference_params.max_calling_iters,\n desc=\"({0} epoch {1})\".format(self.calling_task_name, self.i_epoch),\n file=self.tqdm_out) as progress_bar:\n try:\n for i_calling_iter in progress_bar:\n caller_summary = self.caller.call()\n self.latest_caller_update_summary = caller_summary\n progress_bar.set_description(\"({0} epoch {1}) {2}\".format(\n self.calling_task_name, self.i_epoch, repr(caller_summary)), refresh=False)\n caller_update_size_scalar = caller_summary.reduce_to_scalar()\n if caller_update_size_scalar < self.hybrid_inference_params.caller_update_convergence_threshold:\n iters_converged = True\n if i_calling_iter == 0:\n first_call_converged = True\n raise StopIteration\n\n except StopIteration:\n progress_bar.refresh()\n progress_bar.close()\n self._log_stop(self.calling_task_name, self.i_epoch)\n\n except KeyboardInterrupt:\n progress_bar.refresh()\n progress_bar.close()\n self._log_interrupt(self.calling_task_name, self.i_epoch)\n raise KeyboardInterrupt\n\n finally:\n self.caller.update_auxiliary_vars()\n self.calling_hist.append((self.i_advi, iters_converged, first_call_converged))\n # if there is a self-consistency loop and not converged ...\n if not iters_converged and self.hybrid_inference_params.max_calling_iters > 1:\n _logger.warning('{0} did not converge. Increase maximum calling rounds (current: {1}) '\n 'if this behavior persists.'.format(\n self.calling_task_name, self.hybrid_inference_params.max_calling_iters))\n\n return first_call_converged\n\n\nclass HybridInferenceParameters:\n \"\"\"Hybrid ADVI inference parameters.\"\"\"\n def __init__(self,\n learning_rate: float = 0.05,\n adamax_beta1: float = 0.9,\n adamax_beta2: float = 0.99,\n obj_n_mc: int = 1,\n random_seed: int = 1984,\n total_grad_norm_constraint: Optional[float] = None,\n log_emission_samples_per_round: int = 50,\n log_emission_sampling_median_rel_error: float = 5e-3,\n log_emission_sampling_rounds: int = 10,\n max_advi_iter_first_epoch: int = 100,\n max_advi_iter_subsequent_epochs: int = 100,\n min_training_epochs: int = 5,\n max_training_epochs: int = 50,\n initial_temperature: float = 2.0,\n num_thermal_epochs: int = 20,\n track_model_params: bool = False,\n track_model_params_every: int = 10,\n param_tracker_config: Optional['VariationalParameterTrackerConfig'] = None,\n convergence_snr_averaging_window: int = 500,\n convergence_snr_trigger_threshold: float = 0.1,\n convergence_snr_countdown_window: int = 10,\n max_calling_iters: int = 10,\n caller_update_convergence_threshold: float = 1e-3,\n caller_admixing_rate: float = 0.75,\n sampler_smoothing_window: int = 0,\n caller_summary_statistics_reducer: Callable[[np.ndarray], float] = np.mean,\n disable_sampler: bool = False,\n disable_caller: bool = False,\n disable_annealing: bool = False):\n \"\"\"See `expose_args` for the description of arguments.\"\"\"\n self.learning_rate = learning_rate\n self.adamax_beta1 = adamax_beta1\n self.adamax_beta2 = adamax_beta2\n self.obj_n_mc = obj_n_mc\n self.random_seed = random_seed\n self.total_grad_norm_constraint = total_grad_norm_constraint\n self.log_emission_samples_per_round = log_emission_samples_per_round\n self.log_emission_sampling_median_rel_error = log_emission_sampling_median_rel_error\n self.log_emission_sampling_rounds = log_emission_sampling_rounds\n self.max_advi_iter_first_epoch = max_advi_iter_first_epoch\n self.max_advi_iter_subsequent_epochs = max_advi_iter_subsequent_epochs\n self.min_training_epochs = min_training_epochs\n self.max_training_epochs = max_training_epochs\n self.initial_temperature = initial_temperature\n self.num_thermal_epochs = num_thermal_epochs\n self.track_model_params = track_model_params\n self.track_model_params_every = track_model_params_every\n self.param_tracker_config = param_tracker_config\n self.convergence_snr_averaging_window = convergence_snr_averaging_window\n self.convergence_snr_trigger_threshold = convergence_snr_trigger_threshold\n self.convergence_snr_countdown_window = convergence_snr_countdown_window\n self.max_calling_iters = max_calling_iters\n self.caller_update_convergence_threshold = caller_update_convergence_threshold\n self.caller_admixing_rate = caller_admixing_rate\n self.sampler_smoothing_window = sampler_smoothing_window\n self.caller_summary_statistics_reducer = caller_summary_statistics_reducer\n self.disable_sampler = disable_sampler\n self.disable_caller = disable_caller\n self.disable_annealing = disable_annealing\n\n self._assert_params()\n\n def _assert_params(self):\n assert self.learning_rate > 0\n assert self.adamax_beta1 > 0\n assert self.adamax_beta2 > 0\n assert self.obj_n_mc > 0\n assert self.log_emission_samples_per_round > 0\n assert 0.0 < self.log_emission_sampling_median_rel_error < 1.0\n assert self.log_emission_sampling_rounds > 0\n assert self.max_advi_iter_first_epoch > 0\n assert self.max_advi_iter_subsequent_epochs > 0\n assert self.min_training_epochs > 0\n assert self.max_training_epochs > 0\n assert self.max_training_epochs >= self.min_training_epochs\n assert self.num_thermal_epochs <= self.max_training_epochs\n assert self.initial_temperature >= 1.0\n assert self.disable_annealing or self.num_thermal_epochs > 0\n assert self.track_model_params_every > 0\n assert self.convergence_snr_averaging_window > 0\n assert self.convergence_snr_trigger_threshold > 0\n assert self.max_calling_iters > 0\n assert self.caller_update_convergence_threshold > 0\n assert self.caller_admixing_rate > 0\n assert self.sampler_smoothing_window >= 0\n\n if self.track_model_params:\n assert self.param_tracker_config is not None\n\n if self.disable_annealing and self.initial_temperature > 1.0:\n _logger.warning(\"The initial temperature ({0}) is above 1.0 and annealing is disabled. This run \"\n \"makes inferences in a thermal state. Ignore this warning if \"\n \"this setting is intended.\".format(self.initial_temperature))\n\n @staticmethod\n def expose_args(args: argparse.ArgumentParser, override_default: Dict[str, Any] = None, hide: Set[str] = None):\n \"\"\"Exposes arguments of `__init__` to a given instance of `ArgumentParser`.\n\n Args:\n args: an instance of `ArgumentParser`\n override_default: a dictionary containing arguments the default values of which\n are to be overridden before passing to the argument parser\n hide: a set of arguments not to expose\n\n Returns:\n None\n \"\"\"\n group = args.add_argument_group(title=\"Inference parameters\")\n if override_default is None:\n override_default = dict()\n if hide is None:\n hide = set()\n\n initializer_params = inspect.signature(HybridInferenceParameters.__init__).parameters\n valid_args = {\"--\" + arg for arg in initializer_params.keys()}\n for hidden_arg in hide:\n assert hidden_arg in valid_args, \\\n \"Initializer argument to be hidden {0} is not a valid initializer arguments; possible \" \\\n \"choices are: {1}\".format(hidden_arg, valid_args)\n for override_default_arg in override_default.keys():\n assert override_default_arg in valid_args, \\\n \"Initializer argument of which the default is to be overridden {0} is not a valid initializer \" \\\n \"arguments; possible choices are: {1}\".format(override_default_arg, valid_args)\n\n def process_and_maybe_add(arg, **kwargs):\n full_arg = \"--\" + arg\n if full_arg in hide:\n return\n if full_arg in override_default:\n kwargs['default'] = override_default[full_arg]\n else:\n kwargs['default'] = initializer_params[arg].default\n group.add_argument(full_arg, **kwargs)\n\n def str_to_bool(value: str):\n if value.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif value.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Boolean value expected.')\n\n process_and_maybe_add(\"learning_rate\",\n type=float,\n help=\"Adamax optimizer learning rate\")\n\n process_and_maybe_add(\"adamax_beta1\",\n type=float,\n help=\"Adamax first moment estimator forgetting factor\")\n\n process_and_maybe_add(\"adamax_beta2\",\n type=float,\n help=\"Adamax second moment estimator forgetting factor\")\n\n process_and_maybe_add(\"log_emission_samples_per_round\",\n type=int,\n help=\"Number of log emission posterior samples per sampling round\")\n\n process_and_maybe_add(\"log_emission_sampling_median_rel_error\",\n type=float,\n help=\"Maximum tolerated median relative error in log emission posterior sampling\")\n\n process_and_maybe_add(\"log_emission_sampling_rounds\",\n type=int,\n help=\"Maximum log emission posterior sampling rounds\")\n\n process_and_maybe_add(\"max_advi_iter_first_epoch\",\n type=int,\n help=\"Maximum ADVI iterations in the first epoch (before sampling and calling)\")\n\n process_and_maybe_add(\"max_advi_iter_subsequent_epochs\",\n type=int,\n help=\"Maximum ADVI iterations after the first epoch\")\n\n process_and_maybe_add(\"min_training_epochs\",\n type=int,\n help=\"Minimum number of training epochs before evaluating convergence\")\n\n process_and_maybe_add(\"max_training_epochs\",\n type=int,\n help=\"Maximum number of training epochs before stopping\")\n\n process_and_maybe_add(\"initial_temperature\",\n type=float,\n help=\"Initial temperature for deterministic annealing (must be >= 1.0)\")\n\n process_and_maybe_add(\"num_thermal_epochs\",\n type=int,\n help=\"Annealing duration (in the units of training epochs)\")\n\n process_and_maybe_add(\"convergence_snr_averaging_window\",\n type=int,\n help=\"Averaging window for calculating training SNR for evaluating convergence\")\n\n process_and_maybe_add(\"convergence_snr_trigger_threshold\",\n type=float,\n help=\"The SNR threshold to be reached for triggering convergence\")\n\n process_and_maybe_add(\"convergence_snr_countdown_window\",\n type=int,\n help=\"The number of ADVI iterations during which the SNR is required to stay below the \"\n \"set threshold for convergence\")\n\n process_and_maybe_add(\"max_calling_iters\",\n type=int,\n help=\"Maximum number of calling internal self-consistency iterations\")\n\n process_and_maybe_add(\"caller_update_convergence_threshold\",\n type=float,\n help=\"Maximum tolerated calling update size for convergence\")\n\n process_and_maybe_add(\"caller_admixing_rate\",\n type=float,\n help=\"Admixing ratio of new and old caller posteriors (between 0 and 1; higher means \"\n \"using more of the new posterior)\")\n\n process_and_maybe_add(\"disable_sampler\",\n type=str_to_bool,\n help=\"(advanced) Disable sampler\")\n\n process_and_maybe_add(\"disable_caller\",\n type=str_to_bool,\n help=\"(advanced) Disable caller\")\n\n process_and_maybe_add(\"disable_annealing\",\n type=str_to_bool,\n help=\"(advanced) Keep the temperature pinned at its initial value and disable annealing\")\n\n @staticmethod\n def from_args_dict(args_dict: Dict):\n \"\"\"Initialize an instance of `HybridInferenceParameters` from a dictionary of arguments.\n\n Args:\n args_dict: a dictionary of arguments; the keys must match argument names in\n `HybridInferenceParameters.__init__`\n\n Returns:\n an instance of `HybridInferenceParameters`\n \"\"\"\n relevant_keys = set(inspect.getfullargspec(HybridInferenceParameters.__init__).args)\n relevant_kwargs = {k: v for k, v in args_dict.items() if k in relevant_keys}\n return HybridInferenceParameters(**relevant_kwargs)\n", "meta": {"hexsha": "bcfba7ae91872ab0c11e18ae0388d37f03e62dd8", "size": 36066, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/main/python/org/broadinstitute/hellbender/gcnvkernel/tasks/inference_task_base.py", "max_stars_repo_name": "raomohan89/GATK", "max_stars_repo_head_hexsha": "068b7fdd6d983cf0b7611b03bd0028d85de61bc2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main/python/org/broadinstitute/hellbender/gcnvkernel/tasks/inference_task_base.py", "max_issues_repo_name": "raomohan89/GATK", "max_issues_repo_head_hexsha": "068b7fdd6d983cf0b7611b03bd0028d85de61bc2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main/python/org/broadinstitute/hellbender/gcnvkernel/tasks/inference_task_base.py", "max_forks_repo_name": "raomohan89/GATK", "max_forks_repo_head_hexsha": "068b7fdd6d983cf0b7611b03bd0028d85de61bc2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.64332893, "max_line_length": 119, "alphanum_fraction": 0.6240780791, "include": true, "reason": "import numpy,import theano,import pymc3", "num_tokens": 7208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.24508501313237172, "lm_q1q2_score": 0.12828248309280957}} {"text": "# Copyright 2022 The TEMPO Collaboration\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nModule on for the original time evolving matrix product operator (TEMPO)\nalgorithm. This module is based on [Strathearn2017] and [Strathearn2018].\n\n**[Strathearn2017]**\nA. Strathearn, B.W. Lovett, and P. Kirton, *Efficient real-time path integrals\nfor non-Markovian spin-boson models*. New Journal of Physics, 19(9),\np.093009 (2017).\n\n**[Strathearn2018]**\nA. Strathearn, P. Kirton, D. Kilda, J. Keeling and\nB. W. Lovett, *Efficient non-Markovian quantum dynamics using\ntime-evolving matrix product operators*, Nat. Commun. 9, 3322 (2018).\n\"\"\"\n\nimport sys\nfrom typing import Callable, Dict, Optional, Text\nimport warnings\nfrom copy import copy\n\nimport numpy as np\nfrom numpy import ndarray\nfrom scipy.linalg import expm\nfrom oqupy.correlations import BaseCorrelations\n\nfrom oqupy.bath import Bath\nfrom oqupy.base_api import BaseAPIClass\nfrom oqupy.config import NpDtype, MAX_DKMAX, DEFAULT_TOLERANCE\nfrom oqupy.config import TEMPO_BACKEND_CONFIG\nfrom oqupy.dynamics import Dynamics\nfrom oqupy.system import BaseSystem\nfrom oqupy.tempo.backends.tempo_backend import TempoBackend\nfrom oqupy.operators import commutator, acommutator\nfrom oqupy.util import get_progress\n\n\nclass TempoParameters(BaseAPIClass):\n r\"\"\"\n Parameters for the TEMPO computation.\n\n Parameters\n ----------\n dt: float\n Length of a time step :math:`\\delta t`. - It should be small enough\n such that a trotterisation between the system Hamiltonian and the\n environment it valid, and the environment auto-correlation function\n is reasonably well sampled.\n dkmax: int\n Number of time steps :math:`K\\in\\mathbb{N}` that should be included in\n the non-Markovian memory. - It must be large\n enough such that :math:`\\delta t \\times K` is larger than the\n necessary memory time :math:`\\tau_\\mathrm{cut}`.\n epsrel: float\n The maximal relative error in the singular value truncation (done\n in the underlying tensor network algorithm). - It must be small enough\n such that the numerical compression (using tensor network algorithms)\n does not truncate relevant correlations.\n add_correlation_time: float\n Additional correlation time to include in the last influence\n functional as explained in [Strathearn2017].\n name: str (default = None)\n An optional name for the tempo parameters object.\n description: str (default = None)\n An optional description of the tempo parameters object.\n \"\"\"\n def __init__(\n self,\n dt: float,\n dkmax: int,\n epsrel: float,\n add_correlation_time: Optional[float] = None,\n name: Optional[Text] = None,\n description: Optional[Text] = None) -> None:\n \"\"\"Create a TempoParameters object.\"\"\"\n self.dt = dt\n self.dkmax = dkmax\n self.epsrel = epsrel\n self.add_correlation_time = add_correlation_time\n super().__init__(name, description)\n\n def __str__(self) -> Text:\n ret = []\n ret.append(super().__str__())\n ret.append(\" dt = {} \\n\".format(self.dt))\n ret.append(\" dkmax = {} \\n\".format(self.dkmax))\n ret.append(\" epsrel = {} \\n\".format(self.epsrel))\n ret.append(\" add_correlation_time = {} \\n\".format(\n self.add_correlation_time))\n return \"\".join(ret)\n\n @property\n def dt(self) -> float:\n \"\"\"Length of a time step.\"\"\"\n return self._dt\n\n @dt.setter\n def dt(self, new_dt: float) -> None:\n try:\n tmp_dt = float(new_dt)\n except Exception as e:\n raise AssertionError(\"Argument 'dt' must be float.\") from e\n assert tmp_dt > 0.0, \\\n \"Argument 'dt' must be bigger than 0.\"\n self._dt = tmp_dt\n\n @property\n def dkmax(self) -> float:\n \"\"\"Number of time steps that should be included in the non-Markovian\n memory. \"\"\"\n return self._dkmax\n\n @dkmax.setter\n def dkmax(self, new_dkmax: float) -> None:\n try:\n if new_dkmax is None:\n tmp_dkmax = None\n else:\n tmp_dkmax = int(new_dkmax)\n except Exception as e:\n raise AssertionError(\"Argument 'dkmax' must be int or None.\") \\\n from e\n assert tmp_dkmax is None or tmp_dkmax > 0, \\\n \"Argument 'dkmax' must be bigger than or equal to 0 or None.\"\n self._dkmax = tmp_dkmax\n\n @dkmax.deleter\n def dkmax(self) -> None:\n self._dkmax = None\n\n @property\n def epsrel(self) -> float:\n \"\"\"The maximal relative error in the singular value truncation.\"\"\"\n return self._epsrel\n\n @epsrel.setter\n def epsrel(self, new_epsrel: float) -> None:\n try:\n tmp_epsrel = float(new_epsrel)\n except Exception as e:\n raise AssertionError(\"Argument 'epsrel' must be float.\") from e\n assert tmp_epsrel > 0.0, \\\n \"Argument 'epsrel' must be bigger than 0.\"\n self._epsrel = tmp_epsrel\n\n @property\n def add_correlation_time(self) -> float:\n \"\"\"\n Additional correlation time to include in the last influence\n functional.\n \"\"\"\n return self._add_correlation_time\n\n @add_correlation_time.setter\n def add_correlation_time(self, new_tau: Optional[float] = None) -> None:\n if new_tau is None:\n del self.add_correlation_time\n else:\n # check input: cutoff\n try:\n tmp_new_tau = float(new_tau)\n except Exception as e:\n raise AssertionError( \\\n \"Additional correlation time must be a float.\") from e\n if tmp_new_tau < 0:\n raise ValueError(\n \"Additional correlation time must be non-negative.\")\n self._add_correlation_time = tmp_new_tau\n\n @add_correlation_time.deleter\n def add_correlation_time(self) -> None:\n self._add_correlation_time = None\n\nclass Tempo(BaseAPIClass):\n \"\"\"\n Class representing the entire TEMPO tensornetwork as introduced in\n [Strathearn2018].\n\n Parameters\n ----------\n system: BaseSystem\n The system.\n bath: Bath\n The Bath (includes the coupling operator to the system).\n parameters: TempoParameters\n The parameters for the TEMPO computation.\n initial_state: ndarray\n The initial density matrix of the system.\n start_time: float\n The start time.\n backend: str (default = None)\n The name of the backend to use for the computation. If\n `backend` is ``None`` then the default backend is used.\n backend_config: dict (default = None)\n The configuration of the backend. If `backend_config` is\n ``None`` then the default backend configuration is used.\n name: str (default = None)\n An optional name for the tempo object.\n description: str (default = None)\n An optional description of the tempo object.\n \"\"\"\n def __init__(\n self,\n system: BaseSystem,\n bath: Bath,\n parameters: TempoParameters,\n initial_state: ndarray,\n start_time: float,\n backend_config: Optional[Dict] = None,\n name: Optional[Text] = None,\n description: Optional[Text] = None) -> None:\n \"\"\"Create a Tempo object. \"\"\"\n\n assert isinstance(system, BaseSystem), \\\n \"Argument 'system' must be an instance of BaseSystem.\"\n self._system = system\n\n assert isinstance(bath, Bath), \\\n \"Argument 'bath' must be an instance of Bath.\"\n self._bath = bath\n\n self._correlations = self._bath.correlations\n\n assert isinstance(parameters, TempoParameters), \\\n \"Argument 'parameters' must be an instance of TempoParameters.\"\n self._parameters = parameters\n\n try:\n tmp_initial_state = np.array(initial_state, dtype=NpDtype)\n tmp_initial_state.setflags(write=False)\n except Exception as e:\n raise AssertionError(\"Initial state must be numpy array.\") from e\n assert len(tmp_initial_state.shape) == 2, \\\n \"Initial state is not a matrix.\"\n assert tmp_initial_state.shape[0] == \\\n tmp_initial_state.shape[1], \\\n \"Initial state is not a square matrix.\"\n self._initial_state = tmp_initial_state\n self._dimension = self._initial_state.shape[0]\n\n try:\n tmp_start_time = float(start_time)\n except Exception as e:\n raise AssertionError(\"Start time must be a float.\") from e\n self._start_time = tmp_start_time\n\n if backend_config is None:\n self._backend_config = TEMPO_BACKEND_CONFIG\n else:\n self._backend_config = backend_config\n\n assert self._bath.dimension == self._dimension and \\\n self._system.dimension == self._dimension, \\\n \"Hilbertspace dimensions are unequal: \" \\\n + \"system ({}), \".format(self._system.dimension) \\\n + \"initial state ({}), \".format(self._dimension) \\\n + \"and bath coupling ({}), \".format(self._bath.dimension)\n\n super().__init__(name, description)\n\n tmp_coupling_comm = commutator(self._bath._coupling_operator)\n tmp_coupling_acomm = acommutator(self._bath._coupling_operator)\n self._coupling_comm = tmp_coupling_comm.diagonal()\n self._coupling_acomm = tmp_coupling_acomm.diagonal()\n\n self._dynamics = None\n self._backend_instance = None\n\n self._init_tempo_backend()\n\n def _init_tempo_backend(self):\n \"\"\"Create and initialize the tempo backend. \"\"\"\n dim = self._dimension\n initial_state = self._initial_state.reshape(dim**2)\n influence = self._influence\n unitary_transform = self._bath.unitary_transform\n propagators = self._propagators\n sum_north = np.array([1.0]*(dim**2))\n sum_west = np.array([1.0]*(dim**2))\n dkmax = self._parameters.dkmax\n epsrel = self._parameters.epsrel\n self._backend_instance = TempoBackend(\n initial_state,\n influence,\n unitary_transform,\n propagators,\n sum_north,\n sum_west,\n dkmax,\n epsrel,\n config=self._backend_config)\n\n def _init_dynamics(self):\n \"\"\"Create a Dynamics object with metadata from the Tempo object. \"\"\"\n name = None\n description = \"computed from '{}' tempo\".format(self.name)\n self._dynamics = Dynamics(name=name,\n description=description)\n\n def _influence(self, dk: int):\n \"\"\"Create the influence functional matrix for a time step distance\n of dk. \"\"\"\n return influence_matrix(\n dk,\n parameters=self._parameters,\n correlations=self._correlations,\n coupling_acomm=self._coupling_acomm,\n coupling_comm=self._coupling_comm)\n\n def _propagators(self, step: int):\n \"\"\"Create the system propagators (first and second half) for the time\n step `step`. \"\"\"\n dt = self._parameters.dt\n t = self._time(step)\n first_step = expm(self._system.liouvillian(t+dt/4.0)*dt/2.0)\n second_step = expm(self._system.liouvillian(t+dt*3.0/4.0)*dt/2.0)\n return first_step, second_step\n\n def _time(self, step: int):\n \"\"\"Return the time that corresponds to the time step `step`. \"\"\"\n return self._start_time + float(step)*self._parameters.dt\n\n @property\n def dimension(self) -> ndarray:\n \"\"\"Hilbert space dimension. \"\"\"\n return copy(self._dimension)\n\n def compute(\n self,\n end_time: float,\n progress_type: Text = None) -> Dynamics:\n \"\"\"\n Propagate (or continue to propagate) the TEMPO tensor network to\n time `end_time`.\n\n Parameters\n ----------\n end_time: float\n The time to which the TEMPO should be computed.\n progress_type: str (default = None)\n The progress report type during the computation. Types are:\n {``'silent'``, ``'simple'``, ``'bar'``}. If `None` then\n the default progress type is used.\n\n Returns\n -------\n dynamics: Dynamics\n The instance of Dynamics associated with the TEMPO object.\n \"\"\"\n try:\n tmp_end_time = float(end_time)\n except Exception as e:\n raise AssertionError(\"End time must be a float.\") from e\n\n dim = self._dimension\n if self._backend_instance.step is None:\n step, state = self._backend_instance.initialize()\n self._init_dynamics()\n self._dynamics.add(self._time(step), state.reshape(dim, dim))\n\n start_step = self._backend_instance.step\n end_step = int((end_time - self._start_time)/self._parameters.dt)\n num_step = max(0, end_step - start_step)\n\n progress = get_progress(progress_type)\n with progress(num_step) as prog_bar:\n while self._time(self._backend_instance.step) < tmp_end_time:\n step, state = self._backend_instance.compute_step()\n self._dynamics.add(self._time(step), state.reshape(dim, dim))\n prog_bar.update(self._backend_instance.step - start_step)\n prog_bar.update(self._backend_instance.step - start_step)\n\n return self._dynamics\n\n def get_dynamics(self) -> Dynamics:\n \"\"\"Returns the instance of Dynamics associated with the Tempo object.\n \"\"\"\n return self._dynamics\n\ndef influence_matrix(\n dk: int,\n parameters: TempoParameters,\n correlations: BaseCorrelations,\n coupling_acomm: ndarray,\n coupling_comm: ndarray):\n \"\"\"Compute the influence functional matrix. \"\"\"\n dt = parameters.dt\n dkmax = parameters.dkmax\n\n if dk == 0:\n time_1 = 0.0\n time_2 = None\n shape = \"upper-triangle\"\n elif dk < 0:\n time_1 = float(dkmax) * dt\n if parameters.add_correlation_time is not None:\n time_2 = float(dkmax) * dt \\\n + np.min([float(-dk) * dt,\n 1.0*dt + parameters.add_correlation_time])\n else:\n return None\n shape = \"rectangle\"\n else:\n time_1 = float(dk) * dt\n time_2 = None\n shape = \"square\"\n\n eta_dk = correlations.correlation_2d_integral( \\\n delta=dt,\n time_1=time_1,\n time_2=time_2,\n shape=shape,\n epsrel=parameters.epsrel)\n op_p = coupling_acomm\n op_m = coupling_comm\n\n if dk == 0:\n infl = np.diag(np.exp(-op_m*(eta_dk.real*op_m \\\n + 1j*eta_dk.imag*op_p)))\n else:\n infl = np.exp(-np.outer(eta_dk.real*op_m \\\n + 1j*eta_dk.imag*op_p, op_m))\n\n return infl\n\ndef _analyse_correlation(\n corr_func: Callable[[np.ndarray],np.ndarray],\n times: np.ndarray,\n corr_vals: np.ndarray):\n \"\"\"Check correlation function on a finer grid.\"\"\"\n additional_times = (times[:-1] + times[1:])/2.0\n additional_corr_vals = corr_func(additional_times)\n new_times = list(times)\n new_corr_vals = list(corr_vals)\n for i in range(len(additional_times)):\n new_times.insert(2*i+1,additional_times[i])\n new_corr_vals.insert(2*i+1,additional_corr_vals[i])\n\n errors = []\n integrals = []\n integral = 0.0\n\n for i in range(len(times)-1):\n dt = new_times[2*i+2] - new_times[2*i]\n\n rough_int = 0.5 * dt * (new_corr_vals[2*i] + new_corr_vals[2*i+2])\n fine_int = 0.5 * (rough_int + dt * new_corr_vals[2*i+1])\n error = np.abs(rough_int-fine_int)\n errors.append(error)\n\n rough_abs_int = 0.5 * dt \\\n * (np.abs(new_corr_vals[2*i]) + np.abs(new_corr_vals[2*i+2]))\n fine_abs_int = 0.5 * (rough_abs_int + dt * np.abs(new_corr_vals[2*i+1]))\n integral += fine_abs_int\n integrals.append(integral)\n\n full_abs_integral = integrals[-1]\n\n new_times = np.array(new_times)\n new_corr_val = np.array(new_corr_vals)\n errors = np.array(errors) / full_abs_integral\n integrals = np.array(integrals) / full_abs_integral\n\n return new_times, new_corr_val, errors, integrals\n\ndef _estimate_epsrel(\n dkmax: int,\n tolerance: float) -> float:\n \"\"\"Heuristic estimation of appropriate epsrel for TEMPO.\"\"\"\n power = np.log(dkmax)/np.log(4)-np.log(tolerance)/np.log(10)\n return np.power(10,-power)\n\nGUESS_WARNING_MSG = \"Estimating parameters for TEMPO computation. \" \\\n + \"No guarantee that resulting TEMPO computation converges towards \" \\\n + \"the correct dynamics! \" \\\n + \"Please refer to the TEMPO documentation and check convergence by \" \\\n + \"varying the parameters for TEMPO manually.\"\n\nMAX_DKMAX_WARNING_MSG = f\"Reached maximal recommended `dkmax` ({MAX_DKMAX})! \" \\\n + \"Interrupt TEMPO parameter estimation. \"\\\n + \"Please choose a lower tolerance, or analyse the correlation function \" \\\n + \"to choose TEMPO parameters manually. \" \\\n + \"Could not reach specified tolerance! \"\n\ndef guess_tempo_parameters(\n bath: Bath,\n start_time: float,\n end_time: float,\n system: Optional[BaseSystem] = None,\n tolerance: Optional[float] = DEFAULT_TOLERANCE) -> TempoParameters:\n \"\"\"\n Function to roughly estimate appropriate parameters for a TEMPO\n computation.\n\n .. warning::\n\n No guarantee that resulting TEMPO calculation converges towards the\n correct dynamics! Please refer to the TEMPO documentation and check\n convergence by varying the parameters for TEMPO manually.\n\n Parameters\n ----------\n bath: Bath\n The bath.\n start_time: float\n The start time.\n end_time: float\n The time to which the TEMPO should be computed.\n system: BaseSystem\n The system.\n tolerance: float\n Tolerance for the parameter estimation.\n\n Returns\n -------\n tempo_parameters : TempoParameters\n Estimate of appropriate tempo parameters.\n \"\"\"\n assert isinstance(bath, Bath), \\\n \"Argument 'bath' must be a oqupy.Bath object.\"\n try:\n tmp_start_time = float(start_time)\n tmp_end_time = float(end_time)\n except Exception as e:\n raise AssertionError(\"Start and end time must be a float.\") from e\n if tmp_end_time <= tmp_start_time:\n raise ValueError(\"End time must be bigger than start time.\")\n assert isinstance(system, (type(None), BaseSystem)), \\\n \"Argument 'system' must be 'None' or a oqupy.BaseSystem object.\"\n try:\n tmp_tolerance = float(tolerance)\n except Exception as e:\n raise AssertionError(\"Argument 'tolerance' must be float.\") from e\n assert tmp_tolerance > 0.0, \\\n \"Argument 'tolerance' must be larger then 0.\"\n warnings.warn(GUESS_WARNING_MSG, UserWarning)\n print(\"WARNING: \"+GUESS_WARNING_MSG, file=sys.stderr, flush=True)\n\n max_tau = tmp_end_time - tmp_start_time\n\n corr_func = np.vectorize(bath.correlations.correlation)\n new_times = np.linspace(0, max_tau, 11, endpoint=True)\n new_corr_vals = corr_func(new_times)\n times = new_times\n corr_vals = new_corr_vals\n\n while True:\n if len(new_times) > MAX_DKMAX:\n warnings.warn(MAX_DKMAX_WARNING_MSG, UserWarning)\n break\n times = new_times\n corr_vals = new_corr_vals\n new_times, new_corr_vals, errors, integrals = \\\n _analyse_correlation(corr_func, times, corr_vals)\n cut = np.where(integrals>(1-tolerance))[0][0]\n cut = cut+2 if cut+2<=len(times) else len(times)\n times = times[:cut]\n corr_vals = corr_vals[:cut]\n new_times = new_times[:2*cut-1]\n new_corr_vals = new_corr_vals[:2*cut-1]\n if (errors < tolerance).all():\n break\n\n dt = np.min(times[1:] - times[:-1])\n dkmax = len(times)\n epsrel = _estimate_epsrel(dkmax, tolerance)\n sys.stderr.flush()\n\n return TempoParameters(\n dt=dt,\n dkmax=dkmax,\n epsrel=epsrel,\n name=\"Roughly estimated parameters\",\n description=\"Estimated with 'guess_tempo_parameters()'\")\n\n\ndef tempo_compute(\n system: BaseSystem,\n bath: Bath,\n initial_state: ndarray,\n start_time: float,\n end_time: float,\n parameters: Optional[TempoParameters] = None,\n tolerance: Optional[float] = DEFAULT_TOLERANCE,\n backend_config: Optional[Dict] = None,\n progress_type: Optional[Text] = None,\n name: Optional[Text] = None,\n description: Optional[Text] = None) -> Dynamics:\n \"\"\"\n Shortcut for creating a Tempo object and running the computation.\n\n Parameters\n ----------\n system: BaseSystem\n The system.\n bath: Bath\n The Bath (includes the coupling operator to the system).\n initial_state: ndarray\n The initial density matrix of the system.\n start_time: float\n The start time.\n end_time: float\n The time to which the TEMPO should be computed.\n parameters: TempoParameters\n The parameters for the TEMPO computation.\n tolerance: float\n Tolerance for the parameter estimation (only applicable if\n `parameters` is None).\n backend_config: dict (default = None)\n The configuration of the backend. If `backend_config` is\n ``None`` then the default backend configuration is used.\n progress_type: str (default = None)\n The progress report type during the computation. Types are:\n {``'silent'``, ``'simple'``, ``'bar'``}. If `None` then\n the default progress type is used.\n name: str (default = None)\n An optional name for the tempo object.\n description: str (default = None)\n An optional description of the tempo object.\n \"\"\"\n if parameters is None:\n assert tolerance is not None, \\\n \"If 'parameters' is 'None' then 'tolerance' must be \" \\\n + \"a positive float.\"\n parameters = guess_tempo_parameters(bath=bath,\n start_time=start_time,\n end_time=end_time,\n system=system,\n tolerance=tolerance)\n tempo = Tempo(system,\n bath,\n parameters,\n initial_state,\n start_time,\n backend_config,\n name,\n description)\n tempo.compute(end_time, progress_type=progress_type)\n return tempo.get_dynamics()\n", "meta": {"hexsha": "be4cfc8f89bd0eebb6d0397879e821e0e0a41ff1", "size": 23435, "ext": "py", "lang": "Python", "max_stars_repo_path": "oqupy/tempo/tempo.py", "max_stars_repo_name": "gefux/OQuPy", "max_stars_repo_head_hexsha": "764528fb6181ea62f8829a9e0a9e3faa2af71e1f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "oqupy/tempo/tempo.py", "max_issues_repo_name": "gefux/OQuPy", "max_issues_repo_head_hexsha": "764528fb6181ea62f8829a9e0a9e3faa2af71e1f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "oqupy/tempo/tempo.py", "max_forks_repo_name": "gefux/OQuPy", "max_forks_repo_head_hexsha": "764528fb6181ea62f8829a9e0a9e3faa2af71e1f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9432515337, "max_line_length": 80, "alphanum_fraction": 0.6197141028, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 5419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.2538610013242243, "lm_q1q2_score": 0.1279221250239677}} {"text": "# It defines a new Observation class, subclassed from CompositeSourceSpectrum,\n# that has some special methods and attributes and explicitly removes\n# certain other methods.\n\"\"\"This module handles an observation and related calculations.\"\"\"\nfrom __future__ import division\n\nimport logging\nimport numpy as np\nimport math\n\nfrom . import spectrum\nfrom . import units\nfrom . import binning\nfrom . import exceptions\n\nfrom .obsbandpass import pixel_range, wave_range\nfrom .spectrum import ArraySourceSpectrum\n\n\ntry:\n import pysynphot_utils\n utils_imported = True\nexcept ImportError:\n utils_imported = False\n\n\ndef check_overlap(a, b):\n \"\"\"Check for wavelength overlap between two spectra.\n\n .. note::\n\n Generalized from\n :meth:`pysynphot.spectrum.SpectralElement.check_overlap`.\n\n Parameters\n ----------\n a, b : `~pysynphot.spectrum.SourceSpectrum` or `~pysynphot.spectrum.SpectralElement`\n Typically a source spectrum, spectral element, observation,\n or bandpass from observation mode.\n\n Returns\n -------\n result : {'full', 'partial', 'none'}\n Full, partial, or no overlap.\n\n Raises\n ------\n AttributeError\n Given spectrum does not have flux or throughput.\n\n \"\"\"\n if a.isAnalytic or b.isAnalytic:\n #then it's defined everywhere\n result = 'full'\n else:\n #get the wavelength arrays\n waves = list()\n for x in (a, b):\n if hasattr(x,'throughput'):\n wv = x.wave[np.where(x.throughput != 0)]\n elif hasattr(x,'flux'):\n wv = x.wave\n else:\n raise AttributeError(\"neither flux nor throughput in %s\"%x)\n waves.append(wv)\n\n #get the endpoints\n a1,a2 = waves[0].min(), waves[0].max()\n b1,b2 = waves[1].min(), waves[1].max()\n\n #do the comparison\n if (a1>=b1 and a2<=b2):\n result = 'full'\n elif (a2`.\n An observation is the end point of a chain of spectral manipulation.\n\n Most `~pysynphot.obsbandpass.ObsBandpass` objects have a built-in\n ``binset`` that is optimized for use with the specified observing\n mode (also see :ref:`pysynphot-wavelength-table`).\n Specifying the ``binset`` here would override the built-in one.\n\n Parameters\n ----------\n spec : `~pysynphot.spectrum.SourceSpectrum`\n Source spectrum.\n\n band : `~pysynphot.spectrum.SpectralElement`\n Bandpass.\n\n binset : array_like or `None`\n Wavelength values to be used for binning when converting to counts.\n See :meth:`initbinset`.\n\n force\n See :meth:`~pysynphot.observation.Observation.validate_overlap`.\n\n Attributes\n ----------\n spectrum\n Same as input ``spec``.\n\n bandpass\n Same as input ``band``.\n\n binset\n Same as input ``binset``.\n\n component1, component2 : `~pysynphot.spectrum.SourceSpectrum` or `~pysynphot.spectrum.SpectralElement`\n Components and sub-components that belong to the observation.\n\n operation : str\n This is always \"multiply\".\n\n name : str\n Short description of the observation.\n\n warnings : dict\n To store warnings, which are inherited from all inputs. If they have the same warning keyword, the one from most recently read component is used.\n\n isAnalytic : bool\n Flag to indicate whether this is an analytic spectrum. This is only `True` if both inputs are analytic.\n\n primary_area : number or `None`\n :ref:`pysynphot-area` of the telescope. This is inherited from either of the inputs, if available (not `None`). If inputs have different values, an exception is raised.\n\n waveunits, fluxunits : `~pysynphot.units.Units`\n User units inherited from source spectrum.\n\n wave, flux : array_like\n Wavelength set and associated flux in user units. This is the native dataset.\n\n binwave, binflux : array_like\n Binned dataset.\n\n Raises\n ------\n pysynphot.exceptions.IncompatibleSources\n Input spectra have different telescope areas defined.\n\n \"\"\"\n def __init__(self,spec,band,binset=None,force=None):\n self.spectrum = spec\n self.bandpass = band\n self.warnings={}\n self.validate_overlap(force)\n self.binset = binset\n\n keep=self.warnings\n spectrum.CompositeSourceSpectrum.__init__(self,\n self.spectrum,\n self.bandpass,\n 'multiply')\n\n self.warnings.update(keep)\n\n #The natural waveset of the observation is the merge of the\n #natural waveset of the spectrum with the natural waveset of the\n #bandpass. Because the Observation inherits from a\n #CompositeSourceSpectrum, this will be handled correctly.\n# self._binwave = None\n self._binflux = None\n\n self.initbinset(binset)\n #self.initbinflux()\n\n def validate_overlap(self,force):\n \"\"\"Validate that spectrum and bandpass overlap.\n Warnings are stored in ``self.warnings``.\n\n Parameters\n ----------\n force : {'extrap', 'taper', `None`}\n If `None`, it is required that the spectrum and bandpass fully\n overlap. Partial overlap is allowed if this is set to\n ``'extrap'`` or ``'taper'``. See :func:`validate_overlap`.\n\n \"\"\"\n\n #Wrap the function for convenience\n self.spectrum, self.bandpass, warn = validate_overlap(self.spectrum,\n self.bandpass, force)\n self.warnings.update(warn)\n\n def initbinset(self,binset=None):\n \"\"\"Set ``self.binwave``.\n\n By default, wavelength values for binning are inherited\n from bandpass. If the bandpass has no binning information,\n then source spectrum wavelengths are used. However, if\n user provides values, then those are used without question.\n\n Parameters\n ----------\n binset : array_like or `None`\n Wavelength values to be used for binning when converting to counts.\n\n \"\"\"\n if binset is None:\n msg=\"(%s) does not have a defined binset in the wavecat table. The waveset of the spectrum will be used instead.\"%str(self.bandpass)\n\n try:\n self.binwave = self.bandpass.binset\n except (KeyError, AttributeError):\n self.binwave = self.spectrum.wave\n logging.warning(msg)\n\n if self.binwave is None:\n self.binwave = self.spectrum.wave\n logging.warning(msg)\n else:\n self.binwave=binset\n\n def initbinflux(self):\n \"\"\"Calculate binned flux and edges.\n\n Flux is computed by integrating the spectrum\n on the specified binned wavelength set, using\n information from the natural wavelength set.\n\n Native wave/flux arrays should be considered samples\n of a continuous function, but not their binned counterparts.\n Thus, it makes sense to interpolate ``(wave, flux)`` but not\n ``(binwave, binflux)``.\n\n .. note::\n\n Assumes that the wavelength values in the binned\n wavelength set are the *centers* of the bins.\n\n Uses ``pysynphot.pysynphot_utils.calcbinflux()`` C-extension,\n if available, for binned flux calculation.\n\n \"\"\"\n endpoints = binning.calculate_bin_edges(self.binwave)\n\n # merge these endpoints in with the natural waveset\n spwave = spectrum.MergeWaveSets(self.wave, endpoints)\n spwave = spectrum.MergeWaveSets(spwave,self.binwave)\n\n # compute indices associated to each endpoint.\n indices = np.searchsorted(spwave, endpoints)\n self._indices = indices[:-1]\n self._indices_last = indices[1:]\n\n # prepare integration variables.\n flux = self(spwave)\n avflux = (flux[1:] + flux[:-1]) / 2.0\n self._deltaw = spwave[1:] - spwave[:-1]\n\n # sum over each bin.\n if utils_imported is True:\n self._binflux, self._intwave = \\\n pysynphot_utils.calcbinflux(len(self.binwave),\n self._indices,\n self._indices_last,\n avflux,\n self._deltaw)\n else:\n #Note that, like all Python striding, the range over which\n #we integrate is [first:last).\n self._binflux = np.empty(shape=self.binwave.shape,dtype=np.float64)\n self._intwave = np.empty(shape=self.binwave.shape,dtype=np.float64)\n for i in range(len(self._indices)):\n first = self._indices[i]\n last = self._indices_last[i]\n self._binflux[i]=(avflux[first:last]*self._deltaw[first:last]).sum()/self._deltaw[first:last].sum()\n self._intwave[i]=self._deltaw[first:last].sum()\n\n #Save the endpoints for future use\n self._bin_edges = endpoints\n\n def _getBinfluxProp(self):\n if self._binflux is None:\n self.initbinflux()\n\n if hasattr(self.bandpass, 'primary_area'):\n area = self.bandpass.primary_area\n else:\n area = None\n\n binflux = units.Photlam().Convert(self.binwave,\n self._binflux,\n self.fluxunits.name,\n area=area)\n return binflux\n\n def _getBinwaveProp(self):\n if self._binwave is None:\n self.initbinset(self.binset)\n return self._binwave\n\n binflux = property(_getBinfluxProp,doc='Flux of binned wavelength set.')\n# binwave = property(_getBinwaveProp,doc='Waveset for binned flux')\n\n\n # Multiplication is handled by performing the operation on\n # the spectral component of the Observation, and then creating a\n # new Observation as the result.\n #\n # This is because Observation is a subclass of CompositeSourceSpectrum\n # but with *a lot* of extra functionality involved in handling the\n # binned wave and flux arrays. Simply inheriting the parent class's\n # methods for multiplication does not return an Observation.\n #\n # Note that the order of operations actually implemented therefore varies\n # from what is expected, which naively would be\n # (self.spectrum*self.bandpass) * other\n #\n def __mul__(self, other):\n # If the original object has partial overlap warnings, then\n # the forcing behavior also needs to be propagated.\n\n force = self.warnings.get('PartialOverlap', None)\n\n result = Observation(self.spectrum,\n self.bandpass * other,\n binset=self.binwave,\n force=force)\n return result\n\n def __rmul__(self, other):\n return self.__mul__(other)\n\n #Disable methods that should not be supported by this class\n def __add__(self, other):\n raise NotImplementedError('Observations cannot be added')\n\n def __radd__(self, other):\n raise NotImplementedError('Observations cannot be added')\n\n\n def redshift(self,z):\n \"\"\"Observations cannot be redshifted.\"\"\"\n raise NotImplementedError('Observations cannot be redshifted')\n\n def writefits(self,fname,clobber=True, trimzero=True, binned=True,\n hkeys=None):\n \"\"\"Like :meth:`pysynphot.spectrum.SourceSpectrum.writefits`\n but with ``binned=True`` as default.\n\n \"\"\"\n spectrum.CompositeSourceSpectrum.writefits(self,fname,\n clobber=clobber,\n trimzero=trimzero,\n binned=binned,\n hkeys=hkeys)\n\n def countrate(self,binned=True,range=None,force=False):\n \"\"\"Calculate effective stimulus in count/s.\n Also see :ref:`pysynphot-formula-countrate` and\n :ref:`pysynphot-formula-effstim`.\n\n .. note::\n\n This is the calculation performed when the ETC invokes\n ``countrate``.\n\n Parameters\n -----------\n binned : bool\n If `True` (default), use binned data.\n Otherwise, use native data.\n\n range : tuple or `None`\n If not `None`, it must be a sequence with two floating-point\n elements specifying the wavelength range (*inclusive*) in the\n unit of ``self.waveunits`` in the form of ``(low, high)``;\n This is the range over which the integration will be performed.\n If the specified range does not exactly match a value in the\n wavelength set:\n\n * If ``binned=True``, the bin containing the range value will\n be used. This assumes ``self.binwave`` contains bin centers.\n * If ``binned=False``, native dataset will be interpolated to\n the specified values. (*Not Implemented.*)\n\n force : bool\n If `False` (default), partially overlapping ranges\n will raise an exception. If `True`, a partial overlap will\n return the calculated value instead. Disjoint ranges raise\n an exception regardless.\n\n Returns\n -------\n ans : float\n Count rate.\n\n Raises\n ------\n NotImplementedError\n Wavelength range is defined for unbinned data.\n\n pysynphot.exceptions.DisjointError\n Wavelength range does not overlap with observation.\n\n pysynphot.exceptions.PartialOverlap\n Wavelength range only partially overlaps with observation.\n\n \"\"\"\n\n if self._binflux is None:\n self.initbinflux()\n\n myfluxunits = self.fluxunits.name\n self.convert('counts')\n warn=False\n if binned:\n #No range specified - use full range\n if range is None:\n lx,ux=(None,None)\n #Range is disjoint from binwave\n elif (range[0]>self.binwave[-1] or\n range[1] self._bin_edges[-1]:\n warn=True\n ux=None\n else:\n ux=np.searchsorted(self._bin_edges,range[1])\n\n\n ans = math.fsum(self.binflux[lx:ux])\n if warn and not force:\n raise exceptions.PartialOverlap(\"%s does not fully overlap binwave range %s. Countrate in overlap area is %f\"%(range,[self.binwave[0],self.binwave[-1]],ans))\n\n else:\n if range is None:\n ans = math.fsum(self.flux)\n else:\n raise NotImplementedError(\"Sorry, range+binned=False not yet implemented\")\n self.convert(myfluxunits)\n return ans\n\n def effstim(self,fluxunits='photlam'):\n \"\"\"Compute :ref:`effective stimulus `.\n\n Calculations are done in given flux unit, and wavelengths\n in Angstrom. Native dataset is used.\n\n Parameters\n ----------\n fluxunits : str\n Flux unit.\n\n Returns\n -------\n ans : float\n Effective stimulus.\n\n Raises\n ------\n ValueError\n Invalid integrated flux.\n\n \"\"\"\n oldunits=self.fluxunits\n self.convert(fluxunits)\n x=units.Units(fluxunits)\n try:\n if x.isDensity:\n rate=self.integrate()\n self._fluxcheck(rate)\n if x.isMag:\n ans=x.unitResponse(self.bandpass) - 2.5*math.log10(rate)\n else:\n ans=rate*x.unitResponse(self.bandpass)\n else:\n if x.isMag:\n #its linear unit must be counts\n self.convert('counts')\n total=self.flux.sum()\n self._fluxcheck(total)\n ans=-2.5*math.log10(total)\n else:\n ans=self.flux.sum()\n self._fluxcheck(ans)\n finally:\n self.convert(oldunits)\n del x\n\n return ans\n\n def _fluxcheck(self,totalflux):\n if totalflux <= 0.0:\n raise ValueError('Integrated flux is <= 0')\n if np.isnan(totalflux):\n raise ValueError('Integrated flux is NaN')\n if np.isinf(totalflux):\n raise ValueError('Integrated flux is infinite')\n\n\n def pivot(self,binned=True):\n \"\"\"Calculate :ref:`pivot wavelength `\n of the observation.\n\n .. note::\n\n This is the calculation performed when ETC invokes ``calcphot``.\n\n Parameters\n ----------\n binned : bool\n Use binned dataset for calculations. Otherwise, use native dataset.\n\n Returns\n -------\n ans : float\n Pivot wavelength.\n\n \"\"\"\n if binned:\n wave = self.binwave\n else:\n wave = self.wave\n\n countmulwave = self(wave)*wave\n countdivwave = self(wave)/wave\n\n num = self.trapezoidIntegration(wave,countmulwave)\n den = self.trapezoidIntegration(wave,countdivwave)\n\n if num == 0.0 or den == 0.0:\n return 0.0\n\n return math.sqrt(num/den)\n\n def efflam(self,binned=True):\n \"\"\"Calculate :ref:`effective wavelength `\n of the observation.\n Calculation is done in the flux unit of ``flam``.\n\n .. note::\n\n Similar to IRAF STSDAS SYNPHOT ``efflphot`` task.\n\n Parameters\n ----------\n binned : bool\n Use binned dataset for calculations. Otherwise, use native dataset.\n\n Returns\n -------\n ans : float\n Effective wavelength.\n\n \"\"\"\n myfluxunits=self.fluxunits.name\n self.convert('flam')\n if binned:\n wave=self.binwave\n flux=self.binflux\n else:\n wave=self.wave\n flux=self.flux\n\n num = self.trapezoidIntegration(wave,flux*wave*wave)\n den = self.trapezoidIntegration(wave,flux*wave)\n self.convert(myfluxunits)\n\n if num == 0.0 or den == 0.0:\n return 0.0\n\n return num/den\n\n def sample(self, swave, binned=True, fluxunits='counts'):\n \"\"\"Sample the observation at the given wavelength.\n Also see :ref:`pysynphot-command-sample`.\n\n Parameters\n ----------\n swave : float\n Wavelength to sample.\n\n binned : bool\n Sample binned dataset (no interpolation).\n Otherwise, native (perform interpolation).\n\n fluxunits : {'counts'}\n Only the unit of counts is supported for now.\n\n Returns\n -------\n ans : float\n Sampled flux in given unit.\n\n Raises\n ------\n NotImplementedError\n Flux unit is not supported or non-scalar wavelength is given.\n\n ValueError\n Given wavelength out of range.\n\n \"\"\"\n if self._binflux is None:\n self.initbinflux()\n\n if fluxunits != 'counts':\n s = \"Sorry, only counts are supported at this time\"\n raise NotImplementedError(s)\n else:\n #Save current fluxunits, in case they're different\n saveunits = None\n if not units.ismatch('counts', self.fluxunits):\n saveunits = self.fluxunits\n self.convert('counts')\n\n\n if binned:\n #Then we don't interpolate, just return the appropriate values\n #from binflux\n if np.isscalar(swave):\n #Find the bin in which it belongs.\n #_bin_edge[i] is the low edge of the bin centered\n #at binwave[i].\n\n idx = np.where(swave >= self._bin_edges)[0]\n #idx[-1] is the largest edge that is still smaller\n #than swave\n try:\n ans = self.binflux[idx[-1]]\n except IndexError:\n s = 'Value out of range: wavelength %g not contained in range [%g, %g]'\n s = s % (swave, self.binwave[0], self.binwave[-1])\n raise ValueError(s)\n\n else:\n #The logic for this case doesn't yet work on arrays\n s = \"Sorry, only scalar samples are supported at this time\"\n raise NotImplementedError(s)\n\n else:\n #Then we do interpolate on wave/flux\n if np.isscalar(swave):\n delta = 0.00001\n wv = np.array([swave - delta, swave, swave + delta])\n ans = np.interp(wv, self.wave, self.flux)[1]\n else:\n # This raises UnboundLocalError -- needs to be fixed!\n ans = np.interp(wv, self.wave, self.flux)\n\n\n #Change units back, if necessary, then return\n if saveunits is not None:\n self.convert(saveunits)\n return ans\n\n def pixel_range(self, waverange, waveunits=None, round='round'):\n \"\"\"Calculate the number of wavelength bins within given\n wavelength range.\n\n .. note::\n\n This calls :func:`pysynphot.obsbandpass.pixel_range` with\n ``self.binwave`` as the first argument.\n\n Parameters\n ----------\n waverange, round\n See :func:`pysynphot.obsbandpass.pixel_range`.\n\n waveunits : str, optional\n The unit of the wavelength range.\n If `None` (default), the wavelengths are assumed to be\n in the units of ``self.waveunits``.\n\n Returns\n -------\n num : int or float\n Number of wavelength bins within ``waverange``.\n\n Raises\n ------\n pysynphot.exceptions.UndefinedBinset\n No binned dataset.\n\n \"\"\"\n # make sure we have a binset to work with\n if self.binwave is None:\n raise exceptions.UndefinedBinset('No binset specified for this bandpass.')\n\n # start by converting waverange to self.waveunits, if necessary\n if waveunits is not None:\n waveunits = units.Units(waveunits)\n\n if not isinstance(waverange, np.ndarray):\n waverange = np.array(waverange)\n\n # convert to angstroms and then whatever self.waveunits is\n waverange = waveunits.ToAngstrom(waverange)\n\n waverange = units.Angstrom().Convert(waverange, self.waveunits.name)\n\n return pixel_range(self.binwave, waverange, round=round)\n\n def wave_range(self, cenwave, npix, waveunits=None, round='round'):\n \"\"\"Calculate the wavelength range covered by the given\n number of pixels, centered on the given wavelength.\n\n .. note::\n\n This calls :func:`pysynphot.obsbandpass.wave_range` with\n ``self.binwave`` as the first argument.\n\n Parameters\n ----------\n cenwave, npix, round\n See :func:`pysynphot.obsbandpass.wave_range`.\n\n waveunits : str, optional\n Wavelength unit of the given and the returned wavelength values.\n If `None` (default), the wavelengths are assumed to be in\n the unit of ``self.waveunits``.\n\n Returns\n -------\n waverange : tuple of floats\n The range of wavelengths spanned by ``npix`` centered on\n ``cenwave``.\n\n Raises\n ------\n pysynphot.exceptions.UndefinedBinset\n No binned dataset.\n\n \"\"\"\n # make sure we have a binset to work with\n if self.binwave is None:\n raise exceptions.UndefinedBinset('No binset specified for this bandpass.')\n\n # convert cenwave from waveunits to self.waveunits, if necessary\n if waveunits is not None:\n waveunits = units.Units(waveunits)\n\n # convert to angstroms and then whatever self.waveunits is\n cenwave = waveunits.ToAngstrom(cenwave)\n cenwave = units.Angstrom().Convert(cenwave, self.waveunits.name)\n\n wave1, wave2 = wave_range(self.binwave, cenwave, npix, round=round)\n\n # translate ends to waveunits, if necessary\n if waveunits is not None:\n # convert to angstroms\n wave1 = self.waveunits.ToAngstrom(wave1)\n wave2 = self.waveunits.ToAngstrom(wave2)\n\n # then to waveunits\n wave1 = units.Angstrom().Convert(wave1, waveunits.name)\n wave2 = units.Angstrom().Convert(wave2, waveunits.name)\n\n return wave1, wave2\n\n def as_spectrum(self, binned=True):\n \"\"\"Reduce the observation to a simple spectrum object.\n\n An observation is a complex object with some restrictions on its\n capabilities. At times, it would be useful to work with the\n simulated observation as a simple object that is easier to\n manipulate and takes up less memory.\n\n Parameters\n ----------\n binned : bool\n If `True` (default), export binned dataset. Otherwise, native.\n\n Returns\n -------\n result : `~pysynphot.spectrum.ArraySourceSpectrum`\n Observation dataset as a simple spectrum object.\n\n \"\"\"\n if binned:\n wave, flux = self.binwave, self.binflux\n else:\n wave, flux = self.wave, self.flux\n\n result = ArraySourceSpectrum(wave, flux,\n self.waveunits,\n self.fluxunits,\n name = self.name,\n keepneg = True)\n\n return result\n", "meta": {"hexsha": "1c09aa0b864127de03074fc411a6e728b4ad10a3", "size": 28590, "ext": "py", "lang": "Python", "max_stars_repo_path": "pysynphot/observation.py", "max_stars_repo_name": "dobos/pysynphot", "max_stars_repo_head_hexsha": "5d2e0b52ceda78890940ac9239c2d88e149e0bed", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pysynphot/observation.py", "max_issues_repo_name": "dobos/pysynphot", "max_issues_repo_head_hexsha": "5d2e0b52ceda78890940ac9239c2d88e149e0bed", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pysynphot/observation.py", "max_forks_repo_name": "dobos/pysynphot", "max_forks_repo_head_hexsha": "5d2e0b52ceda78890940ac9239c2d88e149e0bed", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0520231214, "max_line_length": 176, "alphanum_fraction": 0.5754109829, "include": true, "reason": "import numpy", "num_tokens": 6165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.22000709974589316, "lm_q1q2_score": 0.1278908070459794}} {"text": "# Copyright 2020 The PyMC Developers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\n\nfrom copy import copy\nfrom typing import Any, Dict, List, Tuple\n\nimport aesara\nimport numpy as np\n\nfrom aesara import function as aesara_function\n\nfrom pymc.aesaraf import inputvars, join_nonshared_inputs, make_shared_replacements\nfrom pymc.bart.bart import BARTRV\nfrom pymc.bart.tree import LeafNode, SplitNode, Tree\nfrom pymc.blocking import RaveledVars\nfrom pymc.model import modelcontext\nfrom pymc.step_methods.arraystep import ArrayStepShared, Competence\n\n_log = logging.getLogger(\"pymc\")\n\n\nclass ParticleTree:\n \"\"\"\n Particle tree\n \"\"\"\n\n def __init__(self, tree, log_weight, likelihood):\n self.tree = tree.copy() # keeps the tree that we care at the moment\n self.expansion_nodes = [0]\n self.log_weight = log_weight\n self.old_likelihood_logp = likelihood\n self.used_variates = []\n\n def sample_tree_sequential(\n self,\n ssv,\n available_predictors,\n prior_prob_leaf_node,\n X,\n missing_data,\n sum_trees_output,\n mean,\n linear_fit,\n m,\n normal,\n mu_std,\n response,\n ):\n tree_grew = False\n if self.expansion_nodes:\n index_leaf_node = self.expansion_nodes.pop(0)\n # Probability that this node will remain a leaf node\n prob_leaf = prior_prob_leaf_node[self.tree[index_leaf_node].depth]\n\n if prob_leaf < np.random.random():\n tree_grew, index_selected_predictor = grow_tree(\n self.tree,\n index_leaf_node,\n ssv,\n available_predictors,\n X,\n missing_data,\n sum_trees_output,\n mean,\n linear_fit,\n m,\n normal,\n mu_std,\n response,\n )\n if tree_grew:\n new_indexes = self.tree.idx_leaf_nodes[-2:]\n self.expansion_nodes.extend(new_indexes)\n self.used_variates.append(index_selected_predictor)\n\n return tree_grew\n\n\nclass PGBART(ArrayStepShared):\n \"\"\"\n Particle Gibss BART sampling step\n\n Parameters\n ----------\n vars: list\n List of value variables for sampler\n num_particles : int\n Number of particles for the conditional SMC sampler. Defaults to 10\n max_stages : int\n Maximum number of iterations of the conditional SMC sampler. Defaults to 100.\n batch : int\n Number of trees fitted per step. Defaults to \"auto\", which is the 10% of the `m` trees\n during tuning and 20% after tuning.\n model: PyMC Model\n Optional model for sampling step. Defaults to None (taken from context).\n\n Note\n ----\n This sampler is inspired by the [Lakshminarayanan2015] Particle Gibbs sampler, but introduces\n several changes. The changes will be properly documented soon.\n\n References\n ----------\n .. [Lakshminarayanan2015] Lakshminarayanan, B. and Roy, D.M. and Teh, Y. W., (2015),\n Particle Gibbs for Bayesian Additive Regression Trees.\n ArviX, `link `__\n \"\"\"\n\n name = \"bartsampler\"\n default_blocked = False\n generates_stats = True\n stats_dtypes = [{\"variable_inclusion\": np.ndarray, \"bart_trees\": np.ndarray}]\n\n def __init__(self, vars=None, num_particles=10, max_stages=100, batch=\"auto\", model=None):\n _log.warning(\"BART is experimental. Use with caution.\")\n model = modelcontext(model)\n initial_values = model.recompute_initial_point()\n value_bart = inputvars(vars)[0]\n self.bart = model.values_to_rvs[value_bart].owner.op\n\n self.X = self.bart.X\n self.Y = self.bart.Y\n self.missing_data = np.any(np.isnan(self.X))\n self.m = self.bart.m\n self.alpha = self.bart.alpha\n self.k = self.bart.k\n self.response = self.bart.response\n self.split_prior = self.bart.split_prior\n if self.split_prior is None:\n self.split_prior = np.ones(self.X.shape[1])\n\n self.init_mean = self.Y.mean()\n # if data is binary\n Y_unique = np.unique(self.Y)\n if Y_unique.size == 2 and np.all(Y_unique == [0, 1]):\n self.mu_std = 6 / (self.k * self.m ** 0.5)\n # maybe we need to check for count data\n else:\n self.mu_std = self.Y.std() / (self.k * self.m ** 0.5)\n\n self.num_observations = self.X.shape[0]\n self.num_variates = self.X.shape[1]\n self.available_predictors = list(range(self.num_variates))\n\n sum_trees_output = np.full_like(self.Y, self.init_mean).astype(aesara.config.floatX)\n self.a_tree = Tree.init_tree(\n tree_id=0,\n leaf_node_value=self.init_mean / self.m,\n idx_data_points=np.arange(self.num_observations, dtype=\"int32\"),\n m=self.m,\n )\n self.mean = fast_mean()\n self.linear_fit = fast_linear_fit()\n\n self.normal = NormalSampler()\n self.prior_prob_leaf_node = compute_prior_probability(self.alpha)\n self.ssv = SampleSplittingVariable(self.split_prior)\n\n self.tune = True\n self.idx = 0\n self.batch = batch\n\n if self.batch == \"auto\":\n self.batch = max(1, int(self.m * 0.1))\n self.log_num_particles = np.log(num_particles)\n self.indices = list(range(1, num_particles))\n self.len_indices = len(self.indices)\n self.max_stages = max_stages\n\n shared = make_shared_replacements(initial_values, vars, model)\n self.likelihood_logp = logp(initial_values, [model.datalogpt], vars, shared)\n self.init_likelihood = self.likelihood_logp(sum_trees_output)\n self.init_log_weight = self.init_likelihood - self.log_num_particles\n self.all_particles = []\n for i in range(self.m):\n self.a_tree.tree_id = i\n p = ParticleTree(\n self.a_tree,\n self.init_log_weight,\n self.init_likelihood,\n )\n self.all_particles.append(p)\n self.all_trees = np.array([p.tree for p in self.all_particles])\n super().__init__(vars, shared)\n\n def astep(self, q: RaveledVars) -> Tuple[RaveledVars, List[Dict[str, Any]]]:\n point_map_info = q.point_map_info\n sum_trees_output = q.data\n variable_inclusion = np.zeros(self.num_variates, dtype=\"int\")\n\n if self.idx == self.m:\n self.idx = 0\n\n for tree_id in range(self.idx, self.idx + self.batch):\n if tree_id >= self.m:\n break\n # Generate an initial set of SMC particles\n # at the end of the algorithm we return one of these particles as the new tree\n particles = self.init_particles(tree_id)\n # Compute the sum of trees without the tree we are attempting to replace\n self.sum_trees_output_noi = sum_trees_output - particles[0].tree.predict_output()\n\n # The old tree is not growing so we update the weights only once.\n self.update_weight(particles[0])\n for t in range(self.max_stages):\n # Sample each particle (try to grow each tree), except for the first one.\n for p in particles[1:]:\n tree_grew = p.sample_tree_sequential(\n self.ssv,\n self.available_predictors,\n self.prior_prob_leaf_node,\n self.X,\n self.missing_data,\n sum_trees_output,\n self.mean,\n self.linear_fit,\n self.m,\n self.normal,\n self.mu_std,\n self.response,\n )\n if tree_grew:\n self.update_weight(p)\n # Normalize weights\n W_t, normalized_weights = self.normalize(particles)\n\n # Resample all but first particle\n re_n_w = normalized_weights[1:] / normalized_weights[1:].sum()\n new_indices = np.random.choice(self.indices, size=self.len_indices, p=re_n_w)\n particles[1:] = particles[new_indices]\n\n # Set the new weights\n for p in particles:\n p.log_weight = W_t\n\n # Check if particles can keep growing, otherwise stop iterating\n non_available_nodes_for_expansion = []\n for p in particles[1:]:\n if p.expansion_nodes:\n non_available_nodes_for_expansion.append(0)\n if all(non_available_nodes_for_expansion):\n break\n\n # Get the new tree and update\n new_particle = np.random.choice(particles, p=normalized_weights)\n new_tree = new_particle.tree\n self.all_trees[self.idx] = new_tree\n new_particle.log_weight = new_particle.old_likelihood_logp - self.log_num_particles\n self.all_particles[tree_id] = new_particle\n sum_trees_output = self.sum_trees_output_noi + new_tree.predict_output()\n\n if self.tune:\n for index in new_particle.used_variates:\n self.split_prior[index] += 1\n self.ssv = SampleSplittingVariable(self.split_prior)\n else:\n self.batch = max(1, int(self.m * 0.2))\n for index in new_particle.used_variates:\n variable_inclusion[index] += 1\n self.idx += 1\n\n stats = {\"variable_inclusion\": variable_inclusion, \"bart_trees\": copy(self.all_trees)}\n sum_trees_output = RaveledVars(sum_trees_output, point_map_info)\n return sum_trees_output, [stats]\n\n @staticmethod\n def competence(var, has_grad):\n \"\"\"\n PGBART is only suitable for BART distributions\n \"\"\"\n dist = getattr(var.owner, \"op\", None)\n if isinstance(dist, BARTRV):\n return Competence.IDEAL\n return Competence.INCOMPATIBLE\n\n def normalize(self, particles: List[ParticleTree]) -> Tuple[float, np.ndarray]:\n \"\"\"\n Use logsumexp trick to get W_t and softmax to get normalized_weights\n \"\"\"\n log_w = np.array([p.log_weight for p in particles])\n log_w_max = log_w.max()\n log_w_ = log_w - log_w_max\n w_ = np.exp(log_w_)\n w_sum = w_.sum()\n W_t = log_w_max + np.log(w_sum) - self.log_num_particles\n normalized_weights = w_ / w_sum\n # stabilize weights to avoid assigning exactly zero probability to a particle\n normalized_weights += 1e-12\n\n return W_t, normalized_weights\n\n def init_particles(self, tree_id: int) -> np.ndarray:\n \"\"\"\n Initialize particles\n \"\"\"\n p = self.all_particles[tree_id]\n p.log_weight = self.init_log_weight\n p.old_likelihood_logp = self.init_likelihood\n particles = [p]\n\n for _ in self.indices:\n self.a_tree.tree_id = tree_id\n particles.append(\n ParticleTree(\n self.a_tree,\n self.init_log_weight,\n self.init_likelihood,\n )\n )\n\n return np.array(particles)\n\n def update_weight(self, particle: List[ParticleTree]) -> None:\n \"\"\"\n Update the weight of a particle\n\n Since the prior is used as the proposal,the weights are updated additively as the ratio of\n the new and old log-likelihoods.\n \"\"\"\n new_likelihood = self.likelihood_logp(\n self.sum_trees_output_noi + particle.tree.predict_output()\n )\n particle.log_weight += new_likelihood - particle.old_likelihood_logp\n particle.old_likelihood_logp = new_likelihood\n\n\nclass SampleSplittingVariable:\n def __init__(self, alpha_prior):\n \"\"\"\n Sample splitting variables proportional to `alpha_prior`.\n\n This is equivalent as sampling weights from a Dirichlet distribution with `alpha_prior`\n parameter and then using those weights to sample from the available spliting variables.\n This enforce sparsity.\n \"\"\"\n self.enu = list(enumerate(np.cumsum(alpha_prior / alpha_prior.sum())))\n\n def rvs(self):\n r = np.random.random()\n for i, v in self.enu:\n if r <= v:\n return i\n\n\ndef compute_prior_probability(alpha):\n \"\"\"\n Calculate the probability of the node being a LeafNode (1 - p(being SplitNode)).\n Taken from equation 19 in [Rockova2018].\n\n Parameters\n ----------\n alpha : float\n\n Returns\n -------\n list with probabilities for leaf nodes\n\n References\n ----------\n .. [Rockova2018] Veronika Rockova, Enakshi Saha (2018). On the theory of BART.\n arXiv, `link `__\n \"\"\"\n prior_leaf_prob = [0]\n depth = 1\n while prior_leaf_prob[-1] < 1:\n prior_leaf_prob.append(1 - alpha ** depth)\n depth += 1\n return prior_leaf_prob\n\n\ndef grow_tree(\n tree,\n index_leaf_node,\n ssv,\n available_predictors,\n X,\n missing_data,\n sum_trees_output,\n mean,\n linear_fit,\n m,\n normal,\n mu_std,\n response,\n):\n current_node = tree.get_node(index_leaf_node)\n idx_data_points = current_node.idx_data_points\n\n index_selected_predictor = ssv.rvs()\n selected_predictor = available_predictors[index_selected_predictor]\n available_splitting_values = X[idx_data_points, selected_predictor]\n if missing_data:\n idx_data_points = idx_data_points[~np.isnan(available_splitting_values)]\n available_splitting_values = available_splitting_values[\n ~np.isnan(available_splitting_values)\n ]\n\n if available_splitting_values.size == 0:\n return False, None\n\n idx_selected_splitting_values = discrete_uniform_sampler(len(available_splitting_values))\n split_value = available_splitting_values[idx_selected_splitting_values]\n new_split_node = SplitNode(\n index=index_leaf_node,\n idx_split_variable=selected_predictor,\n split_value=split_value,\n )\n\n left_node_idx_data_points, right_node_idx_data_points = get_new_idx_data_points(\n split_value, idx_data_points, selected_predictor, X\n )\n\n if response == \"mix\":\n response = \"linear\" if np.random.random() >= 0.5 else \"constant\"\n\n left_node_value, left_node_linear_params = draw_leaf_value(\n sum_trees_output[left_node_idx_data_points],\n X[left_node_idx_data_points, selected_predictor],\n mean,\n linear_fit,\n m,\n normal,\n mu_std,\n response,\n )\n right_node_value, right_node_linear_params = draw_leaf_value(\n sum_trees_output[right_node_idx_data_points],\n X[right_node_idx_data_points, selected_predictor],\n mean,\n linear_fit,\n m,\n normal,\n mu_std,\n response,\n )\n\n new_left_node = LeafNode(\n index=current_node.get_idx_left_child(),\n value=left_node_value,\n idx_data_points=left_node_idx_data_points,\n linear_params=left_node_linear_params,\n )\n new_right_node = LeafNode(\n index=current_node.get_idx_right_child(),\n value=right_node_value,\n idx_data_points=right_node_idx_data_points,\n linear_params=right_node_linear_params,\n )\n tree.grow_tree(index_leaf_node, new_split_node, new_left_node, new_right_node)\n\n return True, index_selected_predictor\n\n\ndef get_new_idx_data_points(split_value, idx_data_points, selected_predictor, X):\n\n left_idx = X[idx_data_points, selected_predictor] <= split_value\n left_node_idx_data_points = idx_data_points[left_idx]\n right_node_idx_data_points = idx_data_points[~left_idx]\n\n return left_node_idx_data_points, right_node_idx_data_points\n\n\ndef draw_leaf_value(Y_mu_pred, X_mu, mean, linear_fit, m, normal, mu_std, response):\n \"\"\"Draw Gaussian distributed leaf values\"\"\"\n linear_params = None\n if Y_mu_pred.size == 0:\n return 0, linear_params\n else:\n norm = normal.random() * mu_std\n if Y_mu_pred.size == 1:\n mu_mean = Y_mu_pred.item() / m\n elif response == \"constant\":\n mu_mean = mean(Y_mu_pred) / m\n elif response == \"linear\":\n Y_fit, linear_params = linear_fit(X_mu, Y_mu_pred)\n mu_mean = Y_fit / m\n linear_params[2] = norm\n\n draw = norm + mu_mean\n return draw, linear_params\n\n\ndef fast_mean():\n \"\"\"If available use Numba to speed up the computation of the mean.\"\"\"\n try:\n from numba import jit\n except ImportError:\n return np.mean\n\n @jit\n def mean(a):\n count = a.shape[0]\n suma = 0\n for i in range(count):\n suma += a[i]\n return suma / count\n\n return mean\n\n\ndef fast_linear_fit():\n \"\"\"If available use Numba to speed up the computation of the linear fit\"\"\"\n\n def linear_fit(X, Y):\n\n n = len(Y)\n xbar = np.sum(X) / n\n ybar = np.sum(Y) / n\n\n den = X @ X - n * xbar ** 2\n if den > 1e-10:\n b = (X @ Y - n * xbar * ybar) / den\n else:\n b = 0\n a = ybar - b * xbar\n Y_fit = a + b * X\n return Y_fit, [a, b, 0]\n\n try:\n from numba import jit\n\n return jit(linear_fit)\n except ImportError:\n return linear_fit\n\n\ndef discrete_uniform_sampler(upper_value):\n \"\"\"Draw from the uniform distribution with bounds [0, upper_value).\n\n This is the same and np.random.randit(upper_value) but faster.\n \"\"\"\n return int(np.random.random() * upper_value)\n\n\nclass NormalSampler:\n \"\"\"\n Cache samples from a standard normal distribution\n \"\"\"\n\n def __init__(self):\n self.size = 1000\n self.cache = []\n\n def random(self):\n if not self.cache:\n self.update()\n return self.cache.pop()\n\n def update(self):\n self.cache = np.random.normal(loc=0.0, scale=1, size=self.size).tolist()\n\n\ndef logp(point, out_vars, vars, shared):\n \"\"\"Compile Aesara function of the model and the input and output variables.\n\n Parameters\n ----------\n out_vars: List\n containing :class:`pymc.Distribution` for the output variables\n vars: List\n containing :class:`pymc.Distribution` for the input variables\n shared: List\n containing :class:`aesara.tensor.Tensor` for depended shared data\n \"\"\"\n out_list, inarray0 = join_nonshared_inputs(point, out_vars, vars, shared)\n f = aesara_function([inarray0], out_list[0])\n f.trust_input = True\n return f\n", "meta": {"hexsha": "733641038d147a4feb93ad49babb33d40e0a4e76", "size": 19417, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymc/bart/pgbart.py", "max_stars_repo_name": "MarcoGorelli/pymc", "max_stars_repo_head_hexsha": "140dab0199dfb751951ba99175295c07feb00264", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pymc/bart/pgbart.py", "max_issues_repo_name": "MarcoGorelli/pymc", "max_issues_repo_head_hexsha": "140dab0199dfb751951ba99175295c07feb00264", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-11-02T17:24:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-30T18:24:07.000Z", "max_forks_repo_path": "pymc/bart/pgbart.py", "max_forks_repo_name": "MarcoGorelli/pymc", "max_forks_repo_head_hexsha": "140dab0199dfb751951ba99175295c07feb00264", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3625429553, "max_line_length": 98, "alphanum_fraction": 0.6145645568, "include": true, "reason": "import numpy,from numba", "num_tokens": 4329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199306096343, "lm_q2_score": 0.24798743179802785, "lm_q1q2_score": 0.12786726237576054}} {"text": "# Copyright 2018 The Fragpy Developers. All Rights Reserved.\n# \n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\\\n Bond lengths; angles; torsionals\n\"\"\"\n\nfrom fragpy.odict import *\nfrom math import *\nfrom numpy import subtract\nfrom numpy.linalg import norm\nimport numpy as np\n\n\nchecker1=[]\nchecker2=[]\nchecker3=0\n\ndef hbon(list1,list2):\n\n tmpii=[]\n electNEG = ['O','N','F','Cl','S']\n for i in list1:\n closeN = closest(i,list2,checker1,checker2,checker3)\n for j in list2:\n if not closeN == j:\n if j.atm in electNEG:\n bond1 = GetBond(i.q,j.q)\n bondc = covrad[j.atm] + covrad[i.atm]\n bondv = vanrad[j.atm] + vanrad[i.atm]\n if (bond1 > bondc and bond1 < 0.9000*(bondv)):\n angle1 = degrees(GetAngle(closeN.q,i.q,j.q))\n if angle1 > 90:\n tmpii.append([i.n,j.n])\n\n lentmpii = len(tmpii)\n \n for i in list2:\n hclose1=closest(i,list1,checker1,checker2,checker3)\n if not hclose1==[]:\n tmpii.append([hclose1.n,i.n])\n hclose2=closest(i,list1,hclose1,checker2,checker3)\n if not hclose2==[]:\n tmpii.append([hclose2.n,i.n])\n hclose3=closest(i,list1,hclose1,hclose2,hclose2)\n if not hclose3==[]:\n tmpii.append([hclose3.n,i.n])\n\n return(tmpii,lentmpii)\n \ndef hangle(list1,list2,lenHbon): # Hbondlist, nonHbondlist\n hangl=[]\n for i in list1[lenHbon:]:\n tmpii=[]\n for j in list2:\n if i[1]==j[0]:\n tmpii.append(j[1])\n elif i[1]==j[1]:\n tmpii.append(j[0])\n #tmpii=j[1]\n for j in tmpii:\n if not [j,i[1],i[0]] in hangl:\n hangl.append([i[0],i[1],j])\n tmpii = []\n for j in list1[lenHbon:]:\n if (i[1] == j[1] and not i[0] == j[0]):\n tmpii.append(j[0])\n for j in tmpii:\n if not [j,i[1],i[0]] in hangl:\n hangl.append([i[0],i[1],j])\n return hangl \n\ndef hdih(list1,list2):\n hdi=[]\n for i in list1:\n tmpii = []\n for j in list2:\n if (i[1] == j[0] and i[2] == j[1]):\n tmpii.append([i[0],i[1],i[2],j[2]])\n elif (i[1] == j[2] and i[2] == j[1]):\n tmpii.append([i[0],i[1],i[2],j[0]])\n for j in tmpii:\n if not [j[3],j[2],j[1],j[0]] in hdi:\n hdi.append(j)\n tmpii = []\n for j in list1:\n if (j[2] == i[1] and j[1] == i[2]):\n tmpii.append([i[0],i[1],i[2],j[0]])\n for j in tmpii:\n if not [j[3],j[2],j[1],j[0]] in hdi:\n hdi.append(j) \n return hdi\n\ndef angl(list1):\n condlist=[]\n tmpang=[]\n ange=[]\n coun=0\n for i in list1:\n tmpii = []\n for j in list1:\n if (i[0] == j[0] and not i[1] == j[1]):\n tmpii.append([i[1],i[0],j[1]])\n elif i[0] == j[1]:\n tmpii.append([i[1],i[0],j[0]])\n elif i[1] == j[0]:\n tmpii.append([i[0],i[1],j[1]])\n elif (i[1] == j[1] and not i[0] == j[0]):\n tmpii.append([i[0],i[1],j[0]])\n for j in tmpii:\n if not sorted(j) in tmpang:\n ange.append(j)\n tmpang.append(sorted(j))\n return ange\n \ndef dihed(list1):\n condlist=[]\n dihlist=[]\n for i in list1:\n tmpii = []\n for j in list1:\n if (i[1]==j[0] and i[2]==j[1]):\n tmpii.append([i[0],i[1],i[2],j[2]])\n elif (i[1]==j[2] and i[2]==j[1]):\n tmpii.append([i[0],i[1],i[2],j[0]])\n elif (i[1]==j[2] and i[0]==j[1]):\n tmpii.append([i[2],i[1],i[0],j[0]])\n elif (i[1]==j[0] and i[0]==j[1]):\n tmpii.append([i[2],i[1],i[0],j[2]])\n for j in tmpii:\n if not sorted(j) in condlist:\n dihlist.append(j)\n condlist.append(sorted(j))\n return dihlist\n\ndef closest(x,list,check1,check3,check2):\n condition=0\n for i in list:\n if not i==check1:\n if not i==check2:\n if not i == check3:\n d1 = GetBond(x.q,i.q)\n d2 = covrad[x.atm]+covrad[i.atm]\n if d1 <= d2+0.1:\n close=i\n condition=1\n break\n else:\n close=[]\n condition=2\n if condition==0:\n close=[]\n return (close)\n\ndef GetBond(list1,list2):\n bond1 = subtract(list1,list2).tolist()\n bond2 = norm(bond1)\n return bond2\ndef GetAngle(s1,s2,s3):\n import numpy\n\n u = subtract(s1,s2)\n v = subtract(s3,s2)\n ru = norm(u)\n rv = norm(v)\n u = (u/ru).tolist()\n v = (v/rv).tolist()\n angle1 = numpy.arccos(np.dot(u,v))\n return angle1\n\n\ndef GetDihedral(p0,p1,p2,p3):\n b0 = -1.0 * subtract(p1,p0)\n b1 = subtract(p2,p1)\n b2 = subtract(p3,p2)\n b1 /= norm(b1)\n v = subtract(b0,np.dot(b0,b1)*b1)\n w = subtract(b2,np.dot(b2,b1)*b1)\n x = np.dot(v,w)\n y = np.dot(np.cross(b1,v),w)\n return np.arctan2(y,x)\n \n", "meta": {"hexsha": "a76dfd9372b47fcb441973a4b6449ff4205a161e", "size": 6071, "ext": "py", "lang": "Python", "max_stars_repo_path": "fragpy/bon_angle_dih.py", "max_stars_repo_name": "mubaoinam/fragpy", "max_stars_repo_head_hexsha": "2464909d3b407cc225d270051b56342db555f8eb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fragpy/bon_angle_dih.py", "max_issues_repo_name": "mubaoinam/fragpy", "max_issues_repo_head_hexsha": "2464909d3b407cc225d270051b56342db555f8eb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fragpy/bon_angle_dih.py", "max_forks_repo_name": "mubaoinam/fragpy", "max_forks_repo_head_hexsha": "2464909d3b407cc225d270051b56342db555f8eb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6616161616, "max_line_length": 68, "alphanum_fraction": 0.4895404381, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.24798743179802785, "lm_q1q2_score": 0.12786725868406623}} {"text": "import copy\nimport numpy as np\nfrom Classes.TransectData import adjusted_ensemble_duration\nfrom Classes.TransectData import TransectData\nfrom Classes.QComp import QComp\nfrom Classes.MatSonTek import MatSonTek\nfrom MiscLibs.common_functions import cart2pol, sind, pol2cart, rad2azdeg\n\n\nclass MovingBedTests(object):\n \"\"\"Stores and processes moving-bed tests.\n\n Attributes\n ----------\n type: str\n Loop or Stationary\n transect: TransectData\n Object of TransectData\n duration_sec: float\n Duration of test, in secs\n percent_invalid_bt: float\n Percent of invalid bottom track\n compass_diff_deg: float\n Difference in heading for out and back of loop\n flow_dir: float\n Mean flow direction from loop test\n mb_dir: float\n Moving bed or closure error direction\n dist_us_m: float\n Distance moved upstream, in m\n flow_spd_mps: float\n Magnitude of water velocity, in mps\n mb_spd_mps: float\n Magnitude of moving=bed velocity, in mps\n percent_mb: float\n Potential error due to moving bed, in percent\n moving_bed: str\n Moving-bed determined (\"Yes\" or \"No\")\n user_valid: bool\n Boolean to allow user to determine if test should be considered a valid test (True or False)\n test_quality: str\n Quality of test, 'Valid' 'Warnings' 'Errors'\n use_2_correct: bool\n Use this test to correct discharge (True or False)\n selected: bool\n Selected as valid moving-bed test to use for correction or determine moving-bed condition\n messages: list\n List of strings for warning and error messages based on data processing\n near_bed_speed_mps: float\n Mean near-bed water speed for test, in mps\n stationary_us_track: np.array(float)\n Upstream component of the bottom track referenced ship track\n stationary_cs_track: np.array(float)\n Cross=stream component of the bottom track referenced ship track\n stationary_mb_vel: np.array(float)\n Moving-bed velocity by ensemble, m/s\n ref: str\n Identifies reference used to compute moving bed\n bt_percent_mb: float\n Percent moving-bed using only BT\n bt_dist_us_m: float\n Distance upstream using only BT\n bt_mb_dir: float\n Moving-bed direction using only BT\n bt_mb_spd_mps: float\n Moving-bed speed using only BT\n bt_flow_spd_mps: float\n Corrected flow speed using only BT\n gps_percent_mb: float\n Percent moving-bed using BT and GPS\n gps_dist_us_m: float\n Distance upstream using BT and GPS\n gps_mb_dir: float\n Moving-bed direction using BT and GPS\n gps_mb_spd_mps: float\n Moving-bed speed using BT and GPS\n gps_flow_spd_mps: float\n Corrected flow speed using BT and GPS\n \"\"\"\n \n def __init__(self):\n \"\"\"Initialize class and instance variables.\"\"\"\n\n self.type = None # Loop or Stationary\n self.transect = None # Object of TransectData\n self.duration_sec = np.nan # Duration of test in secs\n self.percent_invalid_bt = np.nan # Percent of invalid bottom track\n self.compass_diff_deg = np.nan # Difference in heading for out and back of loop\n self.flow_dir = np.nan # Mean flow direction from loop test\n self.mb_dir = np.nan # Moving bed or closure error direction\n self.dist_us_m = np.nan # Distance moved upstream in m\n self.flow_spd_mps = np.nan # Magnitude of water velocity in mps\n self.mb_spd_mps = np.nan # Magnitude of moving=bed velocity in mps\n self.percent_mb = np.nan # Potential error due to moving bed in percent\n self.moving_bed = np.nan # Moving-bed determined 'Yes' 'No'\n self.user_valid = True # Logical to allow user to determine if test should be considered a valid test\n self.test_quality = None # Quality of test 'Valid' 'Warnings' 'Errors'\n self.use_2_correct = None # Use this test to correct discharge\n self.selected = None # Selected valid moving-bed test to use for correction or determine moving-bed condition\n self.messages = None # Cell array of warning and error messages based on data processing\n self.near_bed_speed_mps = np.nan # Mean near-bed water speed for test in mps\n self.stationary_us_track = np.array([]) # Upstream component of the bottom track referenced ship track\n self.stationary_cs_track = np.array([]) # Cross=stream component of the bottom track referenced ship track\n self.stationary_mb_vel = np.array([]) # Moving-bed velocity by ensemble\n self.ref = 'BT'\n self.bt_percent_mb = np.nan\n self.bt_dist_us_m = np.nan\n self.bt_mb_dir = np.nan\n self.bt_mb_spd_mps = np.nan\n self.bt_flow_spd_mps = np.nan\n self.gps_percent_mb = np.nan\n self.gps_dist_us_m = np.nan\n self.gps_mb_dir = np.nan\n self.gps_mb_spd_mps = np.nan\n self.gps_flow_spd_mps = np.nan\n \n def populate_data(self, source, file=None, test_type=None):\n \"\"\"Process and store moving-bed test data.\n\n Parameters\n ----------\n source: str\n Manufacturer of ADCP, SonTek or TRDI\n file: TransectData or str\n Object of TransectData for TRDI and str of filename for SonTek\n test_type: str\n Type of moving-bed test (Loop or Stationary)\n \"\"\"\n\n if source == 'TRDI':\n self.mb_trdi(file, test_type)\n else:\n self.mb_sontek(file, test_type)\n\n self.process_mb_test(source)\n\n def process_mb_test(self, source):\n \n # Convert to earth coordinates and set the navigation reference to BT\n # for both boat and water data\n self.transect.boat_vel.bt_vel.apply_interpolation(transect=self.transect, interpolation_method='Linear')\n self.transect.change_coord_sys(new_coord_sys='Earth')\n self.transect.change_nav_reference(update=True, new_nav_ref='BT')\n \n # Adjust data for default manufacturer specific handling of invalid data\n delta_t = adjusted_ensemble_duration(self.transect, 'mbt')\n \n if self.type == 'Loop':\n if source == 'TRDI':\n self.loop_test(delta_t)\n else:\n self.loop_test()\n elif self.type == 'Stationary':\n self.stationary_test()\n else:\n raise ValueError('Invalid moving-bed test identifier specified.')\n\n @staticmethod\n def qrev_mat_in(meas_struct):\n \"\"\"Processes the Matlab data structure to obtain a list of TransectData objects containing transect\n data from the Matlab data structure.\n\n Parameters\n ----------\n meas_struct: mat_struct\n Matlab data structure obtained from sio.loadmat\n\n Returns\n -------\n mb_tests: list\n List of MovingBedTests objects\n \"\"\"\n\n mb_tests = []\n if hasattr(meas_struct, 'mbTests'):\n try:\n # If there are multiple test the Matlab structure will be an array\n if type(meas_struct.mbTests) == np.ndarray:\n for test in meas_struct.mbTests:\n temp = MovingBedTests()\n temp.populate_from_qrev_mat(test)\n mb_tests.append(temp)\n # If only one test, that test is not stored in an array\n else:\n temp = MovingBedTests()\n temp.populate_from_qrev_mat(meas_struct.mbTests)\n mb_tests.append(temp)\n except (TypeError, AttributeError):\n pass\n return mb_tests\n\n def populate_from_qrev_mat(self, mat_data):\n \"\"\"Populates the object using data from previously saved QRev Matlab file.\n\n Parameters\n ----------\n mat_data: mat_struct\n Matlab data structure obtained from sio.loadmat\n \"\"\"\n\n self.type = mat_data.type\n self.transect = TransectData()\n self.transect.populate_from_qrev_mat(mat_data.transect)\n self.duration_sec = mat_data.duration_sec\n self.percent_invalid_bt = mat_data.percentInvalidBT\n\n # Handle situation for one or more tests\n if type(mat_data.compassDiff_deg) is float:\n self.compass_diff_deg = mat_data.compassDiff_deg\n else:\n self.compass_diff_deg = self.make_list(mat_data.compassDiff_deg)\n\n # Handle situation for one or more tests\n if type(mat_data.flowDir_deg) is float:\n self.flow_dir = mat_data.flowDir_deg\n else:\n self.flow_dir = self.make_list(mat_data.flowDir_deg)\n\n # Handle situation for one or more tests\n if type(mat_data.mbDir_deg) is float:\n self.mb_dir = mat_data.mbDir_deg\n else:\n self.mb_dir = self.make_list(mat_data.mbDir_deg)\n\n self.dist_us_m = mat_data.distUS_m\n self.flow_spd_mps = mat_data.flowSpd_mps\n self.mb_spd_mps = mat_data.mbSpd_mps\n self.percent_mb = mat_data.percentMB\n self.moving_bed = mat_data.movingBed\n self.user_valid = bool(mat_data.userValid)\n self.test_quality = mat_data.testQuality\n self.use_2_correct = bool(mat_data.use2Correct)\n self.selected = bool(mat_data.selected)\n\n # Handle situation for one or more messages\n if type(mat_data.messages) == np.ndarray:\n self.messages = mat_data.messages.tolist()\n else:\n self.messages = [mat_data.messages]\n\n # Handle situation for one or more tests\n if type(mat_data.nearBedSpeed_mps) is np.ndarray:\n self.near_bed_speed_mps = np.nan\n else:\n self.near_bed_speed_mps = mat_data.nearBedSpeed_mps\n\n self.stationary_us_track = mat_data.stationaryUSTrack\n self.stationary_cs_track = mat_data.stationaryCSTrack\n self.stationary_mb_vel = mat_data.stationaryMBVel\n\n # Feature that can use GPS for moving-bed tests\n if hasattr(mat_data, 'bt_percent_mb'):\n self.bt_percent_mb = mat_data.bt_percent_mb\n self.bt_dist_us_m = mat_data.bt_dist_us_m\n self.bt_mb_dir = mat_data.bt_mb_dir\n self.bt_mb_spd_mps = mat_data.bt_mb_spd_mps\n self.bt_flow_spd_mps = mat_data.bt_flow_spd_mps\n self.gps_percent_mb = mat_data.gps_percent_mb\n self.gps_dist_us_m = mat_data.gps_dist_us_m\n self.gps_mb_dir = mat_data.gps_mb_dir\n self.gps_mb_spd_mps = mat_data.gps_mb_spd_mps\n else:\n self.bt_percent_mb = self.percent_mb\n self.bt_dist_us_m = self.dist_us_m\n self.bt_mb_dir = self.mb_dir\n self.bt_mb_spd_mps = self.mb_spd_mps\n self.bt_flow_spd_mps = self.flow_spd_mps\n self.compute_mb_gps()\n\n @staticmethod\n def make_list(array_in):\n \"\"\"Method to make list from several special cases that can occur in the Matlab data.\n\n Parameters\n ----------\n array_in: np.ndarray\n Input that needs to be convert to a list\n \"\"\"\n\n # This traps messages with the associated codes\n if array_in.size > 3:\n list_out = array_in.tolist()\n else:\n # Create a list of lists\n temp = array_in.tolist()\n if len(temp) > 0:\n internal_list = []\n for item in temp:\n internal_list.append(item)\n list_out = [internal_list]\n else:\n list_out = np.nan\n return list_out\n\n def mb_trdi(self, transect, test_type):\n \"\"\"Function to create object properties for TRDI moving-bed tests\n\n Parameters\n ----------\n transect: TransectData\n Object of TransectData\n test_type: str\n Type of moving-bed test.\"\"\"\n \n self.transect = transect\n self.user_valid = True\n self.type = test_type\n\n def mb_sontek(self, file_name, test_type):\n \"\"\"Function to create object properties for SonTek moving-bed tests\n\n Parameters\n ----------\n file_name: str\n Name of moving-bed test data file\n test_type: str\n Type of moving-bed test.\"\"\"\n self.type = test_type\n\n # Read Matlab file for moving-bed test\n rsdata = MatSonTek(file_name)\n\n # Create transect objects for each discharge transect\n self.transect = TransectData()\n self.transect.sontek(rsdata, file_name)\n \n def loop_test(self, ens_duration=None, ref='BT'):\n \"\"\"Process loop moving bed test.\n\n Parameters\n ----------\n ens_duration: np.array(float)\n Duration of each ensemble, in sec\n ref: str\n Reference used to compare distance moved\n \"\"\"\n\n # Assign data from transect to local variables\n self.transect.boat_interpolations(update=False, target='BT', method='Linear')\n self.transect.boat_interpolations(update=False, target='GPS', method='Linear')\n trans_data = copy.deepcopy(self.transect)\n in_transect_idx = trans_data.in_transect_idx\n n_ensembles = len(in_transect_idx)\n bt_valid = trans_data.boat_vel.bt_vel.valid_data[0, in_transect_idx]\n\n # Set variables to defaults\n self.messages = []\n vel_criteria = 0.012\n\n # Check that there is some valid BT data\n if np.nansum(bt_valid) > 1:\n wt_u = trans_data.w_vel.u_processed_mps[:, in_transect_idx]\n wt_v = trans_data.w_vel.v_processed_mps[:, in_transect_idx]\n if ens_duration is None:\n ens_duration = trans_data.date_time.ens_duration_sec[in_transect_idx]\n\n bt_u = trans_data.boat_vel.bt_vel.u_processed_mps[in_transect_idx]\n bt_v = trans_data.boat_vel.bt_vel.v_processed_mps[in_transect_idx]\n bin_size = trans_data.depths.bt_depths.depth_cell_size_m[:, in_transect_idx]\n\n # Compute closure distance and direction\n bt_x = np.nancumsum(bt_u * ens_duration)\n bt_y = np.nancumsum(bt_v * ens_duration)\n direct, self.bt_dist_us_m = cart2pol(bt_x[-1], bt_y[-1])\n self.bt_mb_dir = rad2azdeg(direct)\n\n # Compute duration of test\n self.duration_sec = np.nansum(ens_duration)\n\n # Compute the moving-bed velocity\n self.bt_mb_spd_mps = self.bt_dist_us_m / self.duration_sec\n\n # Compute discharge weighted mean velocity components for the\n # purposed of computing the mean flow direction\n xprod = QComp.cross_product(transect=trans_data)\n q = QComp.discharge_middle_cells(xprod, trans_data, ens_duration)\n wght = np.abs(q)\n se = np.nansum(np.nansum(wt_u * wght)) / np.nansum(np.nansum(wght))\n sn = np.nansum(np.nansum(wt_v * wght)) / np.nansum(np.nansum(wght))\n direct, flow_speed_q = cart2pol(se, sn)\n\n # Compute flow speed and direction\n self.flow_dir = rad2azdeg(direct)\n \n # Compute the area weighted mean velocity components for the\n # purposed of computing the mean flow speed. Area weighting is used for flow speed instead of\n # discharge so that the flow speed is not included in the weighting used to compute the mean flow speed.\n wght_area = np.multiply(np.multiply(np.sqrt(bt_u ** 2 + bt_v ** 2), bin_size), ens_duration)\n idx = np.where(np.isnan(wt_u) == False)\n se = np.nansum(np.nansum(wt_u[idx] * wght_area[idx])) / np.nansum(np.nansum(wght_area[idx]))\n sn = np.nansum(np.nansum(wt_v[idx] * wght_area[idx])) / np.nansum(np.nansum(wght_area[idx]))\n dir_a, self.bt_flow_spd_mps = cart2pol(se, sn)\n self.bt_flow_spd_mps = self.bt_flow_spd_mps + self.bt_mb_spd_mps\n\n # Compute potential error in BT referenced discharge\n self.bt_percent_mb = (self.bt_mb_spd_mps / self.bt_flow_spd_mps) * 100\n\n # Compute test with GPS\n self.compute_mb_gps()\n\n # Store selected test characteristics\n if ref == 'BT':\n self.mb_spd_mps = self.bt_mb_spd_mps\n self.dist_us_m = self.bt_dist_us_m\n self.percent_mb = self.bt_percent_mb\n self.mb_dir = self.bt_mb_dir\n self.flow_spd_mps = self.bt_flow_spd_mps\n elif not np.isnan(self.gps_percent_mb):\n self.mb_spd_mps = self.gps_mb_spd_mps\n self.dist_us_m = self.gps_dist_us_m\n self.percent_mb = self.gps_percent_mb\n self.mb_dir = self.gps_mb_dir\n self.flow_spd_mps = self.bt_flow_spd_mps\n\n # Assess invalid bottom track\n # Compute percent invalid bottom track\n self.percent_invalid_bt = (np.nansum(bt_valid == False) / len(bt_valid)) * 100\n\n # Determine if more than 9 consecutive seconds of invalid BT occurred\n consect_bt_time = np.zeros(n_ensembles)\n for n in range(1, n_ensembles):\n if bt_valid[n]:\n consect_bt_time[n] = 0\n else:\n consect_bt_time[n] = consect_bt_time[n - 1] + ens_duration[n]\n\n max_consect_bt_time = np.nanmax(consect_bt_time)\n\n # Evaluate compass calibration based on flow direction\n\n # Find apex of loop adapted from\n # http://www.mathworks.de/matlabcentral/newsreader/view_thread/164048\n loop_out = np.array([bt_x[0], bt_y[0], 0])\n loop_return = np.array([bt_x[-1], bt_y[-1], 0])\n\n distance = np.zeros(n_ensembles)\n for n in range(n_ensembles):\n p = np.array([bt_x[n], bt_y[n], 0])\n distance[n] = np.linalg.norm(np.cross(loop_return - loop_out, p - loop_out)) \\\n / np.linalg.norm(loop_return - loop_out)\n\n dmg_idx = np.where(distance == np.nanmax(distance))[0][0]\n\n # Compute flow direction on outgoing part of loop\n u_out = wt_u[:, :dmg_idx + 1]\n v_out = wt_v[:, :dmg_idx + 1]\n wght = np.abs(q[:, :dmg_idx+1])\n se = np.nansum(u_out * wght) / np.nansum(wght)\n sn = np.nansum(v_out * wght) / np.nansum(wght)\n direct, _ = cart2pol(se, sn)\n flow_dir1 = rad2azdeg(direct)\n\n # Compute unweighted flow direction in each cell\n direct, _ = cart2pol(u_out, v_out)\n flow_dir_cell = rad2azdeg(direct)\n\n # Compute difference from mean and correct to +/- 180\n v_dir_corr = flow_dir_cell - flow_dir1\n v_dir_idx = v_dir_corr > 180\n v_dir_corr[v_dir_idx] = 360-v_dir_corr[v_dir_idx]\n v_dir_idx = v_dir_corr < -180\n v_dir_corr[v_dir_idx] = 360 + v_dir_corr[v_dir_idx]\n\n # Number of invalid weights\n idx2 = np.where(np.isnan(wght) == False)\n nwght = len(idx2[0])\n\n # Compute 95% uncertainty using weighted standard deviation\n uncert1 = 2. * np.sqrt(np.nansum(np.nansum(wght * v_dir_corr**2))\n / (((nwght - 1) * np.nansum(np.nansum(wght))) / nwght)) / np.sqrt(nwght)\n\n # Compute flow direction on returning part of loop\n u_ret = wt_u[:, dmg_idx + 1:]\n v_ret = wt_v[:, dmg_idx + 1:]\n wght = np.abs(q[:, dmg_idx+1:])\n se = np.nansum(u_ret * wght) / np.nansum(wght)\n sn = np.nansum(v_ret * wght) / np.nansum(wght)\n direct, _ = cart2pol(se, sn)\n flow_dir2 = rad2azdeg(direct)\n\n # Compute unweighted flow direction in each cell\n direct, _ = cart2pol(u_ret, v_ret)\n flow_dir_cell = rad2azdeg(direct)\n\n # Compute difference from mean and correct to +/- 180\n v_dir_corr = flow_dir_cell - flow_dir2\n v_dir_idx = v_dir_corr > 180\n v_dir_corr[v_dir_idx] = 360 - v_dir_corr[v_dir_idx]\n v_dir_idx = v_dir_corr < -180\n v_dir_corr[v_dir_idx] = 360 + v_dir_corr[v_dir_idx]\n\n # Number of valid weights\n idx2 = np.where(np.isnan(wght) == False)\n nwght = len(idx2[0])\n\n # Compute 95% uncertainty using weighted standard deviation\n uncert2 = 2.*np.sqrt(np.nansum(np.nansum(wght * v_dir_corr**2))\n / (((nwght-1)*np.nansum(np.nansum(wght))) / nwght)) / np.sqrt(nwght)\n\n # Compute and report difference in flow direction\n diff_dir = np.abs(flow_dir1 - flow_dir2)\n if diff_dir > 180:\n diff_dir = diff_dir - 360\n self.compass_diff_deg = diff_dir\n uncert = uncert1 + uncert2\n\n # Compute potential compass error\n idx = np.where(np.isnan(bt_x) == False)\n if len(idx[0]) > 0:\n idx = idx[0][-1]\n width = np.sqrt((bt_x[dmg_idx] - bt_x[idx] / 2) ** 2 + (bt_y[dmg_idx] - bt_y[idx] / 2) ** 2)\n compass_error = (2 * width * sind(diff_dir / 2) * 100) / (self.duration_sec * self.flow_spd_mps)\n\n # Initialize message counter\n self.test_quality = 'Good'\n\n # Low water velocity\n if self.flow_spd_mps < 0.25:\n self.messages.append('WARNING: The water velocity is less than recommended minimum for '\n + 'this test and could cause the loop method to be inaccurate. '\n + 'CONSIDER USING A STATIONARY TEST TO CHECK MOVING-BED CONDITIONS')\n self.test_quality = 'Warnings'\n\n # Percent invalid bottom track\n if self.percent_invalid_bt > 20:\n self.messages.append('ERROR: Percent invalid bottom track exceeds 20 percent. '\n + 'THE LOOP IS NOT ACCURATE. TRY A STATIONARY MOVING-BED TEST.')\n self.test_quality = 'Errors'\n elif self.percent_invalid_bt > 5:\n self.messages.append('WARNING: Percent invalid bottom track exceeds 5 percent. '\n + 'Loop may not be accurate. PLEASE REVIEW DATA.')\n self.test_quality = 'Warnings'\n\n # More than 9 consecutive seconds of invalid BT\n if max_consect_bt_time > 9:\n self.messages.append('ERROR: Bottom track is invalid for more than 9 consecutive seconds.'\n + 'THE LOOP IS NOT ACCURATE. TRY A STATIONARY MOVING-BED TEST.')\n self.test_quality = 'Errors'\n\n if np.abs(compass_error) > 5 and np.abs(diff_dir) > 3 and np.abs(diff_dir) > uncert:\n self.messages.append('ERROR: Difference in flow direction between out and back sections of '\n + 'loop could result in a 5 percent or greater error in final discharge. '\n + 'REPEAT LOOP AFTER COMPASS CAL. OR USE A STATIONARY MOVING-BED TEST.')\n self.test_quality = 'Errors'\n\n else:\n self.messages.append('ERROR: Loop has no valid bottom track data. '\n + 'REPEAT OR USE A STATIONARY MOVING-BED TEST.')\n self.test_quality = 'Errors'\n\n # If loop is valid then evaluate moving-bed condition\n if self.test_quality != 'Errors':\n\n # Check minimum moving-bed velocity criteria\n if self.mb_spd_mps > vel_criteria:\n # Check that closure error is in upstream direction\n if 135 < np.abs(self.flow_dir - self.mb_dir) < 225:\n # Check if moving-bed is greater than 1% of the mean flow speed\n if self.percent_mb > 1:\n self.messages.append('Loop Indicates a Moving Bed -- Use GPS as reference. If GPS is '\n + 'unavailable or invalid use the loop method to correct the '\n + 'final discharge.')\n self.moving_bed = 'Yes'\n else:\n self.messages.append('Moving Bed Velocity < 1% of Mean Velocity -- No Correction Recommended')\n self.moving_bed = 'No'\n else:\n self.messages.append('ERROR: Loop closure error not in upstream direction. '\n + 'REPEAT LOOP or USE STATIONARY TEST')\n self.test_quality = 'Errors'\n self.moving_bed = 'Unknown'\n else:\n self.messages.append('Moving-bed velocity < Minimum moving-bed velocity criteria '\n + '-- No correction recommended')\n self.moving_bed = 'No'\n\n # Notify of differences in results of test between BT and GPS\n if not np.isnan(self.gps_percent_mb):\n if np.abs(self.bt_percent_mb - self.gps_percent_mb) > 2:\n self.messages.append('WARNING - Bottom track and GPS results differ by more than 2%.')\n self.test_quality = 'Warnings'\n\n if np.logical_xor(self.bt_percent_mb >= 1, self.gps_percent_mb >= 1):\n self.messages.append('WARNING - Bottom track and GPS results do not agree.')\n self.test_quality = 'Warnings'\n\n else:\n self.messages.append('ERROR: Due to ERRORS noted above this loop is NOT VALID. '\n + 'Please consider suggestions.')\n self.moving_bed = 'Unknown'\n\n def stationary_test(self, ref='BT'):\n \"\"\"Processed the stationary moving-bed tests.\n \"\"\"\n\n # Assign data from transect to local variables\n trans_data = copy.deepcopy(self.transect)\n in_transect_idx = trans_data.in_transect_idx\n bt_valid = trans_data.boat_vel.bt_vel.valid_data[0, in_transect_idx]\n\n # Check to see that there is valid bottom track data\n self.messages = []\n if np.nansum(bt_valid) > 0:\n # Assign data to local variables\n wt_u = trans_data.w_vel.u_processed_mps[:, in_transect_idx]\n wt_v = trans_data.w_vel.v_processed_mps[:, in_transect_idx]\n ens_duration = trans_data.date_time.ens_duration_sec[in_transect_idx]\n bt_u = trans_data.boat_vel.bt_vel.u_processed_mps[in_transect_idx]\n bt_v = trans_data.boat_vel.bt_vel.v_processed_mps[in_transect_idx]\n\n # Use only data with valid bottom track\n valid_bt = trans_data.boat_vel.bt_vel.valid_data[0, in_transect_idx]\n wt_u[:, valid_bt == False] = np.nan\n wt_v[:, valid_bt == False] = np.nan\n bt_u[valid_bt == False] = np.nan\n bt_v[valid_bt == False] = np.nan\n\n u_water = np.nanmean(wt_u)\n v_water = np.nanmean(wt_v)\n self.flow_dir = np.arctan2(u_water, v_water) * 180 / np.pi\n if self.flow_dir < 0:\n self.flow_dir = self.flow_dir + 360\n\n bin_depth = trans_data.depths.bt_depths.depth_cell_depth_m[:, in_transect_idx]\n trans_select = getattr(trans_data.depths, trans_data.depths.selected)\n depth_ens = trans_select.depth_processed_m[in_transect_idx]\n\n nb_u, nb_v, unit_nbu, unit_nbv = self.near_bed_velocity(wt_u, wt_v, depth_ens, bin_depth)\n \n # Compute bottom track parallel to water velocity\n unit_nb_vel = np.vstack([unit_nbu, unit_nbv])\n bt_vel = np.vstack([bt_u, bt_v])\n bt_vel_up_strm = -1 * np.sum(bt_vel * unit_nb_vel, 0)\n bt_up_strm_dist = bt_vel_up_strm * ens_duration\n bt_up_strm_dist_cum = np.nancumsum(bt_up_strm_dist)\n self.bt_dist_us_m = bt_up_strm_dist_cum[-1]\n\n # Compute bottom track perpendicular to water velocity\n nb_vel_ang, _ = cart2pol(unit_nbu, unit_nbv)\n nb_vel_unit_cs1, nb_vel_unit_cs2 = pol2cart(nb_vel_ang + np.pi / 2, 1)\n nb_vel_unit_cs = np.vstack([nb_vel_unit_cs1, nb_vel_unit_cs2])\n bt_vel_cs = np.sum(bt_vel * nb_vel_unit_cs, 0)\n bt_cs_strm_dist = bt_vel_cs * ens_duration\n bt_cs_strm_dist_cum = np.nancumsum(bt_cs_strm_dist)\n \n # Compute cumulative mean moving bed velocity\n valid_bt_vel_up_strm = np.isnan(bt_vel_up_strm) == False\n\n mb_vel = np.nancumsum(bt_vel_up_strm) / np.nancumsum(valid_bt_vel_up_strm)\n\n # Compute the average ensemble velocities corrected for moving bed\n if mb_vel[-1] > 0:\n u_corrected = np.add(wt_u, (unit_nb_vel[0, :]) * bt_vel_up_strm)\n v_corrected = np.add(wt_v, (unit_nb_vel[1, :]) * bt_vel_up_strm)\n else:\n u_corrected = wt_u\n v_corrected = wt_v\n \n # Compute the mean of the ensemble magnitudes\n\n # Mean is computed using magnitudes because if a Streampro with no compass is the data source the change\n # in direction could be either real change in water direction or an uncompensated turn of the floating\n # platform. This approach is the best compromise when there is no compass or the compass is unreliable,\n # which is often why the stationary method is used. A weighted average is used to account for the possible\n # change in cell size within and ensemble for the RiverRay and RiverPro.\n\n mag = np.sqrt(u_corrected**2 + v_corrected**2)\n depth_cell_size = trans_data.depths.bt_depths.depth_cell_size_m[:, in_transect_idx]\n depth_cell_size[np.isnan(mag)] = np.nan\n mag_w = mag * depth_cell_size\n self.bt_flow_spd_mps = np.nansum(mag_w) / np.nansum(depth_cell_size)\n self.bt_mb_spd_mps = mb_vel[-1]\n self.bt_percent_mb = (self.bt_mb_spd_mps / self.bt_flow_spd_mps) * 100\n if self.bt_percent_mb < 0:\n self.bt_percent_mb = 0\n\n # Compute percent invalid bottom track\n self.percent_invalid_bt = (np.nansum(bt_valid == False) / len(bt_valid)) * 100\n self.duration_sec = np.nansum(ens_duration)\n\n # Compute test using GPS\n self.compute_mb_gps()\n\n # Store selected test characteristics\n if ref == 'BT':\n self.mb_spd_mps = self.bt_mb_spd_mps\n self.dist_us_m = self.bt_dist_us_m\n self.percent_mb = self.bt_percent_mb\n self.mb_dir = self.bt_mb_dir\n self.flow_spd_mps = self.bt_flow_spd_mps\n elif not np.isnan(self.gps_percent_mb):\n self.mb_spd_mps = self.gps_mb_spd_mps\n self.dist_us_m = self.gps_dist_us_m\n self.percent_mb = self.gps_percent_mb\n self.mb_dir = self.gps_mb_dir\n self.flow_spd_mps = self.bt_flow_spd_mps\n\n self.near_bed_speed_mps = np.sqrt(np.nanmean(nb_u)**2 + np.nanmean(nb_v)**2)\n self.stationary_us_track = bt_up_strm_dist_cum\n self.stationary_cs_track = bt_cs_strm_dist_cum\n self.stationary_mb_vel = mb_vel\n\n # Quality check\n self.test_quality = 'Good'\n # Check duration\n if self.duration_sec < 300:\n self.messages.append('WARNING - Duration of stationary test is less than 5 minutes')\n self.test_quality = 'Warnings'\n \n # Check validity of mean moving-bed velocity\n if self.duration_sec > 60:\n mb_vel_std = np.nanstd(mb_vel[-30:], ddof=1)\n cov = mb_vel_std / mb_vel[-1]\n if cov > 0.25 and mb_vel_std > 0.03:\n self.messages.append('WARNING - Moving-bed velocity may not be consistent. '\n + 'Average maybe inaccurate.')\n self.test_quality = 'Warnings'\n \n # Check percentage of invalid BT data\n if np.nansum(ens_duration[valid_bt_vel_up_strm]) <= 120:\n \n self.messages.append('ERROR - Total duration of valid BT data is insufficient for a valid test.')\n self.test_quality = 'Errors'\n self.moving_bed = 'Unknown'\n elif self.percent_invalid_bt > 10:\n self.messages.append('WARNING - Number of ensembles with invalid bottom track exceeds 10%')\n self.test_quality = 'Warnings'\n \n # Determine if the test indicates a moving bed\n if self.test_quality != 'Errors':\n if self.percent_mb >= 1:\n self.moving_bed = 'Yes'\n else:\n self.moving_bed = 'No'\n\n # Notify of differences in results of test between BT and GPS\n if not np.isnan(self.gps_percent_mb):\n if np.abs(self.bt_percent_mb - self.gps_percent_mb) > 2:\n self.messages.append('WARNING - Bottom track and GPS results differ by more than 2%.')\n self.test_quality = 'Warnings'\n\n if np.logical_xor(self.bt_percent_mb >= 1, self.gps_percent_mb >= 1):\n self.messages.append('WARNING - Bottom track and GPS results do not agree.')\n self.test_quality = 'Warnings'\n\n else:\n self.messages.append('ERROR - Stationary moving-bed test has no valid bottom track data.')\n self.test_quality = 'Errors'\n self.moving_bed = 'Unknown'\n self.duration_sec = np.nansum(trans_data.date_time.ens_duration_sec[in_transect_idx])\n self.percent_invalid_bt = 100\n\n def compute_mb_gps(self):\n \"\"\"Computes moving-bed data using GPS.\n \"\"\"\n if np.isnan(self.flow_dir):\n u_water = np.nanmean(self.transect.w_vel.u_processed_mps[:, self.transect.in_transect_idx])\n v_water = np.nanmean(self.transect.w_vel.v_processed_mps[:, self.transect.in_transect_idx])\n self.flow_dir = np.arctan2(u_water, v_water) * 180 / np.pi\n if self.flow_dir < 0:\n self.flow_dir = self.flow_dir + 360\n\n gps_bt = None\n # Use GGA data if available and VTG is GGA is not available\n if self.transect.boat_vel.gga_vel is not None:\n gps_bt = TransectData.compute_gps_bt(self.transect, gps_ref='gga_vel')\n elif self.transect.boat_vel.vtg_vel is not None:\n gps_bt = TransectData.compute_gps_bt(self.transect, gps_ref='vtg_vel')\n if gps_bt is not None and len(gps_bt) > 0:\n self.gps_dist_us_m = gps_bt['mag']\n self.gps_mb_dir = gps_bt['dir']\n self.gps_mb_spd_mps = self.gps_dist_us_m / self.duration_sec\n self.gps_flow_spd_mps = self.bt_flow_spd_mps - self.bt_mb_spd_mps + self.gps_mb_spd_mps\n self.gps_percent_mb = (self.gps_mb_spd_mps / self.gps_flow_spd_mps) * 100\n\n def magvar_change(self, magvar, old_magvar):\n \"\"\"Adjust moving-bed test for change in magvar.\n\n Parameters\n ----------\n magvar: float\n New magvar\n old_magvar: float\n Existing magvar\n \"\"\"\n\n if self.transect.sensors.heading_deg.selected == 'internal':\n magvar_change = magvar - old_magvar\n self.bt_mb_dir = self.bt_mb_dir + magvar_change\n self.flow_dir = self.flow_dir + magvar_change\n\n # Recompute moving-bed tests with GPS and set results using existing reference\n self.compute_mb_gps()\n self.change_ref(self.ref)\n\n def h_offset_change(self, h_offset, old_h_offset):\n \"\"\"Adjust moving-bed test for change in h_offset for external compass.\n\n Parameters\n ----------\n h_offset: float\n New h_offset\n old_h_offset: float\n Existing h_offset\n \"\"\"\n\n if self.transect.sensors.heading_deg.selected == 'external':\n h_offset_change = h_offset - old_h_offset\n self.bt_mb_dir = self.bt_mb_dir + h_offset_change\n self.flow_dir = self.flow_dir + h_offset_change\n\n # Recompute moving-bed tests with GPS and set results using existing reference\n self.compute_mb_gps()\n self.change_ref(self.ref)\n\n def change_ref(self, ref):\n \"\"\"Change moving-bed test fixed reference.\n\n Parameters\n ----------\n ref: str\n Defines specified reference (BT or GPS)\n \"\"\"\n\n if ref == 'BT':\n self.mb_spd_mps = self.bt_mb_spd_mps\n self.dist_us_m = self.bt_dist_us_m\n self.percent_mb = self.bt_percent_mb\n self.mb_dir = self.bt_mb_dir\n self.flow_spd_mps = self.bt_flow_spd_mps\n self.ref = 'BT'\n check_mb = True\n if self.test_quality != 'Errors':\n if self.type == 'Loop':\n if self.mb_spd_mps <= 0.012:\n check_mb = False\n self.moving_bed = 'No'\n else:\n if 135 < np.abs(self.flow_dir - self.mb_dir) < 225:\n check_mb = True\n else:\n check_mb = False\n self.moving_bed = 'Unknown'\n if check_mb:\n if self.percent_mb > 1:\n self.moving_bed = 'Yes'\n else:\n self.moving_bed = 'No'\n else:\n self.moving_bed = 'Unknown'\n elif ref == 'GPS':\n self.mb_spd_mps = self.gps_mb_spd_mps\n self.dist_us_m = self.gps_dist_us_m\n self.percent_mb = self.gps_percent_mb\n self.mb_dir = self.gps_mb_dir\n self.flow_spd_mps = self.gps_flow_spd_mps\n self.ref = 'GPS'\n check_mb = True\n if self.test_quality != 'Errors':\n if self.type == 'Loop':\n if self.mb_spd_mps <= 0.012:\n check_mb = False\n self.moving_bed = 'No'\n else:\n if 135 < np.abs(self.flow_dir - self.mb_dir) < 225:\n check_mb = True\n else:\n check_mb = False\n self.messages.append('ERROR: GPS Loop closure error not in upstream direction. '\n + 'REPEAT LOOP or USE STATIONARY TEST')\n self.moving_bed = 'Unknown'\n if check_mb:\n if self.percent_mb > 1:\n self.moving_bed = 'Yes'\n else:\n self.moving_bed = 'No'\n else:\n self.moving_bed = 'Unknown'\n\n @staticmethod\n def near_bed_velocity(u, v, depth, bin_depth):\n \"\"\"Compute near bed velocities.\n\n Parameters\n ----------\n u: np.array(float)\n u water velocity component\n v: np.array(float)\n v water velocity component\n depth: np.array(float)\n Water depth for each ensemble\n bin_depth: np.array(float)\n Depth to centerline of each bin\n\n Returns\n -------\n nb_u: np.array(float)\n u near-bed velocity component\n nb_v: np.array(float)\n v near-bed velocity component\n unit_nbu: np.array(float)\n u component of the near-bed unit vector\n unit_nbv: np.array(float)\n v component of the near-bed unit vector\n \"\"\"\n\n # Compute z near bed as 10% of depth\n z_near_bed = depth * 0.1\n\n # Initialize variables\n n_ensembles = u.shape[1]\n nb_u = np.tile(np.nan, n_ensembles)\n nb_v = np.tile(np.nan, n_ensembles)\n unit_nbu = np.tile(np.nan, n_ensembles)\n unit_nbv = np.tile(np.nan, n_ensembles)\n z_depth = np.tile(np.nan, n_ensembles)\n u_mean = np.tile(np.nan, n_ensembles)\n v_mean = np.tile(np.nan, n_ensembles)\n speed_near_bed = np.tile(np.nan, n_ensembles)\n\n # Compute near bed velocity for each ensemble\n for n in range(n_ensembles):\n idx = np.where(np.isnan(u[:, n]) == False)\n if len(idx[-1]) > 0:\n if len(idx[-1]) > 0:\n idx = idx[-1][-2::]\n else:\n idx = idx[-1][-1]\n # Compute near-bed velocity\n z_depth[n] = depth[n] - np.nanmean(bin_depth[idx, n], 0)\n u_mean[n] = np.nanmean(u[idx, n], 0)\n v_mean[n] = np.nanmean(v[idx, n], 0)\n nb_u[n] = (u_mean[n] / z_depth[n] ** (1. / 6.)) * (z_near_bed[n] ** (1. / 6.))\n nb_v[n] = (v_mean[n] / z_depth[n] ** (1. / 6.)) * (z_near_bed[n] ** (1. / 6.))\n speed_near_bed[n] = np.sqrt(nb_u[n] ** 2 + nb_v[n] ** 2)\n unit_nbu[n] = nb_u[n] / speed_near_bed[n]\n unit_nbv[n] = nb_v[n] / speed_near_bed[n]\n\n return nb_u, nb_v, unit_nbu, unit_nbv\n\n @staticmethod\n def auto_use_2_correct(moving_bed_tests, boat_ref=None):\n \"\"\"Apply logic to determine which moving-bed tests should be used\n for correcting bottom track referenced discharges with moving-bed conditions.\n\n Parameters\n ----------\n moving_bed_tests: list\n List of MovingBedTests objects.\n boat_ref: str\n Boat velocity reference.\n\n Returns\n -------\n moving_bed_tests: list\n List of MovingBedTests objects.\n \"\"\"\n\n if len(moving_bed_tests) != 0:\n # Initialize variables\n lidx_user = []\n lidx_no_errors = []\n test_type = []\n lidx_stationary = []\n lidx_loop = []\n flow_speed = []\n for test in moving_bed_tests:\n test.use_2_correct = False\n test.selected = False\n # Valid test according to user\n lidx_user.append(test.user_valid == True)\n # Valid test according to quality assessment\n lidx_no_errors.append(test.test_quality != 'Errors')\n # Identify type of test\n test_type.append(test.type)\n lidx_stationary.append(test.type == 'Stationary')\n lidx_loop.append(test.type == 'Loop')\n flow_speed.append(test.flow_spd_mps)\n\n # Combine\n lidx_valid_loop = np.all(np.vstack((lidx_user, lidx_no_errors, lidx_loop)), 0)\n lidx_valid_stationary = np.all(np.vstack((lidx_user, lidx_no_errors, lidx_stationary)), 0)\n\n # Check flow speed\n lidx_flow_speed = np.array(flow_speed) > 0.25\n\n # Determine if there are valid loop tests\n # This is the code in matlab but I don't think it is correct. I the valid loop should also have a valid\n # flow speed, if not then a stationary test, if available could be used.\n lidx_loops_2_select = np.all(np.vstack((lidx_flow_speed, lidx_valid_loop)), 0)\n if np.any(lidx_loops_2_select):\n # Select last loop\n idx_select = np.where(lidx_loops_2_select)[0][-1]\n test_select = moving_bed_tests[idx_select]\n test_select.selected = True\n\n if test_select.moving_bed == 'Yes':\n test_select.use_2_correct = True\n\n # If there are no valid loop look for valid stationary tests\n elif np.any(lidx_valid_stationary):\n moving_bed = []\n for n, lidx in enumerate(lidx_valid_stationary):\n if lidx:\n moving_bed_tests[n].selected = True\n # Determine if any stationary test resulted in a moving bed\n if moving_bed_tests[n].moving_bed == 'Yes':\n moving_bed.append(True)\n else:\n moving_bed.append(False)\n # If any stationary test shows a moving-bed use all valid stationary test to correct BT discharge\n if any(moving_bed) > 0:\n for n, test in enumerate(moving_bed_tests):\n if lidx_valid_stationary[n]:\n test.use_2_correct = True\n\n # If the flow speed is too low but there are not valid stationary tests use the last loop test.\n elif np.any(lidx_valid_loop):\n # Select last loop\n idx_select = np.where(lidx_valid_loop)[0][-1]\n moving_bed_tests[idx_select].selected = True\n if moving_bed_tests[idx_select].moving_bed == 'Yes':\n moving_bed_tests[idx_select].use_2_correct = True\n\n # If the navigation reference for discharge computations is set\n # GPS then none of test should be used for correction. The\n # selected test should be used to determine if there is a valid\n # moving-bed and a moving-bed condition.\n if boat_ref is None:\n ref = 'BT'\n else:\n ref = boat_ref\n\n if ref != 'BT':\n for test in moving_bed_tests:\n test.use_2_correct = False\n return moving_bed_tests\n", "meta": {"hexsha": "bea4666cea3a22831c0099153d71097b04325669", "size": 45706, "ext": "py", "lang": "Python", "max_stars_repo_path": "Classes/MovingBedTests.py", "max_stars_repo_name": "EstebM/QRevPy", "max_stars_repo_head_hexsha": "3f788d1f84dfd075bbf25cf8d4b47943f9bfe682", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Classes/MovingBedTests.py", "max_issues_repo_name": "EstebM/QRevPy", "max_issues_repo_head_hexsha": "3f788d1f84dfd075bbf25cf8d4b47943f9bfe682", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Classes/MovingBedTests.py", "max_forks_repo_name": "EstebM/QRevPy", "max_forks_repo_head_hexsha": "3f788d1f84dfd075bbf25cf8d4b47943f9bfe682", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-12-22T16:50:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-30T17:14:19.000Z", "avg_line_length": 44.0327552987, "max_line_length": 118, "alphanum_fraction": 0.5849997812, "include": true, "reason": "import numpy", "num_tokens": 10417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.24798742068237775, "lm_q1q2_score": 0.12786725295261564}} {"text": "\"\"\"Models of complete paraglider systems.\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nimport scipy.integrate\nimport scipy.optimize\n\nfrom pfh.glidersim import foil_aerodynamics, orientation\nfrom pfh.glidersim.util import cross3, crossmat\n\n\nif TYPE_CHECKING:\n from pfh.glidersim.paraglider_harness import ParagliderHarness\n from pfh.glidersim.paraglider_wing import ParagliderWing\n\n\n__all__ = [\n \"ParagliderSystemDynamics6a\",\n \"ParagliderSystemDynamics6b\",\n \"ParagliderSystemDynamics6c\",\n \"ParagliderSystemDynamics9a\",\n \"ParagliderSystemDynamics9b\",\n \"ParagliderSystemDynamics9c\",\n]\n\n\ndef __dir__():\n return __all__\n\n\nclass ParagliderSystemDynamics6a:\n \"\"\"\n A 6 degrees-of-freedom paraglider model; there is no relative motion\n between the wing and the harness.\n\n This version uses the riser connection midpoint `RM` as the reference point\n for the angular momentum, and can include the effects of apparent mass.\n\n Parameters\n ----------\n wing : ParagliderWing\n payload : ParagliderHarness\n The harness model includes the mass of the pilot.\n use_apparent_mass : bool, optional\n Whether to estimate the effects of apparent inertia.\n \"\"\"\n\n def __init__(\n self,\n wing: ParagliderWing,\n payload: ParagliderHarness,\n *,\n use_apparent_mass: bool = True,\n ) -> None:\n self.wing = wing\n self.payload = payload\n self.use_apparent_mass = use_apparent_mass\n\n def r_CP2RM(self, delta_a: float = 0, delta_w: float = 0):\n \"\"\"\n Compute the reference points for the composite Paraglider system.\n\n All the components of the Paraglider that experience aerodynamic forces\n need their relative wind vectors. Each component is responsible for\n creating a list of the coordinates where they need the value of the\n wind. This function then transforms them into body coordinates.\n\n Parameters\n ----------\n delta_a : float [percentage]\n The fraction of maximum accelerator\n delta_w : float [percentage]\n The fraction of weight shift, from -1 (left) to +1 (right)\n\n Returns\n -------\n ndarray of float, shape (K,3) [m]\n The position of the control points with respect to `RM`.\n \"\"\"\n r_LE2RM = -self.wing.r_RM2LE(delta_a)\n wing_cps = self.wing.r_CP2LE(delta_a=delta_a) + r_LE2RM\n payload_cps = self.payload.r_CP2RM(delta_w)\n return np.vstack((wing_cps, payload_cps))\n\n def accelerations(\n self,\n v_RM2e,\n omega_b2e,\n g,\n delta_a: float = 0,\n delta_bl: float = 0,\n delta_br: float = 0,\n delta_w: float = 0,\n rho_air: float = 1.225,\n v_W2e=(0, 0, 0),\n reference_solution: dict | None = None,\n ):\n r\"\"\"\n Compute the translational and angular accelerations about the center of mass.\n\n Parameters\n ----------\n v_RM2e : array of float, shape (3,) [m/s]\n Translational velocity of `RM` in body frd coordinates, where `RM`\n is the midpoint between the two riser connection points.\n omega_b2e : array of float, shape (3,) [rad/s]\n Angular velocity of the body, in body frd coordinates.\n g : array of float, shape (3,) [m/s^s]\n The gravity vector in body frd\n delta_a : float [percentage]\n The fraction of maximum accelerator\n delta_bl : float [percentage]\n The fraction of maximum left brake\n delta_br : float [percentage]\n The fraction of maximum right brake\n delta_w : float [percentage]\n The fraction of weight shift, from -1 (left) to +1 (right)\n rho_air : float [kg/m^3], optional\n Air density\n v_W2e : ndarray of float, shape (3,) or (K,3) [m/s], optional\n The wind relative to the earth, in body frd coordinates. If it is\n a (3,) array then the wind is uniform at every control point. If\n it is a (K,3) array then it is the vectors for each control point.\n reference_solution : dictionary, optional\n FIXME: docstring. See `Phillips.__call__`\n\n Returns\n -------\n a_RM2e : array of float, shape (3,) [m/s^2]\n Translational acceleration of `RM` in body frd coordinates.\n alpha_b2e : array of float, shape (3,) [rad/s^2]\n Angular acceleration of the body with respect to Earth as the time\n derivative of angular velocity taken with respect to the body\n frame, expressed in body frd coordinates\n :math:`\\left( ^b \\dot{\\omega}_{b/e}^b \\right)`.\n solution : dictionary\n FIXME: docstring. See `Phillips.__call__`\n \"\"\"\n r_CP2RM = self.r_CP2RM(delta_a, delta_w)\n v_W2e = np.asfarray(v_W2e)\n if v_W2e.ndim > 1 and v_W2e.shape[0] != r_CP2RM.shape[0]:\n raise ValueError(\n \"Number of distinct wind vectors in v_W2e do not match the \"\n \"number of control points\",\n )\n v_RM2e = np.asfarray(v_RM2e)\n if v_RM2e.shape != (3,):\n raise ValueError(\"v_RM2e.shape != (3,)\")\n\n # -------------------------------------------------------------------\n # Compute the inertia of the body (wing + payload) with respect to the\n # riser midpoint `RM`.\n r_RM2LE = self.wing.r_RM2LE(delta_a)\n wmp = self.wing.mass_properties(rho_air, r_RM2LE) # R = RM\n pmp = self.payload.mass_properties(delta_w, [0, 0, 0]) # R = RM\n m_b = wmp[\"m_b\"] + pmp[\"m_p\"]\n J_b2RM = wmp[\"J_b2R\"] + pmp[\"J_p2R\"]\n r_B2RM = (wmp[\"m_b\"] * wmp[\"r_B2R\"] + pmp[\"m_p\"] * pmp[\"r_P2R\"]) / m_b\n\n # -------------------------------------------------------------------\n # Compute the relative wind vectors for each control point.\n v_CP2e = v_RM2e + cross3(omega_b2e, r_CP2RM)\n v_W2CP = v_W2e - v_CP2e\n\n # FIXME: \"magic\" indexing established by `self.r_CP2RM`\n v_W2CP_wing = v_W2CP[:-1]\n v_W2CP_payload = v_W2CP[-1]\n\n # -------------------------------------------------------------------\n # Compute the forces and moments of the wing\n try:\n f_b, g_b2RM, ref = self.wing.resultant_force(\n delta_a,\n delta_bl,\n delta_br,\n v_W2CP_wing,\n rho_air,\n g,\n r_RM2LE,\n wmp,\n reference_solution,\n )\n except foil_aerodynamics.ConvergenceError:\n # Maybe it can't recover once Gamma is jacked?\n print(\"\\nBonk! Retrying with the default reference solution\")\n f_b, g_b2RM, ref = self.wing.resultant_force(\n delta_a,\n delta_bl,\n delta_br,\n v_W2CP_wing,\n rho_air,\n g,\n r_RM2LE,\n wmp,\n )\n\n f_p, g_p2RM = self.payload.resultant_force(\n delta_w=delta_w,\n v_W2h=v_W2CP_payload,\n rho_air=rho_air,\n g=g,\n r_R2RM=[0, 0, 0],\n mp=pmp,\n )\n\n # ------------------------------------------------------------------\n # Compute the accelerations \\dot{v_RM2e} and \\dot{omega_b2e}\n #\n # Builds a system of equations by equating derivatives of translational\n # and angular momentum to the forces and moments.\n\n # fmt: off\n\n # Real mass momentums\n v_B2e = v_RM2e + cross3(omega_b2e, r_B2RM)\n p_b2e = m_b * v_B2e # Linear\n h_b2RM = J_b2RM @ omega_b2e + m_b * cross3(r_B2RM, v_RM2e) # Angular\n\n # Build the system matrices for the real mass\n A1 = [m_b * np.eye(3), -m_b * crossmat(r_B2RM)]\n A2 = [m_b * crossmat(r_B2RM), J_b2RM]\n A = np.block([A1, A2])\n B1 = f_b + f_p - cross3(omega_b2e, p_b2e)\n B2 = ( # ref: Hughes Eq:13, p58\n g_b2RM\n + g_p2RM\n - cross3(v_RM2e, p_b2e)\n - cross3(omega_b2e, h_b2RM)\n )\n\n if self.use_apparent_mass:\n amp = self.wing.apparent_mass_properties(\n rho_air,\n r_RM2LE,\n v_RM2e,\n omega_b2e,\n )\n A += amp[\"A_a2R\"] # Incorporate the apparent inertia\n B1 += ( # Apparent inertial force (Barrows Eq:61)\n -cross3(omega_b2e, amp[\"p_a2e\"])\n )\n B2 += ( # Apparent inertial moment (Barrows Eq:64)\n -cross3(v_RM2e, amp[\"p_a2e\"])\n - cross3(omega_b2e, amp[\"h_a2R\"])\n + cross3(v_RM2e, amp[\"M_a\"] @ v_RM2e) # Remove the steady-state term\n )\n\n # fmt: on\n\n B = np.r_[B1, B2]\n x = np.linalg.solve(A, B) # Solve for the derivatives\n a_RM2e = x[:3] # In frame F_b\n alpha_b2e = x[3:] # In frames F_b and F_e\n return a_RM2e, alpha_b2e, ref\n\n def equilibrium_state(\n self,\n delta_a: float = 0,\n delta_b: float = 0,\n rho_air: float = 1.225,\n alpha_0: float = None,\n theta_0: float = 0,\n v_0: float = 10,\n reference_solution: dict | None = None,\n ):\n \"\"\"\n Compute the equilibrium glider state for given inputs.\n\n Assumes that the wing is symmetric about the xz-plane.\n\n Parameters\n ----------\n delta_a : float, optional\n Fraction of accelerator application, where `0 <= delta_a <= 1`\n delta_b : float, optional\n Fraction of symmetric brake application, where `0 <= delta_b <= 1`\n rho_air : float [kg/m^3], optional\n Air density\n alpha_0 : float [rad], optional\n An initial proposal for the body angle of attack. If no value is\n set, the wing equilibrium alpha will be used.\n theta_0 : float [rad], optional\n An initial proposal for the body pitch angle.\n v_0 : float [m/s], optional\n An initial proposal for the body airspeed.\n reference_solution : dictionary, optional\n FIXME: docstring. See `Phillips.__call__`\n\n Returns\n -------\n dictionary\n alpha_b : float [radians]\n Wing angle of attack\n gamma_b : float [radians]\n Wing glide angle\n glide_ratio : float\n Units of ground distance traveled per unit of altitude lost\n Theta_b2e : array of float, shape (3,) [radians]\n Equilibrium orientation of the body relative to Earth as a set\n of Tait-Bryan yaw-pitch-role angles.\n v_RM2e : float [m/s]\n Steady-state velocity of the riser midpoint in body coordinates\n solution : dictionary\n FIXME: docstring. See `Phillips.__call__`\n \"\"\"\n if alpha_0 is None:\n alpha_0 = self.wing.equilibrium_alpha(\n delta_a=delta_a,\n delta_b=delta_b,\n v_mag=v_0,\n rho_air=rho_air,\n reference_solution=reference_solution,\n )\n\n _state = {\n \"delta_a\": delta_a,\n \"delta_bl\": delta_b,\n \"delta_br\": delta_b,\n \"omega_b2e\": np.zeros(3),\n \"rho_air\": rho_air,\n \"reference_solution\": reference_solution,\n }\n\n def _helper(x, state):\n v_x, v_z, theta_b2e = x\n a_RM2e, alpha_b2e, ref = self.accelerations(\n v_RM2e=[v_x, 0, v_z],\n g=9.8 * np.array([-np.sin(theta_b2e), 0, np.cos(theta_b2e)]),\n **state,\n )\n _state[\"reference_solution\"] = ref\n return (a_RM2e[0], a_RM2e[2], alpha_b2e[1])\n\n v_x_0 = v_0 * np.cos(alpha_0)\n v_z_0 = v_0 * np.sin(alpha_0)\n x0 = np.array([v_x_0, v_z_0, theta_0])\n res = scipy.optimize.root(_helper, x0, _state)\n v_RM2e = np.array([res.x[0], 0, res.x[1]]) # In body frd\n alpha_eq = np.arctan2(v_RM2e[2], v_RM2e[0])\n theta_eq = res.x[2]\n gamma_eq = alpha_eq - theta_eq\n\n equilibrium = {\n \"alpha_b\": alpha_eq,\n \"gamma_b\": gamma_eq,\n \"glide_ratio\": 1 / np.tan(gamma_eq),\n \"Theta_b2e\": np.array([0, theta_eq, 0]),\n \"v_RM2e\": v_RM2e,\n \"reference_solution\": _state[\"reference_solution\"],\n }\n\n return equilibrium\n\n\nclass ParagliderSystemDynamics6b(ParagliderSystemDynamics6a):\n \"\"\"\n A 6 degrees-of-freedom paraglider model; there is no relative motion\n between the wing and the harness.\n\n This version uses the body center of mass `B` as the reference point for\n the angular momentum. Using the center of mass produces a decoupled linear\n system, which is easier to reason about, making this model useful for\n validating other models. The system solves for `a_B2e` which is then used\n to compute `a_RM2e`.\n\n This model does not support apparent mass; the apparent mass model requires\n that the reference point lies in the xz-plane, which is not the case for\n `B` during weight shift control. As a result, this model is intended to\n help validate other models involving the real mass only.\n\n Parameters\n ----------\n wing : ParagliderWing\n payload : ParagliderHarness\n The harness model includes the mass of the pilot.\n use_apparent_mass : bool, optional\n Whether to estimate the effects of apparent inertia.\n \"\"\"\n\n def __init__(self, wing: ParagliderWing, payload: ParagliderHarness) -> None:\n self.wing = wing\n self.payload = payload\n\n def accelerations(\n self,\n v_RM2e,\n omega_b2e,\n g,\n delta_a: float = 0,\n delta_bl: float = 0,\n delta_br: float = 0,\n delta_w: float = 0,\n rho_air: float = 1.225,\n v_W2e=(0, 0, 0),\n reference_solution=None,\n ):\n r\"\"\"\n Compute the translational and angular accelerations about the center of mass.\n\n Parameters\n ----------\n v_RM2e : array of float, shape (3,) [m/s]\n Translational velocity of `RM` in body frd coordinates, where `RM` is\n the midpoint between the two riser connection points.\n omega_b2e : array of float, shape (3,) [rad/s]\n Angular velocity of the body, in body frd coordinates.\n g : array of float, shape (3,) [m/s^s]\n The gravity vector in body frd\n delta_a : float [percentage]\n The fraction of maximum accelerator\n delta_bl : float [percentage]\n The fraction of maximum left brake\n delta_br : float [percentage]\n The fraction of maximum right brake\n delta_w : float [percentage]\n The fraction of weight shift, from -1 (left) to +1 (right)\n rho_air : float [kg/m^3], optional\n Air density\n v_W2e : ndarray of float, shape (3,) or (K,3) [m/s], optional\n The wind relative to the earth, in body frd coordinates. If it is\n a (3,) array then the wind is uniform at every control point. If\n it is a (K,3) array then it is the vectors for each control point.\n reference_solution : dictionary, optional\n FIXME: docstring. See `Phillips.__call__`\n\n Returns\n -------\n a_RM2e : array of float, shape (3,) [m/s^2]\n Translational acceleration of `RM` in body frd coordinates.\n alpha_b2e : array of float, shape (3,) [rad/s^2]\n Angular acceleration of the body with respect to Earth as the time\n derivative of angular velocity taken with respect to the body\n frame, expressed in body frd coordinates\n :math:`\\left( ^b \\dot{\\omega}_{b/e}^b \\right)`.\n solution : dictionary\n FIXME: docstring. See `Phillips.__call__`\n \"\"\"\n r_CP2RM = self.r_CP2RM(delta_a, delta_w)\n v_W2e = np.asfarray(v_W2e)\n if v_W2e.ndim > 1 and v_W2e.shape[0] != r_CP2RM.shape[0]:\n raise ValueError(\n \"Number of distinct wind vectors in v_W2e do not match the \"\n \"number of control points\",\n )\n v_RM2e = np.asfarray(v_RM2e)\n if v_RM2e.shape != (3,):\n raise ValueError(\"v_RM2e.shape != (3,)\")\n\n # -------------------------------------------------------------------\n # Compute the inertia of the body (wing + payload) with respect to its\n # center of mass `B`. Because `B` depends on the masses of both\n # components, this model must query those values and compute `B` before\n # computing properties with respect to `B`. This is wasteful, but this\n # model is mostly about checking the other models anyway.\n r_RM2LE = self.wing.r_RM2LE(delta_a)\n wmp0 = self.wing.mass_properties(rho_air, r_RM2LE) # R = RM\n pmp0 = self.payload.mass_properties(delta_w, [0, 0, 0]) # R = RM\n m_b = wmp0[\"m_b\"] + pmp0[\"m_p\"]\n r_B2RM = (wmp0[\"m_b\"] * wmp0[\"r_B2R\"] + pmp0[\"m_p\"] * pmp0[\"r_P2R\"]) / m_b\n r_B2LE = r_B2RM + r_RM2LE\n\n # Recompute the mass properties using `B` as the reference point\n wmp = self.wing.mass_properties(rho_air, r_B2LE) # R = B\n pmp = self.payload.mass_properties(delta_w, r_B2RM) # R = B\n J_b2B = wmp[\"J_b2R\"] + pmp[\"J_p2R\"]\n\n # -------------------------------------------------------------------\n # Compute the relative wind vectors for each control point.\n v_CP2e = v_RM2e + cross3(omega_b2e, r_CP2RM)\n v_W2CP = v_W2e - v_CP2e\n\n # FIXME: \"magic\" indexing established by `self.r_CP2RM`\n v_W2CP_wing = v_W2CP[:-1]\n v_W2CP_payload = v_W2CP[-1]\n\n # -------------------------------------------------------------------\n # Compute the forces and moments of the wing\n try:\n f_b, g_b2B, ref = self.wing.resultant_force(\n delta_a,\n delta_bl,\n delta_br,\n v_W2CP_wing,\n rho_air,\n g,\n r_B2LE,\n wmp,\n reference_solution,\n )\n except foil_aerodynamics.ConvergenceError:\n # Maybe it can't recover once Gamma is jacked?\n print(\"\\nBonk! Retrying with the default reference solution\")\n f_b, g_b2B, ref = self.wing.resultant_force(\n delta_a,\n delta_bl,\n delta_br,\n v_W2CP_wing,\n rho_air,\n g,\n r_B2LE,\n wmp,\n )\n\n f_p, g_p2B = self.payload.resultant_force(\n delta_w=delta_w,\n v_W2h=v_W2CP_payload,\n rho_air=rho_air,\n g=g,\n r_R2RM=r_B2RM,\n mp=pmp,\n )\n\n # ------------------------------------------------------------------\n # Compute the accelerations \\dot{v_RM2e} and \\dot{omega_b2e}\n #\n # Builds a system of equations by equating derivatives of translational\n # and angular momentum to the net forces and moments.\n\n # Real mass momentums\n v_B2e = v_RM2e + cross3(omega_b2e, r_B2RM)\n p_b2e = m_b * v_B2e # Linear\n h_b2B = J_b2B @ omega_b2e # Angular\n\n A1 = [m_b * np.eye(3), np.zeros((3, 3))]\n A2 = [np.zeros((3, 3)), J_b2B]\n A = np.block([A1, A2])\n B1 = f_b + f_p - cross3(omega_b2e, p_b2e)\n B2 = g_b2B + g_p2B - np.cross(omega_b2e, h_b2B) # ref: Hughes Eq:13, p58\n B = np.r_[B1, B2]\n x = np.linalg.solve(A, B) # Solve for the derivatives\n a_B2e = x[:3] # In frame F_b\n alpha_b2e = x[3:] # In frames F_b and F_e\n a_RM2e = a_B2e - np.cross(alpha_b2e, r_B2RM) # In frame F_b\n return a_RM2e, alpha_b2e, ref\n\n\nclass ParagliderSystemDynamics6c(ParagliderSystemDynamics6a):\n \"\"\"\n A 6 degrees-of-freedom paraglider model; there is no relative motion\n between the wing and the harness.\n\n This version uses the body center of mass `B` as the reference point for\n the angular momentum. Similar to 6b, except it solves for v_RM2e directly.\n\n This model does not support apparent mass; the apparent mass model requires\n that the reference point lies in the xz-plane, which is not the case for\n `B` during weight shift control. As a result, this model is intended to\n help validate other models involving the real mass only.\n\n Parameters\n ----------\n wing : ParagliderWing\n payload : ParagliderHarness\n The harness model includes the mass of the pilot.\n \"\"\"\n\n def __init__(self, wing: ParagliderWing, payload: ParagliderHarness) -> None:\n self.wing = wing\n self.payload = payload\n\n def accelerations(\n self,\n v_RM2e,\n omega_b2e,\n g,\n delta_a: float = 0,\n delta_bl: float = 0,\n delta_br: float = 0,\n delta_w: float = 0,\n rho_air: float = 1.225,\n v_W2e=(0, 0, 0),\n r_CP2RM=None,\n reference_solution: dict | None = None,\n ):\n r\"\"\"\n Compute the translational and angular accelerations about the center of mass.\n\n Parameters\n ----------\n v_RM2e : array of float, shape (3,) [m/s]\n Translational velocity of `RM` in body frd coordinates, where `RM` is\n the midpoint between the two riser connection points.\n omega_b2e : array of float, shape (3,) [rad/s]\n Angular velocity of the body, in body frd coordinates.\n g : array of float, shape (3,) [m/s^s]\n The gravity vector in body frd\n delta_a : float [percentage]\n The fraction of maximum accelerator\n delta_bl : float [percentage]\n The fraction of maximum left brake\n delta_br : float [percentage]\n The fraction of maximum right brake\n delta_w : float [percentage]\n The fraction of weight shift, from -1 (left) to +1 (right)\n rho_air : float [kg/m^3], optional\n Air density\n v_W2e : ndarray of float, shape (3,) or (K,3) [m/s], optional\n The wind relative to the earth, in body frd coordinates. If it is\n a (3,) array then the wind is uniform at every control point. If\n it is a (K,3) array then it is the vectors for each control point.\n reference_solution : dictionary, optional\n FIXME: docstring. See `Phillips.__call__`\n\n Returns\n -------\n a_RM2e : array of float, shape (3,) [m/s^2]\n Translational acceleration of `RM` in body frd coordinates.\n alpha_b2e : array of float, shape (3,) [rad/s^2]\n Angular acceleration of the body with respect to Earth as the time\n derivative of angular velocity taken with respect to the body\n frame, expressed in body frd coordinates\n :math:`\\left( ^b \\dot{\\omega}_{b/e}^b \\right)`.\n solution : dictionary\n FIXME: docstring. See `Phillips.__call__`\n \"\"\"\n r_CP2RM = self.r_CP2RM(delta_a, delta_w)\n v_W2e = np.asfarray(v_W2e)\n if v_W2e.ndim > 1 and v_W2e.shape[0] != r_CP2RM.shape[0]:\n raise ValueError(\n \"Number of distinct wind vectors in v_W2e do not match the \"\n \"number of control points\",\n )\n v_RM2e = np.asfarray(v_RM2e)\n if v_RM2e.shape != (3,):\n raise ValueError(\"v_RM2e.shape != (3,)\")\n\n # -------------------------------------------------------------------\n # Compute the inertia of the body (wing + payload) with respect to its\n # center of mass `B`. Because `B` depends on the masses of both\n # components, this model must query those values and compute `B` before\n # computing properties with respect to `B`. This is wasteful, but this\n # model is mostly about checking the other models anyway.\n r_RM2LE = self.wing.r_RM2LE(delta_a)\n wmp0 = self.wing.mass_properties(rho_air, r_RM2LE) # R = RM\n pmp0 = self.payload.mass_properties(delta_w, [0, 0, 0]) # R = RM\n m_b = wmp0[\"m_b\"] + pmp0[\"m_p\"]\n r_B2RM = (wmp0[\"m_b\"] * wmp0[\"r_B2R\"] + pmp0[\"m_p\"] * pmp0[\"r_P2R\"]) / m_b\n r_B2LE = r_B2RM + r_RM2LE\n\n # Recompute the mass properties using `B` as the reference point\n wmp = self.wing.mass_properties(rho_air, r_B2LE) # R = B\n pmp = self.payload.mass_properties(delta_w, r_B2RM) # R = B\n J_b2B = wmp[\"J_b2R\"] + pmp[\"J_p2R\"]\n\n # -------------------------------------------------------------------\n # Compute the relative wind vectors for each control point.\n v_CP2e = v_RM2e + cross3(omega_b2e, r_CP2RM)\n v_W2CP = v_W2e - v_CP2e\n\n # FIXME: \"magic\" indexing established by `self.r_CP2RM`\n v_W2CP_wing = v_W2CP[:-1]\n v_W2CP_payload = v_W2CP[-1]\n\n # -------------------------------------------------------------------\n # Compute the forces and moments of the wing\n try:\n f_b, g_b2B, ref = self.wing.resultant_force(\n delta_a,\n delta_bl,\n delta_br,\n v_W2CP_wing,\n rho_air,\n g,\n r_B2LE,\n wmp,\n reference_solution,\n )\n except foil_aerodynamics.ConvergenceError:\n # Maybe it can't recover once Gamma is jacked?\n print(\"\\nBonk! Retrying with the default reference solution\")\n f_b, g_b2B, ref = self.wing.resultant_force(\n delta_a,\n delta_bl,\n delta_br,\n v_W2CP_wing,\n rho_air,\n g,\n r_B2LE,\n wmp,\n )\n\n f_p, g_p2B = self.payload.resultant_force(\n delta_w=delta_w,\n v_W2h=v_W2CP_payload,\n rho_air=rho_air,\n g=g,\n r_R2RM=r_B2RM,\n mp=pmp,\n )\n\n # ------------------------------------------------------------------\n # Compute the accelerations \\dot{v_RM2e} and \\dot{omega_b2e}\n #\n # Builds a system of equations by equating derivatives of translational\n # and angular momentum to the net forces and moments.\n\n # Real mass momentums\n v_B2e = v_RM2e + cross3(omega_b2e, r_B2RM)\n p_b2e = m_b * v_B2e # Linear\n h_b2B = J_b2B @ omega_b2e # Angular\n\n A1 = [m_b * np.eye(3), -m_b * crossmat(r_B2RM)]\n A2 = [np.zeros((3, 3)), J_b2B]\n A = np.block([A1, A2])\n B1 = f_b + f_p - cross3(omega_b2e, p_b2e)\n B2 = g_b2B + g_p2B - np.cross(omega_b2e, h_b2B) # ref: Hughes Eq:13, p58\n B = np.r_[B1, B2]\n x = np.linalg.solve(A, B) # Solve for the derivatives\n a_RM2e = x[:3] # In frame F_b\n alpha_b2e = x[3:] # In frames F_b and F_e\n return a_RM2e, alpha_b2e, ref\n\n\nclass ParagliderSystemDynamics9a:\n \"\"\"\n A 9 degrees-of-freedom paraglider model, allowing rotation between the wing\n and the harness, with the connection modelled by spring-damper dynamics.\n\n This version uses the riser connection midpoint `RM` as the reference point\n for the angular momentum of both the body (the wing system) and the payload\n (the harness and pilot).\n\n Parameters\n ----------\n wing : ParagliderWing\n payload : ParagliderHarness\n The harness model includes the mass of the pilot.\n kappa_RM : array of float, shape (3,), optional\n Spring-damper coefficients for Theta_p2b (force as a linear function\n of angular displacement).\n kappa_RM_dot : array of float, shape (3,), optional\n Spring-damper coefficients for the derivative of Theta_p2b\n use_apparent_mass : bool, optional\n Whether to estimate the effects of apparent inertia. Default: True\n \"\"\"\n\n def __init__(\n self,\n wing: ParagliderWing,\n payload: ParagliderHarness,\n kappa_RM=(0, 0, 0),\n kappa_RM_dot=(0, 0, 0),\n *,\n use_apparent_mass: bool = True,\n ) -> None:\n self.wing = wing\n self.payload = payload\n self._kappa_RM = np.asfarray(kappa_RM[:])\n self._kappa_RM_dot = np.asfarray(kappa_RM_dot[:])\n self.use_apparent_mass = use_apparent_mass\n\n def r_CP2RM(self, Theta_p2b, delta_a: float = 0, delta_w: float = 0):\n \"\"\"\n Compute the reference points for the composite Paraglider system.\n\n All the components of the Paraglider that experience aerodynamic forces\n need their relative wind vectors. Each component is responsible for\n creating a list of the coordinates where they need the value of the\n wind. This function then transforms them into body coordinates.\n\n Parameters\n ----------\n Theta_p2b : array of float, shape (3,) [radians]\n The [phi, theta, gamma] of a yaw-pitch-roll sequence that encodes\n the relative orientation of the payload with respect to the body.\n delta_a : float [percentage]\n The fraction of maximum accelerator\n delta_w : float [percentage]\n The fraction of weight shift, from -1 (left) to +1 (right)\n\n Returns\n -------\n ndarray of float, shape (K,3) [m]\n The position of the control points with respect to `RM`.\n \"\"\"\n r_LE2RM = -self.wing.r_RM2LE(delta_a)\n wing_cps = self.wing.r_CP2LE(delta_a=delta_a) # In body frd\n payload_cps = self.payload.r_CP2RM(delta_w) # In payload frd\n C_b2p = orientation.euler_to_dcm(Theta_p2b).T\n return np.vstack((wing_cps + r_LE2RM, (C_b2p @ payload_cps.T).T))\n\n def accelerations(\n self,\n v_RM2e,\n omega_b2e,\n omega_p2e,\n Theta_p2b,\n g,\n delta_a: float = 0,\n delta_bl: float = 0,\n delta_br: float = 0,\n delta_w: float = 0,\n rho_air: float = 1.225,\n v_W2e=(0, 0, 0),\n reference_solution: dict | None = None,\n ):\n r\"\"\"\n Compute the translational and angular accelerations about the center of mass.\n\n Parameters\n ----------\n v_RM2e : array of float, shape (3,) [m/s]\n Translational velocity of `RM` in body frd coordinates, where `RM` is\n the midpoint between the two riser connection points.\n omega_b2e : array of float, shape (3,) [rad/s]\n Angular velocity of the body, in body frd coordinates.\n omega_p2e : array of float, shape (3,) [rad/s]\n Angular velocity of the payload, in payload frd coordinates.\n Theta_p2b : array of float, shape (3,) [radians]\n The [phi, theta, gamma] of a yaw-pitch-roll sequence that encodes\n the relative orientation of the payload with respect to the body.\n g : array of float, shape (3,) [m/s^s]\n The gravity vector in body frd\n delta_a : float [percentage]\n The fraction of maximum accelerator\n delta_bl : float [percentage]\n The fraction of maximum left brake\n delta_br : float [percentage]\n The fraction of maximum right brake\n delta_w : float [percentage]\n The fraction of weight shift, from -1 (left) to +1 (right)\n rho_air : float [kg/m^3], optional\n Air density\n v_W2e : ndarray of float, shape (3,) or (K,3) [m/s], optional\n The wind relative to the earth, in body frd coordinates. If it is\n a (3,) array then the wind is uniform at every control point. If\n it is a (K,3) array then it is the vectors for each control point.\n reference_solution : dictionary, optional\n FIXME: docstring. See `Phillips.__call__`\n\n Returns\n -------\n a_RM2e : array of float, shape (3,) [m/s^2]\n Translational acceleration of `RM` in body frd coordinates.\n alpha_b2e : array of float, shape (3,) [rad/s^2]\n Angular acceleration of the body with respect to Earth as the time\n derivative of angular velocity taken with respect to the body\n frame, expressed in body frd coordinates\n :math:`\\left( ^b \\dot{\\omega}_{b/e}^b \\right)`.\n alpha_p2e : array of float, shape (3,) [rad/s^2]\n Angular acceleration of the payload with respect to Earth as the\n time derivative of angular velocity taken with respect to the\n payload frame, expressed in payload frd coordinates\n :math:`\\left( ^p \\dot{\\omega}_{p/e}^p \\right)`.\n solution : dictionary\n FIXME: docstring. See `Phillips.__call__`\n \"\"\"\n r_CP2RM = self.r_CP2RM(Theta_p2b, delta_a, delta_w)\n v_W2e = np.asfarray(v_W2e)\n if v_W2e.ndim > 1 and v_W2e.shape[0] != r_CP2RM.shape[0]:\n raise ValueError(\n \"Number of distinct wind vectors in v_W2e do not match the \"\n \"number of control points\",\n )\n v_W2e = np.broadcast_to(v_W2e, r_CP2RM.shape)\n v_RM2e = np.asfarray(v_RM2e)\n if v_RM2e.shape != (3,):\n raise ValueError(\"v_RM2e.shape != (3,)\")\n\n C_p2b = orientation.euler_to_dcm(Theta_p2b)\n C_b2p = C_p2b.T\n omega_p2b = C_b2p @ omega_p2e - omega_b2e # In body frd\n omega_b2p = -omega_p2b\n\n # -------------------------------------------------------------------\n # Compute the inertia properties of the body and payload about `RM`.\n r_RM2LE = self.wing.r_RM2LE(delta_a)\n wmp = self.wing.mass_properties(rho_air, r_RM2LE) # R = RM\n m_b = wmp[\"m_b\"]\n J_b2RM = wmp[\"J_b2R\"]\n r_B2RM = wmp[\"r_B2R\"]\n\n pmp = self.payload.mass_properties(delta_w, [0, 0, 0]) # R = RM\n m_p = pmp[\"m_p\"]\n J_p2RM = pmp[\"J_p2R\"]\n r_P2RM = pmp[\"r_P2R\"]\n\n # -------------------------------------------------------------------\n # Compute the relative wind vectors for each control point. Body\n # vectors are in body frd, payload vectors are in payload frd.\n v_B2e = v_RM2e + cross3(omega_b2e, r_B2RM)\n v_P2e = C_p2b @ v_RM2e + cross3(omega_p2e, r_P2RM)\n\n # FIXME: \"magic\" indexing established by `self.r_CP2RM`\n r_CP2RM_b = r_CP2RM[:-1]\n r_CP2RM_p = C_p2b @ r_CP2RM[-1]\n\n v_CP2e_b = v_B2e + cross3(omega_b2e, r_CP2RM_b - r_B2RM)\n v_CP2e_p = v_P2e + cross3(omega_p2e, r_CP2RM_p - r_P2RM)\n\n v_W2CP_b = v_W2e[:-1] - v_CP2e_b\n v_W2CP_p = C_p2b @ v_W2e[-1] - v_CP2e_p\n\n # -------------------------------------------------------------------\n # Forces and moments of the wing in body frd\n try:\n f_b, g_b2RM, ref = self.wing.resultant_force(\n delta_a,\n delta_bl,\n delta_br,\n v_W2CP_b,\n rho_air,\n g,\n r_RM2LE,\n wmp,\n reference_solution,\n )\n except foil_aerodynamics.ConvergenceError:\n # Maybe it can't recover once Gamma is jacked?\n print(\"\\nBonk! Retrying with the default reference solution\")\n f_b, g_b2RM, ref = self.wing.resultant_force(\n delta_a,\n delta_bl,\n delta_br,\n v_W2CP_b,\n rho_air,\n g,\n r_RM2LE,\n wmp,\n )\n\n f_p, g_p2RM = self.payload.resultant_force( # In payload frd\n delta_w=delta_w,\n v_W2h=v_W2CP_p,\n rho_air=rho_air,\n g=C_p2b @ g,\n r_R2RM=[0, 0, 0],\n mp=pmp,\n )\n\n # Moment at the connection point `RM` modeled as a spring+damper system\n g_RM = Theta_p2b * self._kappa_RM + omega_p2b * self._kappa_RM_dot\n\n # ------------------------------------------------------------------\n # Build a system of equations by equating the time derivatives of the\n # translation and angular momentum (with respect to the Earth) of the\n # body and payload to the forces and moments on the body and payload.\n #\n # The four unknown vectors are the time derivatives of `v_RM2e`,\n # `omega_b2e` (in body frd), `omega_p2e` (in payload frd), and the\n # internal force on the risers, `F_RM` (in body frd).\n\n # fmt: off\n\n # Real mass momentums\n p_b2e = m_b * v_B2e # Linear\n p_p2e = m_p * v_P2e\n h_b2RM = m_b * cross3(r_B2RM, v_RM2e) + J_b2RM @ omega_b2e # Angular\n h_p2RM = m_p * cross3(r_P2RM, C_p2b @ v_RM2e) + J_p2RM @ omega_p2e\n\n # Build the system matrices for the real mass. A1 and A2 are the forces\n # and moments on the body, A3 and A4 are the forces and moments on the\n # payload. The unknowns are [a_RM2e^b, alpha_b2e^b, alpha_p2e^p, F_RM^b].\n I3, Z3 = np.eye(3), np.zeros((3, 3))\n A1 = [m_b * I3, -m_b * crossmat(r_B2RM), Z3, I3]\n A2 = [m_b * crossmat(r_B2RM), J_b2RM, Z3, Z3]\n A3 = [m_p * C_p2b, Z3, -m_p * crossmat(r_P2RM), -C_p2b]\n A4 = [m_p * crossmat(r_P2RM) @ C_p2b, Z3, J_p2RM, Z3]\n A = np.block([A1, A2, A3, A4])\n\n B1 = f_b - cross3(omega_b2e, p_b2e)\n B2 = ( # ref: Hughes Eq:13, p58\n g_b2RM\n - g_RM\n - cross3(v_RM2e, p_b2e)\n - cross3(omega_b2e, h_b2RM)\n )\n B3 = (\n f_p\n - m_p * C_p2b @ cross3(omega_b2p, v_RM2e)\n - cross3(omega_p2e, p_p2e)\n )\n B4 = (\n g_p2RM\n + C_p2b @ g_RM\n - cross3(C_p2b @ v_RM2e, p_p2e)\n - m_p * cross3(r_P2RM, C_p2b @ cross3(omega_b2p, v_RM2e))\n - cross3(omega_p2e, h_p2RM)\n )\n\n if self.use_apparent_mass:\n amp = self.wing.apparent_mass_properties(\n rho_air,\n r_RM2LE,\n v_RM2e,\n omega_b2e,\n )\n A[:6, :6] += amp[\"A_a2R\"] # Incorporate the apparent inertia\n B1 += ( # Apparent inertial force (Barrows Eq:61)\n -cross3(omega_b2e, amp[\"p_a2e\"])\n )\n B2 += ( # Apparent inertial moment (Barrows Eq:64)\n -cross3(v_RM2e, amp[\"p_a2e\"])\n - cross3(omega_b2e, amp[\"h_a2R\"])\n + cross3(v_RM2e, amp[\"M_a\"] @ v_RM2e) # Remove the steady-state term\n )\n\n # fmt: on\n\n B = np.r_[B1, B2, B3, B4]\n x = np.linalg.solve(A, B)\n a_RM2e = x[:3] # In frame F_b\n alpha_b2e = x[3:6] # In frames F_b and F_e\n alpha_p2e = x[6:9] # In frames F_p and F_e\n F_RM = x[9:] # For debugging\n return a_RM2e, alpha_b2e, alpha_p2e, ref\n\n def equilibrium_state(\n self,\n delta_a: float = 0,\n delta_b: float = 0,\n rho_air: float = 1.225,\n alpha_0: float | None = None,\n theta_0: float = 0,\n v_0: float = 10,\n reference_solution=None,\n ):\n \"\"\"\n Compute the equilibrium glider state for given inputs.\n\n Assumes that the wing is symmetric about the xz-plane.\n\n Parameters\n ----------\n delta_a : float, optional\n Fraction of accelerator application, where `0 <= delta_a <= 1`\n delta_b : float, optional\n Fraction of symmetric brake application, where `0 <= delta_b <= 1`\n rho_air : float [kg/m^3], optional\n Air density\n alpha_0 : float [rad], optional\n An initial proposal for the body angle of attack. If no value is\n set, the wing equilibrium alpha will be used.\n theta_0 : float [rad], optional\n An initial proposal for the body pitch angle.\n v_0 : float [m/s], optional\n An initial proposal for the body airspeed.\n reference_solution : dictionary, optional\n FIXME: docstring. See `Phillips.__call__`\n\n Returns\n -------\n dictionary\n alpha_b : float [radians]\n Wing angle of attack\n gamma_b : float [radians]\n Wing glide angle\n glide_ratio : float\n Units of ground distance traveled per unit of altitude lost\n Theta_b2e : array of float, shape (3,) [radians]\n Equilibrium orientation of the body relative to Earth as a set\n of Tait-Bryan yaw-pitch-role angles.\n v_RM2e : float [m/s]\n Steady-state velocity of the riser midpoint in body coordinates\n solution : dictionary\n FIXME: docstring. See `Phillips.__call__`\n \"\"\"\n if alpha_0 is None:\n alpha_0 = self.wing.equilibrium_alpha(\n delta_a=delta_a,\n delta_b=delta_b,\n v_mag=v_0,\n rho_air=rho_air,\n reference_solution=reference_solution,\n )\n\n _state = {\n \"delta_a\": delta_a,\n \"delta_bl\": delta_b,\n \"delta_br\": delta_b,\n \"omega_b2e\": np.zeros(3),\n \"omega_p2e\": np.zeros(3),\n \"rho_air\": rho_air,\n \"reference_solution\": reference_solution,\n }\n\n def _helper(x, state):\n v_x, v_z, theta_b2e, theta_p2e = x\n theta_p2b = theta_p2e - theta_b2e\n a_RM2e, alpha_b2e, alpha_p2e, ref = self.accelerations(\n v_RM2e=[v_x, 0, v_z],\n g=9.8 * np.array([-np.sin(theta_b2e), 0, np.cos(theta_b2e)]),\n Theta_p2b=[0, theta_p2b, 0],\n **state,\n )\n _state[\"reference_solution\"] = ref\n return (a_RM2e[0], a_RM2e[2], alpha_b2e[1], alpha_p2e[1])\n\n v_x_0 = v_0 * np.cos(alpha_0)\n v_z_0 = v_0 * np.sin(alpha_0)\n theta_p2e_0 = 0 # Assume the payload is hanging straight down\n x0 = np.array([v_x_0, v_z_0, theta_0, theta_p2e_0])\n res = scipy.optimize.root(_helper, x0, _state)\n v_RM2e = np.array([res.x[0], 0, res.x[1]])\n alpha_eq = np.arctan2(v_RM2e[2], v_RM2e[0])\n theta_b2e = res.x[2]\n theta_p2b = res.x[3] - res.x[2]\n gamma_eq = alpha_eq - theta_b2e\n\n equilibrium = {\n \"alpha_b\": alpha_eq,\n \"gamma_b\": gamma_eq,\n \"glide_ratio\": 1 / np.tan(gamma_eq),\n \"Theta_b2e\": np.array([0, theta_b2e, 0]),\n \"Theta_p2b\": np.array([0, theta_p2b, 0]),\n \"v_RM2e\": v_RM2e,\n \"reference_solution\": _state[\"reference_solution\"],\n }\n\n return equilibrium\n\n\nclass ParagliderSystemDynamics9b(ParagliderSystemDynamics9a):\n \"\"\"\n A 9 degrees-of-freedom paraglider model, allowing rotation between the wing\n and the harness, with the connection modelled by spring-damper dynamics.\n\n This model uses the body center of mass `B` as the reference point for the\n angular momentum of the body (the wing system) and the payload center of\n mass `P` for the angular momentum of the payload (the harness and pilot).\n\n This model does not support apparent mass. (Because it uses `B` as the\n reference point for the body dynamics, the system of equations for apparent\n mass would be in terms of `a_B2e`, which makes the equations involving the\n payload dynamics significantly messier.) Its purpose is to check for\n implementation errors in other models involving the real mass only.\n\n Parameters\n ----------\n wing : ParagliderWing\n payload : ParagliderHarness\n The harness model includes the mass of the pilot.\n kappa_RM : array of float, shape (3,), optional\n Spring-damper coefficients for Theta_p2b (force as a linear function\n of angular displacement).\n kappa_RM_dot : array of float, shape (3,), optional\n Spring-damper coefficients for the derivative of Theta_p2b\n \"\"\"\n\n def __init__(\n self,\n wing: ParagliderWing,\n payload: ParagliderHarness,\n kappa_RM=(0, 0, 0),\n kappa_RM_dot=(0, 0, 0),\n ) -> None:\n self.wing = wing\n self.payload = payload\n self._kappa_RM = np.asfarray(kappa_RM[:])\n self._kappa_RM_dot = np.asfarray(kappa_RM_dot[:])\n\n def accelerations(\n self,\n v_RM2e,\n omega_b2e,\n omega_p2e,\n Theta_p2b,\n g,\n delta_a: float = 0,\n delta_bl: float = 0,\n delta_br: float = 0,\n delta_w: float = 0,\n rho_air: float = 1.225,\n v_W2e=(0, 0, 0),\n reference_solution: dict | None = None,\n ):\n r\"\"\"\n Compute the translational and angular accelerations about the center of mass.\n\n Parameters\n ----------\n v_RM2e : array of float, shape (3,) [m/s]\n Translational velocity of `RM` in body frd coordinates, where `RM` is\n the midpoint between the two riser connection points.\n omega_b2e : array of float, shape (3,) [rad/s]\n Angular velocity of the body, in body frd coordinates.\n omega_p2e : array of float, shape (3,) [rad/s]\n Angular velocity of the payload, in payload frd coordinates.\n Theta_p2b : array of float, shape (3,) [radians]\n The [phi, theta, gamma] of a yaw-pitch-roll sequence that encodes\n the relative orientation of the payload with respect to the body.\n g : array of float, shape (3,) [m/s^s]\n The gravity vector in body frd\n delta_a : float [percentage]\n The fraction of maximum accelerator\n delta_bl : float [percentage]\n The fraction of maximum left brake\n delta_br : float [percentage]\n The fraction of maximum right brake\n delta_w : float [percentage]\n The fraction of weight shift, from -1 (left) to +1 (right)\n rho_air : float [kg/m^3], optional\n Air density\n v_W2e : ndarray of float, shape (3,) or (K,3) [m/s], optional\n The wind relative to the earth, in body frd coordinates. If it is\n a (3,) array then the wind is uniform at every control point. If\n it is a (K,3) array then it is the vectors for each control point.\n reference_solution : dictionary, optional\n FIXME: docstring. See `Phillips.__call__`\n\n Returns\n -------\n a_RM2e : array of float, shape (3,) [m/s^2]\n Translational acceleration of `RM` in body frd coordinates.\n alpha_b2e : array of float, shape (3,) [rad/s^2]\n Angular acceleration of the body with respect to Earth as the time\n derivative of angular velocity taken with respect to the body\n frame, expressed in body frd coordinates\n :math:`\\left( ^b \\dot{\\omega}_{b/e}^b \\right)`.\n alpha_p2e : array of float, shape (3,) [rad/s^2]\n Angular acceleration of the payload with respect to Earth as the\n time derivative of angular velocity taken with respect to the\n payload frame, expressed in payload frd coordinates\n :math:`\\left( ^p \\dot{\\omega}_{p/e}^p \\right)`.\n solution : dictionary\n FIXME: docstring. See `Phillips.__call__`\n \"\"\"\n r_CP2RM = self.r_CP2RM(Theta_p2b, delta_a, delta_w)\n v_W2e = np.asfarray(v_W2e)\n if v_W2e.ndim > 1 and v_W2e.shape[0] != r_CP2RM.shape[0]:\n raise ValueError(\n \"Number of distinct wind vectors in v_W2e do not match the \"\n \"number of control points\",\n )\n v_W2e = np.broadcast_to(v_W2e, r_CP2RM.shape)\n v_RM2e = np.asfarray(v_RM2e)\n if v_RM2e.shape != (3,):\n raise ValueError(\"v_RM2e.shape != (3,)\")\n\n C_p2b = orientation.euler_to_dcm(Theta_p2b)\n C_b2p = C_p2b.T\n\n # -------------------------------------------------------------------\n # Compute the inertia properties of the body and payload with respect\n # to their centers of mass (`B` and `P`). This is wasteful since it\n # calls `mass_properties` twice just to get the centers of mass, but\n # it's simple and this model is just for validation anyway.\n r_RM2LE = self.wing.r_RM2LE(delta_a)\n wmp0 = self.wing.mass_properties(rho_air, [0, 0, 0]) # R = LE\n wmp = self.wing.mass_properties(rho_air, wmp0[\"r_B2R\"]) # R = B\n m_b = wmp[\"m_b\"]\n J_b2B = wmp[\"J_b2R\"]\n r_B2RM = wmp0[\"r_B2R\"] - r_RM2LE\n r_B2LE = r_B2RM + r_RM2LE\n\n pmp0 = self.payload.mass_properties(delta_w, [0, 0, 0]) # R = RM\n pmp = self.payload.mass_properties(delta_w, pmp0[\"r_P2R\"]) # R = P\n m_p = pmp[\"m_p\"]\n J_p2P = pmp[\"J_p2R\"]\n r_P2RM = pmp0[\"r_P2R\"]\n\n # -------------------------------------------------------------------\n # Compute the relative wind vectors for each control point. Body\n # vectors are in body frd, payload vectors are in payload frd.\n v_B2e = v_RM2e + cross3(omega_b2e, r_B2RM)\n v_P2e = C_p2b @ v_RM2e + cross3(omega_p2e, r_P2RM)\n\n # FIXME: \"magic\" indexing established by `self.r_CP2RM`\n r_CP2B_b = r_CP2RM[:-1] - r_B2RM\n r_CP2P_p = C_p2b @ r_CP2RM[-1] - r_P2RM\n\n v_CP2e_b = v_B2e + cross3(omega_b2e, r_CP2B_b)\n v_CP2e_p = v_P2e + cross3(omega_p2e, r_CP2P_p)\n\n v_W2CP_b = v_W2e[:-1] - v_CP2e_b\n v_W2CP_p = C_p2b @ v_W2e[-1] - v_CP2e_p\n\n # -------------------------------------------------------------------\n # Forces and moments of the wing in body frd\n try:\n f_b, g_b2B, ref = self.wing.resultant_force(\n delta_a,\n delta_bl,\n delta_br,\n v_W2CP_b,\n rho_air,\n g,\n r_B2LE,\n wmp,\n reference_solution,\n )\n except foil_aerodynamics.ConvergenceError:\n # Maybe it can't recover once Gamma is jacked?\n print(\"\\nBonk! Retrying with the default reference solution\")\n f_b, g_b2B, ref = self.wing.resultant_force(\n delta_a,\n delta_bl,\n delta_br,\n v_W2CP_b,\n rho_air,\n g,\n r_B2LE,\n wmp,\n )\n\n f_p, g_p2P = self.payload.resultant_force( # In payload frd\n delta_w=delta_w,\n v_W2h=v_W2CP_p,\n rho_air=rho_air,\n g=C_p2b @ g,\n r_R2RM=pmp[\"r_P2RM\"],\n mp=pmp,\n )\n\n # Moment at the connection point `RM` modeled as a spring+damper system\n omega_p2b = C_b2p @ omega_p2e - omega_b2e\n g_RM = Theta_p2b * self._kappa_RM + omega_p2b * self._kappa_RM_dot\n\n # ------------------------------------------------------------------\n # Build a system of equations by equating the time derivatives of the\n # translation and angular momentum (with respect to the Earth) of the\n # body and payload to the forces and moments on the body and payload.\n #\n # The four unknown vectors are the time derivatives of `v_RM2e`,\n # `omega_b2e` (in body frd), `omega_p2e` (in payload frd), and the\n # internal force on the risers, `F_RM` (in body frd).\n\n # fmt: off\n\n I3, Z3 = np.eye(3), np.zeros((3, 3))\n A1 = [m_b * I3, -m_b * crossmat(r_B2RM), Z3, I3]\n A2 = [Z3, J_b2B, Z3, -crossmat(r_B2RM)]\n A3 = [m_p * C_p2b, Z3, -m_p * crossmat(r_P2RM), -C_p2b]\n A4 = [Z3, Z3, J_p2P, crossmat(r_P2RM) @ C_p2b]\n A = np.block([A1, A2, A3, A4])\n B1 = (\n f_b\n - m_b * cross3(omega_b2e, v_RM2e)\n - m_b * cross3(omega_b2e, cross3(omega_b2e, r_B2RM))\n )\n B2 = ( # ref: Hughes Eq:13, p58\n g_b2B\n - g_RM\n - cross3(omega_b2e, J_b2B @ omega_b2e)\n )\n B3 = (\n f_p\n - m_p * C_p2b @ cross3(omega_b2e, v_RM2e)\n - m_p * cross3(omega_p2e, cross3(omega_p2e, r_P2RM))\n )\n B4 = g_p2P + C_p2b @ g_RM - cross3(omega_p2e, J_p2P @ omega_p2e)\n\n # fmt: on\n\n B = np.r_[B1, B2, B3, B4]\n x = np.linalg.solve(A, B)\n a_RM2e = x[:3] # In frame F_b\n alpha_b2e = x[3:6] # In frames F_b and F_e\n alpha_p2e = x[6:9] # In frames F_p and F_e\n F_RM = x[9:] # For debugging\n return a_RM2e, alpha_b2e, alpha_p2e, ref\n\n\nclass ParagliderSystemDynamics9c(ParagliderSystemDynamics9a):\n r\"\"\"\n A 9 degrees-of-freedom paraglider model, allowing rotation between the wing\n and the harness, with the connection modelled by spring-damper dynamics.\n\n Similar to ParagliderSystemDynamics9a, this version uses the riser midpoint\n `RM` as the reference point for both the body and the payload. Unlike\n ParagliderSystemDynamics9a, this model computes \\dot{omega_p2b} instead of\n \\dot{omega_p2e} and converts. Also, note that it computes everything in\n body frd and converts omega_p2e back to payload frd at the very end.\n\n FIXME: although 9a and 9b agree, this model produces slightly different\n answers, which might be worth looking into.\n\n Parameters\n ----------\n wing : ParagliderWing\n payload : ParagliderHarness\n The harness model includes the mass of the pilot.\n kappa_RM : array of float, shape (3,), optional\n Spring-damper coefficients for Theta_p2b (force as a linear function\n of angular displacement).\n kappa_RM_dot : array of float, shape (3,), optional\n Spring-damper coefficients for the derivative of Theta_p2b\n use_apparent_mass : bool, optional\n Whether to estimate the effects of apparent inertia. Default: True\n \"\"\"\n\n def accelerations(\n self,\n v_RM2e,\n omega_b2e,\n omega_p2e,\n Theta_p2b,\n g,\n delta_a: float = 0,\n delta_bl: float = 0,\n delta_br: float = 0,\n delta_w: float = 0,\n rho_air: float = 1.225,\n v_W2e=(0, 0, 0),\n reference_solution: dict | None = None,\n ):\n r\"\"\"\n Compute the translational and angular accelerations about the center of mass.\n\n Parameters\n ----------\n v_RM2e : array of float, shape (3,) [m/s]\n Translational velocity of `RM` in body frd coordinates, where `RM`\n is the midpoint between the two riser connection points.\n omega_b2e : array of float, shape (3,) [rad/s]\n Angular velocity of the body, in body frd coordinates.\n omega_p2e : array of float, shape (3,) [rad/s]\n Angular velocity of the payload, in payload frd coordinates.\n Theta_p2b : array of float, shape (3,) [radians]\n The [phi, theta, gamma] of a yaw-pitch-roll sequence that encodes\n the relative orientation of the payload with respect to the body.\n g : array of float, shape (3,) [m/s^s]\n The gravity vector in body frd\n delta_a : float [percentage]\n The fraction of maximum accelerator\n delta_bl : float [percentage]\n The fraction of maximum left brake\n delta_br : float [percentage]\n The fraction of maximum right brake\n delta_w : float [percentage]\n The fraction of weight shift, from -1 (left) to +1 (right)\n rho_air : float [kg/m^3], optional\n Air density\n v_W2e : ndarray of float, shape (3,) or (K,3) [m/s], optional\n The wind relative to the earth, in body frd coordinates. If it is\n a (3,) array then the wind is uniform at every control point. If\n it is a (K,3) array then it is the vectors for each control point.\n reference_solution : dictionary, optional\n FIXME: docstring. See `Phillips.__call__`\n\n Returns\n -------\n a_RM2e : array of float, shape (3,) [m/s^2]\n Translational acceleration of `RM` in body frd coordinates.\n alpha_b2e : array of float, shape (3,) [rad/s^2]\n Angular acceleration of the body with respect to Earth as the time\n derivative of angular velocity taken with respect to the body\n frame, expressed in body frd coordinates\n :math:`\\left( ^b \\dot{\\omega}_{b/e}^b \\right)`.\n alpha_p2e : array of float, shape (3,) [rad/s^2]\n Angular acceleration of the payload with respect to Earth as the\n time derivative of angular velocity taken with respect to the\n payload frame, expressed in payload frd coordinates\n :math:`\\left( ^p \\dot{\\omega}_{p/e}^p \\right)`.\n solution : dictionary\n FIXME: docstring. See `Phillips.__call__`\n \"\"\"\n r_CP2RM = self.r_CP2RM(Theta_p2b, delta_a, delta_w)\n v_W2e = np.asfarray(v_W2e)\n if v_W2e.ndim > 1 and v_W2e.shape[0] != r_CP2RM.shape[0]:\n raise ValueError(\n \"Number of distinct wind vectors in v_W2e do not match the \"\n \"number of control points\",\n )\n v_W2e = np.broadcast_to(v_W2e, r_CP2RM.shape)\n v_RM2e = np.asfarray(v_RM2e)\n if v_RM2e.shape != (3,):\n raise ValueError(\"v_RM2e.shape != (3,)\")\n\n C_p2b = orientation.euler_to_dcm(Theta_p2b)\n C_b2p = C_p2b.T\n omega_p2e = C_b2p @ omega_p2e # Dynamics9a uses `p`, this model uses `b`\n\n # -------------------------------------------------------------------\n # Compute the inertia properties of the body and payload.\n r_RM2LE = self.wing.r_RM2LE(delta_a)\n wmp = self.wing.mass_properties(rho_air, r_RM2LE) # R = RM\n m_b = wmp[\"m_s\"] + wmp[\"m_air\"]\n J_b2RM = wmp[\"J_b2R\"]\n r_B2RM = wmp[\"r_B2R\"]\n\n pmp = self.payload.mass_properties(delta_w, [0, 0, 0]) # R = RM\n m_p = pmp[\"m_p\"]\n J_p2RM = C_b2p @ pmp[\"J_p2R\"] @ C_p2b # In body frd\n r_P2RM = C_b2p @ pmp[\"r_P2R\"] # In body frd\n\n # -------------------------------------------------------------------\n # Compute the relative wind vectors for each control point. All vectors\n # are in body frd.\n omega_p2b = omega_p2e - omega_b2e\n omega_b2p = -omega_p2b\n v_B2e = v_RM2e + cross3(omega_b2e, r_B2RM)\n v_P2e = v_RM2e + cross3(omega_p2e, r_P2RM)\n\n # FIXME: \"magic\" indexing established by `self.r_CP2RM`\n r_CP2RM_b = r_CP2RM[:-1]\n r_CP2RM_p = r_CP2RM[-1]\n\n v_CP2e_b = v_B2e + cross3(omega_b2e, r_CP2RM_b - r_B2RM)\n v_CP2e_p = v_P2e + cross3(omega_p2e, r_CP2RM_p - r_P2RM)\n\n v_W2CP_b = v_W2e[:-1] - v_CP2e_b\n v_W2CP_p = v_W2e[-1] - v_CP2e_p\n\n # -------------------------------------------------------------------\n # Forces and moments of the wing in body frd\n try:\n f_b, g_b2RM, ref = self.wing.resultant_force(\n delta_a,\n delta_bl,\n delta_br,\n v_W2CP_b,\n rho_air,\n g,\n r_RM2LE,\n wmp,\n reference_solution,\n )\n except foil_aerodynamics.ConvergenceError:\n # Maybe it can't recover once Gamma is jacked?\n print(\"\\nBonk! Retrying with the default reference solution\")\n f_b, g_b2RM, ref = self.wing.resultant_force(\n delta_a,\n delta_bl,\n delta_br,\n v_W2CP_b,\n rho_air,\n g,\n r_RM2LE,\n wmp,\n )\n\n f_p, g_p2RM = self.payload.resultant_force( # In payload frd\n delta_w=delta_w,\n v_W2h=C_p2b @ v_W2CP_p,\n rho_air=rho_air,\n g=C_p2b @ g,\n r_R2RM=[0, 0, 0],\n mp=pmp,\n )\n\n # Moment at the connection point `RM` modeled as a spring+damper system\n g_RM = Theta_p2b * self._kappa_RM + omega_p2b * self._kappa_RM_dot\n\n # ------------------------------------------------------------------\n # Build a system of equations by equating the time derivatives of the\n # translation and angular momentum (with respect to the Earth) of the\n # body and payload to the forces and moments on the body and payload.\n #\n # The four unknown vectors are the time derivatives of `v_RM2e^b`,\n # `omega_b2e^b`, `omega_p2e^p`, and the internal force on the risers,\n # `F_RM^b`. All derivatives are from the body frame.\n\n # fmt: off\n\n # Real mass momentums\n p_b2e = m_b * v_B2e # Linear\n p_p2e = m_p * v_P2e\n h_b2RM = m_b * cross3(r_B2RM, v_RM2e) + J_b2RM @ omega_b2e # Angular\n h_p2RM = m_p * cross3(r_P2RM, v_RM2e) + J_p2RM @ omega_p2e\n\n I3, Z3 = np.eye(3), np.zeros((3, 3))\n A1 = [m_b * I3, -m_b * crossmat(r_B2RM), Z3, I3]\n A2 = [m_b * crossmat(r_B2RM), J_b2RM, Z3, Z3]\n A3 = [m_p * I3, -m_p * crossmat(r_P2RM), -m_p * crossmat(r_P2RM), -I3]\n A4 = [m_p * crossmat(r_P2RM), J_p2RM, J_p2RM, Z3]\n A = np.block([A1, A2, A3, A4])\n\n B1 = f_b - cross3(omega_b2e, p_b2e)\n B2 = ( # ref: Hughes Eq:13, p58\n g_b2RM\n - g_RM\n - cross3(v_RM2e, p_b2e)\n - cross3(omega_b2e, h_b2RM)\n )\n B3 = (\n C_b2p @ f_p\n - m_p * cross3(omega_b2p, v_RM2e)\n - m_p * cross3(cross3(omega_b2p, omega_b2e), r_P2RM)\n # - m_p * cross3(cross3(omega_b2p, omega_p2e), r_P2RM) # equivalent\n - cross3(omega_p2e, p_p2e)\n )\n B4 = (\n C_b2p @ g_p2RM\n + g_RM\n - cross3(v_RM2e, p_p2e)\n - m_p * cross3(r_P2RM, cross3(omega_b2p, v_RM2e))\n - cross3(omega_b2p, J_p2RM @ omega_p2e)\n - cross3(omega_p2e, h_p2RM)\n )\n\n if self.use_apparent_mass:\n amp = self.wing.apparent_mass_properties(\n rho_air,\n r_RM2LE,\n v_RM2e,\n omega_b2e,\n )\n A[:6, :6] += amp[\"A_a2R\"] # Incorporate the apparent inertia\n B1 += ( # Apparent inertial force (Barrows Eq:61)\n -cross3(omega_b2e, amp[\"p_a2e\"])\n )\n B2 += ( # Apparent inertial moment (Barrows Eq:64)\n -cross3(v_RM2e, amp[\"p_a2e\"])\n - cross3(omega_b2e, amp[\"h_a2R\"])\n + cross3(v_RM2e, amp[\"M_a\"] @ v_RM2e) # Remove the steady-state term\n )\n\n # fmt: on\n\n B = np.r_[B1, B2, B3, B4]\n x = np.linalg.solve(A, B)\n a_RM2e = x[:3] # In frame F_b\n alpha_b2e = x[3:6] # In frames F_b and F_e\n alpha_p2b = x[6:9] # In frames F_b and F_p\n F_RM = x[9:] # For debugging\n alpha_p2e = alpha_p2b + alpha_b2e + cross3(omega_b2e, omega_p2b)\n alpha_p2e = C_p2b @ alpha_p2e # In frames F_p and F_e\n return a_RM2e, alpha_b2e, alpha_p2e, ref\n", "meta": {"hexsha": "3c5b34418feb1c4d6fc5abc589ae2ae77a39d83d", "size": 63277, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/pfh/glidersim/paraglider.py", "max_stars_repo_name": "pfheatwole/glidersim", "max_stars_repo_head_hexsha": "12cca5fdd39438d0effe549c320a602b27a96e82", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pfh/glidersim/paraglider.py", "max_issues_repo_name": "pfheatwole/glidersim", "max_issues_repo_head_hexsha": "12cca5fdd39438d0effe549c320a602b27a96e82", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pfh/glidersim/paraglider.py", "max_forks_repo_name": "pfheatwole/glidersim", "max_forks_repo_head_hexsha": "12cca5fdd39438d0effe549c320a602b27a96e82", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2293862368, "max_line_length": 85, "alphanum_fraction": 0.5558575786, "include": true, "reason": "import numpy,import scipy", "num_tokens": 17349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.24508500761839527, "lm_q1q2_score": 0.1273268871485475}} {"text": "# -*- coding: utf-8 -*-\n\"\"\"\nColour Checker Chromaticity Coordinates\n=======================================\n\nDefines *Colour Checker* chromaticity coordinates in *CIE xyY* colourspace.\n\nEach *Colour Checker* data is in the form of a list of an :class:`OrderedDict`\nclass instance of 24 samples as follows::\n\n {'name': 'xyY', ..., 'name': 'xyY'}\n\nThe following *Colour Checkers* are available:\n\n- :attr:`colour.characterisation.datasets.colour_checkers.\\\nchromaticity_coordinates.COLORCHECKER_1976`: *Colour Checker* developed by\n *McCamy et al.* at Macbeth, a Division of Kollmorgen.\n- :attr:`colour.characterisation.datasets.colour_checkers.\\\nchromaticity_coordinates.COLORCHECKER_2005`: Reference data from\n *GretagMacbeth* published in 2005.\n- :attr:`colour.characterisation.datasets.colour_checkers.\\\nchromaticity_coordinates.BABELCOLOR_AVERAGE`: Average data derived from\n measurements of 30 *Colour Checker* charts.\n- :attr:`colour.characterisation.datasets.colour_checkers.\\\nchromaticity_coordinates.COLORCHECKER24_BEFORE_NOV2014`: Reference data from\n *X-Rite* published in 2015 and matching the data from *GretagMacbeth*\n published in 2005.\n- :attr:`colour.characterisation.datasets.colour_checkers.\\\nchromaticity_coordinates.COLORCHECKER24_AFTER_NOV2014`: Reference data from\n *X-Rite* published in 2015 and matching the *Colour Checker* edition after\n November 2014.\n\nReferences\n----------\n- :cite:`BabelColor2012b` : BabelColor. (2012). The ColorChecker (since\n 1976!). Retrieved September 26, 2014, from\n http://www.babelcolor.com/main_level/ColorChecker.htm\n- :cite:`BabelColor2012c` : BabelColor. (2012). ColorChecker RGB and\n spectra.\n http://www.babelcolor.com/download/ColorChecker_RGB_and_spectra.xls\n- :cite:`X-Rite2016` : X-Rite. (2016). New color specifications for\n ColorChecker SG and Classic Charts. Retrieved October 29, 2018, from\n http://xritephoto.com/ph_product_overview.aspx?ID=938&Action=Support&\\\nSupportID=5884#\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport numpy as np\nfrom collections import OrderedDict, namedtuple\n\nfrom colour.colorimetry import ILLUMINANTS\nfrom colour.models import Lab_to_XYZ, XYZ_to_xyY\nfrom colour.utilities import CaseInsensitiveMapping\n\n__author__ = 'Colour Developers, Danny Pascale '\n__copyright__ = 'Copyright (C) 2013-2020 - Colour Developers'\n__copyright__ += ', '\n__copyright__ += (\n 'BabelColor ColorChecker data: Copyright (C) 2004-2012 Danny Pascale '\n '(www.babelcolor.com); used by permission.')\n__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-developers@colour-science.org'\n__status__ = 'Production'\n\n__all__ = [\n 'ColourChecker', 'COLORCHECKER_CLASSIC_SAMPLE_LABELS',\n 'COLORCHECKER_1976_DATA', 'COLORCHECKER_1976_ILLUMINANT',\n 'COLORCHECKER_1976', 'COLORCHECKER_2005_DATA',\n 'COLORCHECKER_2005_ILLUMINANT', 'COLORCHECKER_2005',\n 'BABELCOLOR_AVERAGE_DATA', 'BABELCOLOR_AVERAGE_ILLUMINANT',\n 'BABELCOLOR_AVERAGE', 'COLORCHECKER24_BEFORE_NOV2014_LAB_DATA',\n 'COLORCHECKER24_BEFORE_NOV2014_DATA',\n 'COLORCHECKER24_BEFORE_NOV2014_ILLUMINANT',\n 'COLORCHECKER24_BEFORE_NOV2014', 'COLORCHECKER24_AFTER_NOV2014_LAB_DATA',\n 'COLORCHECKER24_AFTER_NOV2014_DATA',\n 'COLORCHECKER24_AFTER_NOV2014_ILLUMINANT', 'COLORCHECKER24_AFTER_NOV2014',\n 'COLOURCHECKERS'\n]\n\n\nclass ColourChecker(\n namedtuple('ColourChecker', ('name', 'data', 'illuminant'))):\n \"\"\"\n *Colour Checker* data.\n\n Parameters\n ----------\n name : unicode\n *Colour Checker* name.\n data : OrderedDict\n chromaticity coordinates in *CIE xyY* colourspace.\n illuminant : array_like\n *Colour Checker* illuminant chromaticity coordinates.\n \"\"\"\n\n\nCOLORCHECKER_CLASSIC_SAMPLE_LABELS = (\n 'dark skin',\n 'light skin',\n 'blue sky',\n 'foliage',\n 'blue flower',\n 'bluish green',\n 'orange',\n 'purplish blue',\n 'moderate red',\n 'purple',\n 'yellow green',\n 'orange yellow',\n 'blue',\n 'green',\n 'red',\n 'yellow',\n 'magenta',\n 'cyan',\n 'white 9.5 (.05 D)',\n 'neutral 8 (.23 D)',\n 'neutral 6.5 (.44 D)',\n 'neutral 5 (.70 D)',\n 'neutral 3.5 (1.05 D)',\n 'black 2 (1.5 D)',\n)\n\"\"\"\n*ColorChecker Classic* illuminant.\n\nCOLORCHECKER_CLASSIC_SAMPLE_LABELS : tuple\n\"\"\"\n\nCOLORCHECKER_1976_DATA = OrderedDict(\n zip(COLORCHECKER_CLASSIC_SAMPLE_LABELS, [\n np.array([0.4002, 0.3504, 0.1005]),\n np.array([0.3773, 0.3446, 0.3582]),\n np.array([0.2470, 0.2514, 0.1933]),\n np.array([0.3372, 0.4220, 0.1329]),\n np.array([0.2651, 0.2400, 0.2427]),\n np.array([0.2608, 0.3430, 0.4306]),\n np.array([0.5060, 0.4070, 0.3005]),\n np.array([0.2110, 0.1750, 0.1200]),\n np.array([0.4533, 0.3058, 0.1977]),\n np.array([0.2845, 0.2020, 0.0656]),\n np.array([0.3800, 0.4887, 0.4429]),\n np.array([0.4729, 0.4375, 0.4306]),\n np.array([0.1866, 0.1285, 0.0611]),\n np.array([0.3046, 0.4782, 0.2339]),\n np.array([0.5385, 0.3129, 0.1200]),\n np.array([0.4480, 0.4703, 0.5910]),\n np.array([0.3635, 0.2325, 0.1977]),\n np.array([0.1958, 0.2519, 0.1977]),\n np.array([0.3101, 0.3163, 0.9001]),\n np.array([0.3101, 0.3163, 0.5910]),\n np.array([0.3101, 0.3163, 0.3620]),\n np.array([0.3101, 0.3163, 0.1977]),\n np.array([0.3101, 0.3163, 0.0900]),\n np.array([0.3101, 0.3163, 0.0313]),\n ]))\n\nCOLORCHECKER_1976_ILLUMINANT = (\n ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['C'])\n\"\"\"\n*ColorChecker 1976* illuminant.\n\nCOLORCHECKER_1976_ILLUMINANT : ndarray\n\"\"\"\n\nCOLORCHECKER_1976 = ColourChecker('ColorChecker 1976', COLORCHECKER_1976_DATA,\n COLORCHECKER_1976_ILLUMINANT)\n\"\"\"\n*Colour Checker* developed by *McCamy et al.* at Macbeth, a Division of\nKollmorgen.\n\nCOLORCHECKER_1976 : ColourChecker\n\"\"\"\n\nCOLORCHECKER_2005_DATA = OrderedDict(\n zip(COLORCHECKER_CLASSIC_SAMPLE_LABELS, [\n np.array([0.4316, 0.3777, 0.1008]),\n np.array([0.4197, 0.3744, 0.3495]),\n np.array([0.2760, 0.3016, 0.1836]),\n np.array([0.3703, 0.4499, 0.1325]),\n np.array([0.2999, 0.2856, 0.2304]),\n np.array([0.2848, 0.3911, 0.4178]),\n np.array([0.5295, 0.4055, 0.3118]),\n np.array([0.2305, 0.2106, 0.1126]),\n np.array([0.5012, 0.3273, 0.1938]),\n np.array([0.3319, 0.2482, 0.0637]),\n np.array([0.3984, 0.5008, 0.4446]),\n np.array([0.4957, 0.4427, 0.4357]),\n np.array([0.2018, 0.1692, 0.0575]),\n np.array([0.3253, 0.5032, 0.2318]),\n np.array([0.5686, 0.3303, 0.1257]),\n np.array([0.4697, 0.4734, 0.5981]),\n np.array([0.4159, 0.2688, 0.2009]),\n np.array([0.2131, 0.3023, 0.1930]),\n np.array([0.3469, 0.3608, 0.9131]),\n np.array([0.3440, 0.3584, 0.5894]),\n np.array([0.3432, 0.3581, 0.3632]),\n np.array([0.3446, 0.3579, 0.1915]),\n np.array([0.3401, 0.3548, 0.0883]),\n np.array([0.3406, 0.3537, 0.0311]),\n ]))\n\nCOLORCHECKER_2005_ILLUMINANT = (\n ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['ICC D50'])\n\"\"\"\n*ColorChecker 2005* illuminant.\n\nCOLORCHECKER_2005_ILLUMINANT : ndarray\n\"\"\"\n\nCOLORCHECKER_2005 = ColourChecker('ColorChecker 2005', COLORCHECKER_2005_DATA,\n COLORCHECKER_2005_ILLUMINANT)\n\"\"\"\nReference data from *GretagMacbeth (2005)*.\n\nCOLORCHECKER_2005 : ColourChecker\n\"\"\"\nBABELCOLOR_AVERAGE_DATA = OrderedDict(\n zip(COLORCHECKER_CLASSIC_SAMPLE_LABELS, [\n np.array([0.4325, 0.3788, 0.1034]),\n np.array([0.4191, 0.3748, 0.3525]),\n np.array([0.2761, 0.3004, 0.1847]),\n np.array([0.3700, 0.4501, 0.1335]),\n np.array([0.3020, 0.2877, 0.2324]),\n np.array([0.2856, 0.3910, 0.4174]),\n np.array([0.5291, 0.4075, 0.3117]),\n np.array([0.2339, 0.2155, 0.1140]),\n np.array([0.5008, 0.3293, 0.1979]),\n np.array([0.3326, 0.2556, 0.0644]),\n np.array([0.3989, 0.4998, 0.4435]),\n np.array([0.4962, 0.4428, 0.4358]),\n np.array([0.2040, 0.1696, 0.0579]),\n np.array([0.3270, 0.5033, 0.2307]),\n np.array([0.5709, 0.3298, 0.1268]),\n np.array([0.4694, 0.4732, 0.6081]),\n np.array([0.4177, 0.2704, 0.2007]),\n np.array([0.2151, 0.3037, 0.1903]),\n np.array([0.3488, 0.3628, 0.9129]),\n np.array([0.3451, 0.3596, 0.5885]),\n np.array([0.3446, 0.3590, 0.3595]),\n np.array([0.3438, 0.3589, 0.1912]),\n np.array([0.3423, 0.3576, 0.0893]),\n np.array([0.3439, 0.3565, 0.0320]),\n ]))\n\nBABELCOLOR_AVERAGE_ILLUMINANT = (\n ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['ICC D50'])\n\"\"\"\n*BabelColor Average* illuminant.\n\nBABELCOLOR_AVERAGE_ILLUMINANT : ndarray\n\"\"\"\n\nBABELCOLOR_AVERAGE = ColourChecker('BabelColor Average',\n BABELCOLOR_AVERAGE_DATA,\n BABELCOLOR_AVERAGE_ILLUMINANT)\n\"\"\"\nAverage data derived from measurements of 30 *Colour Checker* charts.\n\nBABELCOLOR_AVERAGE : ColourChecker\n\"\"\"\n\nCOLORCHECKER24_BEFORE_NOV2014_LAB_DATA = OrderedDict(\n zip(COLORCHECKER_CLASSIC_SAMPLE_LABELS, [\n np.array([37.986, 13.555, 14.059]),\n np.array([65.711, 18.13, 17.81]),\n np.array([49.927, -4.88, -21.905]),\n np.array([43.139, -13.095, 21.905]),\n np.array([55.112, 8.844, -25.399]),\n np.array([70.719, -33.397, -0.199]),\n np.array([62.661, 36.067, 57.096]),\n np.array([40.02, 10.41, -45.964]),\n np.array([51.124, 48.239, 16.248]),\n np.array([30.325, 22.976, -21.587]),\n np.array([72.532, -23.709, 57.255]),\n np.array([71.941, 19.363, 67.857]),\n np.array([28.778, 14.179, -50.297]),\n np.array([55.261, -38.342, 31.37]),\n np.array([42.101, 53.378, 28.19]),\n np.array([81.733, 4.039, 79.819]),\n np.array([51.935, 49.986, -14.574]),\n np.array([51.038, -28.631, -28.638]),\n np.array([96.539, -0.425, 1.186]),\n np.array([81.257, -0.638, -0.335]),\n np.array([66.766, -0.734, -0.504]),\n np.array([50.867, -0.153, -0.27]),\n np.array([35.656, -0.421, -1.231]),\n np.array([20.461, -0.079, -0.973]),\n ]))\n\"\"\"\n*ColorChecker24 - Before November 2014* illuminant.\n\nNotes\n-----\n- *X-Rite* data is given as *CIE L\\\\*a\\\\*b\\\\** colourspace values under\n *CIE Illuminant D Series D50* for the\n *CIE 1931 2 Degree Standard Observer*.\n\nCOLORCHECKER24_BEFORE_NOV2014_LAB_DATA : ndarray\n\"\"\"\n\nCOLORCHECKER24_BEFORE_NOV2014_DATA = OrderedDict(\n zip(\n COLORCHECKER_CLASSIC_SAMPLE_LABELS,\n XYZ_to_xyY(\n Lab_to_XYZ(\n list(COLORCHECKER24_BEFORE_NOV2014_LAB_DATA.values()),\n ILLUMINANTS['CIE 1931 2 Degree Standard Observer'][\n 'ICC D50']))))\n\nCOLORCHECKER24_BEFORE_NOV2014_ILLUMINANT = (\n ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['ICC D50'])\n\"\"\"\n*ColorChecker24 - Before November 2014* illuminant.\n\nCOLORCHECKER24_BEFORE_NOV2014_ILLUMINANT : ndarray\n\"\"\"\n\nCOLORCHECKER24_BEFORE_NOV2014 = ColourChecker(\n 'ColorChecker24 - Before November 2014',\n COLORCHECKER24_BEFORE_NOV2014_DATA,\n COLORCHECKER24_BEFORE_NOV2014_ILLUMINANT)\n\"\"\"\nReference *Colour Checker* data from *X-Rite (2015)*.\n\nNotes\n-----\n- The rounded *ColorChecker24 - Before November 2014* values should match the\n *ColorChecker 2005* values. They are given for reference of the original\n *CIE L\\\\*a\\\\*b\\\\** colourspace values.\n\nCOLORCHECKER24_BEFORE_NOV2014 : ColourChecker\n\"\"\"\n\nCOLORCHECKER24_AFTER_NOV2014_LAB_DATA = OrderedDict((\n ('dark skin', np.array([37.54, 14.37, 14.92])),\n ('light skin', np.array([64.66, 19.27, 17.5])),\n ('blue sky', np.array([49.32, -3.82, -22.54])),\n ('foliage', np.array([43.46, -12.74, 22.72])),\n ('blue flower', np.array([54.94, 9.61, -24.79])),\n ('bluish green', np.array([70.48, -32.26, -0.37])),\n ('orange', np.array([62.73, 35.83, 56.5])),\n ('purplish blue', np.array([39.43, 10.75, -45.17])),\n ('moderate red', np.array([50.57, 48.64, 16.67])),\n ('purple', np.array([30.1, 22.54, -20.87])),\n ('yellow green', np.array([71.77, -24.13, 58.19])),\n ('orange yellow', np.array([71.51, 18.24, 67.37])),\n ('blue', np.array([28.37, 15.42, -49.8])),\n ('green', np.array([54.38, -39.72, 32.27])),\n ('red', np.array([42.43, 51.05, 28.62])),\n ('yellow', np.array([81.8, 2.67, 80.41])),\n ('magenta', np.array([50.63, 51.28, -14.12])),\n ('cyan', np.array([49.57, -29.71, -28.32])),\n ('white 9.5 (.05 D)', np.array([95.19, -1.03, 2.93])),\n ('neutral 8 (.23 D)', np.array([81.29, -0.57, 0.44])),\n ('neutral 6.5 (.44 D)', np.array([66.89, -0.75, -0.06])),\n ('neutral 5 (.70 D)', np.array([50.76, -0.13, 0.14])),\n ('neutral 3.5 (1.05 D)', np.array([35.63, -0.46, -0.48])),\n ('black 2 (1.5 D)', np.array([20.64, 0.07, -0.46])),\n))\n\"\"\"\n*ColorChecker24 - After November 2014* illuminant.\n\nNotes\n-----\n- *X-Rite* data is given as *CIE L\\\\*a\\\\*b\\\\** colourspace values under\n *CIE Illuminant D Series D50* for the\n *CIE 1931 2 Degree Standard Observer*.\n\nCOLORCHECKER24_AFTER_NOV2014_LAB_DATA : ndarray\n\"\"\"\n\nCOLORCHECKER24_AFTER_NOV2014_DATA = OrderedDict(\n zip(\n COLORCHECKER24_AFTER_NOV2014_LAB_DATA.keys(),\n XYZ_to_xyY(\n Lab_to_XYZ(\n list(COLORCHECKER24_AFTER_NOV2014_LAB_DATA.values()),\n ILLUMINANTS['CIE 1931 2 Degree Standard Observer'][\n 'ICC D50']))))\n\nCOLORCHECKER24_AFTER_NOV2014_ILLUMINANT = (\n ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['ICC D50'])\n\"\"\"\n*ColorChecker24 - After November 2014* illuminant.\n\nCOLORCHECKER24_AFTER_NOV2014_ILLUMINANT : ndarray\n\"\"\"\n\nCOLORCHECKER24_AFTER_NOV2014 = ColourChecker(\n 'ColorChecker24 - After November 2014', COLORCHECKER24_AFTER_NOV2014_DATA,\n COLORCHECKER24_AFTER_NOV2014_ILLUMINANT)\n\"\"\"\nReference *Colour Checker* data from *X-Rite (2015)* and matching the\n*Colour Checker* edition after November 2014.\n\nCOLORCHECKER24_AFTER_NOV2014 : ColourChecker\n\"\"\"\n\nCOLOURCHECKERS = CaseInsensitiveMapping({\n 'ColorChecker 1976': COLORCHECKER_1976,\n 'ColorChecker 2005': COLORCHECKER_2005,\n 'BabelColor Average': BABELCOLOR_AVERAGE,\n 'ColorChecker24 - Before November 2014': COLORCHECKER24_BEFORE_NOV2014,\n 'ColorChecker24 - After November 2014': COLORCHECKER24_AFTER_NOV2014,\n})\nCOLOURCHECKERS.__doc__ = \"\"\"\nAggregated *Colour Checker* chromaticity coordinates.\n\nReferences\n----------\n:cite:`BabelColor2012b`, :cite:`BabelColor2012c`, :cite:`X-Rite2016`\n\nCOLOURCHECKERS : CaseInsensitiveMapping\n **{'ColorChecker 1976', 'ColorChecker 2005', 'BabelColor Average',\n 'ColorChecker24 - Before November 2014',\n 'ColorChecker24 - After November 2014'}**\n\nAliases:\n\n- 'babel_average': 'BabelColor Average'\n- 'cc2005': 'ColorChecker 2005'\n- 'ccb2014': 'ColorChecker24 - Before November 2014'\n- 'cca2014': 'ColorChecker24 - After November 2014'\n\"\"\"\nCOLOURCHECKERS['babel_average'] = COLOURCHECKERS['BabelColor Average']\nCOLOURCHECKERS['cc2005'] = COLOURCHECKERS['ColorChecker 2005']\nCOLOURCHECKERS['ccb2014'] = COLOURCHECKERS[\n 'ColorChecker24 - Before November 2014']\nCOLOURCHECKERS['cca2014'] = COLOURCHECKERS[\n 'ColorChecker24 - After November 2014']\n", "meta": {"hexsha": "91359bea5d92939fbd612763e501da29e71e528a", "size": 15410, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/characterisation/datasets/colour_checkers/chromaticity_coordinates.py", "max_stars_repo_name": "OmarWagih1/colour", "max_stars_repo_head_hexsha": "bdc880a2783ff523dafb19f1233212dd03a639bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-20T03:44:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-20T14:08:41.000Z", "max_issues_repo_path": "colour/characterisation/datasets/colour_checkers/chromaticity_coordinates.py", "max_issues_repo_name": "OmarWagih1/colour", "max_issues_repo_head_hexsha": "bdc880a2783ff523dafb19f1233212dd03a639bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colour/characterisation/datasets/colour_checkers/chromaticity_coordinates.py", "max_forks_repo_name": "OmarWagih1/colour", "max_forks_repo_head_hexsha": "bdc880a2783ff523dafb19f1233212dd03a639bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5889145497, "max_line_length": 79, "alphanum_fraction": 0.6417910448, "include": true, "reason": "import numpy", "num_tokens": 5312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.22000709974589316, "lm_q1q2_score": 0.12705308041122587}} {"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: NysanAskar\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom keras import backend as K\r\nimport keras\r\n\r\nfrom tensorflow.keras.layers import (\r\n Add,\r\n Input,\r\n)\r\nfrom utils import xywh_to_x1y1x2y2, broadcast_iou, binary_cross_entropy\r\n\r\nanchors_wh = np.array([[10, 13], [16, 30], [33, 23], [30, 61], [62, 45],\r\n [59, 119], [116, 90], [156, 198], [373, 326]],\r\n np.float32) / 416\r\n\r\nTOTAL_CLASSES = 80\r\n\r\n\r\nbackbone = [\r\n (32, 3, 1, 'same', 'mish', '0'),\r\n [\"SPP\", 1, '1'],\r\n (64, 3, 1, 'same', 'mish', '2'),\r\n [\"CSP\", 2, '3'],\r\n (128, 1, 1, 'same', 'mish', '4'),\r\n [\"CSP\", 8, '5'],\r\n (256, 1, 1, 'same', 'mish', '6'),\r\n [\"CSP\", 8, '7'],\r\n (512, 1, 1, 'same', 'mish', '8'),\r\n [\"CSP\", 4, '9'],\r\n (1024, 1, 1, 'same', 'mish', '10'),\r\n]\r\n\r\nneck = [\r\n (512, 1, 1, 'same', 'leaky', '0'),# input_3\r\n (1024, 3, 1, 'same', 'leaky', '1'),\r\n [\"M\", '2'],\r\n (512, 1, 1, 'same', 'leaky', '3'),\r\n (1024, 3, 1, 'same', 'leaky', '4'),\r\n (512, 1, 1, 'same', 'leaky', '5'),# output_3\r\n (256, 1, 1, 'same', 'leaky', '6'),\r\n \"U\", #'7'\r\n [\"C\",'8'],\r\n (256, 1, 1, 'same', 'mish', '9'),\r\n (512, 3, 1, 'same', 'mish', '10'),\r\n (256, 1, 1, 'same', 'mish', '11'),\r\n (512, 3, 1, 'same', 'mish', '12'),\r\n (256, 1, 1, 'same', 'mish', '13'),# output_2\r\n (128, 1, 1, 'same', 'leaky', '14'),\r\n \"U\", #'15'\r\n [\"C\",'16'],\r\n (128, 1, 1, 'same', 'leaky', '17'),\r\n (256, 3, 1, 'same', 'mish', '18'),\r\n (128, 1, 1, 'same', 'leaky', '19'),\r\n (256, 3, 1, 'same', 'mish', '20'),\r\n (128, 1, 1, 'same', 'leaky', '21'),\r\n (256, 3, 1, 'same', 'mish', '22'),# output_1\r\n]\r\n\r\n\r\nhead = [\r\n [\"S\", 256, '0'],# input_3 -> output_1\r\n (256, 3, 2, 'valid', 'leaky', '1'),# input_3\r\n [\"C\", 256, '2'], # concatanate with input_2\r\n (512, 3, 1, 'same', 'leaky', '3'),\r\n (256, 1, 1, 'same', 'leaky', '4'),\r\n (512, 3, 1, 'same', 'leaky', '5'),\r\n (256, 1, 1, 'same', 'leaky', '6'),\r\n [\"S\", 256, '7'],# output_2\r\n (512, 3, 2, 'valid', 'leaky', '8'),\r\n [\"C\", 512, '9'], # concatanate with input_1\r\n (1024, 3, 1, 'same', 'leaky', '10'),\r\n (512, 1, 1, 'same', 'leaky', '11'),# output_2\r\n (1024, 3, 1, 'same', 'leaky', '12'),\r\n (512, 1, 1, 'same', 'leaky', '13'),\r\n [\"S\", 512, '14'],# output_3\r\n]\r\n\r\n\r\nclass Mish(tf.keras.layers.Layer):\r\n '''\r\n Mish Activation Function.\r\n .. math::\r\n Mish(x) = x * tanh(softplus(x))\r\n '''\r\n def __init__(self, **kwargs):\r\n super(Mish, self).__init__(**kwargs)\r\n def call(self, inputs):\r\n return inputs * K.tanh(K.softplus(inputs))\r\n\r\nclass CNNBlock(tf.keras.layers.Layer):\r\n def __init__(self, out_channels, bn_act=True, padding='same', activation='leaky',**kwargs):\r\n super().__init__()\r\n self.padding = padding\r\n self.conv = tf.keras.layers.Conv2D(filters = out_channels, use_bias=not bn_act, padding=padding, **kwargs)\r\n self.bn = tf.keras.layers.BatchNormalization()\r\n self.leaky = tf.keras.layers.LeakyReLU(0.1)\r\n self.use_bn_act = bn_act\r\n self.zero_pad = tf.keras.layers.ZeroPadding2D(padding=(1, 1))\r\n self.activ_func = activation\r\n self.mish = Mish()\r\n def call(self, input_tensor):\r\n if self.activ_func == 'leaky':\r\n if self.padding == 'same':\r\n if self.use_bn_act:\r\n return self.leaky(self.bn(self.conv(input_tensor)))\r\n else:\r\n return self.conv(input_tensor)\r\n else:\r\n if self.use_bn_act:\r\n z = self.zero_pad(input_tensor)\r\n return self.leaky(self.bn(self.conv(z)))\r\n else:\r\n z = self.zero_pad(input_tensor)\r\n return self.conv(z) # TensorShape([3, 224, 224, 5])\r\n elif self.activ_func == 'mish':\r\n if self.padding == 'same':\r\n if self.use_bn_act:\r\n return self.mish(self.bn(self.conv(input_tensor)))\r\n else:\r\n return self.conv(input_tensor)\r\n else:\r\n if self.use_bn_act:\r\n z = self.zero_pad(input_tensor)\r\n return self.mish(self.bn(self.conv(z)))\r\n else:\r\n z = self.zero_pad(input_tensor)\r\n return self.conv(z) # TensorShape([3, 224, 224, 5])\r\n\r\nclass ResidualBlock(tf.keras.layers.Layer):\r\n def __init__(self, channels, use_residual=True, num_repeats=1):\r\n super().__init__()\r\n self.layers = []\r\n for _ in range(num_repeats):\r\n self.layers += [\r\n keras.Sequential([\r\n CNNBlock(channels, kernel_size=1, activation='mish'),\r\n CNNBlock(channels, kernel_size=3, padding='same', activation='mish')]\r\n )]\r\n self.use_residual = use_residual\r\n self.num_repeats = num_repeats\r\n def call(self, input_tensor):\r\n for layer in self.layers:\r\n if self.use_residual:\r\n x = Add()([input_tensor,layer(input_tensor)])\r\n else:\r\n x = layer(input_tensor)\r\n return x # TensorShape([3, 224, 224, 5])\r\n\r\nclass CSPBlock(tf.keras.layers.Layer):\r\n def __init__(self, channels, num_res_block=1):\r\n super().__init__()\r\n self.conv_1 = CNNBlock(out_channels=channels, padding='valid',\r\n activation='mish', kernel_size=3, strides=2)\r\n self.conv_2 = CNNBlock(out_channels=channels//2, padding='same',\r\n activation='mish', kernel_size=1, strides=1)\r\n self.conv_3 = CNNBlock(out_channels=channels//2, padding='same',\r\n activation='mish', kernel_size=1, strides=1)\r\n self.res_block = ResidualBlock(channels=channels//2, num_repeats=num_res_block)\r\n def call(self, input_tensor):\r\n x = self.conv_1(input_tensor)\r\n x_1 = self.conv_2(x)\r\n x_2 = self.conv_2(x)\r\n x_2 = self.res_block(x_2)\r\n x_2 = self.conv_3(x_2)\r\n x = tf.concat([x_1, x_2], -1)\r\n return x # tf.Tensor: shape=(3, 208, 208, 256)\r\n\r\nclass backbone_layers(tf.keras.layers.Layer):\r\n def __init__(self, in_channels=3):\r\n super().__init__()\r\n self.in_channels = in_channels\r\n self.layers = self._create_conv_layers()\r\n def call(self, x):\r\n outputs = [] # for each scale\r\n for i, layer in enumerate(self.layers):\r\n if i in [6, 8, 10]:\r\n outputs.append(layer(x))\r\n x = layer(x)\r\n return outputs\r\n def _create_conv_layers(self):\r\n layers = []\r\n in_channels = self.in_channels\r\n for module in backbone:\r\n if isinstance(module, tuple):\r\n out_channels, kernel_size, strides, padding, ac_faunc, name_layer = module\r\n layers.append(\r\n CNNBlock(\r\n out_channels,\r\n kernel_size=kernel_size,\r\n strides=strides,\r\n padding=padding, activation = ac_faunc, name = name_layer))\r\n in_channels = out_channels\r\n elif isinstance(module, list):\r\n num_repeats = module[1]\r\n layers.append(CSPBlock(in_channels*2, num_res_block=num_repeats))\r\n return layers\r\n\r\nclass max_pool(tf.keras.layers.Layer):\r\n def __init__(self):\r\n super().__init__()\r\n self.conv_1 = CNNBlock(out_channels=512, kernel_size=1,strides=1,\r\n padding='same', activation = 'leaky')\r\n self.max_1 = tf.keras.layers.MaxPool2D((5, 5), strides=1, padding=\"same\")\r\n self.max_2 = tf.keras.layers.MaxPool2D((9, 9), strides=1, padding=\"same\")\r\n self.max_3 = tf.keras.layers.MaxPool2D((13, 13), strides=1, padding=\"same\")\r\n def call(self, x):\r\n x_1 = self.conv_1(x)\r\n x_max_1 = self.max_1(x_1)\r\n x_max_2 = self.max_2(x_1)\r\n x_max_3 = self.max_3(x_1)\r\n x = tf.concat([x_1, x_max_1,x_max_2,x_max_3], -1)\r\n return x\r\n\r\n\r\nclass concat(tf.keras.layers.Layer):\r\n def __init__(self, channels, ):\r\n super().__init__()\r\n self.conc = tf.keras.layers.Concatenate(axis=-1)\r\n self.conv = CNNBlock(out_channels=channels, kernel_size=1,strides=1,\r\n padding='same', activation = 'leaky')\r\n def call(self, x_1, x_2):\r\n x_2 = self.conv(x_2)\r\n x = self.conc([x_1, x_2,])\r\n return x\r\n\r\n\r\nclass yolov4_neck(tf.keras.layers.Layer):\r\n def __init__(self):\r\n super().__init__()\r\n self.layers = self._create_conv_layers()\r\n def call(self, input_tensor):\r\n outputs = [] # for each scale\r\n route_connections = []\r\n inputs = input_tensor[:2]\r\n x = input_tensor[2]\r\n for i, layer in enumerate(self.layers):\r\n if i in [5, 13, 22]:\r\n outputs.append(layer(x))\r\n elif isinstance(layer, tf.keras.layers.UpSampling2D):\r\n route_connections.append(layer(x))\r\n x = layer(x)\r\n elif isinstance(layer, concat):\r\n x = layer(route_connections.pop(), inputs.pop())\r\n else:\r\n x = layer(x)\r\n return outputs\r\n def _create_conv_layers(self):\r\n layers = []\r\n for module in neck:\r\n if isinstance(module, tuple):\r\n out_channels, kernel_size, strides, padding, act_func, name = module\r\n layers.append(\r\n CNNBlock(\r\n out_channels,\r\n kernel_size=kernel_size,\r\n strides=strides,\r\n padding=padding, activation=act_func))\r\n in_channels = out_channels\r\n elif isinstance(module, list):\r\n l = module[0]\r\n if l == 'M':\r\n layers.append(max_pool())\r\n elif l == 'C':\r\n layers.append(concat(in_channels))\r\n elif isinstance(module, str):\r\n layers.append(tf.keras.layers.UpSampling2D(size=2))\r\n return layers\r\n\r\n\r\n\r\nclass ScalePrediction(tf.keras.layers.Layer):\r\n def __init__(self, in_channels, num_classes):\r\n super().__init__()\r\n self.conv_1 = CNNBlock(2 * in_channels, kernel_size=3, padding='same')\r\n self.conv_2 = CNNBlock((num_classes + 5) * 3, bn_act=False, kernel_size=1)\r\n self.num_classes = num_classes\r\n def call(self, input_tensor):\r\n if input_tensor.get_shape()[1] == 52:\r\n x = self.conv_2(input_tensor)\r\n x = tf.reshape(x, shape=(K.shape(x)[0], K.shape(x)[1], K.shape(x)[2], 3, self.num_classes + 5))\r\n return x\r\n else:\r\n x = self.conv_1(input_tensor)\r\n x = self.conv_2(x)\r\n x = tf.reshape(x, shape=(K.shape(x)[0], K.shape(x)[1], K.shape(x)[2], 3, self.num_classes + 5))\r\n return x # TensorShape([3, 416, 416, 3, 85])\r\n\r\n\r\nclass concat_head(tf.keras.layers.Layer):\r\n def __init__(self, in_channels):\r\n super().__init__()\r\n self.ch = in_channels\r\n self.conc = tf.keras.layers.Concatenate(axis=-1)\r\n self.conv = CNNBlock(self.ch, kernel_size=1,strides=1,\r\n padding='same', activation = 'leaky')\r\n def call(self, x_1, x_2):\r\n x = self.conc([x_1, x_2,])\r\n x = self.conv(x)\r\n return x\r\n\r\n\r\nclass yolov4_head(tf.keras.layers.Layer):\r\n def __init__(self, num_classes):\r\n self.num_classes = num_classes\r\n super().__init__()\r\n self.layers = self._create_conv_layers()\r\n def call(self, input_tensor):\r\n outputs = [] # for each scale\r\n inputs = input_tensor[:2]\r\n x = input_tensor[2]\r\n for i, layer in enumerate(self.layers):\r\n if i in [0, 7, 14]:\r\n outputs.append(layer(x))\r\n continue\r\n elif isinstance(layer, concat_head):\r\n x = layer(x, inputs.pop())\r\n else:\r\n x = layer(x)\r\n return outputs\r\n def _create_conv_layers(self):\r\n layers = []\r\n for module in head:\r\n if isinstance(module, tuple):\r\n out_channels, kernel_size, strides, padding, act_func, name = module\r\n layers.append(\r\n CNNBlock(\r\n out_channels,\r\n kernel_size=kernel_size,\r\n strides=strides,\r\n padding=padding, activation=act_func))\r\n in_channels = out_channels\r\n elif isinstance(module, list):\r\n l, c = module[0], module[1]\r\n if l == 'C':\r\n layers.append(concat_head(in_channels=c))\r\n elif l == 'S':\r\n layers.append(ScalePrediction(in_channels=c, num_classes= self.num_classes))\r\n return layers\r\n\r\n\r\ndef YoloV4(num_classes, shape=(416, 416, 3), training=True):\r\n inputs = Input(shape=shape)\r\n model_backbone = backbone_layers()\r\n out_backbone = model_backbone(inputs)\r\n model_neck = yolov4_neck()\r\n out_neck = model_neck(out_backbone)\r\n model_head = yolov4_head(num_classes)\r\n y_small, y_medium, y_large = model_head(out_neck)\r\n return tf.keras.Model(inputs, (y_small, y_medium, y_large))\r\n\r\n\r\ndef get_absolute_yolo_box(y_pred, valid_anchors_wh, num_classes):\r\n \"\"\"\r\n inputs:\r\n y_pred: Prediction tensor from the model output, in the shape of (batch, grid, grid, anchor, 5 + num_classes)\r\n outputs:\r\n y_box: boxes in shape of (batch, grid, grid, anchor, 4), the last dimension is (xmin, ymin, xmax, ymax)\r\n objectness: probability that an object exists\r\n classes: probability of classes\r\n \"\"\"\r\n t_xy, t_wh, objectness, classes = tf.split(\r\n y_pred, (2, 2, 1, num_classes), axis=-1)\r\n objectness = tf.sigmoid(objectness)\r\n classes = tf.sigmoid(classes)\r\n grid_size = tf.shape(y_pred)[1]\r\n C_xy = tf.meshgrid(tf.range(grid_size), tf.range(grid_size))\r\n C_xy = tf.stack(C_xy, axis=-1)\r\n C_xy = tf.expand_dims(C_xy, axis=2) # [gx, gy, 1, 2]\r\n b_xy = tf.sigmoid(t_xy) + tf.cast(C_xy, tf.float32)\r\n b_xy = b_xy / tf.cast(grid_size, tf.float32)\r\n b_wh = tf.exp(t_wh) * valid_anchors_wh\r\n y_box = tf.concat([b_xy, b_wh], axis=-1)\r\n return y_box, objectness, classes\r\n\r\n\r\ndef get_relative_yolo_box(y_true, valid_anchors_wh):\r\n \"\"\"\r\n This is the inverse of `get_absolute_yolo_box` above.\r\n \"\"\"\r\n grid_size = tf.shape(y_true)[1]\r\n C_xy = tf.meshgrid(tf.range(grid_size), tf.range(grid_size))\r\n C_xy = tf.expand_dims(tf.stack(C_xy, axis=-1), axis=2)\r\n b_xy = y_true[..., 0:2]\r\n b_wh = y_true[..., 2:4]\r\n t_xy = b_xy * tf.cast(grid_size, tf.float32) - tf.cast(C_xy, tf.float32)\r\n t_wh = tf.math.log(b_wh / valid_anchors_wh)\r\n # b_wh could have some cells are 0, divided by anchor could result in inf or nan\r\n t_wh = tf.where(\r\n tf.logical_or(tf.math.is_inf(t_wh), tf.math.is_nan(t_wh)),\r\n tf.zeros_like(t_wh), t_wh)\r\n y_box = tf.concat([t_xy, t_wh], axis=-1)\r\n return y_box\r\n\r\n\r\nclass YoloLoss(object):\r\n def __init__(self, num_classes, valid_anchors_wh):\r\n self.num_classes = num_classes\r\n self.ignore_thresh = 0.5\r\n self.valid_anchors_wh = valid_anchors_wh\r\n self.lambda_coord = 5.0\r\n self.lamda_noobj = 0.5\r\n def __call__(self, y_true, y_pred):\r\n pred_xy_rel = tf.sigmoid(y_pred[..., 0:2]) # (None, grid, grid, 3,2)\r\n pred_wh_rel = y_pred[..., 2:4] # (None, grid, grid, 3,2)\r\n pred_box_abs, pred_obj, pred_class = get_absolute_yolo_box(\r\n y_pred, self.valid_anchors_wh, self.num_classes)\r\n# # pred_box_abs (None, grid, grid, 3, 4), pred_obj (None, grid, grid, 3, 1), pred_class (None, grid, grid, 3, num_classes)\r\n pred_box_abs = xywh_to_x1y1x2y2(pred_box_abs)\r\n true_xy_abs, true_wh_abs, true_obj, true_class = tf.split(\r\n y_true, (2, 2, 1, self.num_classes), axis=-1)\r\n# # true_xy_abs (None, grid, grid, 3, 2), true_wh_abs (None, grid, grid, 3, 2), true_obj (None, grid, grid, 3, 1), true_class (None, grid, grid, 3, num_classes)\r\n true_box_abs = tf.concat([true_xy_abs, true_wh_abs], axis=-1) #true_box_abs (None, grid, grid, 3, 4)\r\n true_box_abs = xywh_to_x1y1x2y2(true_box_abs)\r\n\r\n true_box_rel = get_relative_yolo_box(y_true, self.valid_anchors_wh)\r\n true_xy_rel = true_box_rel[..., 0:2]\r\n true_wh_rel = true_box_rel[..., 2:4]\r\n\r\n weight = 2 - true_wh_abs[..., 0] * true_wh_abs[..., 1] # (None, grid, grid, 3)\r\n\r\n xy_loss = self.calc_xy_loss(true_obj, true_xy_rel, pred_xy_rel, weight)\r\n wh_loss = self.calc_wh_loss(true_obj, true_wh_rel, pred_wh_rel, weight)\r\n class_loss, class_accuracy = self.calc_class_loss(true_obj, true_class, pred_class)\r\n\r\n ignore_mask, mIoU = self.calc_ignore_mask(true_obj, true_box_abs,\r\n pred_box_abs)\r\n obj_loss = self.calc_obj_loss(true_obj, pred_obj, ignore_mask)\r\n\r\n return xy_loss + wh_loss + class_loss + obj_loss, (xy_loss, wh_loss,\r\n class_loss,\r\n obj_loss,class_accuracy, mIoU)\r\n\r\n def calc_ignore_mask(self, true_obj, true_box, pred_box):\r\n # YOLOv3:\r\n true_box_shape = tf.shape(true_box)\r\n # (None, 13, 13, 3, 4)\r\n pred_box_shape = tf.shape(pred_box)\r\n # (None, 507, 4)\r\n true_box = tf.reshape(true_box, [true_box_shape[0], -1, 4])\r\n # sort true_box to have non-zero boxes rank first\r\n true_box = tf.sort(true_box, axis=1, direction=\"DESCENDING\")\r\n # (None, 100, 4)\r\n true_box = true_box[:, 0:100, :]\r\n # (None, 507, 4)\r\n pred_box = tf.reshape(pred_box, [pred_box_shape[0], -1, 4])\r\n # (None, 507, 100)\r\n iou = broadcast_iou(pred_box, true_box)\r\n # (None, 507)\r\n best_iou = tf.reduce_max(iou, axis=-1)\r\n # (None, 13, 13, 3)\r\n best_iou = tf.reshape(best_iou, [pred_box_shape[0], pred_box_shape[1], pred_box_shape[2], pred_box_shape[3]])\r\n # ignore_mask = 1 => don't ignore\r\n # ignore_mask = 0 => should ignore\r\n ignore_mask = tf.cast(best_iou < self.ignore_thresh, tf.float32)\r\n # (None, 13, 13, 3, 1)\r\n ignore_mask = tf.expand_dims(ignore_mask, axis=-1)\r\n # (None, 13, 13, 3, 1)\r\n best_iou = tf.expand_dims(best_iou, axis=-1)\r\n # (None, )\r\n max_iou = tf.reduce_sum((best_iou*true_obj), axis=[1,2,3,4]) / tf.reduce_sum((true_obj[0])+0.001)\r\n return ignore_mask, max_iou\r\n\r\n def calc_obj_loss(self, true_obj, pred_obj, ignore_mask):\r\n \"\"\"\r\n calculate loss of objectness: sum of L2 distances\r\n inputs:\r\n true_obj: objectness from ground truth in shape of (batch, grid, grid, anchor, num_classes)\r\n pred_obj: objectness from model prediction in shape of (batch, grid, grid, anchor, num_classes)\r\n outputs:\r\n obj_loss: objectness loss\r\n \"\"\"\r\n obj_entropy = binary_cross_entropy(pred_obj, true_obj)\r\n\r\n obj_loss = true_obj * obj_entropy\r\n noobj_loss = (1 - true_obj) * obj_entropy * ignore_mask\r\n\r\n obj_loss = tf.reduce_sum(obj_loss, axis=(1, 2, 3, 4))\r\n noobj_loss = tf.reduce_sum(\r\n noobj_loss, axis=(1, 2, 3, 4)) * self.lamda_noobj\r\n return obj_loss + noobj_loss\r\n\r\n def calc_class_loss(self, true_obj, true_class, pred_class):\r\n \"\"\"\r\n calculate loss of class prediction\r\n inputs:\r\n true_obj: if the object present from ground truth in shape of (batch, grid, grid, anchor, 1)\r\n true_class: one-hot class from ground truth in shape of (batch, grid, grid, anchor, num_classes)\r\n pred_class: one-hot class from model prediction in shape of (batch, grid, grid, anchor, num_classes)\r\n outputs:\r\n class_loss: class loss\r\n \"\"\"\r\n pred_class_new = tf.cast(pred_class>0.5, tf.float32)\r\n class_accuracy = 1 - tf.reduce_sum(tf.abs(pred_class_new - true_class), axis=[1,2,3,4]) / tf.cast(tf.size(true_class[0]), tf.float32)\r\n class_loss = binary_cross_entropy(pred_class, true_class)\r\n class_loss = true_obj * class_loss\r\n class_loss = tf.reduce_sum(class_loss, axis=(1, 2, 3, 4))\r\n return class_loss, class_accuracy\r\n\r\n def calc_xy_loss(self, true_obj, true_xy, pred_xy, weight):\r\n \"\"\"\r\n calculate loss of the centroid coordinate: sum of L2 distances\r\n inputs:\r\n true_obj: if the object present from ground truth in shape of (batch, grid, grid, anchor, 1)\r\n true_xy: centroid x and y from ground truth in shape of (batch, grid, grid, anchor, 2)\r\n pred_xy: centroid x and y from model prediction in shape of (batch, grid, grid, anchor, 2)\r\n weight: weight adjustment, reward smaller bounding box\r\n outputs:\r\n xy_loss: centroid loss\r\n \"\"\"\r\n # shape (batch, grid, grid, anchor), eg. (32, 13, 13, 3)\r\n xy_loss = tf.reduce_sum(tf.square(true_xy - pred_xy), axis=-1)\r\n\r\n # in order to element-wise multiply the result from tf.reduce_sum\r\n # we need to squeeze one dimension for objectness here\r\n true_obj = tf.squeeze(true_obj, axis=-1)\r\n xy_loss = true_obj * xy_loss * weight\r\n xy_loss = tf.reduce_sum(xy_loss, axis=(1, 2, 3)) * self.lambda_coord\r\n return xy_loss # (batch_size/None, )\r\n\r\n def calc_wh_loss(self, true_obj, true_wh, pred_wh, weight):\r\n \"\"\"\r\n calculate loss of the width and height: sum of L2 distances\r\n inputs:\r\n true_obj: if the object present from ground truth in shape of (batch, grid, grid, anchor, 1)\r\n true_wh: width and height from ground truth in shape of (batch, grid, grid, anchor, 2)\r\n pred_wh: width and height from model prediction in shape of (batch, grid, grid, anchor, 2)\r\n weight: weight adjustment, reward smaller bounding box\r\n outputs:\r\n wh_loss: width and height loss\r\n \"\"\"\r\n # shape (batch, grid, grid, anchor), eg. (32, 13, 13, 3)\r\n wh_loss = tf.reduce_sum(tf.square(true_wh - pred_wh), axis=-1)\r\n true_obj = tf.squeeze(true_obj, axis=-1)\r\n wh_loss = true_obj * wh_loss * weight\r\n wh_loss = tf.reduce_sum(wh_loss, axis=(1, 2, 3)) * self.lambda_coord\r\n return wh_loss # (batch_size/None,)\r\n\r\n", "meta": {"hexsha": "745ae4c07ad8cce0ad81a400e681ce4518b88017", "size": 22699, "ext": "py", "lang": "Python", "max_stars_repo_path": "yolov4.py", "max_stars_repo_name": "AskarNyssan/YoloV4-tensorflow-2.0", "max_stars_repo_head_hexsha": "91a22c6f5df9ad0bd2dd8e2fa53f4d6ececa9637", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-05-31T10:43:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-04T14:29:40.000Z", "max_issues_repo_path": "yolov4.py", "max_issues_repo_name": "AskarNyssan/YoloV4-tensorflow-2.0", "max_issues_repo_head_hexsha": "91a22c6f5df9ad0bd2dd8e2fa53f4d6ececa9637", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "yolov4.py", "max_forks_repo_name": "AskarNyssan/YoloV4-tensorflow-2.0", "max_forks_repo_head_hexsha": "91a22c6f5df9ad0bd2dd8e2fa53f4d6ececa9637", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.802946593, "max_line_length": 161, "alphanum_fraction": 0.5598484515, "include": true, "reason": "import numpy", "num_tokens": 6114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.23934935817440722, "lm_q1q2_score": 0.12621287142565923}} {"text": "\"\"\"\nmodule for generating C, C++, Fortran77, Fortran90 and python routines that\nevaluate sympy expressions. This module is work in progress. Only the\nmilestones with a '+' character in the list below have been completed.\n\n\n--- How is sympy.utilities.codegen different from sympy.printing.ccode? ---\n\nWe considered the idea to extend the printing routines for sympy functions in\nsuch a way that it prints complete compilable code, but this leads to a few\nunsurmountable issues that can only be tackled with dedicated code generator:\n\n- For C, one needs both a code and a header file, while the printing routines\ngenerate just one string. This code generator can be extended to support .pyf\nfiles for f2py.\n\n- Sympy functions are not concerned with programming-technical issues, such as\ninput, output and input-output arguments. Other examples are contiguous or\nnon-contiguous arrays, including headers of other libraries such as gsl or others.\n\n- It is highly interesting to evaluate several sympy functions in one C routine,\neventually sharing common intermediate results with the help of the cse routine.\nThis is more than just printing.\n\n- From the programming perspective, expressions with constants should be\nevaluated in the code generator as much as possible. This is different for\nprinting.\n\n\n--- Basic assumptions ---\n\n* A generic Routine data structure describes the routine that must be translated\n into C/Fortran/... code. This data structure covers all features present in\n one or more of the supported languages.\n\n* Descendants from the CodeGen class transform multiple Routine instances into\n compilable code. Each derived class translates into a specific language.\n\n* In many cases, one wants a simple workflow. The friendly functions in the last\n part are a simple api on top of the Routine/CodeGen stuff. They are easier to\n use, but are less powerful.\n\n\n--- Milestones ---\n\n+ First working version with scalar input arguments, generating C code, tests\n+ Friendly functions that are easier to use than the rigorous Routine/CodeGen\n workflow.\n+ Integer and Real numbers as input and output\n- Optional extra include lines for libraries/objects that can eval special\n functions\n- Test other C compilers and libraries: gcc, tcc, libtcc, gcc+gsl, ...\n- Output arguments\n- InputOutput arguments\n- Sort input/output arguments properly\n- Contiguous array arguments (sympy matrices)\n- Non-contiguous array arguments (sympy matrices)\n- ccode must raise an error when it encounters something that can not be\n translated into c. ccode(integrate(sin(x)/x, x)) does not make sense.\n- Complex numbers as input and output\n- Also generate .pyf code for f2py\n- A default complex datatype\n- Include extra information in the header: date, user, hostname, sha1 hash, ...\n- Isolate constants and evaluate them beforehand in double precision\n- Common Subexpression Elimination\n- User defined comments in the generated code\n- Fortran 77\n- Fortran 90\n- C++\n- Python\n- ...\n\"\"\"\n\n\nfrom sympy.core.symbol import Symbol\nfrom sympy.core.expr import Expr\nfrom sympy.core.containers import Tuple\nfrom sympy.printing.ccode import ccode\nfrom sympy.printing.fcode import fcode\nfrom sympy.tensor import Idx, IndexedElement\nfrom sympy.core.relational import Equality\nfrom sympy.utilities import flatten\n\nfrom StringIO import StringIO\nimport sympy\nimport os\n\n\n__all__ = [\n # description of routines\n \"Routine\", \"DataType\", \"default_datatypes\", \"get_default_datatype\",\n \"Argument\", \"InputArgument\", \"Result\",\n # routines -> code\n \"CodeGen\", \"CCodeGen\", \"FCodeGen\",\n # friendly functions\n \"codegen\",\n]\n\n\n#\n# Description of routines\n#\n\n\nclass Routine(object):\n \"\"\"Generic description of an evaluation routine for a set of sympy expressions.\n\n A CodeGen class can translate instances of this class into C/Fortran/...\n code. The routine specification covers all the features present in these\n languages. The CodeGen part must raise an exception when certain features\n are not present in the target language. For example, multiple return\n values are possible in Python, but not in C or Fortran. Another example:\n Fortran and Python support complex numbers, while C does not.\n \"\"\"\n def __init__(self, name, expr):\n \"\"\"Initialize a Routine instance.\n\n Arguments:\n name -- A string with the name of this routine in the generated\n code\n expr -- The sympy expression that the Routine instance will represent.\n If given a list or tuple of expressions, the routine\n will be considered to have multiple return values.\n\n A decision about whether to use output arguments or return values,\n is made depending on the mathematical expressions. For an expression\n of type Equality, the left hand side is made into an OutputArgument\n (or an InOutArgument if appropriate). Else, the calculated\n expression is the return values of the routine.\n\n A tuple of exressions can be used to create a routine with both\n return value(s) and output argument(s).\n\n \"\"\"\n arg_list = []\n\n if isinstance(expr, (list, tuple)):\n if not expr:\n raise ValueError(\"No expression given\")\n expressions = Tuple(*expr)\n else:\n expressions = Tuple(expr)\n\n # local variables\n local_vars = set([i.label for i in expressions.atoms(Idx)])\n\n # symbols that should be arguments\n symbols = expressions.atoms(Symbol) - local_vars\n\n # Decide whether to use output argument or return value\n return_val = []\n output_args = []\n for expr in expressions:\n if isinstance(expr, Equality):\n out_arg = expr.lhs\n expr = expr.rhs\n if isinstance(out_arg, IndexedElement):\n dims = out_arg.dimensions\n symbol = out_arg.stem.label\n elif isinstance(out_arg, Symbol):\n dims = []\n symbol = out_arg\n else:\n raise CodeGenError(\"Only IndexedElement or Symbol can define output arguments\")\n\n if expr.has(symbol):\n output_args.append(InOutArgument(symbol, out_arg, expr, dimensions=dims))\n else:\n output_args.append(OutputArgument(symbol, out_arg, expr, dimensions=dims))\n\n # avoid duplicate arguments\n symbols.remove(symbol)\n else:\n return_val.append(Result(expr))\n\n # setup input argument list\n array_symbols = {}\n for array in expressions.atoms(IndexedElement):\n array_symbols[array.stem.label] = array\n\n for symbol in sorted(symbols):\n if symbol in array_symbols:\n dims = []\n array = array_symbols[symbol]\n for i in array.indices:\n if i.lower == None:\n dims.append((S.Zero, S.Zero))\n else:\n dims.append((i.lower, i.upper))\n metadata = {'dimensions': dims}\n else:\n metadata = {}\n\n arg_list.append(InputArgument(symbol, **metadata))\n\n arg_list.extend(output_args)\n\n self.name = name\n self.arguments = arg_list\n self.results = return_val\n self.local_vars = local_vars\n\n @property\n def result_variables(self):\n \"\"\"Returns a tuple of OutputArgument, InOutArgument and Result.\"\"\"\n args = [arg for arg in self.arguments if isinstance(arg, (OutputArgument, InOutArgument))]\n args.extend(self.results)\n return args\n\nclass DataType(object):\n \"\"\"Holds strings for a certain datatype in different programming languages.\"\"\"\n def __init__(self, cname, fname, pyname):\n self.cname = cname\n self.fname = fname\n self.pyname = pyname\n\n\ndefault_datatypes = {\n \"int\": DataType(\"int\", \"INTEGER*4\", \"int\"),\n \"float\": DataType(\"double\", \"REAL*8\", \"float\")\n}\n\n\ndef get_default_datatype(expr):\n \"\"\"Derives a decent data type based on the assumptions on the expression.\"\"\"\n if expr.is_integer:\n return default_datatypes[\"int\"]\n else:\n return default_datatypes[\"float\"]\n\n\nclass Argument(object):\n \"\"\"An abstract Argument data structure: a name and a data type.\n\n This structure is refined in the descendants below.\n \"\"\"\n\n def __init__(self, name, datatype=None, dimensions=None, precision=None):\n \"\"\"Initialize an input argument.\n\n name -- must be of class Symbol\n datatype -- When not given, the data type will be guessed based\n on the assumptions on the symbol argument.\n dimension -- If present, the argument is interpreted as an array.\n Dimensions must be a sequence containing tuples\n of first and last index in the range.\n precision -- FIXME\n \"\"\"\n\n if not isinstance(name, Symbol):\n raise TypeError(\"The first argument must be a sympy symbol.\")\n if datatype is None:\n datatype = get_default_datatype(name)\n elif not isinstance(datatype, DataType):\n raise TypeError(\"The (optional) `datatype' argument must be an instance of the DataType class.\")\n if dimensions and not isinstance(dimensions, (tuple, list)):\n raise TypeError(\"The dimension argument must be a sequence of tuples\")\n self.name = name\n self.datatype = datatype\n self.dimensions = dimensions\n self.precision = precision\n\n def get_symbols(self):\n \"\"\"Returns a set of all symbols related to this argument.\n\n Scalar arguments return themselves in a set, while array arguments return\n the array variable as well as all symbols the specifiy dimensions.\n \"\"\"\n if self.dimensions:\n symbs = set(flatten(self.dimensions))\n symbs.add(self.name)\n return symbs\n else:\n return set([self.name])\n\nclass InputArgument(Argument):\n pass\n\nclass ResultBase(object):\n\n @property\n def needs_initialization(self):\n return self._need_initialization\n\n def _prepare_expr(self):\n \"\"\"Depending on the expression, it may need to be prepared for loops\n\n Example:\n\n The math expression denoting a matrix vector product is\n\n y(i) = A(i,j)*x(j) (imlicit summation over j)\n\n Obviously, the code that calculates the matrix vector product must change\n the right hand side a little in order to store intermediate results\n correctly ....................\n |\n y = 0 |\n do i=1,m |\n do j = 1,n V\n y(i) = A(i,j)*x(i) + y(i)\n end do j\n end do i\n\n This would not be necessary if the left hand side has all indices that are on\n the right hand side. E.g. for a dyadic product:\n\n do i=1,m\n do j = 1,n\n A(i,j) = x(i)*y(j)\n end do j\n end do i\n\n \"\"\"\n rhs_loops = set([ i.label for i in self.expr.atoms(Idx) ])\n lhs_loops = set([ i.label for i in self.result_var.atoms(Idx) ])\n if rhs_loops - lhs_loops:\n self.expr = self.expr + self.result_var\n\nclass OutputArgument(Argument, ResultBase):\n \"\"\"OutputArgument are always initialized in the routine\n \"\"\"\n _need_initialization = True\n def __init__(self, name, result_var, expr, datatype=None, dimensions=None, precision=None):\n Argument.__init__(self, name, datatype, dimensions, precision)\n self.expr = expr\n self.result_var = result_var\n self._prepare_expr()\n\nclass InOutArgument(Argument, ResultBase):\n \"\"\"InOutArgument are never initialized in the routine\n \"\"\"\n _need_initialization = False\n\n def __init__(self, name, result_var, expr, datatype=None, dimensions=None, precision=None):\n Argument.__init__(self, name, datatype, dimensions, precision)\n self.expr = expr\n self.result_var = result_var\n\n\nclass Result(ResultBase):\n \"\"\"An expression for a scalar return value.\n\n The name result is used to avoid conflicts with the reserved word\n 'return' in the python language. It is also shorter than ReturnValue.\n \"\"\"\n _need_initialization = False\n\n def __init__(self, expr, datatype=None):\n \"\"\"Initialize a (scalar) return value.\n\n The second argument is optional. When not given, the data type will\n be guessed based on the assumptions on the expression argument.\n \"\"\"\n if not isinstance(expr, Expr):\n raise TypeError(\"The first argument must be a sympy expression.\")\n if datatype is None:\n datatype = get_default_datatype(expr)\n elif not isinstance(datatype, DataType):\n raise TypeError(\"The (optional) second argument must be an instance of the DataType class.\")\n self.expr = expr\n self.datatype = datatype\n self.result_var = Symbol('result_%s'%hash(expr))\n self._prepare_expr()\n\n#\n# Transformation of routine objects into code\n#\n\n\nclass CodeGen(object):\n \"\"\"Abstract class for the code generators.\"\"\"\n\n def __init__(self, project=\"project\"):\n \"\"\"Initialize a code generator.\n\n Derived classes will offer more options that affect the generated\n code.\n \"\"\"\n self.project = project\n\n def write(self, routines, prefix, to_files=False, header=True, empty=True):\n \"\"\"Writes all the source code files for the given routines.\n\n The generate source is returned as a list of (filename, contents)\n tuples, or is written to files (see options). Each filename consists\n of the given prefix, appended with an appropriate extension.\n\n Arguments:\n routines -- A list of Routine instances to be written\n prefix -- The prefix for the output files\n\n Optional arguments:\n to_files -- When True, the output is effectively written to\n files. [DEFAULT=False] Otherwise, a list of\n (filename, contents) tuples is returned.\n header -- When True, a header comment is included on top of each\n source file. [DEFAULT=True]\n empty -- When True, empty lines are included to structure the\n source files. [DEFAULT=True]\n \"\"\"\n if to_files:\n for dump_fn in self.dump_fns:\n filename = \"%s.%s\" % (prefix, dump_fn.extension)\n f = file(filename, \"w\")\n dump_fn(self, routines, f, prefix, header, empty)\n f.close()\n else:\n result = []\n for dump_fn in self.dump_fns:\n filename = \"%s.%s\" % (prefix, dump_fn.extension)\n contents = StringIO()\n dump_fn(self, routines, contents, prefix, header, empty)\n result.append((filename, contents.getvalue()))\n return result\n\n def dump_code(self, routines, f, prefix, header=True, empty=True):\n \"\"\"Write the code file by calling language specific methods in correct order\n\n The generated file contains all the definitions of the routines in\n low-level code and refers to the header file if appropriate.\n\n Arguments:\n routines -- a list of Routine instances\n f -- a file-like object to write the file to\n prefix -- the filename prefix, used to refer to the proper header\n file. Only the basename of the prefix is used.\n\n Optional arguments:\n header -- When True, a header comment is included on top of each\n source file. [DEFAULT=True]\n empty -- When True, empty lines are included to structure the\n source files. [DEFAULT=True]\n \"\"\"\n\n code_lines = []\n code_lines.extend(self._preprosessor_statements(prefix))\n for routine in routines:\n if empty: code_lines.append(\"\\n\")\n code_lines.extend(self._get_routine_opening(routine))\n code_lines.extend(self._declare_arguments(routine))\n code_lines.extend(self._declare_locals(routine))\n if empty: code_lines.append(\"\\n\")\n code_lines.extend(self._call_printer(routine))\n if empty: code_lines.append(\"\\n\")\n code_lines.extend(self._get_routine_ending(routine))\n\n if header and code_lines:\n self._dump_header(f)\n print >> f, ''.join(code_lines),\n\nclass CodeGenError(Exception):\n pass\n\n\nheader_comment = \"\"\"Code generated with sympy %(version)s\n\nSee http://www.sympy.org/ for more information.\n\nThis file is part of '%(project)s'\n\"\"\"\n\n\nclass CCodeGen(CodeGen):\n\n def _dump_header(self, f):\n \"\"\"Writes a common header for the generated files.\"\"\"\n print >> f, \"/\" + \"*\"*78\n tmp = header_comment % {\"version\": sympy.__version__, \"project\": self.project}\n for line in tmp.splitlines():\n print >> f, \" *%s* \" % line.center(76)\n print >> f, \" \" + \"*\"*78 + \"/\"\n\n def get_prototype_result(self, routine):\n \"\"\"Returns a string for the function prototype for the given routine and\n a single result object, which can be None.\n\n If the routine has multiple result objects, an CodeGenError is\n raised.\n\n See: http://en.wikipedia.org/wiki/Function_prototype\n \"\"\"\n prototype = []\n if len(routine.results) > 1:\n raise CodeGenError(\"C only supports a single or no return value.\")\n elif len(routine.results) == 1:\n result = routine.results[0]\n prototype.append(result.datatype.cname)\n else:\n result = None\n prototype.append(\"void\")\n # name of the routine + arguments + curly opening brackets\n prototype.append(\"%s(%s)\" % (\n routine.name,\n \", \".join(\"%s %s\" % (arg.datatype.cname, arg.name) for arg in routine.arguments)\n ))\n return \" \".join(prototype), result\n\n def _preprosessor_statements(self, prefix):\n code_lines = []\n code_lines.append(\"#include \\\"%s.h\\\"\\n\" % os.path.basename(prefix))\n code_lines.append(\"#include \\n\")\n return code_lines\n\n def _get_routine_opening(self, routine):\n prototype, result = self.get_prototype_result(routine)\n return [\"%s {\\n\" % prototype]\n\n def _declare_arguments(self, routine):\n # arguments are in prototype\n return []\n\n def _declare_locals(self, routine):\n code_list = []\n for var in sorted(routine.local_vars, key=str):\n typeinfo = get_default_datatype(var)\n code_list.append(\"%s %s\\n\" % (typeinfo.cname, var))\n return code_list\n\n def _call_printer(self, routine):\n prototype, result = self.get_prototype_result(routine)\n if result is not None:\n return [\" return %s;\\n\" % ccode(result.expr)]\n else:\n return []\n\n def _get_routine_ending(self, routine):\n return [\"}\\n\"]\n\n def dump_c(self, routines, f, prefix, header=True, empty=True):\n self.dump_code(routines, f, prefix, header, empty)\n dump_c.extension = \"c\"\n\n def dump_h(self, routines, f, prefix, header=True, empty=True):\n \"\"\"Writes the C header file.\n\n This file contains all the function declarations.\n\n Arguments:\n routines -- a list of Routine instances\n f -- a file-like object to write the file to\n prefix -- the filename prefix, used to construct the include\n guards.\n\n Optional arguments:\n header -- When True, a header comment is included on top of each\n source file. [DEFAULT=True]\n empty -- When True, empty lines are included to structure the\n source files. [DEFAULT=True]\n \"\"\"\n if header:\n self._dump_header(f)\n guard_name = \"%s__%s__H\" % (self.project.replace(\" \", \"_\").upper(), prefix.replace(\"/\", \"_\").upper())\n # include guards\n if empty: print >> f\n print >> f, \"#ifndef %s\" % guard_name\n print >> f, \"#define %s\" % guard_name\n if empty: print >> f\n # declaration of the function prototypes\n for routine in routines:\n prototype, result = self.get_prototype_result(routine)\n print >> f, \"%s;\" % prototype\n # end if include guards\n if empty: print >> f\n print >> f, \"#endif\"\n if empty: print >> f\n dump_h.extension = \"h\"\n\n # This list of dump functions is used by CodeGen.write to know which dump\n # functions it has to call.\n dump_fns = [dump_c, dump_h]\n\nclass FCodeGen(CodeGen):\n \"\"\"\n Generator for Fortran 95 code\n \"\"\"\n\n def __init__(self, project='project'):\n CodeGen.__init__(self, project)\n\n def _dump_header(self, f):\n \"\"\"Writes a common header for the generated files.\"\"\"\n print >> f, \"!\" + \"*\"*78\n tmp = header_comment % {\"version\": sympy.__version__, \"project\": self.project}\n for line in tmp.splitlines():\n print >> f, \"!*%s* \" % line.center(76)\n print >> f, \"!\" + \"*\"*78\n\n def _preprosessor_statements(self, prefix):\n return []\n\n def _get_routine_opening(self, routine):\n \"\"\"\n Returns the opening statements of the fortran routine\n \"\"\"\n code_list = []\n if len(routine.results) > 1:\n raise CodeGenError(\"Fortran only supports a single or no return value.\")\n elif len(routine.results) == 1:\n result = routine.results[0]\n code_list.append(result.datatype.fname)\n code_list.append(\"function\")\n else:\n code_list.append(\"subroutine\")\n\n # name of the routine + arguments\n code_list.append(\"%s(%s)\\n\" % (routine.name,\n \", \".join(\"%s\" % arg.name for arg in routine.arguments)))\n code_list = [ \" \".join(code_list) ]\n\n code_list.append('implicit none\\n')\n return code_list\n\n def _declare_arguments(self, routine):\n # argument type declarations\n code_list = []\n array_list = []\n scalar_list = []\n for arg in routine.arguments:\n\n if isinstance(arg, InputArgument):\n typeinfo = \"%s, intent(in)\" % arg.datatype.fname\n elif isinstance(arg, InOutArgument):\n typeinfo = \"%s, intent(inout)\" % arg.datatype.fname\n elif isinstance(arg, OutputArgument):\n typeinfo = \"%s, intent(out)\" % arg.datatype.fname\n else:\n raise CodeGenError(\"Unkown Argument type: %s\"%type(arg))\n\n if arg.dimensions:\n # fortran arrays start at 1\n dimstr = \", \".join([\"%s:%s\"%(dim[0]+1, dim[1]+1)\n for dim in arg.dimensions])\n typeinfo += \", dimension(%s)\" % dimstr\n array_list.append(\"%s :: %s\\n\" % (typeinfo, arg.name))\n else:\n scalar_list.append(\"%s :: %s\\n\" % (typeinfo, arg.name))\n\n # scalars first, because they can be used in array declarations\n code_list.extend(scalar_list)\n code_list.extend(array_list)\n\n return code_list\n\n def _declare_locals(self, routine):\n code_list = []\n for var in sorted(routine.local_vars, key=str):\n typeinfo = get_default_datatype(var)\n code_list.append(\"%s :: %s\\n\" % (typeinfo.fname, var))\n\n return code_list\n\n\n def _get_routine_ending(self, routine):\n \"\"\"\n Returns the closing statements of the fortran routine\n \"\"\"\n if len(routine.results) == 1:\n return [\"end function\\n\"]\n else:\n return [\"end subroutine\\n\"]\n\n def get_interface(self, routine):\n \"\"\"Returns a string for the function interface for the given routine and\n a single result object, which can be None.\n\n If the routine has multiple result objects, a CodeGenError is\n raised.\n\n See: http://en.wikipedia.org/wiki/Function_prototype\n\n \"\"\"\n prototype = [ \"interface\\n\" ]\n prototype.extend(self._get_routine_opening(routine))\n prototype.extend(self._declare_arguments(routine))\n prototype.extend(self._get_routine_ending(routine))\n prototype.append(\"end interface\\n\")\n\n return \"\".join(prototype)\n\n def _get_result(self, routine):\n \"\"\"Returns a single result object, which can be return value or outargument\n \"\"\"\n\n if len(routine.results) > 1:\n raise CodeGenError(\"Fortran only supports a single or no return value.\")\n elif len(routine.results) == 1:\n result = routine.results[0]\n else:\n outargs = [ arg for arg in routine.arguments if\n isinstance(arg, (OutputArgument, InOutArgument))]\n if len(outargs) == 1:\n result = outargs[0]\n else:\n raise CodeGenError(\"FIXME: need one and only one result object. Got %s\"%len(outargs))\n\n return result\n\n def _init_resultvars(self, routine):\n \"\"\"Returns codelines that intialize the result variables if applicable.\n \"\"\"\n code_lines = []\n for arg in routine.arguments:\n if isinstance(arg, OutputArgument):\n if arg.datatype.fname == 'REAL*8':\n code_lines.append(\"%s = 0.d0\\n\" % arg.name)\n elif arg.datatype.fname == 'INTEGER*4':\n code_lines.append(\"%s = 0\\n\" % arg.name)\n else:\n raise NotImplementedError\n if routine.results:\n code_lines.append(\"%s = 0.d0\\n\" % routine.name)\n\n return code_lines\n\n def _call_printer(self, routine):\n code_lines = []\n for result in routine.result_variables:\n if isinstance(result, Result):\n assign_to = routine.name\n elif isinstance(result, (OutputArgument, InOutArgument)):\n assign_to = result.result_var\n\n constants, not_fortran, f_expr = fcode(result.expr,\n assign_to=assign_to, source_format='free', human=False)\n code_lines.extend(constants)\n if result.needs_initialization:\n code_lines.extend(self._init_resultvars(routine))\n code_lines.append(\"%s\\n\" % f_expr)\n return code_lines\n\n def dump_f95(self, routines, f, prefix, header=True, empty=True):\n self.dump_code(routines, f, prefix, header, empty)\n dump_f95.extension = \"f90\"\n\n def dump_h(self, routines, f, prefix, header=True, empty=True):\n \"\"\"Writes the interface header file.\n\n This file contains all the function declarations.\n\n Arguments:\n routines -- a list of Routine instances\n f -- a file-like object to write the file to\n prefix -- the filename prefix, used to construct the include\n guards.\n\n Optional arguments:\n header -- When True, a header comment is included on top of each\n source file. [DEFAULT=True]\n empty -- When True, empty lines are included to structure the\n source files. [DEFAULT=True]\n \"\"\"\n if header:\n self._dump_header(f)\n if empty: print >> f\n # declaration of the function prototypes\n for routine in routines:\n prototype = self.get_interface(routine)\n print >> f, prototype,\n if empty: print >> f\n dump_h.extension = \"h\"\n\n # This list of dump functions is used by CodeGen.write to know which dump\n # functions it has to call.\n dump_fns = [dump_f95, dump_h]\n\n\ndef get_code_generator(language, project):\n CodeGenClass = {\"C\": CCodeGen, \"F95\": FCodeGen}.get(language.upper())\n if CodeGenClass is None:\n raise ValueError(\"Language '%s' is not supported.\" % language)\n return CodeGenClass(project)\n\n\n#\n# Friendly functions\n#\n\n\ndef codegen(name_expr, language, prefix, project=\"project\", to_files=False, header=True, empty=True):\n \"\"\"Write source code for the given expressions in the given language.\n\n Mandatory Arguments:\n name_expr -- A single (name, expression) tuple or a list of\n (name, expression) tuples. Each tuple corresponds to a\n routine. If the expression is an equality (an\n insance of class Equality) the left hand side is considered\n an output argument.\n language -- A string that indicates the source code language. This\n is case insensitive. For the moment, only 'C' is\n supported.\n prefix -- A prefix for the names of the files that contain the source\n code. Proper (language dependent) suffixes will be\n appended.\n\n Optional Arguments:\n project -- A project name, used for making unique preprocessor\n instructions. [DEFAULT=\"project\"]\n to_files -- When True, the code will be written to one or more files\n with the given prefix, otherwise strings with the names\n and contents of these files are returned. [DEFAULT=False]\n header -- When True, a header is written on top of each source file.\n [DEFAULT=True]\n empty -- When True, empty lines are used to structure the code.\n [DEFAULT=True]\n\n >>> from sympy import symbols\n >>> from sympy.utilities.codegen import codegen\n >>> from sympy.abc import x, y, z\n >>> [(c_name, c_code), (h_name, c_header)] = \\\\\n ... codegen((\"f\", x+y*z), \"C\", \"test\", header=False, empty=False)\n >>> print c_name\n test.c\n >>> print c_code,\n #include \"test.h\"\n #include \n double f(double x, double y, double z) {\n return x + y*z;\n }\n >>> print h_name\n test.h\n >>> print c_header,\n #ifndef PROJECT__TEST__H\n #define PROJECT__TEST__H\n double f(double x, double y, double z);\n #endif\n\n \"\"\"\n\n # Initialize the code generator.\n code_gen = get_code_generator(language, project)\n\n # Construct the routines based on the name_expression pairs.\n # mainly the input arguments require some work\n routines = []\n if isinstance(name_expr[0], basestring):\n # single tuple is given, turn it into a singleton list with a tuple.\n name_expr = [name_expr]\n\n for name, expr in name_expr:\n routines.append(Routine(name, expr))\n\n # Write the code.\n return code_gen.write(routines, prefix, to_files, header, empty)\n", "meta": {"hexsha": "826292629d331e6cc7770ddf47e4d4b8d447ac7b", "size": 31344, "ext": "py", "lang": "Python", "max_stars_repo_path": "sympy/utilities/codegen.py", "max_stars_repo_name": "matthew-brett/sympy", "max_stars_repo_head_hexsha": "7b87b62144c28f2e734e9106897c72806b99d181", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sympy/utilities/codegen.py", "max_issues_repo_name": "matthew-brett/sympy", "max_issues_repo_head_hexsha": "7b87b62144c28f2e734e9106897c72806b99d181", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sympy/utilities/codegen.py", "max_forks_repo_name": "matthew-brett/sympy", "max_forks_repo_head_hexsha": "7b87b62144c28f2e734e9106897c72806b99d181", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0934911243, "max_line_length": 109, "alphanum_fraction": 0.608409903, "include": true, "reason": "import sympy,from sympy", "num_tokens": 6634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.25386099567919973, "lm_q1q2_score": 0.12593887349979474}} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Lab 3: Building a Photometric Pipeline\n# \n# In this lab, we'll be using classes and functions to build a pipeline which will automatically extract the fluxes of stars in an image. We're all familiar with aperture photometry, but in this case, we're going to take the additional step of convolving our image with a PSF. \n# \n# Our pipeline will be split into several steps. \n# \n# 1. Reading in an image \n# 2. Finding the local peaks in the image (the stars)\n# 3. Calculating the centroid of each peak region \n# 4. Convolving with the PSF and extracting flux. \n# \n# \n\n# ```{warning}\n# When you modify a class and re-run it, you need to re-instantiate (or make a new instance) of the class for it to reflect the changes. This is a common mistake in notebooks, where a class might get changed but your instance of it didn't get re-created. Watch out for this during the lab -- the safest bet is to just copy-paste your instantiation code (`a = MyObj()` type thing) into each problem so you sure you're working with the latest version of your class. \n# \n# You'll be copying and pasting (and overwriting) your class in this assignment quite a bit. That's not super realistic to reality (where you'd pick one cell and keep modifying it there), but for grading purposes we ask you follow along so we can give credit for each method of the class you complete and demonstrate along the way.\n# ```\n\n# ## Assignment Rubric\n# ````{panels}\n# The points for this assignment are as follows:\n# - Problem 1 (4 pts)\n# - Problem 2 (8 pts)\n# - Problem 3 (5 pts)\n# - Problem 4 (3 pts)\n# ````\n\n# ## Problem 1\n# In this problem, we'll load in the image(s) for use and begin constructing our `PSFPhot` class. \n# \n# ### Problem 1.1\n# Create a script (`.py` file) in this directory and copy into it your `load_fits()` and final `implot()` functions from last lab. Then import them here. \n# \n# Use your `load_fits()` to read in in the image `2020-04-15-0001.fits` and plot it with `implot()`. \n# \n# This image was taken of the M81/M82 field using the Dragonfly Telephoto Array (in a narrowband configuration). \n\n# In[ ]:\n\n\n# import your functions here \n\n\n# In[1]:\n\n\n# Use them to load and show the image we'll be working with\n\n\n# ```{hint}\n# M82 should be visible left of center, M81 on the left hand edge. Two features caused by detector amp glow are also visible at the bottom of the image. \n# ```\n\n# ### Problem 1.2 \n# \n# Finish the syntax for creating the `PSFPhot` class below. The init for the class should ask for three string paths: one to an image, one to a dark file, and one to a flat file. Within `__init__()`, use your `load_fits()` function to get the just the science image and header into the class. Store them as class attributes `self.data_init` and `self.data_header`.\n# \n# Don't forget to add a docstring to your init! It doesn't return anything, but sets the initial attributes.\n\n# In[ ]:\n\n\nclass PSFPhot():\n \n\n\n# ### Problem 1.3 \n# \n# Add a method to your class called `dark_subtract()` which takes an image and a string-path to a dark file. Use `load_fits()` to read it in the dark, and subtract it from the image, and return the output. \n# \n# Add another method called `flat_field()` which takes in an image and a string-path to a flatfield file. Use `load_fits()` to read it in, normalize it to its maximum value, and divide the input image by it. \n# \n# Finally, within your init function, set a new class attribute called `self.data_calibrated`, and set it equal to the output of your calibration methods as run on the set of image paths that have been input. \n# \n# ```{hint}\n# This step can be done in one line with nested functions if you prefer.\n# ``\n# \n# Finally Use `implot()` to plot both the `data_init` and `data_calibrated` and show that your calibrations worked. You should see the amp glow regions dissapear, and the image sky should look nice and uniform.\n\n# In[527]:\n\n\nclass PSFPhot():\n \n\n\n# ```{note}\n# Running the dark/flat methods within init means they'll happen right away when someone instantiates an object of this class. It's a matter of code design and personal preference to do this, versus having the user run those methods manually as part of the UX. I choose to wrap it into the init because it's a basic, common thing all inputs will need done to them.\n# ```\n\n# ### Problem 1.4 \n# \n# The final step in setting up our image for proper analysis is the subtraction of the globally varying sky background. Performing that fit (generally a low order 2D polynomial of some kind) is beyond the scope of this lab, but we encourage you to look into this step more if you are interested. \n# \n# Instead, we're going to return to the `sep` package and take advantage of its background estimation feature. Recall it reads in the base image array and a separate mask. We want the user of this class to be able to supply a mask, so we won't run this step automatically in `__init__()`.\n# \n# Using the same stucture as in Lab 2, we'll calculate the background using `sep`.\n# \n# Add a method to your class that is called `subtract_background`, whose only argument (besides `self`) should be an optional mask (default `None`). \n# \n# Inside, use `sep` to measure the background and access, e.g., the `bkg.back()` method, and subtract this background-image from `self.data_calibrated`. You should set `mask=mask` in the sep call so your method input gets passed through. For convenient access, store the output of `bkg.back()` in a class attribute called `self.background`, and then set `self.image` equal to the background subtracted image. This method is known as a *setter*, because we're setting a class attribute but not returning anything. \n# \n# It can be handy here to add a print statement at the end of the method saying something like `\"Background estimated; output saved to attribute 'image' \"`. Since this is the main image we'll be using from now on, I've elected to give it the short name `image`. You may rather use something like `data_bg_sub`, for example\n# \n# ```{warning}\n# Don't forget about the C order switch with sep.\n# ```\n\n# In[528]:\n\n\nclass PSFPhot():\n \n \n\n\n# Our class usage will now look something like \n# ```\n# pipe = PSFPhot(im_path,dark_path,flat_path)\n# pipe.subtract_background()\n# ```\n# \n# or, if we create a mask (as we will below), \n# ```\n# pipe = PSFPhot(im_path,dark_path,flat_path)\n# mask = # Something here \n# pipe.subtract_background(mask=mask)\n# ```\n# \n\n# ## Problem 2\n# \n# Our goal is to estimate the PSF of the above image, then measure fluxes of the stars and galaxies here accounting for the PSF. \n# \n# To start this process, we need to locate the stars in this image. We saw how to segment an image using `sep` last time, but in this lab we are going to carry out this step ourselves, using two methods. \n# \n# ### Problem 2.1\n# \n# Before we do this, we want to take the step of masking out several regions of the image which may register as peaks but which are not nicely isolated stars. In particular, the two galaxies need to be masked out when both estimating the background and when looking for point sources.\n# \n# \n# Create a mask of the dimensions of the image data, containing `False` everywhere except where we want to mask out the galaxies (rough rectangular regions are fine for this masking). It's easiest to make the full array `False` first, then set the regions we want to mask to `True` via image indexing. \n# \n# Add a method to your class called `set_image_mask()` which overwrites `self.image` with a numpy masked array containing what used to be `self.image` as the data, and a mask that the user inputs. \n# \n# Finally, instantiate your class into a variable and check that the masking and subtraction are both working. You should plot your image by accessing it (it should be a class attribute by now). It should look like mine below.\n# ```{warning}\n# If we have the memory to, it's often worth avoiding overwriting class attributes. Here, we could set the masked image as `self.image_masked`, for example. I've elected not to here for two reasons. One: simplicity. Two: the unmasked version of the image is easily accessible still via `self.image.data`, the data attribute of numpy masked arrays.\n# ```\n\n# In[535]:\n\n\n# Solution\nmask = #define mask \n\nclass PSFPhot():\n \n\n\n# In[536]:\n\n\n# instantiate your class, run the subtraction, input the mask, see that it all works.\n\n\n# \n# ```{note}\n# In our use case for this lab, the mask we will use when background subtracting is the same as the one we'll use for blocking out regions from being included in peak finding and such. But our code is flexible enough to, e.g., mask when background-subtracting but not when peak finding, or vice versa. Our mask setter only affects the image data, and the mask argument in the subtract background method only affects background subtraction.\n# ```\n# \n# ```{tip}\n# As it stands, `set_image_mask()` can only be run *after* `subtract_background()`, because that method sets `self.image` for the first time. We can use the `hasattr(self,'image')` check to see, when `set_image_mask()` is run, if that previous method was already run and `self.image` exists. For now, it's ok to assume the user will use the class in order, but a more robust code would either raise an exception or otherwise handle this case in some way.\n# ```\n\n# Plot the `.background` attribute of your class. It seems our image has a spatially varying background that includes a gradient across the image.\n\n# In[ ]:\n\n\n#plot the background\n\n\n# ### Problem 2.2\n# \n# Now that we have the appropriate image regions masked, we can move on to the peak finder. \n# \n# The \"fast\" or \"efficient\" method of doing this involves some scipy filtering operations. But for our purposes, the \"slow way\" (iterating over the image pixels) takes ~few seconds to run, and is worth doing to build intuition. \n# \n# Add a method to your class to find peaks in an image by looping over each pixel and checking its neighbors, with a \"peak\" being defined as a region of higher flux than all adjacent pixels (i.e., the 8 surrounding pixels). In order to not pick up random noise pixels, also take an input called `threshold`. Within your algorithm, don't return any pixels which are \"peaks\" but for which the pixel value is below this threshold. \n# \n# ```{hint}\n# :class: dropdown\n# This algorithm needs to avoid the edges of the image (since indexing \"i+1\" won't work there). Creating a 1 pixel \"buffer\" in your looping will prevent this. \n# ```\n\n# In[70]:\n\n\n# your code here\n\n\n# The looping solution is slow, and will not scale well if we have to run on many images, but for one image is okay. \n# \n# There are several solutions which generally involve either **filtering** the image or **cross correlating** the image with a template. Here's one such solution.\n\n# In[399]:\n\n\nfrom scipy.ndimage import maximum_filter\n\ndef findpeaks_maxfilter(image, threshold):\n '''\n Algorithm for finding peaks (above a threshold) in an image\n \n Parameters\n ----------\n image: array_like\n 2D array containing the image of interest.\n threshold: float\n minimum pixel value for inclusion in search\n \n Returns\n -------\n peaks: array_like\n array containing the x and y coordinates of peak regions.\n '''\n neighborhood = np.ones((3,3),dtype=bool) # just 3x3 True, defining the neighborhood over which to filter\n # find local maximum for each pixel\n amax = maximum_filter(image, footprint=neighborhood) #max filter will set each 9-square region in the image to the max in that region.\n \n peaks = np.where((image == amax) & (image >= threshold)) #find the pixels unaffected by the max filter.\n peaks = np.array([peaks[0],peaks[1]]).T\n return peaks\n\n\n# Let's take a moment to understand how this algorithm works. The key is in the `maximum_filter()` step. Filtering a 2D image is a process carried out in fourier space, which is what allows scipy to carry it out quickly. But what is maximum filtering?\n# \n# ```{admonition} Definition\n# Maximum Filtering is the process by which all pixels in local neighborhoods within an array are raised to the maximum value of any pixel in that neighborhood\n# ```\n# \n# Let's look at a 1D case. Below, I define a 1D array that has some peaks in it. \n\n# In[110]:\n\n\narray_1dpeaks = np.array([1,1,2,1,2,1,2,1,2,3,4,3,2,1,2,4,5,6,8,6,5,4,3,2,4,3,4,2,1,0.5,1,2,1,2,3,2])\n\n\n# Our data looks like this:\n\n# In[122]:\n\n\nfig, ax = plt.subplots(figsize=(6,6))\nax.plot(array_1dpeaks,lw=1.5,alpha=0.9)\nax.plot(array_1dpeaks,'o',color='C0')\n\n\n# Let's now run the maximum filter on this data and plot it's output. I'm going to pick a neighborhood of 3, which means +/- 1 pixel around each location.\n\n# In[112]:\n\n\nmf = maximum_filter(array_1dpeaks, footprint=np.ones(3,dtype=bool)) \n\n\n# In[120]:\n\n\nfig, ax = plt.subplots(figsize=(6,6))\nax.plot(array_1dpeaks,lw=1.5,alpha=0.9,label='original array')\nax.plot(array_1dpeaks,'o',color='C0')\nax.plot(mf,label='max filtered array')\neq, = np.where(array_1dpeaks==mf)\nax.plot(np.arange(len(mf))[eq],mf[eq],'o',label='local peaks')\nax.legend();\n\n\n# What the filtering has done is for every 3 pixel neighborhood across this array, it's raised the value of all three pixels to the maximum value across the three. So we see that anywhere the three pixels were, e.g., (1,2,1), they are all now 2. What you should notice looking at this plot is that the max filtering has also identified true peaks in our data! Notice that the only spots where the orange curve (the max filtered version of the data) is equal to the original array is exactly at locations that are local maxima. This is because when applying max filtering to an array, the only values *unchanged* by the filtering are those that *are* local maxima (in the neighborhood defined). \n# \n# And thus, we have our peaks! All we need to do is find out `where()` the max filtered array equals the original array. Of course, we can also put in a threshold (in this example, maybe 2.5) to ensure low level noise doesn't enter in. This is why the `findpeaks_maxfilter()` function has a threshold option as well.\n# \n# ```{note}\n# You may notice that the first index in the array is marked as a peak, despite not being one. Edges are always troublesome with these algorithms, and they normally have multiple options for how edges are handled, e.g, interpolating a constant value, reflecting over the edge, etc. For our lab, we're not going to worry about this.\n# ```\n# \n\n# ### Problem 2.3 \n# \n# How fast is max filtering over your looping algorithm?\n# \n# Use the `%%timeit` magic command in your notebook to test how fast the two algorithms are respectively. If you were working with a sample of 1000 images, how long would the looping algorithm take compared to the max-filtering case?\n# \n# ```{hint}\n# Check out the \"Timing Code\" page in the \"Quick Tips\" sidebar tab of our website to see examples of using the `timeit` module.\n# ```\n\n# In[ ]:\n\n\n# time your function\n\n\n# In[ ]:\n\n\n# time the max filter function\n\n\n# How many times faster is the max filtering?\n\n# In[ ]:\n\n\n# Calculate \n\n\n# How long would it take to run each on 1000 images (extrapolating from your results)?\n\n# In[ ]:\n\n\n# Calculate\n\n\n# For the rest of the lab, you can either leave in your peak finder, or replace it with the max-filtering version (turning the function above into a method). \n# \n# Either way, add a peak-finding method into your class, which should be runnable with no inputs, but has an optional threshold argument to set a minimum flux value for inclusion. \n\n# In[ ]:\n\n\n# your class here\n\n\n# ### Problem 2.4 \n# \n# Run your peakfinder on your masked image, and assemble the list of peaks you'll use moving forward. Your peakfinder method should save a class attribute `self.peak_locations` which contains the ($x,y$) pairs of points associated with your peaks. \n# \n# \n# Plot up the original image, but use our \"source circling\" technique from last lab to circle all the peaks found in the masked image. I show mine below. \n# \n# ```{hint}\n# Recall that `implot()` returns a set of `fig, ax`, so you can then plot the circles onto the same axis as the image.\n# ```\n\n# In[549]:\n\n\n# re-instantiate your object, run the subtraction, then your new peak finder here. \n\n\n# ### Problem 2.5 \n# \n# This should look pretty good -- most of what's circled above is clearly a star/point source in the image. However, one problem with this method is that single hot pixels are going to be registered as peaks, even via the clever algorithm. We need a way to eliminate these from our sample before moving on. \n# \n# Adjust your peak-finder method to add in something that checks that not only is there a true peak, but that at least 4 of the pixels around the peak are also elevated in flux (I used 0.5 times the peak flux). The easiest way is to loop over the peaks after they're found and institute the check --- there are far fewer peaks than pixels, so this doesn't significantly affect the runtime. But feel free to find a cleverer solution!\n# \n# ```{warning}\n# Be careful with transpositions in this problem. when you plot coordinates, you plot(x,y), but when you index the image, you index image[y,x]. Always be tracking which is which! \n# ```\n\n# In[619]:\n\n\nclass PSFPhot():\n \n\n\n# Re-find your peaks using your newer, better algorithm, and plot them below as before.\n\n# In[ ]:\n\n\n# your code here\n\n\n# Notice that we've decreased our total number of peaks. But you should find that now, everything currently circled looks like a bright, \"resolved\" star. (resolved insofar as the PSF is spreading the light of the star over multiple pixels). \n# \n# ### Problem 2.6 \n# \n# In your the image above, you should see that ~8-10 stars look like they are circled by several very closely overlapping circles all targeting the same star. Infer (or investigate and determine) why this has happened, and write your answer below. \n# \n# \n# \n\n# *answer here*\n\n# ## Problem 3 \n# \n# We now have a function that can return the peaks in a given image. Our next step is going to be to estimate the exact center of those peaks (stars) using their **centroid**.\n# \n# ```{admonition} Definition\n# The centroid is the light-weighted-mean of a set of pixels. It is not always the maximum-valued pixel, and is determined to sub-pixel accuracy.\n# ```\n# \n# Many of you have seen the centroid formula, but as a reminder, it looks like this (in 1D):\n# \n# \n# $$\n# x_{\\rm com} = \\frac{\\sum{x_i \\hat{f}_i}}{\\sum \\hat{f}_i},\n# $$\n# \n# where $x_i$ are the positions and $\\hat{f}_i$ are the fluxes at those positions. \n# \n# In 2D, when working with images, the $x$ and $y$ centers of mass are independent, and the 2D centroid is just the location ($x_{\\rm com}$, $y_{\\rm com}$). \n# \n# ### Problem 3.1 \n# \n# Add a method to your class called `centroid()` which should read in an $x$ and $y$ peak location (these will be returned by your peak finder), then creates a cutout by indexing `self.image` in a window of N (user-settable), and determine the centroid of this window. The $x,y$ location of this centroid should be returned.\n# \n# One subtlety --- We want to use a window size greater than 1 pixel on either side of each peak. But because our peak finder is likely to have found peaks near the edge of the detector (both because it needs only 1 pixel-thick borders and because it handles edges), if we write a centroid function that, e.g., uses a 10x10 pixel window, we'll end up trying to index over the edge of the original image whenever there's a star near the edge. Because of this, your function should raise an exception if a peak position is entered whose distance from an edge is less than half the window size. \n\n# In[622]:\n\n\nclass PSFPhot():\n # copy down and add to your class\n\n\n# ### Problem 3.2 \n# Use your `centroid()` function to confirm that the algorithm is working by testing it on a few individual peaks from your peak list, and make a plot showing the window region and the determined centroid (along with the location of the input peak). I'm leaving behind a demo of what I mean below. The blue point is the pixel with the peak flux, while the crosshairs center on the determined centroid\n# \n# ```{Note}\n# It's usually ok if the centroid is not at what appears to be the very center of the light distribution of the star. Often due to seeing and detector effects, along with tricks of the stretch you happen to be using, the centroid doesn't look perfectly centered. But it shouldn't be super off, either -- see below.\n# ```\n# In my solution below, I plot 25 stars from my peak finder, with peaks and centroids shown. You should get similar looking results as you query stars in frame.\n# \n\n# In[624]:\n\n\n# You need not plot 25, but check a handful of stars to make sure you're in business.\n\n\n# ### Problem 3.3 \n# \n# If you recall from above, you determined why the peak algorithm occasionally marked a bunch of pixels as peaks within the same star, which shouldn't happen. It should be clear from your answer that these stars will be unusable for the purposes of measuring the PSF of stars in the image. We thus need to remove these ~8-10 stars from our sample. \n# \n# Write a method `check_stars()` which takes in the list of centroids, and identifies these cases. The easiest way to do this is to simply iterate through the list of centroids and compute the distance to all other centroids in the list. Any subgroups with small distances should be removed. (Say, 5-10 pixels). \n# \n# \n# This method should return the final list of centroids for use. Plot them over the data to confirm these \"stacked\" peak cases have been removed. \n# \n\n# In[ ]:\n\n\n# your code here\n\n\n# ## Problem 4\n# \n# Armed with a dark-subtracted, flat-fielded, background-subtracted image, as well as with a list of centroids corresponding to stars in our image, we are ready to estimate the PSF. \n# \n# There are two main functional forms typically used to fit star profiles: 2D Gaussians, and Moffat profiles (which combines the shapes of a Gaussian and Lorentzian to best match both the inner and outer regions of the PSF). \n# \n# We're going to use the [`Gaussian2D`](https://docs.astropy.org/en/stable/api/astropy.modeling.functional_models.Gaussian2D.html) class from `astropy` to do this:\n\n# In[433]:\n\n\nfrom astropy.modeling.functional_models import Gaussian2D\n\n\n# For each star, a Gaussian2D profile (normalized) will be used \"as the PSF\". The parameters we need to know for this profile are $x,y$, for which we'll use the centroids we calculated earlier, the amplitude (set by the normalization), and $\\sigma_x,\\sigma_y$, the standard deviations in the two axes. For this lab, we're going to assume our stars are circular ($\\sigma_x=\\sigma_y$). This is a strictly incorrect, but not a bad assumption for most cases. All other optional arguments we won't need, primarily due to the assumption of circularity. \n# \n# ```{note}\n# We are going to make a point estimate of the \"size\" of the stars in our image, which constrains us from using a more fancy model for the PSF. An example of a more sophisticated setup would be *fitting* a Gaussian or Moffat profile to every star, and in a Bayesian framework marginalizing over the stars to determine the best-fit PSF (including ellipticity, etc) for the image, or, even fancier, interpolating a PSF model which varies over the detector.\n# ```\n# \n# PSF photometry works by multiplying the *data* (say, a cutout around a star) by the *estimated PSF* during the fluxing stage. Instead of picking a radius and performing aperture photometry (which includes fully all pixels within the aperture and throws out all pixels beyond), this method attempts to weight each pixel fractionally by how likely it is to be stellar flux, with the weighting coming from the PSF of the detector. This means further pixels may still be included, but will contribute less than pixels near the center of the star. \n# \n# The formula for measuring the PSF flux of a star is \n# \n# $$\n# f_{\\rm PSF} = \\frac{\\sum \\hat{f_i} p_i}{\\sum p_i^2},\n# $$\n# \n# where $\\hat{f_i}$ are the fluxes in your image and $p_i$ is your PSF estimate. This formula should be reminiscent of the centroiding formula; it's a similar weighting scheme.\n\n# `Gaussian2D` is a class, but we want to interact with it pretty simply, and have simplified inputs. I've made a quick wrapper function below which allows us to enter $\\sigma_x$ and $\\sigma_y$ and then $x,y$ grids created via `np.meshgrid()`, and creates the Gaussian and evaluates it on our grid. \n\n# In[490]:\n\n\ndef eval_gauss(x_arr,y_arr,sigma_x,sigma_y,mu_x,mu_y):\n \n g = Gaussian2D.evaluate(x=x_arr,y=y_arr,amplitude=1,theta=0,x_mean=mu_x,\n y_mean=mu_y,\n x_stddev=sigma_x,\n y_stddev=sigma_y)\n g/=np.sum(g)\n return g\n\n\n# In[491]:\n\n\nxx, yy = np.meshgrid(np.arange(loc[0]-10,loc[0]+10),\n np.arange(loc[1]-10,loc[1]+10))\nmodel = eval_gauss(x_arr=xx,y_arr=yy,sigma=3,mu_x=testx,mu_y=testy)\n\n\n# In[485]:\n\n\nfig, ax = plt.subplots(figsize=(8,8))\nax.imshow(model,origin='lower')\n\n\n# As we can see, I now have a model for the PSF which I can easily create for given inputs. We're going to do this for cutouts around each star, and instead of a random $\\sigma$, we're going to estimated it using the second moment (moment of inertia) of the star itself.\n# \n# The formula for this (from Markevich et al. 1989) is \n# \n# $$\n# \\sigma_x = \\left[\\frac{\\sum x_i^2 \\hat{f}_i}{\\sum \\hat{f}_i} - x_{\\rm com}^2\\right]^{1/2}\n# $$\n# \n# $$\n# \\sigma_y = \\left[\\frac{\\sum y_i^2 \\hat{f}_i}{\\sum \\hat{f}_i} - y_{\\rm com}^2\\right]^{1/2}\n# $$\n# \n# In this case, we'll need to use `meshgrid()` directly within our second moment function, as you can see it depends on the difference between the pixels and the centroid.\n# \n# ### Problem 4.1\n# \n# Add a method to your class called `second_moment` which reads in an image cutout, the meshgrid input (xx,yy) (or constructs it), and finally, a centroid (x and y). Inside, use the formulas above to determine sigma_x and sigma_y, and return them\n\n# In[494]:\n\n\n\n\n\n# Below, I show that a functional form of my second moment code returns 2.92 and 2.98 when run on the example psf I made above (which had a true sigma of 3). \n\n# In[495]:\n\n\nsecond_moment(model,xx,yy,testx,testy)\n\n\n# Within 10%, this calculation, which requires no fitting, tells us $\\sigma$ (under the assumption the distribution is Gaussian). Thus, by running out image cutouts through this function, we can derive for ourselves a good $\\sigma$ to choose in our Gaussian model of the PSF. \n\n# ### Problem 4.2\n# \n# We now have everything we need to run our pipeline. \n# \n# Right now, our final three methods (centroider, star checker, and width-finder) all *return* their values. I had you do it that way for testing purposes. To finalize our \"object oriented pipeline\" though, we should make a wrapper method that will bring them together and handle the outputs.\n# \n# \n# Add a new, final method called `psf_photometry`. When the user runs this method, it should first feed the peaks into the centroid code one by one, assembling a set of centroids. It should then construct cutouts of `self.image` around each peak (or centroid), and feed those, plus the centroids, and appropriate meshgrids into the second moment function to save a pair sigma_x and sigma_y for each star as well. And finally, it should use the eval_gauss function I've provided above to create a reasonable PSF model, then carry out the PSF photometry (using the equation above).\n# \n# At the end of it all, you can save the centroids, widths, and psf-fluxes all to class attributes, where they will remain accessible. You can also find a nice way to return them for extra credit (see below).\n\n# In[ ]:\n\n\n# I know this was long! Congrats for getting here!\n\n\n# ## Bonus Problem (+1 Extra Credit)\n# \n# A convenient way to return the set of measurements carried out by our pipeline is via a `flux table`, like the one returned by `aperture_photometry` from `astropy`. For our purposes, since we'll be spending a lot of time with data frames, let's go with that. \n# \n# Modify your final `psf_photometry` method to assemble a nice `DataFrame` which contains as colummns `peak_x`, `peak_y`, `centroid_x`, `centroid_y`, `width_x`, `width_y`, and `psf_flux`. Each row should be the relevant values for a given star that was originally found by your peakfinder (but which made it through our sample cleaning stage). \n# \n# ```{tip}\n# Inside your final method, you probably have lists or arrays containing the output of your centroid and width methods as they looped over the stars (and your find peak function returns a list of positions outright). So if you set up an empty DataFrame, you can set, e.g., `df['peak_x'] = peaks[:,0]` or something like `df['width_x'] = out_widths`, to set up these columns. As long as you never messed with the order of the lists, it should turn into the desired output frame.\n# ```\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "a5dc2afb9cf61ac7ed06c0f48824dd5d7452bb6c", "size": 28951, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/Lab3/Lab3.py", "max_stars_repo_name": "Astro-330/Astro-330.github.io", "max_stars_repo_head_hexsha": "e7ba5d1db0f369a110419e939d9ed2d29c9d7020", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-08-28T23:26:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T14:35:17.000Z", "max_issues_repo_path": "_build/jupyter_execute/Lab3/Lab3.py", "max_issues_repo_name": "mgebran/Astro-330.github.io", "max_issues_repo_head_hexsha": "e7ba5d1db0f369a110419e939d9ed2d29c9d7020", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_build/jupyter_execute/Lab3/Lab3.py", "max_forks_repo_name": "mgebran/Astro-330.github.io", "max_forks_repo_head_hexsha": "e7ba5d1db0f369a110419e939d9ed2d29c9d7020", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-12-18T00:53:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T14:53:12.000Z", "avg_line_length": 49.4888888889, "max_line_length": 694, "alphanum_fraction": 0.7308555836, "include": true, "reason": "from scipy,from astropy", "num_tokens": 7301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.2509127812837603, "lm_q1q2_score": 0.12545639064188016}} {"text": "import numpy as np\nimport warnings\nimport sys\ntry:\n import pycuda.autoinit\n import pycuda.driver as drv\n from pycuda import gpuarray\n from pycuda.compiler import SourceModule\n import pycuda.cumath\n pycuda_available = True\nexcept:\n pycuda_available = False\n\nuse_gpu = False\n\ndefault_blocksize = 128\n\ndef enable_gpu(enable=True):\n \"\"\"Sets the use_gpu flag to enable/disable the use of CUDA kernels.\n\n Args:\n enable (bool): Set use_gpu flag to this value (default=True).\n \"\"\"\n # todo: do gpuarrays require cuda toolkit? otherwise distinguish if only gpuarrays work but no kernel compilation\n global use_gpu\n \n if use_gpu == enable:\n return\n \n if not enable:\n use_gpu = False\n sys.stdout.write('Disabling GPU usage.\\n')\n sys.stdout.flush()\n return\n \n if not pycuda_available:\n warnings.warn(\"Unable to import PyCuda - fall back to CPU mode\")\n use_gpu = False\n sys.stdout.write('Disabling GPU usage.\\n')\n sys.stdout.flush()\n else:\n try:\n test_fun = SourceModule(\"\"\"\n __global__ void test_kernel(float *x)\n {\n unsigned int i = blockIdx.x * blockDim.x + threadIdx.x;\n x[i] = 2 * i;\n }\"\"\").get_function(\"test_kernel\")\n x = gpuarray.to_gpu(np.zeros(128, dtype=np.float32))\n test_fun(x, block=(128,1,1), grid=(1,1))\n assert np.allclose(x.get(), 2 * np.arange(128))\n use_gpu = True\n sys.stdout.write('Enabling GPU usage.\\n')\n sys.stdout.flush()\n return\n\n except Exception as e:\n warnings.warn(\"CUDA test kernel failed - fall back to CPU mode\")\n print(e)\n use_gpu = False\n sys.stdout.write('Disabling GPU usage.\\n')\n sys.stdout.flush()\n\n\n# The following cuda kernel multiplies the coupling matrix to a vector. It is based on linear interpolation of \n# the lookup table.\n#\n# input arguments of the cuda kernel:\n# n (np.uint32): n[i] contains the mutlipole multi-index with regard to self.l_max and self.m_max of the i-th\n# entry of a system vector\n# m (np.float32): m[i] contains the multipole order with regard to particle.l_max and particle.m_max\n# x_pos (np.float32): x_pos[i] contains the respective particle x-position\n# y_pos (np.float32): y_pos[i] contains the respective particle y-position\n# z_pos (np.float32): z_pos[i] contains the respective particle z-position\n# re_lookup_pl (np.float32): the real part of the lookup table for the z1+z2 part of the Sommerfeld integral,\n# in the format (rho, sum_z, n1, n2)\n# im_lookup_pl (np.float32): the imaginary part of the lookup table for the z1+z2 part of the Sommerfeld\n# integral, in the format (rho, sum_z, n1, n2)\n# re_lookup_mn (np.float32): the real part of the lookup table for the z1-z2 part of the Sommerfeld integral,\n# in the format (rho, diff_z, n1, n2)\n# im_lookup_mn (np.float32): the imaginary part of the lookup table for the z1-z2 part of the Sommerfeld\n# integral, in the format (rho, diff_z, n1, n2)\n# re_in_vec (np.float32): the real part of the vector to be multiplied with the coupling matrix\n# im_in_vec (np.float32): the imaginary part of the vector to be multiplied with the coupling matrix\n# re_result_vec (np.float32): the real part of the vector into which the result is written\n# im_result_vec (np.float32): the imaginary part of the vector into which the result is written\nlinear_volume_lookup_source = \"\"\"\n #define BLOCKSIZE %i\n #define NUMBER_OF_UNKNOWNS %i\n #define Z_ARRAY_LENGTH %i\n #define MIN_RHO %f\n #define MIN_Z_SUM %f\n #define MIN_Z_DIFF %f\n #define LOOKUP_RESOLUTION %f\n __global__ void coupling_kernel(const int *n, const float *m, const float *x_pos, const float *y_pos,\n const float *z_pos, const float *re_lookup_pl, const float *im_lookup_pl,\n const float *re_lookup_mn, const float *im_lookup_mn,\n const float *re_in_vec, const float *im_in_vec,\n float *re_result, float *im_result)\n {\n unsigned int i1 = blockIdx.x * blockDim.x + threadIdx.x;\n if(i1 >= NUMBER_OF_UNKNOWNS) return;\n\n const float x1 = x_pos[i1];\n const float y1 = y_pos[i1];\n const float z1 = z_pos[i1];\n\n const int n1 = n[i1];\n const float m1 = m[i1];\n\n re_result[i1] = 0.0;\n im_result[i1] = 0.0;\n \n for (int i2=0; i2= NUMBER_OF_UNKNOWNS) return;\n\n const float x1 = x_pos[i1];\n const float y1 = y_pos[i1];\n const float z1 = z_pos[i1];\n\n const int n1 = n[i1];\n const float m1 = m[i1];\n\n re_result[i1] = 0.0;\n im_result[i1] = 0.0;\n \n for (int i2=0; i2= NUMBER_OF_UNKNOWNS) return;\n \n const float x1 = x_pos[i1];\n const float y1 = y_pos[i1];\n \n const int n1 = n[i1];\n const float m1 = m[i1];\n\n re_result[i1] = 0.0;\n im_result[i1] = 0.0;\n \n for (int i2=0; i2= NUMBER_OF_UNKNOWNS) return;\n \n const float x1 = x_pos[i1];\n const float y1 = y_pos[i1];\n \n const int n1 = n[i1];\n const float m1 = m[i1];\n\n re_result[i1] = 0.0;\n im_result[i1] = 0.0;\n \n for (int i2=0; i2= RHO_ARRAY_LENGTH * Z_ARRAY_LENGTH) return;\n \n unsigned int i_rho = i / Z_ARRAY_LENGTH;\n unsigned int i_z = i %% Z_ARRAY_LENGTH; \n \n float re_res = 0.0;\n float im_res = 0.0;\n \n int i_kr = i_rho * K_ARRAY_LENGTH;\n int i_kz = i_z * K_ARRAY_LENGTH;\n\n float re_integrand_kp1 = re_bes_jac[i_kr] * re_belbee[i_kz] - im_bes_jac[i_kr] * im_belbee[i_kz];\n float im_integrand_kp1 = re_bes_jac[i_kr] * im_belbee[i_kz] + im_bes_jac[i_kr] * re_belbee[i_kz];\n\n for (int i_k=0; i_k<(K_ARRAY_LENGTH-1); i_k++)\n {\n i_kr = i_rho * K_ARRAY_LENGTH + i_k;\n i_kz = i_z * K_ARRAY_LENGTH + i_k;\n\n float re_integrand = re_integrand_kp1;\n float im_integrand = im_integrand_kp1;\n\n re_integrand_kp1 = re_bes_jac[i_kr+1] * re_belbee[i_kz+1] - im_bes_jac[i_kr+1] * im_belbee[i_kz+1];\n im_integrand_kp1 = re_bes_jac[i_kr+1] * im_belbee[i_kz+1] + im_bes_jac[i_kr+1] * re_belbee[i_kz+1];\n \n float re_sint = re_integrand + re_integrand_kp1;\n float im_sint = im_integrand + im_integrand_kp1;\n \n re_res += 0.5 * (re_sint * re_d_kappa[i_k] - im_sint * im_d_kappa[i_k]);\n im_res += 0.5 * (re_sint * im_d_kappa[i_k] + im_sint * re_d_kappa[i_k]);\n }\n \n re_result[i] = re_res;\n im_result[i] = im_res;\n \n }\"\"\"\n\n# This cuda kernel is used for the calculation of radial lookup tables (see smuthi.particle_coupling module).\nradial_lookup_assembly_code = \"\"\"\n #define BLOCKSIZE %i\n #define RHO_ARRAY_LENGTH %i\n #define K_ARRAY_LENGTH %i\n \n __global__ void helper(const float *re_bes_jac, const float *im_bes_jac, const float *re_belbee, \n const float *im_belbee, const float *re_d_kappa, const float *im_d_kappa, \n float *re_result, float *im_result)\n {\n unsigned int i = blockIdx.x * blockDim.x + threadIdx.x;\n if(i >= RHO_ARRAY_LENGTH) return;\n \n float re_res = 0.0;\n float im_res = 0.0;\n \n int i_kr = i * K_ARRAY_LENGTH;\n\n float re_integrand_kp1 = re_bes_jac[i_kr] * re_belbee[0] - im_bes_jac[i_kr] * im_belbee[0];\n float im_integrand_kp1 = re_bes_jac[i_kr] * im_belbee[0] + im_bes_jac[i_kr] * re_belbee[0];\n\n for (int i_k=0; i_k<(K_ARRAY_LENGTH-1); i_k++)\n {\n i_kr = i * K_ARRAY_LENGTH + i_k;\n \n float re_integrand = re_integrand_kp1;\n float im_integrand = im_integrand_kp1;\n\n re_integrand_kp1 = re_bes_jac[i_kr+1] * re_belbee[i_k+1] - im_bes_jac[i_kr+1] * im_belbee[i_k+1];\n im_integrand_kp1 = re_bes_jac[i_kr+1] * im_belbee[i_k+1] + im_bes_jac[i_kr+1] * re_belbee[i_k+1];\n \n float re_sint = re_integrand + re_integrand_kp1;\n float im_sint = im_integrand + im_integrand_kp1;\n \n re_res += 0.5 * (re_sint * re_d_kappa[i_k] - im_sint * im_d_kappa[i_k]);\n im_res += 0.5 * (re_sint * im_d_kappa[i_k] + im_sint * re_d_kappa[i_k]);\n }\n \n re_result[i] = re_res;\n im_result[i] = im_res;\n \n }\"\"\"\n\n# This cuda kernel is used for the evaluation of the electric field of plane wave expansions.\npwe_electric_field_evaluation_code = \"\"\"\n #define LEN_X %i\n #define LEN_K %i\n #define LEN_A %i\n #define RE_ONE_OVER_K %.10f\n #define IM_ONE_OVER_K %.10f\n \n __device__ void alpha_integral(const int i_k, const float x, const float y, const float z, \n const float re_kp, const float im_kp, const float re_kz, const float im_kz, \n const float *alpha_array, \n const float *re_g_te_array, const float *im_g_te_array,\n const float *re_g_tm_array, const float *im_g_tm_array,\n float *re_integral_x, float *im_integral_x,\n float *re_integral_y, float *im_integral_y,\n float *re_integral_z, float *im_integral_z)\n {\n float a = 0.0;\n \n float re_x_result = 0.0;\n float im_x_result = 0.0;\n float re_y_result = 0.0;\n float im_y_result = 0.0;\n float re_z_result = 0.0;\n float im_z_result = 0.0;\n \n float re_e_x_alpha_integrand = 0.0;\n float im_e_x_alpha_integrand = 0.0;\n float re_e_y_alpha_integrand = 0.0;\n float im_e_y_alpha_integrand = 0.0;\n float re_e_z_alpha_integrand = 0.0;\n float im_e_z_alpha_integrand = 0.0;\n\n for (int i_a=0; i_a0)\n {\n re_x_result += 0.5 * d_a * (re_e_x_alpha_integrand + re_e_x_alpha_integrand_old);\n im_x_result += 0.5 * d_a * (im_e_x_alpha_integrand + im_e_x_alpha_integrand_old);\n re_y_result += 0.5 * d_a * (re_e_y_alpha_integrand + re_e_y_alpha_integrand_old);\n im_y_result += 0.5 * d_a * (im_e_y_alpha_integrand + im_e_y_alpha_integrand_old);\n re_z_result += 0.5 * d_a * (re_e_z_alpha_integrand + re_e_z_alpha_integrand_old);\n im_z_result += 0.5 * d_a * (im_e_z_alpha_integrand + im_e_z_alpha_integrand_old);\n }\n }\n re_integral_x[0] = re_x_result;\n im_integral_x[0] = im_x_result;\n re_integral_y[0] = re_y_result;\n im_integral_y[0] = im_y_result;\n re_integral_z[0] = re_z_result;\n im_integral_z[0] = im_z_result;\n }\n \n \n __global__ void electric_field(const float *re_kp_array, const float *im_kp_array, \n const float *re_kz_array, const float *im_kz_array,\n const float *alpha_array, \n const float *x_array, const float *y_array, const float *z_array,\n const float *re_g_te_array, const float *im_g_te_array,\n const float *re_g_tm_array, const float *im_g_tm_array,\n float *re_e_x, float *im_e_x, float *re_e_y, float *im_e_y, \n float *re_e_z, float *im_e_z)\n {\n unsigned int i = blockIdx.x * blockDim.x + threadIdx.x;\n if (i >= LEN_X) return;\n \n float x = x_array[i];\n float y = y_array[i];\n float z = z_array[i];\n \n float re_kp = 0.0;\n float im_kp = 0.0;\n\n float re_x_result = 0.0;\n float im_x_result = 0.0;\n float re_y_result = 0.0;\n float im_y_result = 0.0;\n float re_z_result = 0.0;\n float im_z_result = 0.0;\n \n float re_x_kappa_integrand = 0.0;\n float im_x_kappa_integrand = 0.0;\n float re_y_kappa_integrand = 0.0;\n float im_y_kappa_integrand = 0.0;\n float re_z_kappa_integrand = 0.0;\n float im_z_kappa_integrand = 0.0;\n \n for (int i_k=0; i_k0)\n {\n re_x_result += 0.5 * (re_d_kp * (re_x_kappa_integrand + re_x_kappa_integrand_old) \n - im_d_kp * (im_x_kappa_integrand + im_x_kappa_integrand_old));\n im_x_result += 0.5 * (re_d_kp * (im_x_kappa_integrand + im_x_kappa_integrand_old) \n + im_d_kp * (re_x_kappa_integrand + re_x_kappa_integrand_old));\n re_y_result += 0.5 * (re_d_kp * (re_y_kappa_integrand + re_y_kappa_integrand_old) \n - im_d_kp * (im_y_kappa_integrand + im_y_kappa_integrand_old));\n im_y_result += 0.5 * (re_d_kp * (im_y_kappa_integrand + im_y_kappa_integrand_old) \n + im_d_kp * (re_y_kappa_integrand + re_y_kappa_integrand_old));\n re_z_result += 0.5 * (re_d_kp * (re_z_kappa_integrand + re_z_kappa_integrand_old) \n - im_d_kp * (im_z_kappa_integrand + im_z_kappa_integrand_old));\n im_z_result += 0.5 * (re_d_kp * (im_z_kappa_integrand + im_z_kappa_integrand_old) \n + im_d_kp * (re_z_kappa_integrand + re_z_kappa_integrand_old));\n }\n }\n re_e_x[i] = re_x_result;\n im_e_x[i] = im_x_result;\n re_e_y[i] = re_y_result;\n im_e_y[i] = im_y_result;\n re_e_z[i] = re_z_result;\n im_e_z[i] = im_z_result;\n }\n\"\"\"\n", "meta": {"hexsha": "b0b47a1867f6854ca512f0c1e85a5e432439af59", "size": 36781, "ext": "py", "lang": "Python", "max_stars_repo_path": "smuthi/cuda_sources.py", "max_stars_repo_name": "KMCzajkowski/smuthi", "max_stars_repo_head_hexsha": "a86e1c894ac2067a05c123b8e9a621597c198caa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-02-29T14:54:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T11:51:11.000Z", "max_issues_repo_path": "smuthi/cuda_sources.py", "max_issues_repo_name": "KMCzajkowski/smuthi", "max_issues_repo_head_hexsha": "a86e1c894ac2067a05c123b8e9a621597c198caa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "smuthi/cuda_sources.py", "max_forks_repo_name": "KMCzajkowski/smuthi", "max_forks_repo_head_hexsha": "a86e1c894ac2067a05c123b8e9a621597c198caa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-05-15T06:54:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-27T11:30:14.000Z", "avg_line_length": 47.6437823834, "max_line_length": 121, "alphanum_fraction": 0.5856284495, "include": true, "reason": "import numpy,import pycuda,from pycuda", "num_tokens": 10605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.22000710997428735, "lm_q1q2_score": 0.1253716349488137}} {"text": "#!/usr/bin/env python2\nfrom __future__ import print_function\nimport sys\nsys.path.append('../lib')\nimport os\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib.path import Path\nfrom matplotlib.patches import PathPatch\nimport string\n\nimport protocols\nimport model as m\nfrom parameters import simvc, get_qc\nfrom parameters import simvc_fix, simvc_fix_typical_values\nfrom parameters import simvc_typical_values\nfrom releakcorrect import I_releak, score_leak, protocol_leak_check\n\nfrom scipy.optimize import fmin\n# Set seed\nnp.random.seed(101)\n\nsavedir = './figs'\nif not os.path.isdir(savedir):\n os.makedirs(savedir)\n\n#refcell = 'D19'\n\ndef get_fix_param(var, val):\n \"\"\"\n var: variable name.\n val: variable value to fix.\n \"\"\"\n out = {}\n for i, j in zip(var, val):\n out[i] = j\n return out\n\ndef rmsd_compute(t1, t2):\n # Normalised RMSD value between trace 1 ``t1`` and trace 2 ``t2``\n #\n # Note, usually normalise to data, so \n # - ``t2`` data (or anything as reference)\n # - ``t1`` simulation (or anything for comparison)\n return np.sqrt(np.mean((t1 - t2) ** 2)) / np.sqrt(np.mean(t2 ** 2))\n\n\n#\n# Protocol info\n#\nprotocol_funcs = {\n 'staircaseramp': protocols.leak_staircase,\n 'pharma': protocols.pharma, # during drug application\n 'apab': 'protocol-apab.csv',\n 'apabv3': 'protocol-apabv3.csv',\n 'ap05hz': 'protocol-ap05hz.csv',\n 'ap1hz': 'protocol-ap1hz.csv',\n 'ap2hz': 'protocol-ap2hz.csv',\n 'sactiv': protocols.sactiv,\n 'sinactiv': protocols.sinactiv,\n}\nprotocol_dir = '../protocol-time-series'\nprotocol_list = [\n 'staircaseramp',\n # 'sactiv',\n # 'sinactiv',\n 'pharma',\n 'apab',\n 'apabv3',\n # 'ap05hz',\n 'ap1hz',\n 'ap2hz',\n]\nvalidation_idx = [\n None,\n # 1,\n # 2,\n 3,\n 4,\n 5,\n # 6,\n 7,\n 8,\n]\n\n# IV protocol special treatment\nprotocol_iv = [\n 'sactiv',\n 'sinactiv',\n]\nprotocol_iv_times = {\n 'sactiv': protocols.sactiv_times,\n 'sinactiv': protocols.sinactiv_times,\n}\nprotocol_iv_convert = {\n 'sactiv': protocols.sactiv_convert,\n 'sinactiv': protocols.sinactiv_convert,\n}\nprotocol_iv_args = {\n 'sactiv': protocols.sactiv_iv_arg,\n 'sinactiv': protocols.sinactiv_iv_arg,\n}\nprotocol_iv_v = {\n 'sactiv': protocols.sactiv_v,\n 'sinactiv': protocols.sinactiv_v,\n}\n\ndata_dir_staircase = '../data'\ndata_dir = '../data-autoLC'\nfile_dir = '../../hERGRapidCharacterisation/room-temperature-only/out'\nfile_dir2 = './out'\nfile_list = [\n 'herg25oc1',\n ]\ntemperatures = np.array([25.0])\ntemperatures += 273.15 # in K\nfit_seed = '542811797'\nfit_seed2 = '717354021'\n\nfile_name = file_list[0]\ntemperature = temperatures[0]\n\n# Load RMSD matrix\nrmsd_matrix_file = '../../hERGRapidCharacterisation/room-temperature-only/figs/rmsd-hist-%s-autoLC-releak/rmsd-matrix.txt' \\\n % file_name\nrmsd_cells_file = '../../hERGRapidCharacterisation/room-temperature-only/figs/rmsd-hist-%s-autoLC-releak/rmsd-matrix-cells.txt' \\\n % file_name\n\nrmsd_matrix = np.loadtxt(rmsd_matrix_file)\n\nwith open(rmsd_matrix_file, 'r') as f:\n rmsd_prt = f.readline().strip('\\n').strip('#').split()\n\nrmsd_cells = []\nwith open(rmsd_cells_file, 'r') as f:\n for l in f:\n if not l.startswith('#'):\n rmsd_cells.append(l.strip('\\n').split('-')[1])\n\n\nrmsd_matrix_file2 = './out/rmsd-hist-%s-fixkinetics-simvclinleak-scheme3/rmsd-matrix.txt' \\\n % file_name\nrmsd_cells_file2 = './out/rmsd-hist-%s-fixkinetics-simvclinleak-scheme3/rmsd-matrix-cells.txt' \\\n % file_name\n\nrmsd_matrix2 = np.loadtxt(rmsd_matrix_file2)\n\nwith open(rmsd_matrix_file2, 'r') as f:\n rmsd_prt2 = f.readline().strip('\\n').strip('#').split()\n\nrmsd_cells2 = []\nwith open(rmsd_cells_file2, 'r') as f:\n for l in f:\n if not l.startswith('#'):\n rmsd_cells2.append(l.strip('\\n').split('-')[1])\n\n\nrankedlabels = [r'$*$',\n u'\\u2021',\n r'#',\n u'\\u2666']\n\n\n#\n# Do a very very tailored version........ :(\n#\nfig = plt.figure(figsize=(16, 15))\nbigxgap = 12\nn_xgrid = 84\nbigygap = 5\nn_ygrid = 31\ngrid = plt.GridSpec(2 * n_ygrid + 1 * bigygap, 3 * n_xgrid + 2 * bigxgap,\n hspace=0.0, wspace=0.0)\naxes = np.empty([10, int(len(protocol_list) / 2)], dtype=object)\n# long list here:\nfor i in range(int(len(protocol_list) / 2)):\n i_grid = i * (n_xgrid + bigxgap)\n f_grid = (i + 1) * n_xgrid + i * bigxgap\n\n # First 'row'\n axes[0, i] = fig.add_subplot(grid[0:3, i_grid:f_grid])\n axes[0, i].set_xticklabels([])\n axes[1, i] = fig.add_subplot(grid[3:9, i_grid:f_grid])\n axes[1, i].set_xticklabels([])\n axes[2, i] = fig.add_subplot(grid[9:15, i_grid:f_grid])\n axes[2, i].set_xticklabels([])\n axes[3, i] = fig.add_subplot(grid[15:21, i_grid:f_grid])\n # Histogram\n axes[4, i] = fig.add_subplot(grid[24:31, i_grid:f_grid])\n\n # Second 'row'\n n_shift = n_ygrid + bigygap\n axes[5, i] = fig.add_subplot(grid[n_shift+0:n_shift+3, i_grid:f_grid])\n axes[5, i].set_xticklabels([])\n axes[6, i] = fig.add_subplot(grid[n_shift+3:n_shift+9, i_grid:f_grid])\n axes[6, i].set_xticklabels([])\n axes[7, i] = fig.add_subplot(grid[n_shift+9:n_shift+15, i_grid:f_grid])\n axes[7, i].set_xticklabels([])\n axes[8, i] = fig.add_subplot(grid[n_shift+15:n_shift+21, i_grid:f_grid])\n # Histogram\n axes[9, i] = fig.add_subplot(grid[n_shift+24:n_shift+31, i_grid:f_grid])\n\n # Set x-labels\n axes[3, i].set_xlabel('Time (s)', fontsize=14)\n axes[4, i].set_xlabel('RRMSE', fontsize=14)\n axes[8, i].set_xlabel('Time (s)', fontsize=14)\n axes[9, i].set_xlabel('RRMSE', fontsize=14)\n\n# Set labels\naxes[0, 0].set_ylabel('Voltage\\n(mV)', fontsize=14)\naxes[1, 0].set_ylabel(u'Best\\n(*)', fontsize=14, color='#d95f02')\naxes[2, 0].set_ylabel(u'Median\\n(\\u2021)', fontsize=14, color='#d95f02')\naxes[3, 0].set_ylabel(u'90%ile\\n(#)', fontsize=14, color='#d95f02')\naxes[4, 0].set_ylabel('Frequency\\n(N=%s)' % len(rmsd_cells), fontsize=14)\naxes[5, 0].set_ylabel('Voltage\\n(mV)', fontsize=14)\naxes[6, 0].set_ylabel(u'Best\\n(*)', fontsize=14, color='#d95f02')\naxes[7, 0].set_ylabel(u'Median\\n(\\u2021)', fontsize=14, color='#d95f02')\naxes[8, 0].set_ylabel(u'90%ile\\n(#)', fontsize=14, color='#d95f02')\naxes[9, 0].set_ylabel('Frequency\\n(N=%s)' % len(rmsd_cells), fontsize=14)\n\naxes[2, 0].text(-0.3, 0.5, 'Current (pA)', rotation=90, fontsize=18,\n transform=axes[2, 0].transAxes, ha='center', va='center')\naxes[7, 0].text(-0.275, 0.5, 'Current (pA)', rotation=90, fontsize=18,\n transform=axes[7, 0].transAxes, ha='center', va='center')\n\n\n#\n# Model\n#\nprt2model = {}\nprt2fixkineticsmodel = {}\nfor prt in protocol_list:\n\n protocol_def = protocol_funcs[prt]\n if type(protocol_def) is str:\n protocol_def = '%s/%s' % (protocol_dir, protocol_def)\n\n prt2model[prt] = m.Model('../mmt-model-files/ideal-ikr.mmt',\n protocol_def=protocol_def,\n temperature=temperature, # K\n transform=None,\n useFilterCap=False) # ignore capacitive spike\n\n prt2fixkineticsmodel[prt] = m.Model(\n '../mmt-model-files/simplified-voltage-clamp-ikr-linleak.mmt',\n protocol_def=protocol_def,\n temperature=temperature, # K\n transform=None,\n useFilterCap=False) # ignore capacitive spike\n\n\n#\n# Plot\n#\nmid = []\nupper = []\nlower = []\nmid2 = []\nupper2 = []\nlower2 = []\nfor i_prt, prt in enumerate(protocol_list):\n\n # Calculate axis index\n ai, aj = 5 * int(i_prt / 3), i_prt % 3\n\n # Title\n if prt == 'staircaseramp':\n axes[ai, aj].set_title('Calibration', fontsize=16)\n else:\n axes[ai, aj].set_title('Validation %s' % validation_idx[i_prt],\n fontsize=16)\n\n # Add label!\n axes[ai, aj].text(-0.1, 1.4, string.ascii_uppercase[i_prt],\n transform=axes[ai, aj].transAxes, size=20,\n weight='bold')\n\n # Time point\n times = np.loadtxt('%s/%s-%s-times.csv' % (data_dir, file_name,\n prt), delimiter=',', skiprows=1) * 1e3 # s -> ms\n\n # Protocol\n model = prt2model[prt]\n modelfixkinetics = prt2fixkineticsmodel[prt]\n # Set which parameters to be inferred\n modelfixkinetics.set_parameters([\n 'ikr.g',\n #'voltageclamp.rseries',\n 'voltageclamp.voffset_eff',\n 'voltageclamp.gLeak'])\n if prt not in protocol_iv:\n times_sim = np.copy(times)\n voltage = model.voltage(times_sim)\n else:\n times_sim = protocol_iv_times[prt](times[1] - times[0])\n voltage = model.voltage(times_sim)\n voltage, t = protocol_iv_convert[prt](voltage, times_sim)\n assert(np.mean(np.abs(t - times)) < 1e-8)\n axes[ai, aj].set_ylim((np.min(voltage) - 10, np.max(voltage) + 15))\n\n # Plot protocol\n if prt not in protocol_iv:\n axes[ai, aj].plot(times * 1e-3, voltage, c='#696969')\n else:\n # protocol\n for i in range(voltage.shape[1]):\n axes[ai, aj].plot(times * 1e-3, voltage[:, i], c='#696969')\n\n # Calculate ranking\n rmsd = rmsd_matrix[:, rmsd_prt.index(prt)]\n best_cell = np.argmin(rmsd)\n median_cell = np.argsort(rmsd)[len(rmsd)//2]\n p90_cell = np.argsort(rmsd)[int(len(rmsd)*0.9)]\n rankedcells = [rmsd_cells[best_cell],\n rmsd_cells[median_cell],\n rmsd_cells[p90_cell]]\n rankedvalues = [rmsd[best_cell],\n rmsd[median_cell],\n rmsd[p90_cell]]\n #rmsd[rmsd_cells.index(refcell)]]\n\n rmsd2 = rmsd_matrix2[:, rmsd_prt2.index(prt)]\n #best_cell2 = np.argmin(rmsd2)\n #median_cell2 = np.argsort(rmsd2)[len(rmsd2)//2]\n #p90_cell2 = np.argsort(rmsd2)[int(len(rmsd2)*0.9)]\n #NOTE Compare with the 'red' cells; not its own ranking!!\n best_cell2 = rmsd_cells2.index(rmsd_cells[best_cell])\n median_cell2 = rmsd_cells2.index(rmsd_cells[median_cell])\n p90_cell2 = rmsd_cells2.index(rmsd_cells[p90_cell])\n rankedcells2 = [rmsd_cells2[best_cell2],\n rmsd_cells2[median_cell2],\n rmsd_cells2[p90_cell2]]\n rankedvalues2 = [rmsd2[best_cell2],\n rmsd2[median_cell2],\n rmsd2[p90_cell2]]\n #rmsd2[rmsd_cells2.index(refcell)]]\n\n # Parameters\n fn = '%s/%s-scheme3-simvclinleak/%s-cells-%s.txt' % \\\n (file_dir2, file_name, file_name, fit_seed2)\n scheme3_cell_list = []\n with open(fn, 'r') as f:\n for l in f:\n if not l.startswith('#'):\n scheme3_cell_list.append(l.split()[0])\n\n param_file = '%s/%s-scheme3-simvclinleak/%s-solution_i-%s.txt' % \\\n (file_dir2, file_name, file_name, fit_seed2)\n obtained_parameters_all = np.loadtxt(param_file)\n\n ikr_param = [\n 'ikr.p1', 'ikr.p2', 'ikr.p3', 'ikr.p4',\n 'ikr.p5', 'ikr.p6', 'ikr.p7', 'ikr.p8', \n ]\n p_ikr = np.loadtxt('%s/%s-scheme3-simvclinleak/%s-solution-%s.txt' % \\\n (file_dir2, file_name, file_name, fit_seed2))\n\n for i_cell, cell in enumerate(rankedcells):\n # Data\n if prt == 'staircaseramp':\n data = np.loadtxt('%s/%s-%s-%s.csv' % (data_dir_staircase,\n file_name, prt, cell), delimiter=',', skiprows=1)\n elif prt not in protocol_iv:\n data = np.loadtxt('%s/%s-%s-%s.csv' % (data_dir, file_name,\n prt, cell), delimiter=',', skiprows=1)\n # Re-leak correct the leak corrected data...\n g_releak = fmin(score_leak, [0.0], args=(data, voltage, times,\n protocol_leak_check[prt]), disp=False)\n data = I_releak(g_releak[0], data, voltage)\n else:\n data = np.loadtxt('%s/%s-%s-%s.csv' % (data_dir, file_name,\n prt, cell), delimiter=',', skiprows=1)\n # Re-leak correct the leak corrected data...\n for i in range(data.shape[1]):\n g_releak = fmin(score_leak, [0.0], args=(data[:, i],\n voltage[:, i], times,\n protocol_leak_check[prt]), disp=False)\n data[:, i] = I_releak(g_releak[0], data[:, i], voltage[:, i])\n assert(len(data) == len(times))\n\n # Fitted parameters\n param_file = '%s/%s/%s-staircaseramp-%s-solution-%s.txt' % \\\n (file_dir, file_name, file_name, cell, fit_seed)\n obtained_parameters = np.loadtxt(param_file) * 1e-3 # V, s -> mV, ms\n\n # For fix kinetics model\n rseal, cm, rseries = get_qc('../qc', file_name, cell)\n #print('Est. Rseal, Cm, Rseries:', rseal, cm, rseries, '(GOhm, pF, GOhm)')\n alpha = 0.8 # rseries %compensation\n simvc_fix_values = [cm, rseries * alpha, rseries]\n extra_fix = ['voltageclamp.rseries']\n updateELeakCorrection = False\n if updateELeakCorrection:\n leakbeforeparam = np.loadtxt('../qc/' + file_name + '-staircaseramp-leak_before.txt')\n leakafterparam = np.loadtxt('../qc/' + file_name + '-staircaseramp-leak_after.txt')\n cell_id_file = '../qc/%s-staircaseramp-cell_id.txt' % file_name\n cell_ids = []\n with open(cell_id_file, 'r') as f:\n for l in f:\n if not l.startswith('#'):\n cell_ids.append(l.split()[0])\n cell_idx = cell_ids.index(cell)\n ga, Ea = leakbeforeparam[cell_idx]\n gb, Eb = leakafterparam[cell_idx]\n ELeakCorrection = - (ga * Ea - gb * Eb) / (gb - ga)\n #print('E_Leak correction: ', ELeakCorrection, ' (mV)')\n if np.abs(ELeakCorrection) > 200: print('==' * 30, ga, Ea, gb, Eb)\n extra_fix += ['voltageclamp.ELeak']\n simvc_fix_values += [ELeakCorrection]\n fix_p = get_fix_param(ikr_param + simvc_fix + extra_fix,\n np.append(p_ikr, simvc_fix_values))\n modelfixkinetics.set_fix_parameters(fix_p)\n\n scheme3_cell_idx = scheme3_cell_list.index(cell)\n obtained_parameters2 = obtained_parameters_all[scheme3_cell_idx]\n\n # Simulation\n simulation = model.simulate(obtained_parameters, times_sim)\n simulationfixkinetics = modelfixkinetics.simulate(obtained_parameters2, times_sim)\n if prt != 'staircaseramp' and prt not in protocol_iv:\n # Re-leak correct the leak corrected simulationfixkinetics... TODO?\n g_releak_simulationfixkinetics = fmin(score_leak, [0.1], args=(simulationfixkinetics, voltage, times,\n protocol_leak_check[prt]), disp=False)\n simulationfixkinetics = I_releak(g_releak_simulationfixkinetics[0], simulationfixkinetics, voltage)\n if prt in protocol_iv:\n simulation, t = protocol_iv_convert[prt](simulation, times_sim)\n assert(np.mean(np.abs(t - times)) < 1e-6)\n simulationfixkinetics, t = protocol_iv_convert[prt](\n simulationfixkinetics, times_sim)\n assert(np.mean(np.abs(t - times)) < 1e-6)\n # Re-leak correct the leak corrected simulationfixkinetics... TODO?\n for i in range(simulationfixkinetics.shape[1]):\n g_releak_simulationfixkinetics = fmin(score_leak, [0.1], args=(simulationfixkinetics[:, i],\n voltage[:, i], times,\n protocol_leak_check[prt]), disp=False)\n simulationfixkinetics[:, i] = I_releak(g_releak_simulationfixkinetics[0], simulationfixkinetics[:, i], voltage[:, i])\n\n # Work out ylim\n maximum = np.percentile(simulation, 100)\n minimum = np.percentile(simulation, 0.0)\n amplitude = maximum - minimum\n if prt in ['apabv3', 'ap05hz']:\n maximum += 0.6 * amplitude\n minimum -= 0.6 * amplitude\n elif prt in ['apab', 'ap1hz']:\n maximum += 0.3 * amplitude\n minimum -= 0.3 * amplitude\n else:\n maximum += 0.15 * amplitude\n minimum -= 0.15 * amplitude\n axes[ai + i_cell + 1, aj].set_ylim([minimum, maximum])\n \n # Plot\n if prt not in protocol_iv:\n # recording\n axes[ai + i_cell + 1, aj].plot(times * 1e-3, data, lw=1, alpha=0.5,\n c='#9ecae1', label='data')\n # simulation\n if prt == 'staircaseramp':\n axes[ai + i_cell + 1, aj].plot(times * 1e-3, simulation, lw=2,\n c='#d95f02', label='model fit to data')\n axes[ai + i_cell + 1, aj].plot(times * 1e-3, simulationfixkinetics, lw=2,\n c='#1b9e77', label='model (fix kinetics) fit to data')\n else:\n axes[ai + i_cell + 1, aj].plot(times * 1e-3, simulation, lw=2,\n c='#d95f02', label='model prediction')\n axes[ai + i_cell + 1, aj].plot(times * 1e-3, simulationfixkinetics, lw=2,\n c='#1b9e77', label='model (fix kinetics) prediction')\n else:\n iv_v = protocol_iv_v[prt]() # mV\n # recording\n iv_i = protocols.get_corrected_iv(data, times,\n *protocol_iv_args[prt]())\n axes[ai + i_cell + 1, aj].plot(iv_v, iv_i / np.max(iv_i), lw=2,\n alpha=0.25, c='#9ecae1', label='data')\n # simulation\n iv_i = protocols.get_corrected_iv(simulation, times,\n *protocol_iv_args[prt]())\n axes[ai + i_cell + 1, aj].plot(iv_v, iv_i / np.max(iv_i), lw=2,\n alpha=1, c='#d95f02', label='model prediction')\n # simulationfixkinetics\n iv_i_fixkinetics = protocols.get_corrected_iv(simulationfixkinetics, times,\n *protocol_iv_args[prt]())\n axes[ai + i_cell + 1, aj].plot(iv_v, iv_i_fixkinetics / np.max(iv_i_fixkinetics), lw=2,\n alpha=1, c='#1b9e77', label='model (fix kinetics) prediction')\n if prt == 'sactiv':\n axes[ai + i_cell + 1, aj].set_ylim([-0.05, 1.05])\n elif prt == 'sinactiv':\n axes[ai + i_cell + 1, aj].set_ylim([-5, 1.05])\n \n if False:\n print(prt, i_cell, cell)\n print('red', rmsd_compute(simulation, data))\n print('green', rmsd_compute(simulationfixkinetics, data))\n \n # Plot rmsd histogram\n rmse_min = min(np.min(rmsd), np.min(rmsd2))\n rmse_max = max(np.max(rmsd), np.max(rmsd2))\n rmse_range = rmse_max - rmse_min\n bins = np.linspace(rmse_min - 0.1 * rmse_range,\n rmse_max + 0.1 * rmse_range, 20)\n n, b, _ = axes[ai + 4, aj].hist(rmsd, bins=bins, color='#d95f02', alpha=0.25)\n n2, b2, _ = axes[ai + 4, aj].hist(rmsd2, bins=bins, color='#2ca02c', alpha=0.25)\n\n mid.append(np.percentile(rmsd, 50))\n upper.append(np.percentile(rmsd, 90))\n lower.append(np.percentile(rmsd, 10))\n mid2.append(np.percentile(rmsd2, 50))\n upper2.append(np.percentile(rmsd2, 90))\n lower2.append(np.percentile(rmsd2, 10))\n\n # Add labels\n rankedidx = []\n for i, v in enumerate(rankedvalues):\n idx = np.where(b <= v)[0][-1]\n if idx in rankedidx:\n print('Ref. marker might clash with other markers...')\n shift = 4\n else:\n shift = 0\n axes[ai + 4, aj].text((b[idx] + b[idx + 1]) / 2., n[idx] + 3 + shift,\n rankedlabels[i], fontsize=16, color='#d95f02',\n ha='center', va='center')\n if n[idx] > 0.8 * max(np.max(n), np.max(n2)):\n axes[ai + 4, aj].set_ylim([0, max(np.max(n2), np.max(n)) + 8 + shift])\n rankedidx.append(idx)\n\n rankedidx2 = []\n for i, v in enumerate(rankedvalues2):\n idx = np.where(b2 <= v)[0][-1]\n if idx in rankedidx2:\n print('Ref. marker might clash with other markers...')\n shift = 4\n elif idx in rankedidx:\n diff = np.abs(n[idx] - n2[idx])\n if diff < max(np.max(n2), np.max(n)) * 0.1:\n shift = max(np.max(n2), np.max(n)) * 0.2\n else:\n shift = 0\n else:\n shift = 0\n axes[ai + 4, aj].text((b2[idx] + b2[idx + 1]) / 2., n2[idx] + 3 + shift,\n rankedlabels[i], fontsize=16, color='#2ca02c',\n ha='center', va='center')\n if n2[idx] > 0.8 * max(np.max(n2), np.max(n)):\n axes[ai + 4, aj].set_ylim([0, max(np.max(n2), np.max(n)) + 8 + shift])\n rankedidx2.append(idx)\n\n\n#\n# Final adjustment and save\n#\n#axes[1, 0].legend()\n#axes[1, 1].legend()\nimport matplotlib.patches as mpatches\ndata_patch = mpatches.Patch(color='#9ecae1', label='Data')\nh1_patch = mpatches.Patch(color='#d95f02', label='Hypothesis 1: independent kinetics models')\nh2_patch = mpatches.Patch(color='#1b9e77', label='Hypothesis 2: identical kinetics models')\naxes[0, 0].legend(handles=[data_patch, h1_patch, h2_patch], loc='upper left', bbox_to_anchor=(-.025, 2.75), fontsize=14, ncol=3, columnspacing=5.5)\n#grid.tight_layout(fig, pad=0.6, rect=(0.02, 0.0, 1, 0.99)) # not working...\n#grid.update(wspace=0.2, hspace=0.0)\nplt.savefig('%s/rmsd-hist-fix-kinetics-simvclinleak-scheme3-part1.pdf' % (savedir), bbox_inch='tight',\n pad_inches=0, format='pdf')\nplt.savefig('%s/rmsd-hist-fix-kinetics-simvclinleak-scheme3-part1.png' % (savedir), bbox_inch='tight',\n pad_inches=0, dpi=300)\n\nprint('Done')\n\n\n#\n# Table\n#\ntex = ''\ntex += '\\\\begin{tabularx}{\\\\textwidth}{@{}l' \\\n + 'XXc' * (len(protocol_list) - 1) + 'XX@{}}\\n'\ntex += '\\\\toprule\\n'\ntex += ' '\nfor i_prt, prt in enumerate(protocol_list):\n # span 2 columns\n if prt == 'staircaseramp':\n tex += ' & \\multicolumn{2}{c}{Cal.}'\n else:\n tex += ' & \\multicolumn{2}{c}{Val.~%s}' % validation_idx[i_prt]\n\n if i_prt < len(protocol_list) - 1:\n tex += ' & \\phantom{}'\ntex += ' \\\\\\\\\\n'\n\nii = 1\nfor i_prt, prt in enumerate(protocol_list):\n ii += 1\n tex += '\\\\cmidrule{%s-%s}' % (ii, ii + 1)\n ii += 2\ntex += '\\n'\n\ntex += ' '\nfor i_prt, prt in enumerate(protocol_list):\n tex += ' & H1 & H2'\n if i_prt < len(protocol_list) - 1:\n tex += ' &'\ntex += ' \\\\\\\\\\n'\n\ntex += '\\\\midrule\\n'\n\ntex += 'Median'\nfor i_prt, prt in enumerate(protocol_list):\n tex += ' & %.2f & %.2f' % (mid[i_prt], mid2[i_prt])\n if i_prt < len(protocol_list) - 1:\n tex += ' &'\ntex += ' \\\\\\\\\\n'\n\ntex += '10\\\\textsuperscript{th} \\\\%ile'\nfor i_prt, prt in enumerate(protocol_list):\n tex += ' & %.2f & %.2f' % (lower[i_prt], lower2[i_prt])\n if i_prt < len(protocol_list) - 1:\n tex += ' &'\ntex += ' \\\\\\\\\\n'\n\ntex += '90\\\\textsuperscript{th} \\\\%ile'\nfor i_prt, prt in enumerate(protocol_list):\n tex += ' & %.2f & %.2f' % (upper[i_prt], upper2[i_prt])\n if i_prt < len(protocol_list) - 1:\n tex += ' &'\ntex += ' \\\\\\\\\\n'\ntex += '\\\\bottomrule\\n'\ntex += '\\\\end{tabularx}'\n\nprint(tex)\n\n", "meta": {"hexsha": "43177c9ba882e62a34ab9d5d5ee2cf114edf0fae", "size": 23150, "ext": "py", "lang": "Python", "max_stars_repo_path": "herg-real-data/plot-rmsd-hist-fix-kinetics-simvclinleak-scheme3-part1.py", "max_stars_repo_name": "CardiacModelling/VoltageClampModel", "max_stars_repo_head_hexsha": "f30271da75e3c70526e53fb51dc12b317ab3b714", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-12-13T16:51:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T00:26:24.000Z", "max_issues_repo_path": "herg-real-data/plot-rmsd-hist-fix-kinetics-simvclinleak-scheme3-part1.py", "max_issues_repo_name": "CardiacModelling/VoltageClampModel", "max_issues_repo_head_hexsha": "f30271da75e3c70526e53fb51dc12b317ab3b714", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-03T08:13:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T11:04:46.000Z", "max_forks_repo_path": "herg-real-data/plot-rmsd-hist-fix-kinetics-simvclinleak-scheme3-part1.py", "max_forks_repo_name": "CardiacModelling/VoltageClampModel", "max_forks_repo_head_hexsha": "f30271da75e3c70526e53fb51dc12b317ab3b714", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6297468354, "max_line_length": 147, "alphanum_fraction": 0.5818142549, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.2337063569140403, "lm_q1q2_score": 0.125055904344753}} {"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n# This old version has been retrieved to use the Spectrum class to do photometry\n# Functionalities have been removed\n\nimport abc\nimport math\nfrom copy import deepcopy\nfrom collections import OrderedDict\n\nimport numpy as np\n\nfrom astropy.utils import lazyproperty\nfrom astropy.io import ascii\nimport astropy.units as u\nimport astropy.constants as const\nfrom astropy import cosmology\n\n# from ._registry import Registry\n\n__all__ = [\n \"get_bandpass\",\n \"get_magsystem\",\n \"read_bandpass\",\n \"Bandpass\",\n \"Spectrum\",\n \"MagSystem\",\n \"SpectralMagSystem\",\n \"ABMagSystem\",\n \"CompositeMagSystem\",\n]\n\nHC_ERG_AA = const.h.cgs.value * const.c.to(u.AA / u.s).value\n\n# _BANDPASSES = Registry()\n# _MAGSYSTEMS = Registry()\n\n\ndef get_bandpass(name):\n \"\"\"Get a Bandpass from the registry by name.\"\"\"\n if isinstance(name, Bandpass):\n return name\n return _BANDPASSES.retrieve(name)\n\n\ndef get_magsystem(name):\n \"\"\"Get a MagSystem from the registry by name.\"\"\"\n if isinstance(name, MagSystem):\n return name\n return _MAGSYSTEMS.retrieve(name)\n\n\ndef read_bandpass(\n fname, fmt=\"ascii\", wave_unit=u.AA, trans_unit=u.dimensionless_unscaled, name=None\n):\n \"\"\"Read bandpass from two-column ASCII file containing wavelength and\n transmission in each line.\n\n Parameters\n ----------\n fname : str\n File name.\n fmt : {'ascii'}\n File format of file. Currently only ASCII file supported.\n wave_unit : `~astropy.units.Unit` or str, optional\n Wavelength unit. Default is Angstroms.\n trans_unit : `~astropy.units.Unit`, optional\n Transmission unit. Can be `~astropy.units.dimensionless_unscaled`,\n indicating a ratio of transmitted to incident photons, or units\n proportional to inverse energy, indicating a ratio of transmitted\n photons to incident energy. Default is ratio of transmitted to\n incident photons.\n name : str, optional\n Identifier. Default is `None`.\n\n Returns\n -------\n band : `~sncosmo.Bandpass`\n \"\"\"\n\n if fmt != \"ascii\":\n raise ValueError(\n \"format {0} not supported. Supported formats: 'ascii'\".format(fmt)\n )\n t = ascii.read(fname, names=[\"wave\", \"trans\"])\n return Bandpass(\n t[\"wave\"], t[\"trans\"], wave_unit=wave_unit, trans_unit=trans_unit, name=name\n )\n\n\nclass Bandpass(object):\n \"\"\"Transmission as a function of spectral wavelength.\n\n Parameters\n ----------\n wave : list_like\n Wavelength. Monotonically increasing values.\n trans : list_like\n Transmission fraction.\n wave_unit : `~astropy.units.Unit` or str, optional\n Wavelength unit. Default is Angstroms.\n trans_unit : `~astropy.units.Unit`, optional\n Transmission unit. Can be `~astropy.units.dimensionless_unscaled`,\n indicating a ratio of transmitted to incident photons, or units\n proportional to inverse energy, indicating a ratio of transmitted\n photons to incident energy. Default is ratio of transmitted to\n incident photons.\n name : str, optional\n Identifier. Default is `None`.\n\n Examples\n --------\n >>> b = Bandpass([4000., 4200., 4400.], [0.5, 1.0, 0.5])\n >>> b.wave\n array([ 4000., 4200., 4400.])\n >>> b.trans\n array([ 0.5, 1. , 0.5])\n >>> b.dwave\n array([ 200., 200., 200.])\n >>> b.wave_eff\n 4200.0\n\n \"\"\"\n\n def __init__(\n self,\n wave,\n trans,\n wave_unit=u.AA,\n trans_unit=u.dimensionless_unscaled,\n name=None,\n ):\n wave = np.asarray(wave, dtype=np.float64)\n trans = np.asarray(trans, dtype=np.float64)\n if wave.shape != trans.shape:\n raise ValueError(\"shape of wave and trans must match\")\n if wave.ndim != 1:\n raise ValueError(\"only 1-d arrays supported\")\n\n # Ensure that units are actually units and not quantities, so that\n # `to` method returns a float and not a Quantity.\n wave_unit = u.Unit(wave_unit)\n trans_unit = u.Unit(trans_unit)\n\n if wave_unit != u.AA:\n wave = wave_unit.to(u.AA, wave, u.spectral())\n\n # If transmission is in units of inverse energy, convert to\n # unitless transmission:\n #\n # (transmitted photons / incident photons) =\n # (photon energy) * (transmitted photons / incident energy)\n #\n # where photon energy = h * c / lambda\n if trans_unit != u.dimensionless_unscaled:\n trans = (HC_ERG_AA / wave) * trans_unit.to(u.erg ** -1, trans)\n\n # Check that values are monotonically increasing.\n # We could sort them, but if this happens, it is more likely a user\n # error or faulty bandpass definition. So we leave it to the user to\n # sort them.\n if not np.all(np.ediff1d(wave) > 0.0):\n raise ValueError(\n \"bandpass wavelength values must be monotonically\"\n \" increasing when supplied in wavelength or \"\n \"decreasing when supplied in energy/frequency.\"\n )\n self.wave = wave\n self._dwave = np.gradient(wave)\n self.trans = trans\n self.name = name\n\n @property\n def dwave(self):\n \"\"\"Gradient of wavelengths, numpy.gradient(wave).\"\"\"\n return self._dwave\n\n @lazyproperty\n def wave_eff(self):\n \"\"\"Effective wavelength of bandpass in Angstroms.\"\"\"\n weights = self.trans * np.gradient(self.wave)\n return np.sum(self.wave * weights) / np.sum(weights)\n\n def to_unit(self, unit):\n \"\"\"Return wavelength and transmission in new wavelength units.\n\n If the requested units are the same as the current units, self is\n returned.\n\n Parameters\n ----------\n unit : `~astropy.units.Unit` or str\n Target wavelength unit.\n\n Returns\n -------\n wave : `~numpy.ndarray`\n trans : `~numpy.ndarray`\n \"\"\"\n\n if unit is u.AA:\n return self.wave, self.trans\n\n d = u.AA.to(unit, self.wave, u.spectral())\n t = self.trans\n if d[0] > d[-1]:\n d = np.flipud(d)\n t = np.flipud(t)\n return d, t\n\n def __repr__(self):\n name = \"\"\n if self.name is not None:\n name = \" {0!r:s}\".format(self.name)\n return \"\".format(name, id(self))\n\n\nclass Spectrum(object):\n \"\"\"A spectrum, representing wavelength and spectral density values.\n\n Parameters\n ----------\n wave : list_like\n Wavelength values.\n flux : list_like\n Spectral flux density values.\n error : list_like, optional\n 1 standard deviation uncertainty on flux density values.\n wave_unit : `~astropy.units.Unit`\n Units.\n unit : `~astropy.units.BaseUnit`\n For now, only units with flux density in energy (not photon counts).\n z : float, optional\n Redshift of spectrum (default is `None`)\n dist : float, optional\n Luminosity distance in Mpc, used to adjust flux upon redshifting.\n The default is ``None``.\n meta : OrderedDict, optional\n Metadata.\n \"\"\"\n\n def __init__(\n self,\n wave,\n flux,\n error=None,\n unit=(u.erg / u.s / u.cm ** 2 / u.AA),\n wave_unit=u.AA,\n z=None,\n dist=None,\n meta=None,\n ):\n self._wave = np.asarray(wave)\n self._flux = np.asarray(flux)\n self._wunit = wave_unit\n self._unit = unit\n self._z = z\n self._dist = dist\n\n if error is not None:\n self._error = np.asarray(error)\n if self._wave.shape != self._error.shape:\n raise ValueError(\"shape of wavelength and variance must match\")\n else:\n self._error = None\n\n if meta is None:\n self.meta = OrderedDict()\n else:\n self.meta = deepcopy(meta)\n\n if self._wave.shape != self._flux.shape:\n raise ValueError(\"shape of wavelength and flux must match\")\n if self._wave.ndim != 1:\n raise ValueError(\"only 1-d arrays supported\")\n\n @property\n def wave(self):\n \"\"\"Wavelength values.\"\"\"\n return self._wave\n\n @property\n def flux(self):\n \"\"\"Spectral flux density values\"\"\"\n return self._flux\n\n @property\n def error(self):\n \"\"\"Uncertainty on flux density.\"\"\"\n return self._error\n\n @property\n def wave_unit(self):\n \"\"\"Units of wavelength.\"\"\"\n return self._wunit\n\n @property\n def unit(self):\n \"\"\"Units of flux density.\"\"\"\n return self._unit\n\n @property\n def z(self):\n \"\"\"Redshift of spectrum.\"\"\"\n return self._z\n\n @z.setter\n def z(self, value):\n self._z = value\n\n @property\n def dist(self):\n \"\"\"Distance to object in Mpc.\"\"\"\n return self._dist\n\n @dist.setter\n def dist(self, value):\n self._dist = value\n\n def bandflux(self, band):\n \"\"\"Perform synthentic photometry in a given bandpass.\n\n The bandpass transmission is interpolated onto the wavelength grid\n of the spectrum. The result is a weighted sum of the spectral flux\n density values (weighted by transmission values).\n\n Parameters\n ----------\n band : Bandpass object or name of registered bandpass.\n\n Returns\n -------\n bandflux : float\n Total flux in ph/s/cm^2. If part of bandpass falls\n outside the spectrum, `None` is returned instead.\n bandfluxerr : float\n Error on flux. Only returned if the `error` attribute is not\n `None`.\n \"\"\"\n\n band = get_bandpass(band)\n bwave, btrans = band.to_unit(self._wunit)\n\n if bwave[0] < self._wave[0] or bwave[-1] > self._wave[-1]:\n return None\n\n mask = (self._wave > bwave[0]) & (self._wave < bwave[-1])\n d = self._wave[mask]\n f = self._flux[mask]\n\n # First convert to ergs/s/cm^2/(wavelength unit)...\n target_unit = u.erg / u.s / u.cm ** 2 / self._wunit\n if self._unit != target_unit:\n f = self._unit.to(target_unit, f, u.spectral_density(self._wunit, d))\n\n # Then convert ergs to photons: photons = Energy / (h * nu).\n f = f / const.h.cgs.value / self._wunit.to(u.Hz, d, u.spectral())\n\n trans = np.interp(d, bwave, btrans)\n binw = np.gradient(d)\n ftot = np.sum(f * trans * binw)\n\n if self._error is None:\n return ftot\n\n else:\n e = self._error[mask]\n\n # Do the same conversion as above\n if self._unit != target_unit:\n e = self._unit.to(target_unit, e, u.spectral_density(self._wunit, d))\n e = e / const.h.cgs.value / self._wunit.to(u.Hz, d, u.spectral())\n etot = np.sqrt(np.sum((e * binw) ** 2 * trans))\n return ftot, etot\n\n def redshifted_to(self, z, adjust_flux=False, dist=None, cosmo=None):\n \"\"\"Return a new Spectrum object at a new redshift.\n\n The current redshift must be defined (self.z cannot be `None`).\n A factor of (1 + z) / (1 + self.z) is applied to the wavelength.\n The inverse factor is applied to the flux so that the bolometric\n flux (e.g., erg/s/cm^2) remains constant.\n\n .. note:: Currently this only works for units in ergs.\n\n Parameters\n ----------\n z : float\n Target redshift.\n adjust_flux : bool, optional\n If True, the bolometric flux is adjusted by\n ``F_out = F_in * (D_in / D_out) ** 2``, where ``D_in`` and\n ``D_out`` are current and target luminosity distances,\n respectively. ``D_in`` is self.dist. If self.dist is ``None``,\n the distance is calculated from the current redshift and\n given cosmology.\n dist : float, optional\n Output distance in Mpc. Used to adjust bolometric flux if\n ``adjust_flux`` is ``True``. Default is ``None`` which means\n that the distance is calculated from the redshift and the\n cosmology.\n cosmo : `~astropy.cosmology.Cosmology` instance, optional\n The cosmology used to estimate distances if dist is not given.\n Default is ``None``, which results in using the default\n cosmology.\n\n Returns\n -------\n spec : Spectrum object\n A new spectrum object at redshift z.\n \"\"\"\n\n if self._z is None:\n raise ValueError(\n \"Must set current redshift in order to redshift\" \" spectrum\"\n )\n\n if self._wunit.physical_type == u.m.physical_type:\n factor = (1.0 + z) / (1.0 + self._z)\n elif self._wunit.physical_type == u.Hz.physical_type:\n factor = (1.0 + self._z) / (1.0 + z)\n else:\n raise ValueError(\"wavelength must be in wavelength or frequency\")\n\n d = self._wave * factor\n f = self._flux / factor\n if self._error is not None:\n e = self._error / factor\n else:\n e = None\n\n if adjust_flux:\n if self._dist is None and self._z == 0.0:\n raise ValueError(\n \"When current redshift is 0 and adjust_flux \"\n \"is requested, current distance must be \"\n \"defined\"\n )\n if dist is None and z == 0.0:\n raise ValueError(\n \"When redshift is 0 and adjust_flux \"\n \"is requested, dist must be defined\"\n )\n if cosmo is None:\n cosmo = cosmology.get_current()\n\n if self._dist is None:\n dist_in = cosmo.luminosity_distance(self._z)\n else:\n dist_in = self._dist\n\n if dist is None:\n dist = cosmo.luminosity_distance(z)\n\n if dist_in <= 0.0 or dist <= 0.0:\n raise ValueError(\"Distances must be greater than 0.\")\n\n # Adjust the flux\n factor = (dist_in / dist) ** 2\n f *= factor\n if e is not None:\n e *= factor\n\n return Spectrum(\n d,\n f,\n error=e,\n z=z,\n dist=dist,\n meta=self.meta,\n unit=self._unit,\n wave_unit=self._wunit,\n )\n\n\nclass MagSystem(object):\n \"\"\"An abstract base class for magnitude systems.\"\"\"\n\n __metaclass__ = abc.ABCMeta\n\n def __init__(self, name=None):\n self._zpbandflux = {}\n self._name = name\n\n @abc.abstractmethod\n def _refspectrum_bandflux(self, band):\n \"\"\"Flux of the fundamental spectrophotometric standard.\"\"\"\n pass\n\n @property\n def name(self):\n \"\"\"Name of magnitude system.\"\"\"\n return self._name\n\n @name.setter\n def name(self, value):\n self._name = value\n\n def zpbandflux(self, band):\n \"\"\"Flux of an object with magnitude zero in the given bandpass.\n\n Parameters\n ----------\n bandpass : `~sncosmo.spectral.Bandpass` or str\n\n Returns\n -------\n bandflux : float\n Flux in photons / s / cm^2.\n \"\"\"\n\n band = get_bandpass(band)\n try:\n return self._zpbandflux[band]\n except KeyError:\n bandflux = self._refspectrum_bandflux(band)\n self._zpbandflux[band] = bandflux\n\n return bandflux\n\n def band_flux_to_mag(self, flux, band):\n \"\"\"Convert flux (photons / s / cm^2) to magnitude.\"\"\"\n return -2.5 * math.log10(flux / self.zpbandflux(band))\n\n def band_mag_to_flux(self, mag, band):\n \"\"\"Convert magnitude to flux in photons / s / cm^2\"\"\"\n return self.zpbandflux(band) * 10.0 ** (-0.4 * mag)\n\n\nclass CompositeMagSystem(MagSystem):\n \"\"\"A magnitude system defined in a specific set of bands.\n\n In each band, there is a fundamental standard with a known\n (generally non-zero) magnitude.\n\n Parameters\n ----------\n bands: iterable of `~sncosmo.Bandpass` or str\n The filters in the magnitude system.\n standards: iterable of `~sncosmo.MagSystem` or str,\n The spectrophotmetric flux standards for each band, in the\n same order as `bands`.\n offsets: list_like\n The magnitude of standard in the given band.\n \"\"\"\n\n def __init__(self, bands, standards, offsets, name=None):\n super(CompositeMagSystem, self).__init__(name=name)\n\n if not len(bands) == len(offsets) == len(standards):\n raise ValueError(\"Lengths of bands, standards, and offsets \" \"must match.\")\n\n self._bands = [get_bandpass(band) for band in bands]\n self._standards = [get_magsystem(s) for s in standards]\n self._offsets = offsets\n\n @property\n def bands(self):\n return self._bands\n\n @property\n def standards(self):\n return self._standards\n\n @property\n def offsets(self):\n return self._offsets\n\n def _refspectrum_bandflux(self, band):\n if band not in self._bands:\n raise ValueError(\"band not in local magnitude system\")\n i = self._bands.index(band)\n standard = self._standards[i]\n offset = self._offsets[i]\n\n return 10.0 ** (0.4 * offset) * standard.zpbandflux(band)\n\n def __str__(self):\n s = \"CompositeMagSystem {!r}:\\n\".format(self.name)\n\n for i in range(len(self._bands)):\n s += \" {!r}: system={!r} offset={}\\n\".format(\n self._bands[i].name, self._standards[i].name, self._offsets[i]\n )\n return s\n\n\nclass SpectralMagSystem(MagSystem):\n \"\"\"A magnitude system defined by a fundamental spectrophotometric\n standard.\n\n Parameters\n ----------\n refspectrum : `sncosmo.Spectrum`\n The spectrum of the fundamental spectrophotometric standard.\n \"\"\"\n\n def __init__(self, refspectrum, name=None):\n super(SpectralMagSystem, self).__init__(name)\n self._refspectrum = refspectrum\n\n def _refspectrum_bandflux(self, band):\n return self._refspectrum.bandflux(band)\n\n\nclass ABMagSystem(MagSystem):\n \"\"\"Magnitude system where a source with F_nu = 3631 Jansky at all\n frequencies has magnitude 0 in all bands.\"\"\"\n\n def _refspectrum_bandflux(self, band):\n bwave, btrans = band.to_unit(u.Hz)\n\n # AB spectrum is 3631 x 10^{-23} erg/s/cm^2/Hz\n # Get spectral values in photons/cm^2/s/Hz at bandpass wavelengths\n # by dividing by (h \\nu).\n f = 3631.0e-23 / const.h.cgs.value / bwave\n\n binw = np.gradient(bwave)\n return np.sum(f * btrans * binw)\n", "meta": {"hexsha": "4863ed107e49b2f85cba6f4651986b3f6cc6a6b8", "size": 18789, "ext": "py", "lang": "Python", "max_stars_repo_path": "modelSED/sncosmo_spectral_v13.py", "max_stars_repo_name": "simeonreusch/model_sed", "max_stars_repo_head_hexsha": "ababa66850280a1be152a6ecdf25dafcf1fca00e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-30T12:23:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-30T12:23:13.000Z", "max_issues_repo_path": "modelSED/sncosmo_spectral_v13.py", "max_issues_repo_name": "simeonreusch/modelSED", "max_issues_repo_head_hexsha": "ababa66850280a1be152a6ecdf25dafcf1fca00e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modelSED/sncosmo_spectral_v13.py", "max_forks_repo_name": "simeonreusch/modelSED", "max_forks_repo_head_hexsha": "ababa66850280a1be152a6ecdf25dafcf1fca00e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3537964459, "max_line_length": 87, "alphanum_fraction": 0.5836393635, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 4536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.2422056341953392, "lm_q1q2_score": 0.12488604869144034}} {"text": "\"\"\"\n:mod:`mirgecom.eos` provides implementations of gas equations of state.\n\nEquations of State\n^^^^^^^^^^^^^^^^^^\nThis module is designed provide Equation of State objects used to compute and\nmanage the relationships between and among state and thermodynamic variables.\n\n.. autoclass:: EOSDependentVars\n.. autoclass:: GasEOS\n.. autoclass:: MixtureEOS\n.. autoclass:: IdealSingleGas\n.. autoclass:: PyrometheusMixture\n\"\"\"\n\n__copyright__ = \"\"\"\nCopyright (C) 2021 University of Illinois Board of Trustees\n\"\"\"\n\n__license__ = \"\"\"\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\"\n\nfrom dataclasses import dataclass\nimport numpy as np\nfrom pytools import memoize_in\nfrom meshmode.mesh import BTAG_ALL, BTAG_NONE # noqa\nfrom mirgecom.fluid import ConservedVars, make_conserved\nfrom abc import ABCMeta, abstractmethod\n\n\n@dataclass\nclass EOSDependentVars:\n \"\"\"State-dependent quantities for :class:`GasEOS`.\n\n Prefer individual methods for model use, use this\n structure for visualization or probing.\n\n .. attribute:: temperature\n .. attribute:: pressure\n \"\"\"\n\n temperature: np.ndarray\n pressure: np.ndarray\n\n\nclass GasEOS(metaclass=ABCMeta):\n r\"\"\"Abstract interface to equation of state class.\n\n Equation of state (EOS) classes are responsible for\n computing relations between fluid or gas state variables.\n\n Each interface call takes an :class:`~mirgecom.fluid.ConservedVars` object\n array representing the simulation state quantities. Each EOS class\n implementation should document its own state data requirements.\n\n .. automethod:: pressure\n .. automethod:: temperature\n .. automethod:: sound_speed\n .. automethod:: internal_energy\n .. automethod:: gas_const\n .. automethod:: dependent_vars\n .. automethod:: total_energy\n .. automethod:: kinetic_energy\n .. automethod:: gamma\n .. automethod:: transport_model\n .. automethod:: get_internal_energy\n \"\"\"\n\n @abstractmethod\n def pressure(self, cv: ConservedVars):\n \"\"\"Get the gas pressure.\"\"\"\n\n @abstractmethod\n def temperature(self, cv: ConservedVars):\n \"\"\"Get the gas temperature.\"\"\"\n\n @abstractmethod\n def sound_speed(self, cv: ConservedVars):\n \"\"\"Get the gas sound speed.\"\"\"\n\n @abstractmethod\n def gas_const(self, cv: ConservedVars):\n r\"\"\"Get the specific gas constant ($R_s$).\"\"\"\n\n @abstractmethod\n def heat_capacity_cp(self, cv: ConservedVars):\n r\"\"\"Get the specific heat capacity at constant pressure ($C_p$).\"\"\"\n\n @abstractmethod\n def heat_capacity_cv(self, cv: ConservedVars):\n r\"\"\"Get the specific heat capacity at constant volume ($C_v$).\"\"\"\n\n @abstractmethod\n def internal_energy(self, cv: ConservedVars):\n \"\"\"Get the thermal energy of the gas.\"\"\"\n\n @abstractmethod\n def total_energy(self, cv: ConservedVars, pressure: np.ndarray):\n \"\"\"Get the total (thermal + kinetic) energy for the gas.\"\"\"\n\n @abstractmethod\n def kinetic_energy(self, cv: ConservedVars):\n \"\"\"Get the kinetic energy for the gas.\"\"\"\n\n @abstractmethod\n def gamma(self, cv: ConservedVars):\n \"\"\"Get the ratio of gas specific heats Cp/Cv.\"\"\"\n\n @abstractmethod\n def transport_model(self):\n \"\"\"Get the transport model if it exists.\"\"\"\n\n @abstractmethod\n def get_internal_energy(self, temperature, *, mass, species_mass_fractions):\n \"\"\"Get the fluid internal energy from temperature and mass.\"\"\"\n\n def dependent_vars(self, cv: ConservedVars) -> EOSDependentVars:\n \"\"\"Get an agglomerated array of the dependent variables.\"\"\"\n return EOSDependentVars(\n pressure=self.pressure(cv),\n temperature=self.temperature(cv),\n )\n\n\nclass MixtureEOS(GasEOS):\n r\"\"\"Abstract interface to gas mixture equation of state class.\n\n This EOS base class extends the GasEOS base class to include the\n necessary interface for dealing with gas mixtures.\n\n .. automethod:: get_density\n .. automethod:: get_species_molecular_weights\n .. automethod:: get_production_rates\n .. automethod:: species_enthalpies\n .. automethod:: get_species_source_terms\n \"\"\"\n\n @abstractmethod\n def get_density(self, pressure, temperature, species_mass_fractions):\n \"\"\"Get the density from pressure, temperature, and species fractions (Y).\"\"\"\n\n @abstractmethod\n def get_species_molecular_weights(self):\n \"\"\"Get the species molecular weights.\"\"\"\n\n @abstractmethod\n def species_enthalpies(self, cv: ConservedVars):\n \"\"\"Get the species specific enthalpies.\"\"\"\n\n @abstractmethod\n def get_production_rates(self, cv: ConservedVars):\n \"\"\"Get the production rate for each species.\"\"\"\n\n @abstractmethod\n def get_species_source_terms(self, cv: ConservedVars):\n r\"\"\"Get the species mass source terms to be used on the RHS for chemistry.\"\"\"\n\n\nclass IdealSingleGas(GasEOS):\n r\"\"\"Ideal gas law single-component gas ($p = \\rho{R}{T}$).\n\n The specific gas constant, R, defaults to the air-like 287.1 J/(kg*K),\n but can be set according to simulation units and materials.\n\n Each interface call expects that the :class:`~mirgecom.fluid.ConservedVars`\n object representing the simulation conserved quantities contains at least\n the canonical conserved quantities mass ($\\rho$), energy ($\\rho{E}$), and\n momentum ($\\rho\\vec{V}$).\n\n .. automethod:: __init__\n .. automethod:: pressure\n .. automethod:: temperature\n .. automethod:: sound_speed\n .. automethod:: internal_energy\n .. automethod:: gas_const\n .. automethod:: dependent_vars\n .. automethod:: total_energy\n .. automethod:: kinetic_energy\n .. automethod:: gamma\n .. automethod:: transport_model\n .. automethod:: get_internal_energy\n \"\"\"\n\n def __init__(self, gamma=1.4, gas_const=287.1, transport_model=None):\n \"\"\"Initialize Ideal Gas EOS parameters.\"\"\"\n self._gamma = gamma\n self._gas_const = gas_const\n self._transport_model = transport_model\n\n def transport_model(self):\n \"\"\"Get the transport model object for this EOS.\"\"\"\n return self._transport_model\n\n def gamma(self, cv: ConservedVars = None):\n \"\"\"Get specific heat ratio Cp/Cv.\"\"\"\n return self._gamma\n\n def heat_capacity_cp(self, cv: ConservedVars = None):\n r\"\"\"Get specific heat capacity at constant pressure.\n\n Parameters\n ----------\n cv: :class:`~mirgecom.fluid.ConservedVars`\n :class:`~mirgecom.fluid.ConservedVars` containing at least the mass\n ($\\rho$), energy ($\\rho{E}$), momentum ($\\rho\\vec{V}$), and the vector of\n species masses, ($\\rho{Y}_\\alpha$).\n \"\"\"\n return self._gas_const * self._gamma / (self._gamma - 1)\n\n def heat_capacity_cv(self, cv: ConservedVars = None):\n r\"\"\"Get specific heat capacity at constant volume.\n\n Parameters\n ----------\n cv: :class:`~mirgecom.fluid.ConservedVars`\n :class:`~mirgecom.fluid.ConservedVars` containing at least the mass\n ($\\rho$), energy ($\\rho{E}$), momentum ($\\rho\\vec{V}$), and the vector of\n species masses, ($\\rho{Y}_\\alpha$).\n \"\"\"\n return self._gas_const / (self._gamma - 1)\n\n def gas_const(self, cv: ConservedVars = None):\n \"\"\"Get specific gas constant R.\"\"\"\n return self._gas_const\n\n def kinetic_energy(self, cv: ConservedVars):\n r\"\"\"Get kinetic (i.e. not internal) energy of gas.\n\n The kinetic energy is calculated as:\n\n .. math::\n\n k = \\frac{1}{2\\rho}(\\rho\\vec{V} \\cdot \\rho\\vec{V})\n\n Parameters\n ----------\n cv: :class:`~mirgecom.fluid.ConservedVars`\n :class:`~mirgecom.fluid.ConservedVars` containing at least the mass\n ($\\rho$), energy ($\\rho{E}$), momentum ($\\rho\\vec{V}$).\n\n Returns\n -------\n :class:`~meshmode.dof_array.DOFArray`\n The kinetic energy of the fluid flow\n \"\"\"\n mom = cv.momentum\n return (0.5 * np.dot(mom, mom) / cv.mass)\n\n def internal_energy(self, cv: ConservedVars):\n r\"\"\"Get internal thermal energy of gas.\n\n The internal energy (e) is calculated as:\n\n .. math::\n\n e = \\rho{E} - \\frac{1}{2\\rho}(\\rho\\vec{V} \\cdot \\rho\\vec{V})\n\n Parameters\n ----------\n cv: :class:`~mirgecom.fluid.ConservedVars`\n :class:`~mirgecom.fluid.ConservedVars` containing at least the mass\n ($\\rho$), energy ($\\rho{E}$), momentum ($\\rho\\vec{V}$).\n\n Returns\n -------\n :class:`~meshmode.dof_array.DOFArray`\n The internal energy of the fluid material\n \"\"\"\n return (cv.energy - self.kinetic_energy(cv))\n\n def pressure(self, cv: ConservedVars):\n r\"\"\"Get thermodynamic pressure of the gas.\n\n Gas pressure (p) is calculated from the internal energy (e) as:\n\n .. math::\n\n p = (\\gamma - 1)e\n\n Parameters\n ----------\n cv: :class:`~mirgecom.fluid.ConservedVars`\n :class:`~mirgecom.fluid.ConservedVars` containing at least the mass\n ($\\rho$), energy ($\\rho{E}$), momentum ($\\rho\\vec{V}$).\n\n Returns\n -------\n :class:`~meshmode.dof_array.DOFArray`\n The fluid pressure\n \"\"\"\n return self.internal_energy(cv) * (self._gamma - 1.0)\n\n def sound_speed(self, cv: ConservedVars):\n r\"\"\"Get the speed of sound in the gas.\n\n The speed of sound (c) is calculated as:\n\n .. math::\n\n c = \\sqrt{\\frac{\\gamma{p}}{\\rho}}\n\n Parameters\n ----------\n cv: :class:`~mirgecom.fluid.ConservedVars`\n :class:`~mirgecom.fluid.ConservedVars` containing at least the mass\n ($\\rho$), energy ($\\rho{E}$), momentum ($\\rho\\vec{V}$).\n\n Returns\n -------\n :class:`~meshmode.dof_array.DOFArray`\n The speed of sound in the fluid\n \"\"\"\n actx = cv.array_context\n return actx.np.sqrt(self._gamma / cv.mass * self.pressure(cv))\n\n def temperature(self, cv: ConservedVars):\n r\"\"\"Get the thermodynamic temperature of the gas.\n\n The thermodynamic temperature (T) is calculated from\n the internal energy (e) and specific gas constant (R)\n as:\n\n .. math::\n\n T = \\frac{(\\gamma - 1)e}{R\\rho}\n\n Parameters\n ----------\n cv: :class:`~mirgecom.fluid.ConservedVars`\n :class:`~mirgecom.fluid.ConservedVars` containing at least the mass\n ($\\rho$), energy ($\\rho{E}$), momentum ($\\rho\\vec{V}$).\n\n Returns\n -------\n :class:`~meshmode.dof_array.DOFArray`\n The fluid temperature\n \"\"\"\n return (\n (((self._gamma - 1.0) / self._gas_const)\n * self.internal_energy(cv) / cv.mass)\n )\n\n def total_energy(self, cv, pressure):\n r\"\"\"\n Get gas total energy from mass, pressure, and momentum.\n\n The total energy density (rhoE) is calculated from\n the mass density (rho) , pressure (p) , and\n momentum (rhoV) as:\n\n .. math::\n\n \\rho{E} = \\frac{p}{(\\gamma - 1)} +\n \\frac{1}{2}\\rho(\\vec{v} \\cdot \\vec{v})\n\n .. note::\n\n The total_energy function computes cv.energy from pressure,\n mass, and momentum in this case. In general in the EOS we need\n DV = EOS(CV), and inversions CV = EOS(DV). This is one of those\n inversion interfaces.\n\n Parameters\n ----------\n cv: :class:`~mirgecom.fluid.ConservedVars`\n :class:`~mirgecom.fluid.ConservedVars` containing at least the mass\n ($\\rho$), energy ($\\rho{E}$), momentum ($\\rho\\vec{V}$).\n\n pressure: :class:`~meshmode.dof_array.DOFArray`\n The fluid pressure\n\n Returns\n -------\n :class:`~meshmode.dof_array.DOFArray`\n The total energy of the fluid (i.e. internal + kinetic)\n \"\"\"\n return (pressure / (self._gamma - 1.0)\n + self.kinetic_energy(cv))\n\n def get_internal_energy(self, temperature, mass, species_mass_fractions=None):\n r\"\"\"Get the gas thermal energy from temperature, and fluid density.\n\n The gas internal energy $e$ is calculated from:\n\n .. math::\n\n e = R_s T \\frac{\\rho}{\\left(\\gamma - 1\\right)}\n\n Parameters\n ----------\n temperature: :class:`~meshmode.dof_array.DOFArray`\n The fluid temperature\n mass: float or :class:`~meshmode.dof_array.DOFArray`\n The fluid mass density\n species_mass_fractions:\n Unused\n \"\"\"\n return self._gas_const * mass * temperature / (self._gamma - 1)\n\n\nclass PyrometheusMixture(MixtureEOS):\n r\"\"\"Ideal gas mixture ($p = \\rho{R}_\\mathtt{mix}{T}$).\n\n This is the :mod:`pyrometheus`-based EOS. Please refer to the :any:`documentation\n of Pyrometheus ` for underlying implementation details.\n\n Each interface call expects that the :class:`mirgecom.fluid.ConservedVars` object\n representing the simulation conserved quantities contains at least the\n canonical conserved quantities mass ($\\rho$), energy ($\\rho{E}$), and\n momentum ($\\rho\\vec{V}$), and the vector of species masses, ($\\rho{Y}_\\alpha$).\n\n .. important::\n When using this EOS, users should take care to match solution initialization\n with the appropriate units that are used in the user-provided `Cantera`\n mechanism input files.\n\n .. automethod:: __init__\n .. automethod:: pressure\n .. automethod:: temperature\n .. automethod:: sound_speed\n .. automethod:: internal_energy\n .. automethod:: gas_const\n .. automethod:: dependent_vars\n .. automethod:: total_energy\n .. automethod:: kinetic_energy\n .. automethod:: gamma\n .. automethod:: transport_model\n .. automethod:: get_internal_energy\n .. automethod:: get_density\n .. automethod:: get_species_molecular_weights\n .. automethod:: get_production_rates\n .. automethod:: species_enthalpies\n .. automethod:: get_species_source_terms\n \"\"\"\n\n def __init__(self, pyrometheus_mech, temperature_guess=300.0,\n transport_model=None):\n \"\"\"Initialize Pyrometheus-based EOS with mechanism class.\n\n Parameters\n ----------\n pyrometheus_mech: :class:`pyrometheus.Thermochemistry`\n The :mod:`pyrometheus` mechanism :class:`~pyrometheus.Thermochemistry`\n object that is generated by the user with a call to\n *pyrometheus.get_thermochem_class*. To create the mechanism\n object, users need to provide a mechanism input file. Several built-in\n mechanisms are provided in `mirgecom/mechanisms/` and can be used through\n the :meth:`mirgecom.mechanisms.get_mechanism_cti`.\n\n tguess: float\n This provides a constant starting temperature for the Newton iterations\n used to find the mixture temperature. It defaults to 300.0 Kelvin. This\n parameter is important for the performance and proper function of the\n code. Users should set a tguess that is close to the average temperature\n of the simulated domain. Ideally, we would use the last computed\n temperature for the guess, but doing so requires restart infrastructure\n that is TBD.\n \"\"\"\n self._pyrometheus_mech = pyrometheus_mech\n self._tguess = temperature_guess\n self._transport_model = transport_model\n\n def transport_model(self):\n \"\"\"Get the transport model object for this EOS.\"\"\"\n return self._transport_model\n\n def heat_capacity_cp(self, cv: ConservedVars):\n r\"\"\"Get mixture-averaged specific heat capacity at constant pressure.\n\n Parameters\n ----------\n cv: :class:`~mirgecom.fluid.ConservedVars`\n :class:`~mirgecom.fluid.ConservedVars` containing at least the mass\n ($\\rho$), energy ($\\rho{E}$), momentum ($\\rho\\vec{V}$), and the vector of\n species masses, ($\\rho{Y}_\\alpha$).\n \"\"\"\n temp = self.temperature(cv)\n y = cv.species_mass_fractions\n return self._pyrometheus_mech.get_mixture_specific_heat_cp_mass(temp, y)\n\n def heat_capacity_cv(self, cv: ConservedVars):\n r\"\"\"Get mixture-averaged specific heat capacity at constant volume.\n\n Parameters\n ----------\n cv: :class:`~mirgecom.fluid.ConservedVars`\n :class:`~mirgecom.fluid.ConservedVars` containing at least the mass\n ($\\rho$), energy ($\\rho{E}$), momentum ($\\rho\\vec{V}$), and the vector of\n species masses, ($\\rho{Y}_\\alpha$).\n \"\"\"\n temp = self.temperature(cv)\n y = cv.species_mass_fractions\n return (\n self._pyrometheus_mech.get_mixture_specific_heat_cp_mass(temp, y)\n / self.gamma(cv)\n )\n\n def gamma(self, cv: ConservedVars):\n r\"\"\"Get mixture-averaged specific heat ratio for mixture $\\frac{C_p}{C_p - R_s}$.\n\n Parameters\n ----------\n cv: :class:`~mirgecom.fluid.ConservedVars`\n :class:`~mirgecom.fluid.ConservedVars` containing at least the mass\n ($\\rho$), energy ($\\rho{E}$), momentum ($\\rho\\vec{V}$), and the vector of\n species masses, ($\\rho{Y}_\\alpha$).\n \"\"\"\n temperature = self.temperature(cv)\n y = cv.species_mass_fractions\n cp = self._pyrometheus_mech.get_mixture_specific_heat_cp_mass(temperature, y)\n rspec = self.gas_const(cv)\n return cp / (cp - rspec)\n\n def gas_const(self, cv: ConservedVars):\n r\"\"\"Get specific gas constant $R_s$.\n\n The mixture specific gas constant is calculated\n as $R_s = \\frac{R}{\\sum{\\frac{{Y}_\\alpha}{{M}_\\alpha}}}$ by the\n :mod:`pyrometheus` mechanism provided by the user. ${M}_\\alpha$ are the\n species molar masses.\n\n Parameters\n ----------\n cv: :class:`~mirgecom.fluid.ConservedVars`\n :class:`~mirgecom.fluid.ConservedVars` containing at least the mass\n ($\\rho$), energy ($\\rho{E}$), momentum ($\\rho\\vec{V}$), and the vector\n of species masses, ($\\rho{Y}_\\alpha$).\n \"\"\"\n y = cv.species_mass_fractions\n return self._pyrometheus_mech.get_specific_gas_constant(y)\n\n def kinetic_energy(self, cv: ConservedVars):\n r\"\"\"Get kinetic (i.e. not internal) energy of gas.\n\n The kinetic energy is calculated as:\n\n .. math::\n\n k = \\frac{1}{2\\rho}(\\rho\\vec{V} \\cdot \\rho\\vec{V})\n\n Parameters\n ----------\n cv: :class:`~mirgecom.fluid.ConservedVars`\n :class:`~mirgecom.fluid.ConservedVars` containing at least the mass\n ($\\rho$), energy ($\\rho{E}$), momentum ($\\rho\\vec{V}$), and the vector\n of species masses, ($\\rho{Y}_\\alpha$).\n \"\"\"\n mom = cv.momentum\n return (0.5 * np.dot(mom, mom) / cv.mass)\n\n def internal_energy(self, cv: ConservedVars):\n r\"\"\"Get internal thermal energy of gas.\n\n The internal energy ($e$) is calculated as:\n\n .. math::\n\n e = \\rho{E} - \\frac{1}{2\\rho}(\\rho\\vec{V} \\cdot \\rho\\vec{V})\n\n Parameters\n ----------\n cv: :class:`~mirgecom.fluid.ConservedVars`\n :class:`~mirgecom.fluid.ConservedVars` containing at least the mass\n ($\\rho$), energy ($\\rho{E}$), momentum ($\\rho\\vec{V}$), and the vector\n of species masses, ($\\rho{Y}_\\alpha$).\n\n Returns\n -------\n :class:`~meshmode.dof_array.DOFArray`\n Internal energy of the fluid\n \"\"\"\n return (cv.energy - self.kinetic_energy(cv))\n\n def get_density(self, pressure, temperature, species_mass_fractions):\n r\"\"\"Get the density from pressure, temperature, and species fractions (Y).\n\n The gas density $\\rho$ is calculated from pressure, temperature and $R$ as:\n\n .. math::\n\n \\rho = \\frac{p}{R_s T}\n\n Parameters\n ----------\n pressure: :class:`~meshmode.dof_array.DOFArray`\n The fluid pressure\n temperature: :class:`~meshmode.dof_array.DOFArray`\n The fluid temperature\n species_mass_fractions: numpy.ndarray\n Object array of species mass fractions\n\n Returns\n -------\n :class:`~meshmode.dof_array.DOFArray`\n The total fluid mass density\n \"\"\"\n return self._pyrometheus_mech.get_density(pressure, temperature,\n species_mass_fractions)\n\n def get_internal_energy(self, temperature, species_mass_fractions,\n mass=None):\n r\"\"\"Get the gas thermal energy from temperature, and species fractions (Y).\n\n The gas internal energy $e$ is calculated from:\n\n .. math::\n\n e = R_s T \\sum{Y_\\alpha h_\\alpha}\n\n Parameters\n ----------\n temperature: :class:`~meshmode.dof_array.DOFArray`\n The fluid temperature\n species_mass_fractions: numpy.ndarray\n Object array of species mass fractions\n mass:\n Unused\n \"\"\"\n return self._pyrometheus_mech.get_mixture_internal_energy_mass(\n temperature, species_mass_fractions)\n\n def get_species_molecular_weights(self):\n \"\"\"Get the species molecular weights.\"\"\"\n return self._pyrometheus_mech.wts\n\n def species_enthalpies(self, cv: ConservedVars):\n \"\"\"Get the species specific enthalpies.\"\"\"\n return self._pyrometheus_mech.get_species_enthalpies_rt(self.temperature(cv))\n\n def get_production_rates(self, cv: ConservedVars):\n r\"\"\"Get the production rate for each species.\n\n Parameters\n ----------\n cv: :class:`~mirgecom.fluid.ConservedVars`\n :class:`~mirgecom.fluid.ConservedVars` containing at least the mass\n ($\\rho$), energy ($\\rho{E}$), momentum ($\\rho\\vec{V}$), and the vector\n of species masses, ($\\rho{Y}_\\alpha$).\n\n Returns\n -------\n numpy.ndarray\n The chemical production rates for each species\n \"\"\"\n temperature = self.temperature(cv)\n y = cv.species_mass_fractions\n return self._pyrometheus_mech.get_net_production_rates(\n cv.mass, temperature, y)\n\n def pressure(self, cv: ConservedVars):\n r\"\"\"Get thermodynamic pressure of the gas.\n\n Gas pressure ($p$) is calculated from the internal energy ($e$) as:\n\n .. math::\n\n p = (\\gamma_{\\mathtt{mix}} - 1)e\n\n Parameters\n ----------\n cv: :class:`~mirgecom.fluid.ConservedVars`\n :class:`~mirgecom.fluid.ConservedVars` containing at least the mass\n ($\\rho$), energy ($\\rho{E}$), momentum ($\\rho\\vec{V}$), and the vector\n of species masses, ($\\rho{Y}_\\alpha$).\n\n Returns\n -------\n :class:`~meshmode.dof_array.DOFArray`\n The pressure of the fluid.\n \"\"\"\n @memoize_in(cv, (PyrometheusMixture.pressure,\n type(self._pyrometheus_mech)))\n def get_pressure():\n temperature = self.temperature(cv)\n y = cv.species_mass_fractions\n return self._pyrometheus_mech.get_pressure(cv.mass, temperature, y)\n return get_pressure()\n\n def sound_speed(self, cv: ConservedVars):\n r\"\"\"Get the speed of sound in the gas.\n\n The speed of sound ($c$) is calculated as:\n\n .. math::\n\n c = \\sqrt{\\frac{\\gamma_{\\mathtt{mix}}{p}}{\\rho}}\n\n Parameters\n ----------\n cv: :class:`~mirgecom.fluid.ConservedVars`\n :class:`~mirgecom.fluid.ConservedVars` containing at least the mass\n ($\\rho$), energy ($\\rho{E}$), momentum ($\\rho\\vec{V}$), and the vector\n of species masses, ($\\rho{Y}_\\alpha$).\n\n Returns\n -------\n :class:`~meshmode.dof_array.DOFArray`\n The speed of sound in the fluid.\n \"\"\"\n @memoize_in(cv, (PyrometheusMixture.sound_speed,\n type(self._pyrometheus_mech)))\n def get_sos():\n actx = cv.array_context\n return actx.np.sqrt((self.gamma(cv) * self.pressure(cv)) / cv.mass)\n return get_sos()\n\n def temperature(self, cv: ConservedVars):\n r\"\"\"Get the thermodynamic temperature of the gas.\n\n The thermodynamic temperature ($T$) is calculated from\n the internal energy ($e$) and specific gas constant ($R_s$)\n as:\n\n .. math::\n\n T = \\frac{(\\gamma_{\\mathtt{mix}} - 1)e}{R_s \\rho}\n\n Parameters\n ----------\n cv: :class:`~mirgecom.fluid.ConservedVars`\n :class:`~mirgecom.fluid.ConservedVars` containing at least the mass\n ($\\rho$), energy ($\\rho{E}$), momentum ($\\rho\\vec{V}$), and the vector\n of species masses, ($\\rho{Y}_\\alpha$).\n\n Returns\n -------\n :class:`~meshmode.dof_array.DOFArray`\n The temperature of the fluid.\n \"\"\"\n @memoize_in(cv, (PyrometheusMixture.temperature,\n type(self._pyrometheus_mech)))\n def get_temp():\n y = cv.species_mass_fractions\n e = self.internal_energy(cv) / cv.mass\n return self._pyrometheus_mech.get_temperature(e, self._tguess,\n y, True)\n return get_temp()\n\n def total_energy(self, cv, pressure):\n r\"\"\"\n Get gas total energy from mass, pressure, and momentum.\n\n The total energy density ($\\rho E$) is calculated from\n the mass density ($\\rho$) , pressure ($p$) , and\n momentum ($\\rho\\vec{V}$) as:\n\n .. math::\n\n \\rho E = \\frac{p}{(\\gamma_{\\mathtt{mix}} - 1)} +\n \\frac{1}{2}\\rho(\\vec{v} \\cdot \\vec{v})\n\n .. note::\n\n The total_energy function computes cv.energy from pressure,\n mass, and momentum in this case. In general in the EOS we need\n DV = EOS(CV), and inversions CV = EOS(DV). This is one of those\n inversion interfaces.\n\n Parameters\n ----------\n cv: :class:`~mirgecom.fluid.ConservedVars`\n :class:`~mirgecom.fluid.ConservedVars` containing at least the mass\n ($\\rho$), energy ($\\rho{E}$), momentum ($\\rho\\vec{V}$), and the vector\n of species masses, ($\\rho{Y}_\\alpha$).\n pressure: :class:`~meshmode.dof_array.DOFArray`\n The fluid pressure\n\n Returns\n -------\n :class:`~meshmode.dof_array.DOFArray`\n The total energy fo the fluid (i.e. internal + kinetic)\n \"\"\"\n return (pressure / (self.gamma(cv) - 1.0)\n + self.kinetic_energy(cv))\n\n def get_species_source_terms(self, cv: ConservedVars):\n r\"\"\"Get the species mass source terms to be used on the RHS for chemistry.\n\n Parameters\n ----------\n cv: :class:`~mirgecom.fluid.ConservedVars`\n :class:`~mirgecom.fluid.ConservedVars` containing at least the mass\n ($\\rho$), energy ($\\rho{E}$), momentum ($\\rho\\vec{V}$), and the vector\n of species masses, ($\\rho{Y}_\\alpha$).\n\n Returns\n -------\n :class:`~mirgecom.fluid.ConservedVars`\n Chemistry source terms\n \"\"\"\n omega = self.get_production_rates(cv)\n w = self.get_species_molecular_weights()\n dim = cv.dim\n species_sources = w * omega\n rho_source = 0 * cv.mass\n mom_source = 0 * cv.momentum\n energy_source = 0 * cv.energy\n\n return make_conserved(dim, rho_source, energy_source, mom_source,\n species_sources)\n", "meta": {"hexsha": "2cdef4057fa710380b20cd2e85a116aec3dbdd1e", "size": 28792, "ext": "py", "lang": "Python", "max_stars_repo_path": "mirgecom/eos.py", "max_stars_repo_name": "nchristensen/mirgecom", "max_stars_repo_head_hexsha": "f27285d1fc7e077e0b1ac6872712d88517588e33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mirgecom/eos.py", "max_issues_repo_name": "nchristensen/mirgecom", "max_issues_repo_head_hexsha": "f27285d1fc7e077e0b1ac6872712d88517588e33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mirgecom/eos.py", "max_forks_repo_name": "nchristensen/mirgecom", "max_forks_repo_head_hexsha": "f27285d1fc7e077e0b1ac6872712d88517588e33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1980440098, "max_line_length": 89, "alphanum_fraction": 0.6099611003, "include": true, "reason": "import numpy", "num_tokens": 6836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.24508502416032488, "lm_q1q2_score": 0.12445708302576844}} {"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.6.0\n# kernelspec:\n# display_name: deep_ml_curriculum\n# language: python\n# name: deep_ml_curriculum\n# ---\n\n# # Time Series Anaysis\n# Time Series are a sequence of data points ordered in time. Each data point contains one or more values and also has a time stamp. For instance, the average daily temperature is a time series. Time Series Analysis (TSA) is studying the behaviour of time series. \n#\n# An important part of time series analysis (TSA) is time series forcasting (TSF) which is using a sequence of data to predict future behaviour. In this session we will discuss TSA, and tool and technques in TSA. The next session will be focused on forcasting.\n#\n#\n# TSA has its own unique vocabulary and technical terms. Throughout this notebook we will explain some of these terms and what they mean in practice.\n#\n#\n# ## Tools\n#\n# One of the main tools for TSA is __Pandas__. In previous notebooks we learned about Pandas and it's capabilities in reading, writing, and manipulating tabular data. Pandas also has a wide range of functionalities for TSA. \n#\n# Another common tool for TSA in python is __Statsmodels__. Statsmodels is library with wide range of statistical analysis tools and a sub-module dedicated to TSA.\n\n# +\n# Our main packages for TSA\nimport pandas as pd\n\n# For math and array operations\nimport numpy as np\n\n# For plotting\nimport matplotlib.pyplot as plt\n# -\n\n# Later, we will import statsmodels sub-modules as we need them.\n\n# ## Pandas for time series\n#\n# Pandas has functionalities for reading time and date. \n\ndata_normal = pd.read_csv(\"../../data/processed/Generated/SampleSales.csv\")\ndata_normal[\"Date\"]\n\n# When reading data that contains date/time we can ask pandas to parse it as datetimes with `parse_dates = ['Column_name']`.\n\ndata_date_parsed = pd.read_csv(\n \"../../data/processed/Generated/SampleSales.csv\", parse_dates=[\"Date\"]\n)\ndata_date_parsed[\"Date\"]\n\n# In the first scenario when we print 'Date' column at the bottom it prints `dtype = object` which in this case it means pandas understands the dates as a string (or text). It has no understanding of what the dates actually mean. But in the second scenario, the type is `datetime64[ns]` which is a date/time object with accuracy of nanoseconds. Now pandas knows these are dates and it knows the year, month, day, etc. Also, despite showing only year, month, and day it is saving it to nanoseconds accuracy, which means we could also have time of the day included as well.\n#\n\n# Also, by passing `index_col = 'Date'` we can let pandas know that in the index column, instead of using numbers (0, 1, 2, ...) use the _'Date'_ column. This will make it easier to access data based on date.\n\ndata_index_parsed = pd.read_csv(\n \"../../data/processed/Generated/SampleSales.csv\",\n parse_dates=[\"Date\"],\n index_col=[\"Date\"],\n)\n\n# Notice freq is none, that makes sense since we don't have values for every day\ndata_index_parsed.index\n\ndata_index_parsed['Total'].plot()\n\ndata_index_parsed\n\n# Now we can get the data for a certain date or time period. Let stick to the ISO format which is year-month-day, this sidesteps the confusion over US vs UK date formats.\n\ndata_index_parsed.loc[\"2014-12-19\"]\n\ndata_index_parsed.loc[\"2014-11-01\":\"2014-12-01\"]\n\n# Also, if you have an array of dates in string format you can use `.to_datetime()` to convert it to datetime object. The date string can be in many formats and pandas can usually figure it out.\n\npd.to_datetime([\"1/3/2019\", \"July 23rd, 1964\", \"2006-01-09\"])\n\n# Or you can specify which format pandas should use.\n\npd.to_datetime([\"1/3/2019\"], format=\"%d/%m/%Y\")\n\npd.to_datetime([\"1/3/2019\"], format=\"%m/%d/%Y\")\n\n# ## Resampling\n# There are times you might need weekly data but you have it on daily basis. You can use resampling to transform the data into the new time intervals. This is also useful when you are dealing with datapoints which are not equally spaced. Let's have another look at the data we loaded earlier.\n\ndata_index_parsed.head(10)\n\n# This data shows the time and amount of purchases from a shop. The purchases are not taking place on a fixed interval. They can happen anytime. We can resample this data into weekly sales which makes it easier to analyse. To do this, we need to use the `.resample()` method and pass in the new interval. After that we need to specify how we want the data in each interval to be aggregated. In this case, we choose the sum function because we want the total sales in each week.\n\ndf = data_index_parsed.resample(\"W\").sum()\ndf.head(10)\n\n# Now we have weekly sales. Note that we passed in \"W\" to convert the data into weekly sales. There are a range of options available in pandas for various intervals. The table below shows a range of options for resampling.
\n# Note that not all the options on the table below are applicable for resampling. The options for resampling are \"M\", \"A\", \"Q\", \"BM\", \"BA\", \"BQ\", and \"W\". The other options in the table have other application which we will discuss later.\n\n# DateOffsets and their frequency strings. ([Source](https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#dateoffset-objects))
\n#\n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n#
Date OffsetFrequency StringDescription
DateOffsetNoneGeneric offset class, defaults to 1 calendar day
BDay or BusinessDay'B'business day (weekday)
CDay or CustomBusinessDay'C'custom business day
Week'W'one week, optionally anchored on a day of the week
WeekOfMonth'WOM'the x-th day of the y-th week of each month
LastWeekOfMonth'LWOM'the x-th day of the last week of each month
MonthEnd'M'calendar month end
MonthBegin'MS'calendar month begin
BMonthEnd or BusinessMonthEnd'BM'business month end
BMonthBegin or BusinessMonthBegin'BMS'business month begin
CBMonthEnd or CustomBusinessMonthEnd'CBM'custom business month end
CBMonthBegin or CustomBusinessMonthBegin'CBMS'custom business month begin
SemiMonthEnd'SM'15th (or other day_of_month) and calendar month end
SemiMonthBegin'SMS'15th (or other day_of_month) and calendar month begin
QuarterEnd'Q'calendar quarter end
QuarterBegin'QS'calendar quarter begin
BQuarterEnd'BQbusiness quarter end
BQuarterBegin'BQS'business quarter begin
FY5253Quarter'REQ'retail (aka 52-53 week) quarter
YearEnd'A'calendar year end
YearBegin'AS' or 'BYS'calendar year begin
BYearEnd'BA'business year end
BYearBegin'BAS'business year begin
FY5253'RE'retail (aka 52-53 week) year
EasterNoneEaster holiday
BusinessHour'BH'business hour
CustomBusinessHour'CBH'custom business hour
Day'D'one absolute day
Hour'H'one hour
Minute'T' or 'min'one minute
Second'S'one second
Milli'L' or 'ms'one millisecond
Micro'U' or 'us'one microsecond
Nano'N'one nanosecond
\n#\n\n\n\n# Lets compare differen't resamplings\nax=plt.gca()\ndata_index_parsed['Total'].resample(\"D\").sum().plot(label=\"Day\", ax=ax)\ndata_index_parsed['Total'].resample(\"W\").sum().plot(label=\"Week\", ax=ax)\ndata_index_parsed['Total'].resample(\"M\").sum().plot(label=\"Month\", ax=ax)\nplt.ylabel('Total')\nplt.legend()\n\n# ## Shifting\n# Shifiting is moving the data forward or backward in time. For instance, the code below shifts the data one week to the future.\n\n# Pandas knows the interval is a week\ndf.info()\n\ndf.head()\n\ndf.shift(periods=1)\n\n# Notice the value that belonged to \"2014-11-09\" now belongs to \"2014-11-09\". Also, you can see in the first row since there was no data point to be moved there, its new value is `NaN`.
\n# Now the question is how does pandas know how much it should shift the data? In other words, why did it decide to move the data one week and not one day? The answer is because pandas knows our data is weekly, so when we asked it to shift the data by one period it assumed one week. This is called the frequency of the data and we can check it using `.info()` as we did above.\n\n\n\n# The frequency is \"W-SUN\" which means weekly data and each week starts at sunday.\n\n# __What if we want Monday to be start of the week?__
\n# When we were resampling the data we asked pandas to create weekly data. We can specify which day should start of the week.\n\ndata_index_parsed.resample(\"W-MON\").sum()\n\n# __What if we only wanted to shift the data one day and not one week?__
\n# We can specify a frequency when shifting.\n\ndf.shift(periods=1, freq=\"D\")\n\n# Note in the above example only the dates changed and `NaN` didn't appear in the first row.\n\n# We can also shift backward. If we do this, `NaN` will appear at the end of the data.\n\ndf.shift(-2)\n\n# ## Rolling\n# Rolling is applying a function to a number of consecutive data points. For instance, at each point in time we take the average of the past 4 weeks. Taking average of past few periods is also know as __Moving Average Smoothing__.
\n# We first need to select the window (how many values we should consider), and then apply an aggregation function. (e.g. mean, sum, etc.)\n#\n#\n# \n#
\n# \n\ndf.rolling(window=4).mean()\n\n# __Note:__ Since the first three points didn't have three instances before them, the moving average was not calculated for them.\n\n# Let's save the moving average in the same data frame and plot the result to better understand why we would do this.\n\ndf[\"MA-4\"] = df.rolling(window=4).mean() # MA-4 for moving average of size 4 window\ndf.plot(y=[\"Total\", \"MA-4\"], figsize=(16, 8))\n\n# Let's try a larger window size. Because now we have two columns in the data, we need to specify which column we are taking a moving average of.\n\ndf[\"MA-13\"] = (\n df[\"Total\"].rolling(window=13).mean()\n) # MA-4 for moving average of size 4 window\ndf.plot(y=[\"Total\", \"MA-4\", \"MA-13\"], figsize=(16, 8))\n\n# As the name suggests __Moving Average Smoothing__ creates a smoothed out version of the data. The larger the window size, smoother the data will be. This is helpful when we want to get rid of noise in the data so we can have a better look at the trends. However, noise reduction comes at a cost. The downside of using moving average is the it creates lag in the data. For instance if there is a sudden increase in the data moving average responds to this change slower. It also doesn't reach the peaks of the original data. In the plot above you can see that \"MA-13\" does not show the high and low values of the data but only follows th main trend.\n\n# Another useful function pandas provide is **expanding**. While at each point rolling applied a function over a fixed window, expanding applies a function over all the points that came before that specific point. For instance, if we apply mean function at 10th point we will have the average of first 10 points and at 20th point we will have the average of first 20 points.\n#\n# exanding().sum() is the same as .cumsum()\n#\n\ndf[\"Total\"].expanding().sum().plot()\n\n# exanding().sum() is the same as .cumsum(), but you can use operations other than sum\ndf[\"Total\"].cumsum().plot()\n\n#
\n#

Exercise

\n#\n# Here's an exercise to get you familiar with the Pandas docs on timeseries.\n#\n# You need to change the timezone on a dataframe but your not sure how. \n# \n# - Look through [the dataframe docs](https://pandas.pydata.org/docs/reference/frame.html) and find how to set a timezone on a series that doesn't have one (but you know it's 'Australia/Perth')\n# - Set it to 'Australia/Perth'\n# - plot it\n#\n#\n#
\n# → Hints\n#\n# * Start in the Time-Series related section\n# * Scan it, then Ctrl-F for `timezone`\n# * Jargon is `localize` a `tz naive` series\n#\n#
\n#\n#
\n#
\n#
\n# \n# → Solution\n# \n#\n# ```python\n# # DataFrame.tz_localize\n# df.tz_localize('Australia/Perth').plot(\n# ```\n#\n#
\n#\n#
\n\n# Other operations:\n# \n# - https://pandas.pydata.org/pandas-docs/stable/reference/general_functions.html#top-level-dealing-with-datetimelike\n# - https://pandas.pydata.org/pandas-docs/stable/reference/frame.html#time-series-related\n# - https://pandas.pydata.org/pandas-docs/stable/reference/series.html#time-series-related\n\n# ## Lowess Smoothing\n# Now that we learned about moving average smoothing, let's discuss another technique. Locally weighted scatterplot smoothing (LOWESS) is another technique for smoothing. \n#\n# Lowess creates local models for small subsets of data and uses a weighted average of them for smoothing. \n#\n\n# The implementation of Lowess in statsmodels can be found in nonparametric sub-module.\nfrom statsmodels.nonparametric.smoothers_lowess import lowess\n\n# To create a smoothed output it requires x and y values. For time series x would be the time dimension and y would be the values.\n\nx = df.index\ny = df[\"Total\"]\nresult = lowess(y, x)\ndf[\"Lowess\"] = result[\n :, 1\n] # Lowess returns x and y. The second column (column index 1) are the values we need.\ndf.plot(y=[\"Total\", \"Lowess\"])\n\n\n\n# ## Time Series Decomposition\n\n# The goal of decomposition is to break down time series into different elements each describing a specific behaviour of data.\n\n# ### STL Decomposition\n\n# Seasonal-Trend decomposition with LOESS (STL) is another method for decomposition of time series. This method breaks down the data into three elements:\n# 1. Trend\n# 2. Seasonality\n# 3. Residual (Error or Noise)\n#\n# We learned about LOWESS for smoothing (LOESS is a similar method with only minor differences). LOESS showed the capability to extract the trend of time series. By removing the trend from the data STL assumes the remainder is sum of a seasonal component and some residual. Seasonal component is the repeating pattern of data. The sort of behaviour that repeats weekly, monthly, etc.
STL can decompose the time serie in two ways. First is additive method, where the original data is sum of its components:\n# $$y_t = \\tau_t + s_t + r_t $$\n# Second, the multiplicative approach where the data is product of its components:\n# $$y_t = \\tau_t \\times s_t \\times r_t $$\n# Statsmodel has a function for STL called `seasonal_decompose`.\n\n# This data shows the number of customers a retail shop had per months\ncust = pd.read_csv(\n \"../../data/processed/Generated/Customers.csv\", parse_dates=True, index_col=\"Month\"\n)\ncust.head()\n\n# Let's have quick look at the data.\n\ncust.plot(y=\"Customers\")\n\n# We can clearly see a repeating pattern. That's called seasonality and we expect STL to be able to capture this behaviour.\n\nfrom statsmodels.tsa.seasonal import seasonal_decompose\nresult = seasonal_decompose(cust[\"Customers\"], model='additive')\n\n# Now the time serie is decomposed and we can plot the result.\n\nax = result.plot()\nax.set_figwidth(16)\nax.set_figheight(8)\n\n# By default the model used additive approach for the data. If we want to use multiplicative approach we need to specify it in the function. But what is the difference between additive and multiplicative? Additive approach is used when the height of the repeating patterns are constant. This means the amplitude of seasonal component is not changing. But in this data we can clearly see the seasonal component is getting larger and larger. This is also visible in the residual component. The residual component is meant to look like random noise but we can clearly see some regular oscillation in there. So let's try multiplicative approach.\n\nresult = seasonal_decompose(cust[\"Customers\"], model=\"multiplicative\")\nprint('sum of residuals {:2.2f}'.format(result.resid.sum()))\nax = result.plot()\nax.set_figwidth(16)\nax.set_figheight(8)\n\n# __Note:__ While residuals in additive model is around zero, in multiplicative model they are around one.\n\n# As we can see, multiplicative approach looks much better. There is still a bit of pattern in residuals but it has improved significantly compared to additive approach.\n\n# ## Exercise\n#
\n#\n# let's try these on real data, which will be much harder. Use the data below and perform the following analyses:\n# \n# - STL decomposition using additive method.\n# \n#
\n# Hints\n# \n# * Find the relevent code, copy it, and change it to use `df['target']` \n#
\n#
\n#\n\ndf = block0 = pd.read_csv(\"../../data/processed/smartmeter/block_0.csv\", parse_dates=['day'], index_col=['day'])[['energy_sum']]\ndf = df.groupby('day').mean().iloc[:100]\ndf = df.rename(columns={'energy_sum':'target'})\ndf.plot()\ndf\n\n# Exercise 1\nfrom statsmodels.tsa.seasonal import seasonal_decompose\nresult = seasonal_decompose(df['target'],model = 'add')\nresult.plot();\nprint('sum of residuals {:2.2f}'.format(result.resid.sum()))\n\n#\n#
\n# \n# ### Solution\n#
See solution\n#\n#\n#\n# ```Python\n# # Exercise 1\n# from statsmodels.tsa.seasonal import seasonal_decompose\n# result = seasonal_decompose(df['target'],model = 'add')\n# result.plot();\n# print(f'sum of residuals {result.resid.sum():2.2f}')\n# ```\n#\n#
\n#
\n\n# In the next notebook we will look at how to do predictions, including seasonality\n\n# ## Further Reading:\n# - [Pandas time-series documentation](https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html)\n# - [Statsmodel documentation](https://www.statsmodels.org/)\n# - [Forecasting: Principles and Practice](https://otexts.com/fpp2/)\n# - [Exponential Smoothing](https://en.wikipedia.org/wiki/Exponential_smoothing)\n# - [Gentle Introduction to Exponential smoothing](https://machinelearningmastery.com/exponential-smoothing-for-time-series-forecasting-in-python/)\n#\n#\n\n\n", "meta": {"hexsha": "f1cf92c10f0d899584d04e1b90088b9225e184ce", "size": 20491, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/b09_Time_Series_Analysis/TSA.py", "max_stars_repo_name": "lixuekai2001/ml_for_log_data", "max_stars_repo_head_hexsha": "1e01c4c6c9a3ee6e20c5cfe8db44029c0aeaedd8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-09-24T06:34:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T14:43:11.000Z", "max_issues_repo_path": "notebooks/b09_Time_Series_Analysis/TSA.py", "max_issues_repo_name": "lixuekai2001/ml_for_log_data", "max_issues_repo_head_hexsha": "1e01c4c6c9a3ee6e20c5cfe8db44029c0aeaedd8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/b09_Time_Series_Analysis/TSA.py", "max_forks_repo_name": "lixuekai2001/ml_for_log_data", "max_forks_repo_head_hexsha": "1e01c4c6c9a3ee6e20c5cfe8db44029c0aeaedd8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-10-14T07:13:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T01:59:41.000Z", "avg_line_length": 37.7366482505, "max_line_length": 650, "alphanum_fraction": 0.6757600898, "include": true, "reason": "import numpy,import statsmodels,from statsmodels", "num_tokens": 5573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.2568319856991699, "lm_q1q2_score": 0.12440429887798916}} {"text": "#!/usr/bin/env python3\n\nimport os\nimport glob\nimport numpy as np\nimport scipy\nfrom ffindex import *\nfrom parsers import parse_hhr, parse_pdb_lines\nfrom pyrosetta import *\n\ninit(\"-mute all\")\n\nMAXSEQ=20000\n\n#============================================\n# Global variables such as data directory path\n#============================================\nLABEL_dir = \"/net/scratch/minkbaek/SStor/labels\"\nTEMPL_dir = \"/net/scratch/minkbaek/trRefine/added/templ/sub_0/templates\"\n#TEMPL_dir = \"/net/scratch/minkbaek/SStor/templs\"\nDECOY_DIR = \"/projects/casp/dldata\"\n\n\nblosum_mtx = np.array([[ 4, -1, -2, -2, 0, -1, -1, 0, -2, -1, -1, -1, -1, -2, -1, 1, 0, -3, -2, 0], \n [ -1, 5, 0, -2, -3, 1, 0, -2, 0, -3, -2, 2, -1, -3, -2, -1, -1, -3, -2, -3], \n [ -2, 0, 6, 1, -3, 0, 0, 0, 1, -3, -3, 0, -2, -3, -2, 1, 0, -4, -2, -3], \n [ -2, -2, 1, 6, -3, 0, 2, -1, -1, -3, -4, -1, -3, -3, -1, 0, -1, -4, -3, -3], \n [ 0, -3, -3, -3, 9, -3, -4, -3, -3, -1, -1, -3, -1, -2, -3, -1, -1, -2, -2, -1], \n [ -1, 1, 0, 0, -3, 5, 2, -2, 0, -3, -2, 1, 0, -3, -1, 0, -1, -2, -1, -2], \n [ -1, 0, 0, 2, -4, 2, 5, -2, 0, -3, -3, 1, -2, -3, -1, 0, -1, -3, -2, -2], \n [ 0, -2, 0, -1, -3, -2, -2, 6, -2, -4, -4, -2, -3, -3, -2, 0, -2, -2, -3, -3], \n [ -2, 0, 1, -1, -3, 0, 0, -2, 8, -3, -3, -1, -2, -1, -2, -1, -2, -2, 2, -3], \n [ -1, -3, -3, -3, -1, -3, -3, -4, -3, 4, 2, -3, 1, 0, -3, -2, -1, -3, -1, 3], \n [ -1, -2, -3, -4, -1, -2, -3, -4, -3, 2, 4, -2, 2, 0, -3, -2, -1, -2, -1, 1], \n [ -1, 2, 0, -1, -3, 1, 1, -2, -1, -3, -2, 5, -1, -3, -1, 0, -1, -3, -2, -2], \n [ -1, -1, -2, -3, -1, 0, -2, -3, -2, 1, 2, -1, 5, 0, -2, -1, -1, -1, -1, 1], \n [ -2, -3, -3, -3, -2, -3, -3, -3, -1, 0, 0, -3, 0, 6, -4, -2, -2, 1, 3, -1], \n [ -1, -2, -2, -1, -3, -1, -1, -2, -2, -3, -3, -1, -2, -4, 7, -1, -1, -4, -3, -2], \n [ 1, -1, 1, 0, -1, 0, 0, 0, -1, -2, -2, 0, -1, -2, -1, 4, 1, -3, -2, -2], \n [ 0, -1, 0, -1, -1, -1, -1, -2, -2, -1, -1, -1, -1, -2, -1, 1, 5, -2, -2, 0], \n [ -3, -3, -4, -4, -2, -2, -3, -2, -2, -3, -2, -3, -1, 1, -4, -3, -2, 11, 2, -3], \n [ -2, -2, -2, -3, -2, -1, -2, -3, 2, -1, -1, -2, -1, 3, -3, -2, -2, 2, 7, -1], \n [ 0, -3, -3, -3, -1, -2, -2, -3, -3, 3, 1, -2, 1, -1, -2, -2, 0, -3, -1, 4]]).astype(np.float32)\nblosum_mtx /= 10.0 # same as Nao's\n\ntip_atoms = {\"ALA\": \"CB\", \"CYS\": \"SG\", \"ASP\": \"CG\", \"GLU\": \"CD\",\n \"PHE\": \"CZ\", \"GLY\": \"CA\", \"HIS\":\"NE2\", \"ILE\":\"CD1\",\n \"LYS\": \"NZ\", \"LEU\": \"CG\", \"MET\": \"SD\", \"ASN\": \"CG\", \n \"PRO\": \"CG\", \"GLN\": \"CD\", \"ARG\": \"CZ\", \"SER\": \"OG\", \n \"THR\":\"OG1\", \"VAL\": \"CB\", \"TRP\":\"CH2\", \"TYR\": \"OH\"}\n\ndef f(X, cutoff=3, scaling=3.0):\n X_prime = np.maximum(X, np.zeros_like(X) + cutoff) - cutoff\n return np.arcsinh(X_prime)/scaling\n\ndef blosum(seq):\n return blosum_mtx[seq]\n\ndef t2q(tmplt,nres):\n\n dmin = 2.0\n dmax = 20.0\n\n qmap = tmplt['qmap']\n L = qmap.shape[0]\n\n # bin distance matrix\n nbins = 18\n bins = np.linspace(dmin, dmax, nbins+1)\n dist = tmplt['dist6d']\n dist[dist<0.001] = 999.9\n dbin = np.digitize(dist, bins).astype(np.float32)\n dbin[dbin > nbins] = 0\n\n f1d = np.zeros((nres,4), dtype=np.float32)\n f1d[qmap] = np.concatenate([\n tmplt['phi'][:,None],\n tmplt['psi'][:,None],\n tmplt['scores'][:,None],\n tmplt['conf'][:,None]\n ], axis=-1)\n\n f2d = np.zeros((nres,nres,6), dtype=np.float32)\n f2d[np.ix_(qmap,qmap)] = np.concatenate([\n dbin[:,:,None],\n tmplt['omega6d'][:,:,None],\n tmplt['theta6d'][:,:,None],\n tmplt['phi6d'][:,:,None],\n np.tile(tmplt['stats'][None,None,:],[L,L,1])\n ], axis=-1)\n\n return [f1d,f2d]\n\ndef subsample_msa(msa):\n n_sub = int(msa.shape[0]/2)\n if n_sub < 5:\n return msa\n seq = msa[0]\n tmp = msa[1:]\n np.random.shuffle(tmp)\n return np.concatenate([seq[np.newaxis,:], tmp[:n_sub-1,:]], axis=0)\n\ndef get_seqsep(n_res):\n pos = np.arange(n_res)\n pos = pos.astype(np.float32)\n tiled_pos = np.tile(pos, (n_res, 1))\n seqsep = np.abs(tiled_pos - tiled_pos.T)/100.0 - 1.0\n return seqsep\n\ndef get_labels(pdb, noise_level=0.0):\n label_fn = os.path.join(LABEL_dir, pdb + \".npz\")\n data = np.load(label_fn)\n #\n msa = subsample_msa(data['msa'])\n seq = blosum(msa[0])\n #\n dssp = data['dssp'].astype(np.float32)\n phi = data['phi'].astype(np.float32)\n psi = data['psi'].astype(np.float32)\n omg = data['omg'].astype(np.float32)\n omg = np.stack((1-omg, omg), axis=-1)\n\n return dssp, phi, psi, omg, msa, seq\n\ndef get_input_features(filename, is_train=True, mask_diag=8):\n fn_s = glob.glob(\"%s/%s/*.npz\"%(DECOY_DIR, filename))\n np.random.shuffle(fn_s)\n fn = fn_s[0]\n #\n data = np.load(fn)\n #\n seqsep = get_seqsep(data['maps'].shape[0])\n #\n # structure-based features\n d_CB = f(data['maps'][:,:,0].astype(np.float32))\n o_map = np.stack([data[\"omega6d\"], data[\"theta6d\"], data[\"phi6d\"]], axis=-1).astype(np.float32)\n o_map = np.concatenate([np.sin(o_map), np.cos(o_map)], axis=-1)\n feat_2d = np.concatenate((d_CB[:,:,None], o_map, seqsep[:,:,None]), axis=-1)\n if is_train: # add gaussian noise in training stage to avoid overfitting\n scale = np.random.uniform(low=0.05, high=0.15)\n noise = np.random.normal(scale=scale, size=feat_2d.shape).astype(np.float32)\n feat_2d += noise\n feat_2d = np.nan_to_num(feat_2d)\n #\n if mask_diag > -1:\n for i in range(feat_2d.shape[-1]):\n for k in range(mask_diag):\n np.fill_diagonal(feat_2d[k:,:,i], 0.0)\n np.fill_diagonal(feat_2d[:,k:,i], 0.0)\n #\n # Template information\n nres = data['maps'].shape[0]\n tlist = glob.glob(\"%s/%s/*.npz\"%(TEMPL_dir, filename))\n np.random.shuffle(tlist)\n n_templ = np.random.randint(10, 26)\n tlist = tlist[:n_templ]\n pthreads = [t2q(np.load(f), nres) for f in tlist]\n pth_1d = np.stack([p[0] for p in pthreads], axis=0)\n pth_2d = np.stack([p[1] for p in pthreads], axis=0)\n #\n return feat_2d, pth_1d, pth_2d\n\ndef load_train_data(pdb, noise_level=0.0, tag=None, is_train=True, mask_diag=8):\n #\n SS_label, phi_label, psi_label, omg_label, msa, seq = get_labels(pdb, noise_level=noise_level)\n feat_2d, pth_1d, pth_2d = get_input_features(pdb, is_train=is_train, mask_diag=mask_diag)\n #\n \n return seq, msa, feat_2d, pth_1d, pth_2d, SS_label, phi_label, psi_label, omg_label\n\n# TODO\n# input feature generation for prediction\ndef read_msa(a3m_fn):\n import string\n\n seqs = []\n table = str.maketrans(dict.fromkeys(string.ascii_lowercase))\n\n # read file\n with open(a3m_fn) as fp:\n for line in fp:\n if line[0] == '>': continue\n seqs.append(line.rstrip().translate(table)) # remove lowercase letters\n # convert letters into numbers\n alphabet = np.array(list(\"ARNDCQEGHILKMFPSTWYV-\"), dtype='|S1').view(np.uint8)\n msa = np.array([list(s) for s in seqs], dtype='|S1').view(np.uint8)\n for i in range(alphabet.shape[0]):\n msa[msa == alphabet[i]] = i\n\n msa[msa > 20] = 20\n return msa\n\ndef get_dihedrals(a, b, c, d):\n b0 = -1.0*(b - a)\n b1 = c - b\n b2 = d - c\n\n b1 /= np.linalg.norm(b1, axis=-1)[:,None]\n\n v = b0 - np.sum(b0*b1, axis=-1)[:,None]*b1\n w = b2 - np.sum(b2*b1, axis=-1)[:,None]*b1\n\n x = np.sum(v*w, axis=-1)\n y = np.sum(np.cross(b1, v)*w, axis=-1)\n\n return np.arctan2(y, x)\n\ndef get_angles(a, b, c):\n v = a - b\n v /= np.linalg.norm(v, axis=-1)[:,None]\n \n w = c - b\n w /= np.linalg.norm(w, axis=-1)[:,None]\n \n x = np.sum(v*w, axis=1)\n\n return np.arccos(np.clip(x, -1.0, 1.0))\n\ndef get_dist_ori_maps(model, resNo_s, n_res, dmax=20.0, return_sep=False):\n atm_names = list()\n for i in range(1, model.size()+1):\n if model.residue(i).name()[:3] == \"GLY\":\n atm_names.append('CA')\n else:\n atm_names.append('CB')\n #\n CA = np.zeros((n_res, 3), dtype=np.float32)\n N = np.zeros((n_res, 3), dtype=np.float32)\n O = np.zeros((n_res, 3), dtype=np.float32)\n C = np.zeros((n_res, 3), dtype=np.float32)\n CB = np.zeros((n_res, 3), dtype=np.float32)\n #\n for idx, resNo in enumerate(resNo_s):\n i = idx + 1 # resNo in pose\n CA[resNo, :] = np.array(model.residue(i).atom(\"CA\").xyz())\n N[resNo, :] = np.array(model.residue(i).atom(\"N\").xyz())\n O[resNo, :] = np.array(model.residue(i).atom(\"O\").xyz())\n C[resNo, :] = np.array(model.residue(i).atom(\"C\").xyz())\n CB[resNo, :] = np.array(model.residue(i).atom(atm_names[idx]).xyz())\n #\n mask = np.zeros((n_res, n_res), dtype=np.float32)\n for i in resNo_s:\n for j in resNo_s:\n mask[i,j] = 1.0\n #\n dist_CB_CB = scipy.spatial.distance.cdist(CB, CB, metric='euclidean')\n #\n dist_maps = f(dist_CB_CB[:,:,None])\n #\n # recreate Cb from given N, Ca, C\n b = CA - N\n c = C - CA\n a = np.cross(b, c)\n Cb = -0.58273431*a + 0.56802827*b - 0.54067466*c + CA\n #\n # neighbor search\n kdCb = scipy.spatial.cKDTree(Cb)\n indices = kdCb.query_ball_tree(kdCb, dmax)\n #\n # indices of contacting residues\n idx = np.array([[i,j] for i in range(len(indices)) for j in indices[i] if (i != j) and (i in resNo_s) and (j in resNo_s)]).T\n idx0 = idx[0]\n idx1 = idx[1]\n #\n # matrix of Ca-Cb-Cb-Ca dihedrals\n omega6d = np.zeros((n_res, n_res))\n ang = get_dihedrals(CA[idx0], CB[idx0], CB[idx1], CA[idx1])\n omega6d[idx0, idx1] = ang\n #\n # matrix of polar coord theta\n theta6d = np.zeros((n_res, n_res))\n ang = get_dihedrals(N[idx0], CA[idx0], Cb[idx0], Cb[idx1])\n theta6d[idx0, idx1] = ang \n #\n # matrix of polar coord phi\n phi6d = np.zeros((n_res, n_res))\n ang = get_angles(CA[idx0], Cb[idx0], Cb[idx1])\n phi6d[idx0, idx1] = ang\n #\n if return_sep:\n dist6d = np.zeros((nres, nres), dtype=np.float32)\n dist6d[idx0, idx1] = np.linalg.norm(Cb[idx1]-Cb[idx0], axis=-1)\n return dist6d, omega6d, theta6d, phi6d\n #\n ori_map = np.stack([omega6d, theta6d, phi6d], axis=-1).astype(np.float32)\n ori_map = np.concatenate([np.sin(ori_map), np.cos(ori_map)], axis=-1)\n #\n ori_map = ori_map * mask[:,:,None]\n dist_maps = dist_maps * mask[:,:,None]\n #\n return dist_maps, ori_map\n\ndef get_phipsi(xyz, tmap):\n nres = xyz.shape[1]\n \n N = xyz[0]\n Ca = xyz[1]\n C = xyz[2]\n\n C_prev = np.insert(C, 0, np.nan, axis=0)\n N_next = np.insert(N, nres, np.nan, axis=0)\n \n phi = get_dihedrals(C_prev[:-1,:], N, Ca, C)\n psi = get_dihedrals(N, Ca, C, N_next[1:,:])\n phi[0] = 0.0\n psi[-1] = 0.0\n tor = np.stack((phi, psi), axis=-1)[tmap]\n return tor\n\n# get 6d coordinates from x,y,z coords of N,Ca,C atoms\ndef get_coords6d(xyz, dmax):\n\n nres = xyz.shape[1]\n\n # three anchor atoms\n N = xyz[0]\n Ca = xyz[1]\n C = xyz[2]\n\n # recreate Cb given N,Ca,C\n b = Ca - N\n c = C - Ca\n a = np.cross(b, c)\n Cb = -0.58273431*a + 0.56802827*b - 0.54067466*c + Ca\n\n # fast neighbors search to collect all\n # Cb-Cb pairs within dmax\n kdCb = scipy.spatial.cKDTree(Cb)\n indices = kdCb.query_ball_tree(kdCb, dmax)\n\n # indices of contacting residues\n idx = np.array([[i,j] for i in range(len(indices)) for j in indices[i] if i != j]).T\n idx0 = idx[0]\n idx1 = idx[1]\n\n # Cb-Cb distance matrix\n dist6d = np.zeros((nres, nres))\n dist6d[idx0,idx1] = np.linalg.norm(Cb[idx1]-Cb[idx0], axis=-1)\n\n # matrix of Ca-Cb-Cb-Ca dihedrals\n omega6d = np.zeros((nres, nres))\n omega6d[idx0,idx1] = get_dihedrals(Ca[idx0], Cb[idx0], Cb[idx1], Ca[idx1])\n\n # matrix of polar coord theta\n theta6d = np.zeros((nres, nres))\n theta6d[idx0,idx1] = get_dihedrals(N[idx0], Ca[idx0], Cb[idx0], Cb[idx1])\n\n # matrix of polar coord phi\n phi6d = np.zeros((nres, nres))\n phi6d[idx0,idx1] = get_angles(Ca[idx0], Cb[idx0], Cb[idx1])\n\n return dist6d, omega6d, theta6d, phi6d\n\ndef get_2D_str_feat(model, n_res):\n resNo_s = list()\n for i in range(1, model.size()+1):\n resNo = model.pdb_info().number(i) # resNo in PDB file\n resNo_s.append(resNo-1) # -1 to make it as python array index\n resNo_s = np.array(resNo_s)\n d_map, o_map = get_dist_ori_maps(model, resNo_s, n_res)\n seqsep = get_seqsep(n_res)\n return np.concatenate((d_map, o_map, seqsep[:,:,None]), axis=-1) \n\ndef make_input_features(a3m_fn, pdb_fn=None, hhr_fn=None, ffdb=None, mask_diag=8, seqID=999.0):\n if isinstance(a3m_fn, str):\n msa = read_msa(a3m_fn)\n else:\n msa = a3m_fn\n seq = blosum(msa[0])\n if len(msa) > MAXSEQ:\n msa = msa[:MAXSEQ]\n #\n if pdb_fn == None: return seq, msa\n model = pose_from_file(pdb_fn)\n feat_2d = get_2D_str_feat(model, len(msa[0]))\n for i in range(feat_2d.shape[-1]):\n for k in range(mask_diag):\n np.fill_diagonal(feat_2d[k:,:,i], 0.0)\n np.fill_diagonal(feat_2d[:,k:,i], 0.0)\n \n pth_1d = list()\n pth_2d = list()\n if hhr_fn != None:\n L0 = len(msa[0])\n dmin = 2.0\n dmax = 20.0\n nbins = 18\n dbins = np.linspace(dmin, dmax, nbins+1)\n hhr = parse_hhr(hhr_fn, ffdb.index, seqID)\n for i, hit in enumerate(hhr[:10]):\n # extract template from FFindexDB\n entry = get_entry_by_name(hit[0], ffdb.index)\n data = read_entry_lines(entry, ffdb.data)\n xyz_tmp, idx_tmp = parse_pdb_lines(data)\n idx_tmp = idx_tmp-1 # change residue indices to start from 0\n\n # 6d coordinates\n d, o, t, p = get_coords6d(xyz_tmp, 20.0)\n db = np.digitize(d,dbins)\n\n # residue indices in the query and the template\n sel = np.intersect1d(hit[1][:,1], idx_tmp, return_indices=True)[1]\n qmap = hit[1][sel,0]\n tmap = hit[1][sel,1]\n\n # format 1d features\n f1d_a = np.zeros((L0,2), dtype=np.float32)\n f1d_a[qmap] = get_phipsi(xyz_tmp, tmap)\n f1d_k = np.zeros((L0,2), dtype=np.float32)\n f1d_k[qmap] = hit[1][sel,2:]\n pth_1d.append(np.concatenate((f1d_a, f1d_k), axis=-1))\n\n # format 2d features\n f2d_k = np.zeros((L0,L0,6), dtype=np.float32)\n ij = np.ix_(qmap,qmap.T)\n f2d_k[:,:,0][ij] = db[tmap][:,tmap]\n f2d_k[:,:,1][ij] = o[tmap][:,tmap]\n f2d_k[:,:,2][ij] = t[tmap][:,tmap]\n f2d_k[:,:,3][ij] = p[tmap][:,tmap]\n f2d_k[:,:,4:][ij] = np.array(hit[2:])#s0d[i][None,None,:]\n pth_2d.append(f2d_k)\n\n pth_1d = np.array(pth_1d)\n pth_2d = np.array(pth_2d)\n #\n return seq, msa, feat_2d, pth_1d, pth_2d\n", "meta": {"hexsha": "dca4d18b127254d0f379a32fddfd433b953baef9", "size": 15221, "ext": "py", "lang": "Python", "max_stars_repo_path": "trRefine/SStor_pred/data_loader.py", "max_stars_repo_name": "NatureGeorge/trRosetta2", "max_stars_repo_head_hexsha": "dba6078ebda9f2429264ace3deaffe50d9899def", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 73, "max_stars_repo_stars_event_min_datetime": "2021-05-21T07:03:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:11:28.000Z", "max_issues_repo_path": "trRefine/SStor_pred/data_loader.py", "max_issues_repo_name": "partrita/trRosetta2", "max_issues_repo_head_hexsha": "7036f81cdcfac6adcfebdc1ee917f46d8345229a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2021-05-20T21:35:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-05T15:38:55.000Z", "max_forks_repo_path": "trRefine/SStor_pred/data_loader.py", "max_forks_repo_name": "partrita/trRosetta2", "max_forks_repo_head_hexsha": "7036f81cdcfac6adcfebdc1ee917f46d8345229a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2021-05-24T10:26:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T14:11:45.000Z", "avg_line_length": 35.6463700234, "max_line_length": 128, "alphanum_fraction": 0.5209250378, "include": true, "reason": "import numpy,import scipy", "num_tokens": 5883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.20689403903542758, "lm_q1q2_score": 0.1241753908702121}} {"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2018 Brno University of Technology FIT\n# Author: Jan Profant \n# All Rights Reserved\n\nimport h5py\nimport numpy as np\nfrom scipy.io.idl import AttrDict\nfrom scipy.sparse import coo_matrix\n\nfrom vbdiar.utils.utils import Utils\n\n\nclass PLDA(object):\n\n V = None\n U = None\n D = None\n mc = None\n mu = None\n _R = None\n _T = None\n _y = None\n _x = None\n Syy = None\n vdim = None\n srank = None\n crank = None\n noise_type = None\n\n def init(self, vdim, srank, crank, diag=\"isotropic\"):\n \"\"\"\n\n Args:\n vdim:\n srank:\n crank:\n diag:\n \"\"\"\n self.vdim = vdim\n self.srank = srank\n self.crank = crank\n self.noise_type = diag\n\n np.random.seed(7)\n self.V = np.array(np.random.randn(vdim, srank), np.float) * 1e0\n self.U = np.array(np.random.randn(vdim, crank), np.float) * 1e0\n if diag == \"zero\":\n self.D = np.zeros((vdim, 1), np.float)\n else:\n self.D = np.ones((vdim, 1), np.float)\n\n self.mu = np.zeros((vdim, 1), np.float)\n\n # expectations\n self._R = np.eye(self.srank + self.crank, self.srank + self.crank)\n self._T = np.zeros((self.srank + self.crank, self.vdim))\n self.Syy = np.zeros((self.srank, self.srank))\n # point estimates\n self._y = None\n self._x = None\n\n def __str__(self):\n return \"= PLDA model d=%d,s=%d,c=%d,type=%s\" % (self.vdim, self.srank, self.crank, self.noise_type)\n\n def __init__(self, model_file):\n \"\"\"\n\n Args:\n model_file:\n\n Returns:\n\n \"\"\"\n model = h5py.File(model_file, 'r')\n v, u, d, noise_type, mu = model['V'][:], model['U'][:], model['D'][:], model['noise_type'], model['mu'][:]\n vdim, srank = v.shape\n crank = u.shape[1]\n self.init(vdim, srank, crank, noise_type)\n self.V = v\n self.U = u\n self.D = d\n self.mu = mu\n self.cache_statistics()\n\n @staticmethod\n def symmetrize(a):\n a = a + a.T\n a *= 0.5\n return a\n\n @staticmethod\n def logdet_chol(chol_m):\n \"\"\"Return the log determinant of a matrix given the cholesky decomposition\"\"\"\n return 2 * np.sum(np.log(np.diagonal(chol_m)))\n\n @staticmethod\n def invhandle(m, func_only=True):\n \"\"\"Return a function handle on multiplying a matrix\n by the inverse of the marix provided in this function\n if func_only=False then return: [logdet,chol,handle]\n (Niko's style)\n This is used when scoring the PLDA system\n \"\"\"\n cm = np.linalg.cholesky(m)\n\n def h(a):\n return np.linalg.solve(cm.T, np.linalg.solve(cm, a.T))\n\n if func_only:\n return h\n else:\n logdet = PLDA.logdet_chol(cm)\n return [logdet, cm, h]\n\n def cache_statistics(self):\n \"\"\"\n various values independant of the data in the cache object\n \"\"\"\n # values independant of the data\n mc = AttrDict()\n mc.UD = self.U*self.D\n mc.VD = self.V*self.D\n mc.J = np.dot(self.U.T, mc.VD)\n\n mc.K = np.sqrt(self.D) * self.U\n mc.K = PLDA.symmetrize(np.dot(mc.K.T, mc.K)+np.eye(self.crank))\n\n mc.iK = np.linalg.inv(mc.K)\n mc.P0 = mc.VD.T-np.dot(np.dot(mc.J.T, mc.iK), mc.UD.T)\n self.mc = mc\n return mc\n\n def score_with_constant_n(self, nt, ft, nt2, ft2):\n \"\"\" Compute verification score\n This changes for every pair nT nt and can be done only once for 1 session training\n fT = P*y_head = (V'D-J'iK*U'D)*f, where f is the first order stats\n \"\"\"\n # Covariance and first order stats preparation\n Py = PLDA.symmetrize(np.dot(self.mc.P0, self.V)) # (DV-iKJDU)V=VDV-JiKJ\n\n # P in eq. 31, EM for PLDA by Niko\n Py_Train = nt * Py + np.eye(self.srank)\n Py_Test = nt2 * Py + np.eye(self.srank)\n Py_SameSpk = (nt2 + nt) * Py + np.eye(self.srank)\n\n [logdetQ1, cholQ1, hQ1] = PLDA.invhandle(Py_Train, func_only=False)\n [logdetQ2, cholQ2, hQ2] = PLDA.invhandle(Py_Test, func_only=False)\n [logdetQ12, cholQ12, hQ12] = PLDA.invhandle(Py_SameSpk, func_only=False)\n # fT*hQ1(fT.T) is terms y_head*P*y_head in eq 30, EM for PLDA by Niko\n Q1 = 0.5 * (logdetQ1 + sum(ft * hQ12(ft.T)) - sum(ft * hQ1(ft.T)))\n Q2 = 0.5 * (logdetQ2 + sum(ft2 * hQ12(ft2.T)) - sum(ft2 * hQ2(ft2.T)))\n # Q2=Q2[np.newaxis,:] (can be dangerous)\n Q1 = Q1[:, np.newaxis]\n scores = np.dot(ft.T, hQ12(ft2.T))\n Q2 -= 0.5 * logdetQ12\n scores += Q1\n scores += Q2\n return scores\n\n def prepare_stats(self, data):\n \"\"\" Convert data (e.g. i-vectors) to statistics useful for scoring\n Input:\n data: ivect-dim x nb_ex matrix\n seg2model: defines of multisession enrollment (or test). It is\n 2 column array of integer indices mapping rows of data\n (1st column) to rows of output statistics (2nd column).\n By default (seg2model=None) each vector in data has its\n own output vector of statistics (i.e. single session\n enrollment or test). seg2model can be also represented\n by coo_matrix or by 1D array of labels if each input\n vector belongs to exactly one enrollment.\n Output: a AttrDict object with\n N: vector of counts for each speaker\n F: array of sum of ivector for each speaker transformed by P0\n to srank dimensionality\n \"\"\"\n seg2model = np.arange(len(data))\n if seg2model.ndim == 1:\n seg2model = np.c_[np.arange(len(data)), seg2model]\n seg2model = coo_matrix((np.ones(len(seg2model)), (seg2model[:, 0], seg2model[:, 1])))\n\n stats = AttrDict()\n stats.N = np.array(seg2model.T.sum(1))\n stats.F = np.dot(self.mc.P0, seg2model.T.dot(data - self.mu).T).T\n return stats\n\n def score(self, test, enroll):\n \"\"\"\n Score ivectors based on the PLDA model\n Input:\n PLDA object. PLDA.V and PLDA.U gives the subspaces\n stats objects: enroll and test\n Output:\n 2D array of scores of all possibilities\n \"\"\"\n test = test - self.mu\n enroll = enroll - self.mu\n test = Utils.l2_norm(test)\n enroll = Utils.l2_norm(enroll)\n Tstats = self.prepare_stats(test)\n tstats = self.prepare_stats(enroll)\n # Create scores\n scores = np.zeros((len(Tstats.N), len(tstats.N)), 'f')\n (a, b) = scores.shape\n\n # Score for each uniq combination of N enroll and M test sessions (only enroll for now)\n for n_enroll_sessions in np.unique(Tstats.N):\n idxs_T = np.where(Tstats.N == n_enroll_sessions)[0]\n for n_test_sessions in np.unique(tstats.N):\n idxs_t = np.where(tstats.N == n_test_sessions)[0]\n scores[np.ix_(idxs_T, idxs_t)] = self.score_with_constant_n(n_enroll_sessions, Tstats.F[idxs_T, :].T,\n n_test_sessions, tstats.F[idxs_t, :].T)\n return scores.T\n\n\n", "meta": {"hexsha": "803c7a4374c90b92a872ee587d4126af475bf886", "size": 7551, "ext": "py", "lang": "Python", "max_stars_repo_path": "VBDiarization_not_working/vbdiar/scoring/plda.py", "max_stars_repo_name": "yt2639/CMI_VoiceAnalysis", "max_stars_repo_head_hexsha": "74d30bbda66296acdb53f7c0028b7daa034e86bf", "max_stars_repo_licenses": ["CNRI-Python"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "VBDiarization_not_working/vbdiar/scoring/plda.py", "max_issues_repo_name": "yt2639/CMI_VoiceAnalysis", "max_issues_repo_head_hexsha": "74d30bbda66296acdb53f7c0028b7daa034e86bf", "max_issues_repo_licenses": ["CNRI-Python"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VBDiarization_not_working/vbdiar/scoring/plda.py", "max_forks_repo_name": "yt2639/CMI_VoiceAnalysis", "max_forks_repo_head_hexsha": "74d30bbda66296acdb53f7c0028b7daa034e86bf", "max_forks_repo_licenses": ["CNRI-Python"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-08T15:10:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-08T15:10:40.000Z", "avg_line_length": 34.4794520548, "max_line_length": 117, "alphanum_fraction": 0.5493312144, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.23370635157681105, "lm_q1q2_score": 0.12414700804351243}} {"text": "# ============================================================================\n# 付録 G 電気ヒートポンプ・ガス瞬間式併用型給湯温水暖房機\n# (給湯熱源:電気ヒートポンプ・ガス瞬間式併用、暖房熱源:ガス瞬間式)\n# ============================================================================\n\nimport numpy as np\nimport pandas as pd\n\nfrom pyhees.section7_1_c import \\\n get_e_k_d, \\\n get_e_s_d, \\\n get_e_w_d, \\\n get_e_b1_d, \\\n get_e_b2_d, \\\n get_e_ba1_d, \\\n get_e_ba2_d, \\\n get_f_hs\n\n\n# ============================================================================\n# G.3 試験された値を用いる方法\n# ============================================================================\n\n\n# ============================================================================\n# G.3.3 ハイブリッド給湯機の仕様\n# ============================================================================\n\n# ハイブリッド給湯機の仕様一覧を読み込む\ndef load_specification(filename):\n \"\"\"\n\n Args:\n filename: ファイル名\n\n Returns:\n\n \"\"\"\n global csv\n csv = pd.read_csv(filename, encoding='Shift_JIS')\n\n\n# ハイブリッド給湯機の仕様を取得する\ndef get_specification(package_id):\n \"\"\"\n\n Args:\n package_id: パッケージID\n\n Returns:\n ハイブリッド給湯機の仕様\n\n \"\"\"\n list = csv[csv['NO'] == int(package_id)]\n data = list.values[0, 12:25]\n return {\n 'a_HP': data[0],\n 'b_HP': data[1],\n 'a_TU': data[2],\n 'b_TU': data[3],\n 'e_HP_std_m7': data[4],\n 'e_HP_std_2': data[5],\n 'e_HP_std_7': data[6],\n 'e_HP_std_25': data[7],\n 'Q_HP_max': data[8],\n 'etr_loss_TU': data[9],\n 'Theta_ex_min_HP': data[10],\n 'e_BB_jis': data[11],\n # 'R_day': data[12]\n #TODO: 読込方法は要検討\n 'R_day': 0.5\n }\n\n\n# 直接指定されたハイブリッド給湯機のパラメーターを取得する\ndef get_input_specification(hybrid_param):\n \"\"\"\n\n Args:\n hybrid_param: ハイブリッド給湯機のパラメーター\n\n Returns:\n ハイブリッド給湯機のパラメーター\n\n \"\"\"\n return {\n 'a_HP': hybrid_param['a_HP'],\n 'a_TU': hybrid_param['a_TU'],\n 'b_HP': hybrid_param['b_HP'],\n 'b_TU': hybrid_param['b_TU'],\n 'e_HP_std_m7': hybrid_param['e_HP_std_m7'],\n 'e_HP_std_2': hybrid_param['e_HP_std_2'],\n 'e_HP_std_7': hybrid_param['e_HP_std_7'],\n 'e_HP_std_25': hybrid_param['e_HP_std_25'],\n 'Q_HP_max': hybrid_param['Q_HP_max'],\n 'etr_loss_TU': hybrid_param['etr_loss_TU'],\n 'Theta_ex_min_HP': hybrid_param['Theta_ex_min_HP'],\n 'e_BB_jis': hybrid_param['e_BB_jis'],\n 'R_day': hybrid_param['R_day']\n }\n\n# ============================================================================\n# G.3.4 消費電力量\n# ============================================================================\n\n# 1日当たりの給湯機の消費電量量 (8)\ndef calc_E_E_hs_d_t(bath_function, package_id, hybrid_param, theta_ex_d_Ave_d, L_dashdash_k_d_t, L_dashdash_s_d_t, L_dashdash_w_d_t,\n L_dashdash_b1_d_t, L_dashdash_b2_d_t, L_dashdash_ba1_d_t, L_dashdash_ba2_d_t, W_dash_ba1_d_t):\n \"\"\"\n\n Args:\n bath_function: param package_id:\n hybrid_param: param theta_ex_d_Ave_d:\n L_dashdash_k_d_t: param L_dashdash_s_d_t:\n L_dashdash_w_d_t: param L_dashdash_b1_d_t:\n L_dashdash_b2_d_t: param L_dashdash_ba1_d_t:\n L_dashdash_ba2_d_t: param W_dash_ba1_d_t:\n package_id: \n theta_ex_d_Ave_d: \n L_dashdash_s_d_t: \n L_dashdash_b1_d_t: \n L_dashdash_ba1_d_t: \n W_dash_ba1_d_t: \n\n Returns:\n\n \"\"\"\n # ハイブリッド給湯機の仕様\n if package_id != None:\n # 試験された値を用いる場合\n spec = get_specification(package_id)\n else:\n # パラメーターが直接指定された場合\n spec = get_input_specification(hybrid_param)\n\n # 1時間当たりの太陽熱補正給湯熱負荷 (MJ/h)\n L_dashdash_d_t = get_L_dashdash_d_t(L_dashdash_k_d_t, L_dashdash_s_d_t, L_dashdash_w_d_t, L_dashdash_b1_d_t,\n L_dashdash_b2_d_t, L_dashdash_ba1_d_t)\n\n # 1日当たりの太陽熱補正給湯熱負荷 (MJ/d)\n L_dashdash_d = get_L_dashdash_d(L_dashdash_d_t)\n\n # 1日当たりの電気ヒートポンプが分担する給湯熱負荷 (MJ/d)\n L_HP_d = get_L_HP_d(spec['Theta_ex_min_HP'], spec['a_HP'], spec['b_HP'], spec['etr_loss_TU'], spec['Q_HP_max'],\n L_dashdash_d, theta_ex_d_Ave_d)\n\n # 1日当たりの電気ヒートポンプの加熱量 (MJ/d)\n Q_HP_d = get_Q_HP_d(L_HP_d, spec['etr_loss_TU'])\n\n # 電気ヒートポンプの日平均熱効率 (-)\n e_HP_d = get_e_HP_d(spec['e_HP_std_m7'], spec['e_HP_std_2'], spec['e_HP_std_7'], spec['e_HP_std_25'], theta_ex_d_Ave_d)\n\n # 1時間当たりの電気ヒートポンプの消費電力量 (kWh/h)\n E_E_hs_HP_d_t = get_E_E_hs_HP_d_t(Q_HP_d, e_HP_d, spec['R_day'], L_dashdash_d, L_dashdash_d_t)\n\n # 1時間当たりのタンクユニットの消費電力量 (kWh/h)\n E_E_hs_TU_d_t = get_E_E_hs_TU_d_t(spec['a_TU'], spec['b_TU'], L_dashdash_d, L_dashdash_d_t)\n\n # 1時間当たりの保温時における消費電力量 (kWh/h)\n L_dashdash_ba2_d = get_L_dashdash_ba2_d(L_dashdash_ba2_d_t)\n L_BB_ba2_d = get_L_BB_ba2_d(L_dashdash_ba2_d)\n L_BB_ba2_d_t = get_L_BB_ba2_d_t(L_dashdash_ba2_d_t)\n E_E_hs_BB_d_t = get_E_E_hs_BB_d_t(W_dash_ba1_d_t, L_BB_ba2_d, L_BB_ba2_d_t, bath_function)\n\n print('E_E_hs_HP = {}'.format(np.sum(E_E_hs_HP_d_t)))\n print('E_E_hs_TU = {}'.format(np.sum(E_E_hs_TU_d_t)))\n print('E_E_hs_BB = {}'.format(np.sum(E_E_hs_BB_d_t)))\n\n return E_E_hs_HP_d_t + E_E_hs_TU_d_t + E_E_hs_BB_d_t\n\n\n# 1時間当たりの電気ヒートポンプ消費電力量 (kWh/h) (9-1) (9-2)\ndef get_E_E_hs_HP_d_t(Q_HP_d, e_HP_d, R_day, L_dashdash_d, L_dashdash_d_t):\n \"\"\"\n\n Args:\n Q_HP_d: 1日当たりの電気ヒートポンプの過熱量 (MJ/d)\n e_HP_d: 電気ヒートポンプの日平均熱効率 (-)\n R_day: ヒートポンプ昼間沸上率(-)\n L_dashdash_d: 1日当たりの太陽熱補正給湯熱負荷 (MJ/d)\n L_dashdash_d_t: 1時間当たりの太陽熱補正給湯熱負荷 (MJ/h)\n\n Returns:\n 1時間当たりの電気ヒートポンプ消費電力量 (kWh/h)\n\n \"\"\"\n E_E_hs_HP_d_t = np.zeros(24 * 365)\n\n # 24時間化\n L_dashdash_d = np.repeat(L_dashdash_d, 24)\n e_HP_d = np.repeat(e_HP_d, 24)\n Q_HP_d = np.repeat(Q_HP_d, 24)\n\n # ヒートポンプ昼間沸上運転開始時刻\n t_bw_start = get_t_bw_start()\n\n # ヒートポンプ昼間沸上運転終了時刻\n t_bw_end = get_t_bw_end()\n\n # t_bw_start <= t < t_bw_end の場合 (9-1)\n t1 = np.tile(np.logical_and(t_bw_start <= np.arange(24), np.arange(24) < t_bw_end), 365)\n\n E_E_hs_HP_d_t[t1] = Q_HP_d[t1] / (3.6 * e_HP_d[t1]) * R_day * (1 / (t_bw_end - t_bw_start))\n\n # 0 <= t < t_bw_start または t_bw_end <= t < 24 の場合 (9-2)\n t2 = np.tile(np.logical_or(np.logical_and(0 <= np.arange(24), np.arange(24) < t_bw_start),\n np.logical_and(t_bw_end <= np.arange(24), np.arange(24) < 24)), 365)\n\n t3 = np.tile(np.logical_and(t_bw_start <= np.arange(24), np.arange(24) < t_bw_end - 1), 365)\n\n temp = L_dashdash_d_t.copy()\n temp[t2] = 0.0\n L_dashdash_d_t_start_end = np.repeat(np.sum(temp.reshape((365, 24)), axis=1), 24)\n\n f1 = L_dashdash_d != L_dashdash_d_t_start_end\n\n f2 = np.logical_and(t2, f1)\n\n E_E_hs_HP_d_t[f2] = Q_HP_d[f2] / (3.6 * e_HP_d[f2]) * (1 - R_day) * \\\n (L_dashdash_d_t[f2] / (L_dashdash_d[f2] - L_dashdash_d_t_start_end[f2]))\n\n return E_E_hs_HP_d_t\n\n\ndef get_t_bw_start():\n \"\"\"ヒートポンプ昼間沸上運転開始時刻\n\n Args:\n\n Returns:\n int: ヒートポンプ昼間沸上運転開始時刻\n\n \"\"\"\n return 9\n\n\ndef get_t_bw_end():\n \"\"\"ヒートポンプ昼間沸上運転終了時刻\n\n Args:\n\n Returns:\n int: ヒートポンプ昼間沸上運転終了時刻\n\n \"\"\"\n return 16\n\n\n# 1時間当たりのタンクユニットの消費電力量 (10)\ndef get_E_E_hs_TU_d_t(a_TU, b_TU, L_dashdash_d, L_dashdash_d_t):\n \"\"\"\n\n Args:\n a_TU: param b_TU:\n L_dashdash_d: param L_dashdash_d_t:\n b_TU: \n L_dashdash_d_t: \n\n Returns:\n\n \"\"\"\n E_E_hs_TU_d_t = np.zeros(24 * 365)\n\n # L_dashdash_d_t > 0\n f1 = L_dashdash_d_t > 0\n E_E_hs_TU_d_t[f1] = a_TU * L_dashdash_d_t[f1] + b_TU / 24\n\n # L_dashdash_d = 0\n f2 = L_dashdash_d_t == 0\n E_E_hs_TU_d_t[f2] = b_TU / 24\n\n return E_E_hs_TU_d_t\n\n\n# 1日当たりの保温時における消費電力量 (11)\ndef get_E_E_hs_BB_d_t(W_dash_ba1_d_t, L_BB_ba2_d, L_BB_ba2_d_t, bath_function):\n \"\"\"\n\n Args:\n W_dash_ba1_d_t: param L_BB_ba2_d:\n L_BB_ba2_d_t: param bath_function:\n L_BB_ba2_d: \n bath_function: \n\n Returns:\n\n \"\"\"\n if bath_function == '給湯単機能' or bath_function == 'ふろ給湯機(追焚なし)':\n # (11a)\n return (0.000393 * W_dash_ba1_d_t * 10 ** 3 / 3600)\n elif bath_function == 'ふろ給湯機(追焚あり)':\n # (11b)\n L_BB_ba2_d = np.repeat(L_BB_ba2_d, 24)\n E_E_hs_BB_d_t = np.zeros(24 * 365)\n\n fb1 = L_BB_ba2_d > 0\n E_E_hs_BB_d_t[fb1] = ((0.01723 * L_BB_ba2_d[fb1] + 0.06099) * 10 ** 3 / 3600) \\\n * L_BB_ba2_d_t[fb1] / L_BB_ba2_d[fb1]\n\n fb2 = L_BB_ba2_d == 0\n E_E_hs_BB_d_t[fb2] = 0\n\n return E_E_hs_BB_d_t\n else:\n raise ValueError(bath_function)\n\n\n# ============================================================================\n# G.3.5 ガス消費量\n# ============================================================================\n\n# 1日当たりの給湯機のガス消費量 (12)\ndef get_E_G_hs_d_t(bath_function, package_id, theta_ex_d_Ave_d, L_dashdash_k_d_t, L_dashdash_s_d_t, L_dashdash_w_d_t,\n L_dashdash_b1_d_t, L_dashdash_b2_d_t, L_dashdash_ba1_d_t, L_dashdash_ba2_d_t, W_dash_ba1_d_t, hybrid_param):\n \"\"\"\n\n Args:\n bath_function: param package_id:\n theta_ex_d_Ave_d: param L_dashdash_k_d_t:\n L_dashdash_s_d_t: param L_dashdash_w_d_t:\n L_dashdash_b1_d_t: param L_dashdash_b2_d_t:\n L_dashdash_ba1_d_t: param L_dashdash_ba2_d_t:\n W_dash_ba1_d_t: param hybrid_param:\n package_id: \n L_dashdash_k_d_t: \n L_dashdash_w_d_t: \n L_dashdash_b2_d_t: \n L_dashdash_ba2_d_t: \n hybrid_param: \n\n Returns:\n\n \"\"\"\n # ハイブリッド給湯機の仕様\n if package_id != None:\n # 試験された値を用いる場合\n spec = get_specification(package_id)\n else:\n # パラメーターが直接指定された場合\n spec = get_input_specification(hybrid_param)\n\n # 当該給湯機に対する効率の補正係数\n f_hs = get_f_hs(spec['e_BB_jis'])\n\n L_dashdash_d_t = get_L_dashdash_d_t(\n L_dashdash_k_d_t=L_dashdash_k_d_t,\n L_dashdash_s_d_t=L_dashdash_s_d_t,\n L_dashdash_w_d_t=L_dashdash_w_d_t,\n L_dashdash_b1_d_t=L_dashdash_b1_d_t,\n L_dashdash_b2_d_t=L_dashdash_b2_d_t,\n L_dashdash_ba1_d_t=L_dashdash_ba1_d_t,\n )\n L_dashdash_k_d = get_L_dashdash_k_d(L_dashdash_k_d_t)\n L_dashdash_s_d = get_L_dashdash_s_d(L_dashdash_s_d_t)\n L_dashdash_w_d = get_L_dashdash_w_d(L_dashdash_w_d_t)\n L_dashdash_b1_d = get_L_dashdash_b1_d(L_dashdash_b1_d_t)\n L_dashdash_b2_d = get_L_dashdash_b2_d(L_dashdash_b2_d_t)\n L_dashdash_ba1_d = get_L_dashdash_ba1_d(L_dashdash_ba1_d_t)\n L_dashdash_ba2_d = get_L_dashdash_ba1_d(L_dashdash_ba2_d_t)\n L_dashdash_d = get_L_dashdash_d(L_dashdash_d_t)\n\n L_HP = get_L_HP_d(\n Theta_ex_min_HP=spec['Theta_ex_min_HP'],\n a_HP=spec['a_HP'],\n b_HP=spec['b_HP'],\n etr_loss_TU=spec['etr_loss_TU'],\n Q_HP_max=spec['Q_HP_max'],\n L_dashdash_d=L_dashdash_d,\n theta_ex_d_Ave_d=theta_ex_d_Ave_d\n )\n L_BB_k_d = get_L_BB_k_d(L_HP, L_dashdash_d, L_dashdash_k_d)\n L_BB_s_d = get_L_BB_s_d(L_HP, L_dashdash_d, L_dashdash_s_d)\n L_BB_w_d = get_L_BB_w_d(L_HP, L_dashdash_d, L_dashdash_w_d)\n L_BB_b1_d = get_L_BB_b1_d(L_HP, L_dashdash_d, L_dashdash_b1_d)\n L_BB_b2_d = get_L_BB_b2_d(L_HP, L_dashdash_d, L_dashdash_b2_d)\n L_BB_ba1_d = get_L_BB_ba1_d(L_HP, L_dashdash_d, L_dashdash_ba1_d)\n L_BB_ba2_d = get_L_BB_ba2_d(L_dashdash_ba2_d)\n\n L_BB_k_d_t = get_L_BB_k_d_t(L_BB_k_d, L_dashdash_k_d_t)\n L_BB_s_d_t = get_L_BB_s_d_t(L_BB_s_d, L_dashdash_s_d_t)\n L_BB_w_d_t = get_L_BB_w_d_t(L_BB_w_d, L_dashdash_w_d_t)\n L_BB_b1_d_t = get_L_BB_b1_d_t(L_BB_b1_d, L_dashdash_b1_d_t)\n L_BB_b2_d_t = get_L_BB_b2_d_t(L_BB_b2_d, L_dashdash_b2_d_t)\n L_BB_ba1_d_t = get_L_BB_ba1_d_t(L_BB_ba1_d, L_dashdash_ba1_d_t)\n L_BB_ba2_d_t = get_L_BB_ba2_d_t(L_dashdash_ba2_d_t)\n\n # 日平均給湯機効率\n e_BB_k_d = get_e_k_d(theta_ex_d_Ave_d, L_BB_k_d, L_BB_w_d, f_hs)\n e_BB_s_d = get_e_s_d(theta_ex_d_Ave_d, L_BB_s_d, f_hs)\n e_BB_w_d = get_e_w_d(theta_ex_d_Ave_d, L_BB_k_d, L_BB_w_d, f_hs)\n\n if bath_function == '給湯単機能':\n\n # 日平均給湯機効率\n e_BB_b1_d = get_e_b1_d(theta_ex_d_Ave_d, L_BB_b1_d, f_hs)\n e_BB_ba1_d = get_e_ba1_d(theta_ex_d_Ave_d, L_BB_ba1_d, f_hs)\n\n # (12a)\n E_G_hs_d_t = L_BB_k_d_t / np.repeat(e_BB_k_d, 24) \\\n + L_BB_s_d_t / np.repeat(e_BB_s_d, 24) \\\n + L_BB_w_d_t / np.repeat(e_BB_w_d, 24) \\\n + L_BB_b1_d_t / np.repeat(e_BB_b1_d, 24) \\\n + L_BB_ba1_d_t / np.repeat(e_BB_ba1_d, 24)\n elif bath_function == 'ふろ給湯機(追焚なし)':\n\n # 日平均給湯機効率\n e_BB_b2_d = get_e_b2_d(theta_ex_d_Ave_d, L_BB_b2_d, f_hs)\n e_BB_ba1_d = get_e_ba1_d(theta_ex_d_Ave_d, L_BB_ba1_d, f_hs)\n\n # (12b)\n E_G_hs_d_t = L_BB_k_d_t / np.repeat(e_BB_k_d, 24) \\\n + L_BB_s_d_t / np.repeat(e_BB_s_d, 24) \\\n + L_BB_w_d_t / np.repeat(e_BB_w_d, 24) \\\n + L_BB_b2_d_t / np.repeat(e_BB_b2_d, 24) \\\n + L_BB_ba1_d_t / np.repeat(e_BB_ba1_d, 24)\n elif bath_function == 'ふろ給湯機(追焚あり)':\n\n # 日平均給湯機効率\n e_BB_b2_d = get_e_b2_d(theta_ex_d_Ave_d, L_BB_b2_d, f_hs)\n e_BB_ba2_d = get_e_ba2_d(theta_ex_d_Ave_d, L_BB_ba2_d, f_hs)\n\n # (12c)\n E_G_hs_d_t = L_BB_k_d_t / np.repeat(e_BB_k_d, 24) \\\n + L_BB_s_d_t / np.repeat(e_BB_s_d, 24) \\\n + L_BB_w_d_t / np.repeat(e_BB_w_d, 24) \\\n + L_BB_b2_d_t / np.repeat(e_BB_b2_d, 24) \\\n + L_BB_ba2_d_t / np.repeat(e_BB_ba2_d, 24)\n else:\n raise ValueError(bath_function)\n\n return E_G_hs_d_t\n\n\n# ============================================================================\n# G.3.6 電気ヒートポンプの加熱量\n# ============================================================================\n\n# 1日当たりの電気ヒートポンプの加熱量 (13)\ndef get_Q_HP_d(L_HP_d, etr_loss_TU):\n \"\"\"\n\n Args:\n L_HP_d: param etr_loss_TU:\n etr_loss_TU: \n\n Returns:\n\n \"\"\"\n return L_HP_d / (1 - etr_loss_TU)\n\n\n# ============================================================================\n# G.3.7 電気ヒートポンプの日平均熱効率\n# ============================================================================\n\n# 電気ヒートポンプの日平均熱効率 (14)\ndef get_e_HP_d(e_HP_std_m7, e_HP_std_2, e_HP_std_7, e_HP_std_25, theta_ex_d_Ave_d):\n \"\"\"\n\n Args:\n e_HP_std_m7: param e_HP_std_2:\n e_HP_std_7: param e_HP_std_25:\n theta_ex_d_Ave_d: \n e_HP_std_2: \n e_HP_std_25: \n\n Returns:\n\n \"\"\"\n e_HP_d = np.zeros(365)\n\n # 1) theta_ex_d_Ave_d < 2\n f1 = (theta_ex_d_Ave_d < 2)\n e_HP_d[f1] = e_HP_std_2 - (2 - theta_ex_d_Ave_d[f1]) / 9 * (e_HP_std_2 - e_HP_std_m7)\n\n # 2) 2 <= theta_ex_d_Ave_d < 7\n f2 = np.logical_and(2 <= theta_ex_d_Ave_d, theta_ex_d_Ave_d < 7)\n e_HP_d[f2] = e_HP_std_7 - (7 - theta_ex_d_Ave_d[f2]) / 5 * (e_HP_std_7 - e_HP_std_2)\n\n # 3) 7 <= theta_ex_d_Ave_d < 25\n f3 = np.logical_and(7 <= theta_ex_d_Ave_d, theta_ex_d_Ave_d < 25)\n e_HP_d[f3] = e_HP_std_25 - (25 - theta_ex_d_Ave_d[f3]) / 18 * (e_HP_std_25 - e_HP_std_7)\n\n # 4) 25 <= theta_ex_d_Ave_d\n f4 = 25 <= theta_ex_d_Ave_d\n e_HP_d[f4] = e_HP_std_25\n\n return e_HP_d\n\n\n# ============================================================================\n# G.3.8 給湯熱負荷\n# ============================================================================\n\n# バックアップボイラーが分担する給湯熱負荷\n\n# (15a)\ndef get_L_BB_k_d_t(L_BB_k_d, L_dashdash_k_d_t):\n \"\"\"\n\n Args:\n L_BB_k_d: param L_dashdash_k_d_t:\n L_dashdash_k_d_t: \n\n Returns:\n\n \"\"\"\n L_BB_k_d_t = np.zeros(24 * 365)\n\n L_BB_k_d = np.repeat(L_BB_k_d, 24)\n L_dashdash_k_d = np.repeat(get_L_dashdash_k_d(L_dashdash_k_d_t), 24)\n\n f = L_dashdash_k_d > 0\n L_BB_k_d_t[f] = L_BB_k_d[f] * L_dashdash_k_d_t[f] / L_dashdash_k_d[f]\n\n return L_BB_k_d_t\n\n\n# (15b)\ndef get_L_BB_s_d_t(L_BB_s_d, L_dashdash_s_d_t):\n \"\"\"\n\n Args:\n L_BB_s_d: param L_dashdash_s_d_t:\n L_dashdash_s_d_t: \n\n Returns:\n\n \"\"\"\n L_BB_s_d_t = np.zeros(24 * 365)\n\n L_BB_s_d = np.repeat(L_BB_s_d, 24)\n L_dashdash_s_d = np.repeat(get_L_dashdash_s_d(L_dashdash_s_d_t), 24)\n\n f = L_dashdash_s_d > 0\n L_BB_s_d_t[f] = L_BB_s_d[f] * L_dashdash_s_d_t[f] / L_dashdash_s_d[f]\n\n return L_BB_s_d_t\n\n\n# (15c)\ndef get_L_BB_w_d_t(L_BB_w_d, L_dashdash_w_d_t):\n \"\"\"\n\n Args:\n L_BB_w_d: param L_dashdash_w_d_t:\n L_dashdash_w_d_t: \n\n Returns:\n\n \"\"\"\n L_BB_w_d_t = np.zeros(24 * 365)\n\n L_BB_w_d = np.repeat(L_BB_w_d, 24)\n L_dashdash_w_d = np.repeat(get_L_dashdash_w_d(L_dashdash_w_d_t), 24)\n\n f = L_dashdash_w_d > 0\n L_BB_w_d_t[f] = L_BB_w_d[f] * L_dashdash_w_d_t[f] / L_dashdash_w_d[f]\n\n return L_BB_w_d_t\n\n\n# (15d)\ndef get_L_BB_b1_d_t(L_BB_b1_d, L_dashdash_b1_d_t):\n \"\"\"\n\n Args:\n L_BB_b1_d: param L_dashdash_b1_d_t:\n L_dashdash_b1_d_t: \n\n Returns:\n\n \"\"\"\n L_BB_b1_d_t = np.zeros(24 * 365)\n\n L_BB_b1_d = np.repeat(L_BB_b1_d, 24)\n L_dashdash_b1_d = np.repeat(get_L_dashdash_b1_d(L_dashdash_b1_d_t), 24)\n\n f = L_dashdash_b1_d > 0\n L_BB_b1_d_t[f] = L_BB_b1_d[f] * L_dashdash_b1_d_t[f] / L_dashdash_b1_d[f]\n\n return L_BB_b1_d_t\n\n\n# (15e)\ndef get_L_BB_b2_d_t(L_BB_b2_d, L_dashdash_b2_d_t):\n \"\"\"\n\n Args:\n L_BB_b2_d: param L_dashdash_b2_d_t:\n L_dashdash_b2_d_t: \n\n Returns:\n\n \"\"\"\n L_BB_b2_d_t = np.zeros(24 * 365)\n\n L_BB_b2_d = np.repeat(L_BB_b2_d, 24)\n L_dashdash_b2_d = np.repeat(get_L_dashdash_b2_d(L_dashdash_b2_d_t), 24)\n\n f = L_dashdash_b2_d > 0\n L_BB_b2_d_t[f] = L_BB_b2_d[f] * L_dashdash_b2_d_t[f] / L_dashdash_b2_d[f]\n\n return L_BB_b2_d_t\n\n\n# (15f)\ndef get_L_BB_ba1_d_t(L_BB_ba1_d, L_dashdash_ba1_d_t):\n \"\"\"\n\n Args:\n L_BB_ba1_d: param L_dashdash_ba1_d_t:\n L_dashdash_ba1_d_t: \n\n Returns:\n\n \"\"\"\n L_BB_ba1_d_t = np.zeros(24 * 365)\n\n L_BB_ba1_d = np.repeat(L_BB_ba1_d, 24)\n L_dashdash_ba1_d = np.repeat(get_L_dashdash_ba1_d(L_dashdash_ba1_d_t), 24)\n\n f = L_dashdash_ba1_d > 0\n L_BB_ba1_d_t[f] = L_BB_ba1_d[f] * L_dashdash_ba1_d_t[f] / L_dashdash_ba1_d[f]\n\n return L_BB_ba1_d_t\n\n\n# (15g)\ndef get_L_BB_ba2_d_t(L_dashdash_ba2_d_t):\n \"\"\"\n\n Args:\n L_dashdash_ba2_d_t: \n\n Returns:\n\n \"\"\"\n return L_dashdash_ba2_d_t\n\n\n# (16a)\ndef get_L_BB_k_d(L_HP_d, L_dashdash_d, L_dashdash_k_d):\n \"\"\"\n\n Args:\n L_HP_d: param L_dashdash_d:\n L_dashdash_k_d: \n L_dashdash_d: \n\n Returns:\n\n \"\"\"\n return L_dashdash_k_d - L_HP_d * (L_dashdash_k_d / L_dashdash_d)\n\n\n# (16b)\ndef get_L_BB_s_d(L_HP_d, L_dashdash_d, L_dashdash_s_d):\n \"\"\"\n\n Args:\n L_HP_d: param L_dashdash_d:\n L_dashdash_s_d: \n L_dashdash_d: \n\n Returns:\n\n \"\"\"\n return L_dashdash_s_d - L_HP_d * (L_dashdash_s_d / L_dashdash_d)\n\n\n# (16c)\ndef get_L_BB_w_d(L_HP_d, L_dashdash_d, L_dashdash_w_d):\n \"\"\"\n\n Args:\n L_HP_d: param L_dashdash_d:\n L_dashdash_w_d: \n L_dashdash_d: \n\n Returns:\n\n \"\"\"\n return L_dashdash_w_d - L_HP_d * (L_dashdash_w_d / L_dashdash_d)\n\n\n# (16d)\ndef get_L_BB_b1_d(L_HP_d, L_dashdash_d, L_dashdash_b1_d):\n \"\"\"\n\n Args:\n L_HP_d: param L_dashdash_d:\n L_dashdash_b1_d: \n L_dashdash_d: \n\n Returns:\n\n \"\"\"\n return L_dashdash_b1_d - L_HP_d * (L_dashdash_b1_d / L_dashdash_d)\n\n\n# (16e)\ndef get_L_BB_b2_d(L_HP_d, L_dashdash_d, L_dashdash_b2_d):\n \"\"\"\n\n Args:\n L_HP_d: param L_dashdash_d:\n L_dashdash_b2_d: \n L_dashdash_d: \n\n Returns:\n\n \"\"\"\n return L_dashdash_b2_d - L_HP_d * (L_dashdash_b2_d / L_dashdash_d)\n\n\n# (16f)\ndef get_L_BB_ba1_d(L_HP_d, L_dashdash_d, L_dashdash_ba1_d):\n \"\"\"\n\n Args:\n L_HP_d: param L_dashdash_d:\n L_dashdash_ba1_d: \n L_dashdash_d: \n\n Returns:\n\n \"\"\"\n return L_dashdash_ba1_d - L_HP_d * (L_dashdash_ba1_d / L_dashdash_d)\n\n\n# (16g)\ndef get_L_BB_ba2_d(L_dashdash_ba2_d):\n \"\"\"\n\n Args:\n L_dashdash_ba2_d: \n\n Returns:\n\n \"\"\"\n return L_dashdash_ba2_d\n\n\n# ============================================================================\n# G.4 1日当たり/1時間当たりの太陽熱補正給湯熱負荷\n# ============================================================================\n\n\n# 1日当たりの電気ヒートポンプが分担する給湯熱負荷 (17)\ndef get_L_HP_d(Theta_ex_min_HP, a_HP, b_HP, etr_loss_TU, Q_HP_max, L_dashdash_d, theta_ex_d_Ave_d):\n \"\"\"\n\n Args:\n Theta_ex_min_HP: param a_HP:\n b_HP: param etr_loss_TU:\n Q_HP_max: param L_dashdash_d:\n theta_ex_d_Ave_d: \n a_HP: \n etr_loss_TU: \n L_dashdash_d: \n\n Returns:\n\n \"\"\"\n L_HP_d = np.zeros(365)\n\n # 1. theta_ex_d_Ave_d >= Theta_ex_min_HP (17a)\n f1 = (theta_ex_d_Ave_d >= Theta_ex_min_HP)\n L_HP_d[f1] = np.clip(\n (a_HP * L_dashdash_d[f1] + b_HP) * (1 - etr_loss_TU),\n None,\n np.clip(L_dashdash_d[f1], None, Q_HP_max * (1 - etr_loss_TU))\n )\n\n # 2. theta_ex_d_Ave_d < Theta_ex_min_HP (17b)\n f2 = (theta_ex_d_Ave_d < Theta_ex_min_HP)\n L_HP_d[f2] = 0\n\n return L_HP_d\n\n\n# 1日当たりの太陽熱補正給湯熱負荷 (MJ/d) (18)\ndef get_L_dashdash_d(L_dashdash_d_t):\n \"\"\"\n\n Args:\n L_dashdash_d_t: 1時間当たりの太陽熱補正給湯熱負荷 (MJ/h)\n\n Returns:\n 1日当たりの太陽熱補正給湯熱負荷 (MJ/d)\n\n \"\"\"\n return np.sum(L_dashdash_d_t.reshape(365, 24), axis=1)\n\n\n# 1時間当たりの太陽熱補正給湯熱負荷 (MJ/h) (19)\ndef get_L_dashdash_d_t(L_dashdash_k_d_t, L_dashdash_s_d_t, L_dashdash_w_d_t, L_dashdash_b1_d_t, L_dashdash_b2_d_t,\n L_dashdash_ba1_d_t):\n \"\"\"\n\n Args:\n L_dashdash_k_d_t: 1時間当たりの台所水栓における太陽熱補正給湯熱負荷 (MJ/h)\n L_dashdash_s_d_t: 1時間当たりの浴室シャワー水栓における太陽熱補正給湯負荷 (MJ/h)\n L_dashdash_w_d_t: 1時間当たりの洗面水栓における太陽熱補正給湯負荷 (MJ/h)\n L_dashdash_b1_d_t: 1時間当たりの浴槽水栓湯はり時における太陽熱補正給湯負荷 (MJ/h)\n L_dashdash_b2_d_t: 1時間当たりの浴槽自動湯はり時における太陽熱補正給湯負荷 (MJ/h)\n L_dashdash_ba1_d_t: 1時間当たりの浴槽水栓さし湯時における太陽熱補正給湯負荷 (MJ/h)\n\n Returns:\n 1時間当たりの太陽熱補正給湯熱負荷 (MJ/h)\n\n \"\"\"\n return L_dashdash_k_d_t \\\n + L_dashdash_s_d_t \\\n + L_dashdash_w_d_t \\\n + L_dashdash_b1_d_t \\\n + L_dashdash_b2_d_t \\\n + L_dashdash_ba1_d_t\n\n\n# 1日当たりの台所水栓における太陽熱補正給湯熱負荷 (MJ/d)\ndef get_L_dashdash_k_d(L_dashdash_k_d_t):\n \"\"\"\n\n Args:\n L_dashdash_k_d_t: 1時間当たりの台所水栓における太陽熱補正給湯熱負荷 (MJ/h)\n\n Returns:\n 1日当たりの台所水栓における太陽熱補正給湯熱負荷 (MJ/d)\n\n \"\"\"\n return np.sum(L_dashdash_k_d_t.reshape((365, 24)), axis=1)\n\n\n# 1日当たりの浴室シャワー水栓における太陽熱補正給湯負荷 (MJ/d)\ndef get_L_dashdash_s_d(L_dashdash_s_d_t):\n \"\"\"\n\n Args:\n L_dashdash_s_d_t: 1時間当たりの浴室シャワー水栓における太陽熱補正給湯負荷 (MJ/h)\n\n Returns:\n 1日当たりの浴室シャワー水栓における太陽熱補正給湯負荷 (MJ/d)\n\n \"\"\"\n return np.sum(L_dashdash_s_d_t.reshape((365, 24)), axis=1)\n\n\n# 1日当たりの洗面水栓における太陽熱補正給湯負荷 (MJ/d)\ndef get_L_dashdash_w_d(L_dashdash_w_d_t):\n \"\"\"\n\n Args:\n L_dashdash_w_d_t: 1時間当たりの洗面水栓における太陽熱補正給湯負荷 (MJ/h)\n\n Returns:\n 1日当たりの洗面水栓における太陽熱補正給湯負荷 (MJ/d)\n\n \"\"\"\n return np.sum(L_dashdash_w_d_t.reshape((365, 24)), axis=1)\n\n\n# 1日当たりの浴槽水栓湯はり時における太陽熱補正給湯負荷 (MJ/d)\ndef get_L_dashdash_b1_d(L_dashdash_b1_d_t):\n \"\"\"\n\n Args:\n L_dashdash_b1_d_t: 1時間当たりの浴槽水栓湯はり時における太陽熱補正給湯負荷 (MJ/h)\n\n Returns:\n 1日当たりの浴槽水栓湯はり時における太陽熱補正給湯負荷 (MJ/d)\n\n \"\"\"\n return np.sum(L_dashdash_b1_d_t.reshape((365, 24)), axis=1)\n\n\n# 1日当たりの浴槽自動湯はり時における太陽熱補正給湯負荷 (MJ/d)\ndef get_L_dashdash_b2_d(L_dashdash_b2_d_t):\n \"\"\"\n\n Args:\n L_dashdash_b2_d_t: 1時間当たりの浴槽自動湯はり時における太陽熱補正給湯負荷 (MJ/h)\n\n Returns:\n 1日当たりの浴槽自動湯はり時における太陽熱補正給湯負荷 (MJ/d)\n\n \"\"\"\n return np.sum(L_dashdash_b2_d_t.reshape((365, 24)), axis=1)\n\n\n# 1日当たりの浴槽水栓さし湯時における太陽熱補正給湯負荷 (MJ/d)\ndef get_L_dashdash_ba1_d(L_dashdash_ba1_d_t):\n \"\"\"\n\n Args:\n L_dashdash_ba1_d_t: 1時間当たりの浴槽水栓さし湯時における太陽熱補正給湯負荷 (MJ/h)\n\n Returns:\n 1日当たりの浴槽水栓さし湯時における太陽熱補正給湯負荷 (MJ/d)\n\n \"\"\"\n return np.sum(L_dashdash_ba1_d_t.reshape((365, 24)), axis=1)\n\n\n# 1日当たりの浴槽追焚時における太陽熱補正給湯負荷 (MJ/d)\ndef get_L_dashdash_ba2_d(L_dashdash_ba2_d_t):\n \"\"\"\n\n Args:\n L_dashdash_ba2_d_t: 1時間当たりの浴槽追焚時における太陽熱補正給湯負荷 (MJ/h)\n\n Returns:\n 1日当たりの浴槽追焚時における太陽熱補正給湯負荷 (MJ/d)\n\n \"\"\"\n return np.sum(L_dashdash_ba2_d_t.reshape((365, 24)), axis=1)\n", "meta": {"hexsha": "1e9c03c2c9eb79bb337fb83028896848f4f2b1e1", "size": 23772, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/pyhees/section7_1_g_3.py", "max_stars_repo_name": "jjj-design/pyhees", "max_stars_repo_head_hexsha": "d63e7cd84abfc2f509bc1cd1256598a10aac1825", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pyhees/section7_1_g_3.py", "max_issues_repo_name": "jjj-design/pyhees", "max_issues_repo_head_hexsha": "d63e7cd84abfc2f509bc1cd1256598a10aac1825", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-01-04T07:29:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T08:02:51.000Z", "max_forks_repo_path": "src/pyhees/section7_1_g_3.py", "max_forks_repo_name": "jjj-design/pyhees", "max_forks_repo_head_hexsha": "d63e7cd84abfc2f509bc1cd1256598a10aac1825", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-01-19T07:57:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T00:25:54.000Z", "avg_line_length": 25.8954248366, "max_line_length": 132, "alphanum_fraction": 0.6170705031, "include": true, "reason": "import numpy", "num_tokens": 10108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.2450850131323717, "lm_q1q2_score": 0.12349985042160282}} {"text": "\"\"\"The module contains everything to handle cross section interfaces.\"\"\"\n\nfrom abc import ABCMeta, abstractmethod\nfrom os.path import isfile, join\n\nimport numpy as np\n\nimport prince_cr.decays as decs\nfrom prince_cr.data import spec_data\nfrom prince_cr.util import (\n get_2Dinterp_object, get_interp_object, info, bin_widths, get_AZN)\nimport prince_cr.config as config\n\nclass CrossSectionBase(object, metaclass=ABCMeta):\n \"\"\"Base class for cross section interfaces to tabulated models.\n\n The class is abstract and it is not inteded to be instantiated.\n\n Child Classes either define the tables:\n self._egrid_tab\n self._nonel_tab\n self._incl_tab\n self._incl_diff\n\n Or directly reimplememnt the functions\n nonel(self, mother, daughter)\n incl(self, mother, daughter)\n incl_diff(self, mother, daughter)\n\n The flag self.supports_redistributions = True/False should be set\n To tell the class to include/ignore incl_diff\n \"\"\"\n def __init__(self):\n # Tuple, defining min and max energy cuts on the grid\n self._range = None\n # Energy grid, as defined in files\n self._egrid_tab = None\n # Dictionary of nonel. cross sections on egrid, indexed by (mother)\n self._nonel_tab = {}\n # Dictionary of incl. cross sections on egrid, indexed by (mother, daughter)\n self._incl_tab = {}\n # Dictionary of incl. diff. cross sections on egrid, indexed by (mother, daughter)\n self._incl_diff_tab = {}\n # List of available mothers for nonel cross sections\n self.nonel_idcs = []\n # List of available (mothers,daughter) reactions in incl. cross sections\n self.incl_idcs = []\n # List of available (mothers,daughter) reactions in incl. diff. cross sections\n self.incl_diff_idcs = []\n # Common grid in x (the redistribution variable)\n self.xbins = None\n\n # Flag, which tells if the model supports secondary redistributions\n if not hasattr(self, 'supports_redistributions'):\n self.supports_redistributions = None # JH: to differ from explicitly set False\n # List of all known particles (after optimization)\n self.known_species = []\n # List of all boost conserving inclusive channels (after optimization)\n self.known_bc_channels = []\n # List of all differential inclusive channels (after optimization)\n self.known_diff_channels = []\n # Dictionary of (mother, daughter) reactions for each mother\n self.reactions = {}\n\n # Class name of the model\n self.mname = self.__class__.__name__\n\n def set_range(self, e_min=None, e_max=None):\n \"\"\"Set energy range within which to return tabulated data.\n\n Args:\n e_min (float): minimal energy in GeV\n e_max (float): maximal energy in GeV\n \"\"\"\n if e_min is None:\n e_min = np.min(self._egrid_tab)\n if e_max is None:\n e_max = np.max(self._egrid_tab)\n\n info(5, \"Setting range to {0:3.2e} - {1:3.2e}\".format(e_min, e_max))\n self._range = np.where((self._egrid_tab >= e_min)\n & (self._egrid_tab <= e_max))[0]\n info(\n 2, \"Range set to {0:3.2e} - {1:3.2e}\".format(\n np.min(self._egrid_tab[self._range]),\n np.max(self._egrid_tab[self._range])))\n\n @property\n def egrid(self):\n \"\"\"Returns energy grid of the tabulated data in selected range.\n\n Returns:\n (numpy.array): Energy grid in GeV\n \"\"\"\n\n return self._egrid_tab[self._range]\n\n @property\n def xcenters(self):\n \"\"\"Returns centers of the grid in x.\n\n Returns:\n (numpy.array): x grid\n \"\"\"\n\n return 0.5 * (self.xbins[1:] + self.xbins[:-1])\n\n @property\n def xwidths(self):\n \"\"\"Returns bin widths of the grid in x.\n\n Returns:\n (numpy.array): x widths\n \"\"\"\n\n return self.xbins[1:] - self.xbins[:-1]\n\n @property\n def resp(self):\n \"\"\"Return ResponseFunction corresponding to this cross section\n Will only create the Response function once. \n \"\"\"\n if not hasattr(self, '_resp'):\n info(2, 'First Call, creating instance of ResponseFunction now')\n from .response import ResponseFunction\n self._resp = ResponseFunction(self)\n return self._resp\n\n def is_differential(self, mother, daughter):\n \"\"\"Returns true if the model supports redistributions and requested\n mother/daughter combination should return non-zero redistribution matrices.\n\n Args:\n mother (bool): Neucosma ID of mother particle\n daughter (bool): Neucosma ID of daughter particle\n\n Returns:\n (bool): ``True`` if the model has this particular redistribution function\n \"\"\"\n # info(10, mother, daughter, \" asking for redist\")\n # if not self.supports_redistributions:\n # info(10, mother, daughter, \" model doesn't support redist\")\n # return False\n if (daughter <= config.redist_threshold_ID\n or (mother, daughter) in self.incl_diff_idcs):\n info(60, 'Daughter requires redistribution.', mother, daughter)\n return True\n info(60, 'Daughter conserves boost.', mother, daughter)\n return False\n\n def _update_indices(self):\n \"\"\"Updates the list of indices according to entries in the\n _tab variables\"\"\"\n\n self.nonel_idcs = sorted(self._nonel_tab.keys())\n self.incl_idcs = sorted(self._incl_tab.keys())\n self.incl_diff_idcs = sorted(self._incl_diff_tab.keys())\n\n def generate_incl_channels(self, mo_indices):\n \"\"\"Generates indices for all allowed channels given mo_indices\n Note: By default this returns an empty list,\n meant to be overwritten in cases where \n the child class needs to dynamically generate indices\n \n Args:\n mo_indices (list of ints): list of indices for mother nuclei\n\n Returns:\n Returns:\n list of tuples: list of allowed channels given as (mo_idx, da_idx)\n \"\"\"\n incl_channels = []\n\n return incl_channels\n\n def _optimize_and_generate_index(self):\n \"\"\"Construct a list of mothers and (mother, daughter) indices.\n\n Args:\n just_reactions (bool): If True then fill just the reactions index.\n \"\"\"\n\n # Integrate out short lived processes and leave only stable particles\n # in the databases\n self._reduce_channels()\n\n # Go through all three cross section categories\n # index contents in the ..known..variable\n self.reactions = {}\n\n self._update_indices()\n\n for mo, da in self.incl_idcs:\n if da >= 100 and get_AZN(da)[0] > get_AZN(mo)[0]:\n raise Exception(\n 'Daughter {0} heavier than mother {1}. Physics??'.format(\n da, mo))\n\n if mo not in self.reactions:\n self.reactions[mo] = []\n self.known_species.append(mo)\n\n if (mo, da) not in self.reactions[mo]:\n # Make sure it's a unique list\n self.reactions[mo].append((mo, da))\n if self.is_differential(mo, da):\n # Move the distributions which are expected to be differential\n # to _incl_diff_tab\n self._incl_diff_tab[(mo, da)] = self._arange_on_xgrid(\n self._incl_tab.pop((mo, da)))\n info(10, \"Channel {0} -> {1} forced to be differential.\")\n else:\n self.known_bc_channels.append((mo, da))\n self.known_species.append(da)\n\n for mo, da in list(self._incl_diff_tab.keys()):\n if da >= 100 and get_AZN(da)[0] > get_AZN(mo)[0]:\n raise Exception(\n 'Daughter {0} heavier than mother {1}. Physics??'.format(\n da, mo))\n\n if mo not in self.reactions:\n self.reactions[mo] = []\n self.known_species.append(mo)\n\n if (mo, da) not in self.reactions[mo]:\n # Make sure it's a unique list to avoid unnecessary loops\n self.reactions[mo].append((mo, da))\n self.known_diff_channels.append((mo, da))\n self.known_species.append(da)\n\n # Remove duplicates\n self.known_species = sorted(list(set(self.known_species)))\n self.known_bc_channels = sorted(list(set(self.known_bc_channels)))\n self.known_diff_channels = sorted(list(set(self.known_diff_channels)))\n\n for sp in self.known_species:\n if sp >= 100 and (sp, sp) not in self.known_diff_channels:\n self.known_bc_channels.append((mo, mo))\n if (mo, mo) not in self.reactions[mo]:\n self.reactions[mo].append((mo, mo))\n\n # Make sure the indices are up to date\n self._update_indices()\n\n # Count numbers of channels for statistics\n # Count number of incl channels for activated nuclear species\n # n_incl = np.sum([\n # len(self.reactions[mother])\n # for mother in self.spec_man.known_species if mother >= 100\n # ])\n\n def _reduce_channels(self):\n \"\"\"Follows decay chains until all inclusive reactions point to\n stable final state particles.\n\n The \"tau_dec_threshold\" parameter in the config controls the\n definition of stable. Unstable nuclei for which no decay channels\n are known, will be forced to beta-decay until they reach a stable\n element.\n \"\"\"\n from prince_cr.util import AdditiveDictionary\n # TODO: check routine, how to avoid empty channels and\n # mothers with zero nonel cross sections\n\n # The new dictionary that will replace _incl_tab\n new_incl_tab = AdditiveDictionary()\n new_dec_diff_tab = AdditiveDictionary()\n\n threshold = config.tau_dec_threshold\n\n # How to indent debug printout for recursion\n dbg_indent = lambda lev: 4 * lev * \"-\" + \">\" if lev else \"\"\n\n info(2, \"Integrating out species with lifetime smaller than\",\n threshold)\n info(3, (\n \"Before optimization, the number of known primaries is {0} with \" +\n \"in total {1} inclusive channels\").format(len(self._nonel_tab),\n len(self._incl_tab)))\n\n if self.xbins is None:\n info(\n 4,\n 'Model does not provide a native xbins. Assuming JH special sophia',\n 'binning.')\n from .photo_meson import SophiaSuperposition\n self.xbins = SophiaSuperposition().xbins\n\n bc = self.xcenters\n bw = bin_widths(self.xbins)\n # The x_mu/x_pi grid\n # dec_grid = np.fromfunction(\n # lambda j, i: 10**(np.log10(bc[1] / bc[0]) * (j - i)), (len(bc),\n # len(bc)))\n\n # dec_grid = np.outer(bc, 1 / bc)\n\n dec_bins = np.outer(self.xbins, 1 / bc)\n dec_bins_lower = dec_bins[:-1]\n dec_bins_upper = dec_bins[1:]\n\n # dec_grid[dec_grid > 1.] *= 0.\n # The differential element dx_mu/x_pi\n int_scale = np.tile(bw / bc, (len(bc), 1))\n\n from functools import lru_cache\n @lru_cache(maxsize=512, typed=False)\n def decay_cached(mother,daughter):\n dec_dist = int_scale * decs.get_decay_matrix_bin_average(\n mother, daughter, dec_bins_lower, dec_bins_upper)\n \n return dec_dist\n\n def convolve_with_decay_distribution(diff_dist, mother, daughter,\n branching_ratio):\n r\"\"\"Computes the prompt decay xdist by convolving the x distribution\n of the unstable particle with the decay product distribution.\n\n :math:`\\frac{{\\rm d}N^{A\\gamma \\to \\mu}}{{\\rm d}x_j} = \n \\sum_{i=0}^{N_x}~\\Delta x_i \n \\frac{{\\rm d}N^{A\\gamma \\to \\pi}}{{\\rm d} x_i}~\n \\frac{{\\rm d}N^{\\pi \\to \\mu}}{{\\rm d} x_j}`\n \"\"\"\n # dec_dist = int_scale * decs.get_decay_matrix(\n # mother, daughter, dec_grid)\n dec_dist = decay_cached(mother,daughter)\n\n info(20, 'convolving with decay dist', mother, daughter)\n # Handle the case where table entry is (energy_grid, matrix)\n if not isinstance(diff_dist, tuple):\n return branching_ratio * dec_dist.dot(diff_dist)\n else:\n return diff_dist[0], branching_ratio * dec_dist.dot(\n diff_dist[1])\n\n def follow_chain(first_mo, da, csection, reclev):\n \"\"\"Recursive function to follow decay chains until all\n final state particles are stable.\n \n The result is saved in two dictionaries; one for the boost\n conserving inclusive channels and the other one collects\n channels with meson or lepton decay products, which will\n need special care due to energy redistributions of these\n secondaries.\n \"\"\"\n\n info(10, dbg_indent(reclev), 'Entering with', first_mo, da)\n\n if da not in spec_data:\n info(\n 3, dbg_indent(reclev),\n 'daughter {0} unknown, forcing beta decay. Not Implemented yet!!'\n .format(da))\n return\n\n # Daughter is stable. Add it to the new dictionary and terminate\n # recursion\n if spec_data[da][\"lifetime\"] >= threshold:\n if self.is_differential(None, da):\n # If the daughter is a meson or lepton, use the dictionary for\n # differential channels\n info(\n 20, dbg_indent(reclev),\n 'daughter {0} stable and differential. Adding to ({1}, {2})'\n .format(da, first_mo, da))\n new_dec_diff_tab[(first_mo, da)] = csection\n else:\n info(\n 20, dbg_indent(reclev),\n 'daughter {0} stable. Adding to ({1}, {2})'.format(\n da, first_mo, da))\n new_incl_tab[(first_mo, da)] = csection\n return\n\n # ..otherwise follow decay products of this daughter, tracking the\n # original mother particle (first_mo). The cross section (csection) is\n # reduced by the branching ratio (br) of this particular channel\n for br, daughters in spec_data[da][\"branchings\"]:\n info(10, dbg_indent(reclev),\n (\"{3} -> {0:4d} -> {2:4.2f}: {1}\").format(\n da, \", \".join(map(str, daughters)), br, first_mo))\n\n for chained_daughter in daughters:\n # Follow each secondary and increment the recursion level by one\n if self.is_differential(None, chained_daughter):\n info(10, 'daughter', chained_daughter, 'of', da,\n 'is differential')\n follow_chain(\n first_mo, chained_daughter,\n convolve_with_decay_distribution(\n self._arange_on_xgrid(csection), da,\n chained_daughter, br), reclev + 1)\n else:\n follow_chain(first_mo, chained_daughter, br * csection,\n reclev + 1)\n\n # Remove all unstable particles from the dictionaries\n for mother in sorted(self._nonel_tab.keys()):\n if mother not in spec_data or spec_data[mother][\n \"lifetime\"] < threshold:\n info(\n 20,\n \"Primary species {0} does not fulfill stability criteria.\".\n format(mother))\n _ = self._nonel_tab.pop(mother)\n # Only stable (interacting) mother particles are left\n self._update_indices()\n\n for (mother, daughter) in self.incl_idcs:\n\n if mother not in self.nonel_idcs:\n info(\n 30, \"Removing {0}/{1} from incl, since mother not stable \".\n format(mother, daughter))\n _ = self._incl_tab.pop((mother, daughter))\n\n elif self.is_differential(mother, daughter):\n # Move the distributions which are expected to be differential\n # to _incl_diff_tab\n self._incl_diff_tab[(mother,\n daughter)] = self._arange_on_xgrid(\n self._incl_tab.pop(\n (mother, daughter)))\n\n self._update_indices()\n\n for (mother, daughter) in self.incl_diff_idcs:\n\n if mother not in self.nonel_idcs:\n info(\n 30,\n \"Removing {0}/{1} from diff incl, since mother not stable \"\n .format(mother, daughter))\n _ = self._incl_diff_tab.pop((mother, daughter))\n\n self._update_indices()\n\n # Launch the reduction for each inclusive channel\n for (mo, da), value in list(self._incl_tab.items()):\n #print mo, da, value\n #print '---'*30\n follow_chain(mo, da, value, 0)\n\n for (mo, da), value in list(self._incl_diff_tab.items()):\n #print mo, da, value\n #print '---'*30\n follow_chain(mo, da, value, 0)\n\n # Overwrite the old incl dictionary\n self._incl_tab = dict(new_incl_tab)\n # Overwrite the old incl_diff dictionary\n self._incl_diff_tab = dict(new_dec_diff_tab)\n # Reduce also the incl_diff_tab by removing the unknown mothers. At this stage\n # of the code, the particles with redistributions are\n info(\n 3,\n (\"After optimization, the number of known primaries is {0} with \" +\n \"in total {1} inclusive channels\").format(\n len(self._nonel_tab),\n len(self._incl_tab) + len(self._incl_diff_tab)))\n info(2, f'Cache used for decays, {decay_cached.cache_info()}') # pylint:disable=no-value-for-parameter\n\n def nonel_scale(self, mother, scale='A'):\n \"\"\"Returns the nonel cross section scaled by `scale`.\n\n Convenience funtion for plotting, where it is important to\n compare the cross section per nucleon.\n\n Args:\n mother (int): Mother nucleus(on)\n scale (float): If `A` then nonel/A is returned, otherwise\n scale can be any float.\n\n Returns:\n (numpy.array, numpy.array): Tuple of Energy grid in GeV,\n scale * inclusive cross section\n in :math:`cm^{-2}`\n \"\"\"\n\n egr, csection = self.nonel(mother)\n\n if scale == 'A':\n scale = 1. / get_AZN(mother)[0]\n\n return egr, scale * csection\n\n def incl_scale(self, mother, daughter, scale='A'):\n \"\"\"Same as :func:`~cross_sections.CrossSectionBase.nonel_scale`,\n just for inclusive cross sections.\n \"\"\"\n\n egr, csection = self.incl(mother, daughter)\n\n if scale == 'A':\n scale = 1. / get_AZN(mother)[0]\n\n return egr, scale * csection\n\n def nonel(self, mother):\n \"\"\"Returns non-elastic cross section.\n\n Absorption cross section of `mother`, which is\n the total minus elastic, or in other words, the inelastic\n cross section.\n\n Args:\n mother (int): Mother nucleus(on)\n\n Returns:\n (numpy.array, numpy.array): Tuple of Energy grid in GeV, inclusive cross\n section in :math:`cm^{-2}`\n \"\"\"\n\n if mother not in self._nonel_tab:\n raise Exception('Mother {0} unknown.'.format(mother))\n\n if isinstance(self._nonel_tab[mother], tuple):\n return self._nonel_tab[mother]\n else:\n return self.egrid, self._nonel_tab[mother][self._range]\n\n def incl(self, mother, daughter):\n \"\"\"Returns inclusive cross section.\n\n Inclusive cross section for daughter in photo-nuclear\n interactions of `mother`.\n\n Args:\n mother (int): Mother nucleus(on)\n daughter (int): Daughter nucleus(on)\n\n Returns:\n (numpy.array): Inclusive cross section in :math:`cm^{-2}`\n on self._egrid_tab\n \"\"\"\n\n from scipy.integrate import trapz\n\n if (mother, daughter) in self._incl_diff_tab:\n # Return the integral of the differential for the inclusive\n egr_incl, cs_diff = self.incl_diff(mother, daughter)\n # diff_mat = diff_mat.transpose()\n cs_incl = trapz(cs_diff,\n x=self.xcenters,\n dx=bin_widths(self.xbins),\n axis=0)\n\n if isinstance(self._incl_diff_tab[(mother, daughter)], tuple):\n return egr_incl, cs_incl\n\n return self.egrid, cs_incl[self._range]\n\n elif (mother, daughter) not in self._incl_tab:\n raise Exception(\n self.__class__.__name__ + '::'\n '({0},{1}) combination not in inclusive cross sections'.format(\n mother, daughter))\n\n # If _nonel_tab contains tuples of (egrid, cs) return tuple\n # otherwise return (egrid, cs) in range defined by self.range\n\n if isinstance(self._incl_tab[(mother, daughter)], tuple):\n return self._incl_tab[(mother, daughter)]\n return self.egrid, self._incl_tab[(mother, daughter)][self._range]\n\n def incl_diff(self, mother, daughter):\n \"\"\"Returns inclusive cross section.\n\n Inclusive differential cross section for daughter in photo-nuclear\n interactions of `mother`. Only defined, if the daughter is distributed \n in :math:`x = E_{da} / E_{mo}`\n\n Args:\n mother (int): Mother nucleus(on)\n daughter (int): Daughter nucleus(on)\n\n Returns:\n (numpy.array): Inclusive cross section in :math:`cm^{-2}`\n on self._egrid_tab\n \"\"\"\n\n if (mother, daughter) not in self._incl_diff_tab:\n raise Exception(\n self.__class__.__name__ +\n '({0},{1}) combination not in inclusive differential cross sections'\n .format(mother, daughter))\n\n # If _nonel_tab contains tuples of (egrid, cs) return tuple\n # otherwise return (egrid, cs) in range defined by self.range\n\n if isinstance(self._incl_diff_tab[(mother, daughter)], tuple):\n return self._incl_diff_tab[(mother, daughter)]\n return self.egrid, self._incl_diff_tab[(mother,\n daughter)][:, self._range]\n\n def _arange_on_xgrid(self, incl_cs):\n \"\"\"Returns the inclusive cross section on an xgrid at x=1.\"\"\"\n\n egr, cs = None, None\n\n if isinstance(incl_cs, tuple):\n egr, cs = incl_cs\n else:\n cs = incl_cs\n\n nxbins = len(self.xbins) - 1\n if len(cs.shape) > 1 and cs.shape[0] != nxbins:\n raise Exception(\n 'One dimensional cross section expected, instead got',\n cs.shape, '\\n', cs)\n elif len(cs.shape) == 2 and cs.shape[0] == nxbins:\n info(20, 'Supplied 2D distribution seems to be distributed in x.')\n if isinstance(incl_cs, tuple):\n return egr, cs\n return cs\n\n csec = np.zeros((nxbins, cs.shape[0]))\n # NOTE: The factor 2 in the following line is a workarround to account for the latter linear interpolation\n # This is needed because linear spline integral will result in a trapz,\n # which has half the area of the actual first bin\n corr_factor = 2 * self.xwidths[-1] / (self.xcenters[-1] -\n self.xcenters[-2])\n csec[-1, :] = cs / self.xwidths[-1] * corr_factor\n info(\n 4,\n 'Warning! Workaround to account for linear interpolation in x, factor 2 added!'\n )\n if isinstance(incl_cs, tuple):\n return egr, csec\n return csec\n\n def multiplicities(self, mother, daughter):\n '''Return the multiplicities from either the inclusive channels, or the\n differential ones integrated by x, as a function of Energy.\n '''\n egrid_incl, cs_incl = self.incl(mother, daughter)\n egrid_nonel, cs_nonel = self.nonel(mother)\n\n if egrid_incl.shape != egrid_nonel.shape:\n raise Exception('Problem with different grid shapes')\n\n multiplicities = cs_incl / np.where(cs_nonel == 0, np.inf, cs_nonel)\n\n return egrid_nonel, multiplicities\n\n\nif __name__ == \"__main__\":\n pass\n", "meta": {"hexsha": "5d14f7c2f9a776c1168f35db712e89e460713ce1", "size": 25395, "ext": "py", "lang": "Python", "max_stars_repo_path": "prince_cr/cross_sections/base.py", "max_stars_repo_name": "afedynitch/PriNCe", "max_stars_repo_head_hexsha": "372f037f6c114528c52c6d5ca3624897b72a8605", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-05-01T12:21:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-26T16:18:39.000Z", "max_issues_repo_path": "prince_cr/cross_sections/base.py", "max_issues_repo_name": "afedynitch/PriNCe", "max_issues_repo_head_hexsha": "372f037f6c114528c52c6d5ca3624897b72a8605", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-05-03T11:37:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-15T12:37:40.000Z", "max_forks_repo_path": "prince_cr/cross_sections/base.py", "max_forks_repo_name": "afedynitch/PriNCe", "max_forks_repo_head_hexsha": "372f037f6c114528c52c6d5ca3624897b72a8605", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-16T01:35:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T13:08:11.000Z", "avg_line_length": 39.0692307692, "max_line_length": 114, "alphanum_fraction": 0.567985824, "include": true, "reason": "import numpy,from scipy", "num_tokens": 5572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.22541662103868043, "lm_q1q2_score": 0.12324387014292348}} {"text": "\"\"\"\nModule for handling atomic elements.\n\"\"\"\nfrom numpy import vectorize\n\n\nclass Element:\n \"\"\"\n Class for storing and accessing atomic elements. \n\n Args:\n input_value: The atomic number, symbol, or name of the element\n \"\"\"\n\n def __init__(self, input_value):\n self.input = input_value\n\n # list with atomic number z, short name, full name, valence,\n # valence electrons, covalent radius, vdW radius, metallic radius\n self.elements_list = [\n (1, \"H\", \"Hydrogen\", 1.0, 1, 0.31, 1.20, None),\n (2, \"He\", \"Helium\", 0.5, 2, 0.28, 1.40, None),\n (3, \"Li\", \"Lithium\", 1.0, 1, 1.28, 1.82, 1.52),\n (4, \"Be\", \"Beryllium\", 2.0, 2, 0.96, 1.53, 1.12),\n (5, \"B\", \"Boron\", 3.0, 3, 0.84, 1.92, None),\n (6, \"C\", \"Carbon\", 4.0, 4, 0.78, 1.70, None),\n (7, \"N\", \"Nitrogen\", 3.0, 5, 0.78, 1.55, None),\n (8, \"O\", \"Oxygen\", 2.0, 6, 0.70, 1.52, None),\n (9, \"F\", \"Fluorine\", 1.0, 7, 0.57, 1.47, None),\n (10, \"Ne\", \"Neon\", 0.5, 8, 0.58, 1.54, None),\n (11, \"Na\", \"Sodium\", 1.0, 1, 1.66, 2.27, 1.86),\n (12, \"Mg\", \"Magnesium\", 2.0, 2, 1.41, 1.73, 1.60),\n (13, \"Al\", \"Aluminium\", 3.0, 3, 1.21, 1.84, 1.43),\n (14, \"Si\", \"Silicon\", 4.0, 4, 1.11, 2.10, None),\n (15, \"P\", \"Phosphorus\", 3.0, 5, 1.07, 1.80, None),\n (16, \"S\", \"Sulfur\", 2.0, 6, 1.25, 1.80, None),\n (17, \"Cl\", \"Chlorine\", 1.0, 7, 1.02, 1.75, None),\n (18, \"Ar\", \"Argon\", 0.5, 8, 1.06, 1.88, None),\n (19, \"K\", \"Potassium\", 1.0, 1, 2.03, 2.75, 2.27),\n (20, \"Ca\", \"Calcium\", 2.0, 2, 1.76, 2.31, 1.97),\n (21, \"Sc\", \"Scandium\", 3.0, 3, 1.70, 2.11, 1.62),\n (22, \"Ti\", \"Titanium\", 4.0, 4, 1.60, 2.00, 1.47),\n (23, \"V\", \"Vanadium\", 4.0, 5, 1.53, 2.00, 1.34),\n (24, \"Cr\", \"Chromium\", 3.0, 6, 1.39, 2.00, 1.28),\n (25, \"Mn\", \"Manganese\", 4.0, 5, 1.39, 2.00, 1.27),\n (26, \"Fe\", \"Iron\", 3.0, 3, 1.32, 2.00, 1.26),\n (27, \"Co\", \"Cobalt\", 3.0, 3, 1.26, 2.00, 1.25),\n (28, \"Ni\", \"Nickel\", 2.0, 3, 1.24, 1.63, 1.24),\n (29, \"Cu\", \"Copper\", 2.0, 2, 1.32, 1.40, 1.28),\n (30, \"Zn\", \"Zinc\", 2.0, 2, 1.22, 1.39, 1.34),\n (31, \"Ga\", \"Gallium\", 3.0, 3, 1.22, 1.87, 1.35),\n (32, \"Ge\", \"Germanium\", 4.0, 4, 1.20, 2.11, None),\n (33, \"As\", \"Arsenic\", 3.0, 5, 1.19, 1.85, None),\n (34, \"Se\", \"Selenium\", 2.0, 6, 1.20, 1.90, None),\n (35, \"Br\", \"Bromine\", 1.0, 7, 1.20, 1.85, None),\n (36, \"Kr\", \"Krypton\", 0.5, 8, 1.16, 2.02, None),\n (37, \"Rb\", \"Rubidium\", 1.0, 1, 2.20, 3.03, 2.48),\n (38, \"Sr\", \"Strontium\", 2.0, 2, 1.95, 2.49, 2.15),\n (39, \"Y\", \"Yttrium\", 3.0, 3, 1.90, 2.00, 1.80),\n (40, \"Zr\", \"Zirconium\", 4.0, 4, 1.75, 2.00, 1.60),\n (41, \"Nb\", \"Niobium\", 5.0, 5, 1.64, 2.00, 1.46),\n (42, \"Mo\", \"Molybdenum\", 4.0, 6, 1.54, 2.00, 1.39),\n (43, \"Tc\", \"Technetium\", 4.0, 5, 1.47, 2.00, 1.36),\n (44, \"Ru\", \"Ruthenium\", 4.0, 3, 1.46, 2.00, 1.34),\n (45, \"Rh\", \"Rhodium\", 4.0, 3, 1.42, 1.63, 1.34),\n (46, \"Pd\", \"Palladium\", 4.0, 3, 1.39, 1.72, 1.37),\n (47, \"Ag\", \"Silver\", 1.0, 2, 1.45, 1.58, 1.44),\n (48, \"Cd\", \"Cadmium\", 2.0, 2, 1.44, 1.93, 1.51),\n (49, \"In\", \"Indium\", 3.0, 3, 1.42, 2.17, 1.67),\n (50, \"Sn\", \"Tin\", 4.0, 4, 1.39, 2.06, None),\n (51, \"Sb\", \"Antimony\", 3.0, 5, 1.39, 2.06, None),\n (52, \"Te\", \"Tellurium\", 2.0, 6, 1.38, 2.06, None),\n (53, \"I\", \"Iodine\", 1.0, 7, 1.39, 1.98, None),\n (54, \"Xe\", \"Xenon\", 0.5, 8, 1.40, 2.16, None),\n (55, \"Cs\", \"Caesium\", 1.0, 1, 2.44, 3.43, 2.65),\n (56, \"Ba\", \"Barium\", 2.0, 2, 2.15, 2.68, 2.22),\n (57, \"La\", \"Lanthanum\", 3.0, 3, 2.07, 2.10, 1.87),\n (58, \"Ce\", \"Cerium\", 4.0, 3, 2.04, 2.10, 1.818),\n (59, \"Pr\", \"Praseodymium\", 3.0, 3, 2.03, 2.10, 1.824),\n (60, \"Nd\", \"Neodymium\", 3.0, 3, 2.01, 2.10, 1.814),\n (61, \"Pm\", \"Promethium\", 3.0, 3, 1.99, 2.10, 1.834),\n (62, \"Sm\", \"Samarium\", 3.0, 3, 1.98, 2.10, 1.804),\n (63, \"Eu\", \"Europium\", 3.0, 3, 1.98, 2.10, 1.804),\n (64, \"Gd\", \"Gadolinium\", 3.0, 3, 1.96, 2.10, 1.804),\n (65, \"Tb\", \"Terbium\", 3.0, 3, 1.94, 2.10, 1.773),\n (66, \"Dy\", \"Dysprosium\", 3.0, 3, 1.92, 2.10, 1.781),\n (67, \"Ho\", \"Holmium\", 3.0, 3, 1.92, 2.10, 1.762),\n (68, \"Er\", \"Erbium\", 3.0, 3, 1.89, 2.10, 1.761),\n (69, \"Tm\", \"Thulium\", 3.0, 3, 1.90, 2.10, 1.759),\n (70, \"Yb\", \"Ytterbium\", 3.0, 3, 1.87, 2.10, 1.76),\n (71, \"Lu\", \"Lutetium\", 3.0, 3, 1.87, 2.10, 1.738),\n (72, \"Hf\", \"Hafnium\", 4.0, 3, 1.75, 2.10, 1.59),\n (73, \"Ta\", \"Tantalum\", 5.0, 3, 1.70, 2.10, 1.46),\n (74, \"W\", \"Tungsten\", 4.0, 3, 1.62, 2.10, 1.39),\n (75, \"Re\", \"Rhenium\", 4.0, 3, 1.51, 2.10, 1.37),\n (76, \"Os\", \"Osmium\", 4.0, 3, 1.44, 2.10, 1.35),\n (77, \"Ir\", \"Iridium\", 4.0, 3, 1.41, 2.10, 1.355),\n (78, \"Pt\", \"Platinum\", 4.0, 3, 1.36, 1.75, 1.385),\n (79, \"Au\", \"Gold\", 1.0, 3, 1.36, 1.66, 1.44),\n (80, \"Hg\", \"Mercury\", 2.0, 3, 1.32, 1.55, 1.51),\n (81, \"Tl\", \"Thallium\", 3.0, 3, 1.45, 1.96, 1.70),\n (82, \"Pb\", \"Lead\", 4.0, 4, 1.46, 2.02, None),\n (83, \"Bi\", \"Bismuth\", 3.0, 5, 1.48, 2.07, None),\n (84, \"Po\", \"Polonium\", 2.0, 6, 1.40, 1.97, None),\n (85, \"At\", \"Astatine\", 1.0, 7, 1.50, 2.02, None),\n (86, \"Rn\", \"Radon\", 0.5, 8, 1.50, 2.20, None),\n (87, \"Fr\", \"Francium\", 1.0, 1, 2.60, 3.48, None),\n (88, \"Ra\", \"Radium\", 2.0, 2, 2.21, 2.83, None),\n (89, \"Ac\", \"Actinium\", 3.0, 3, 2.15, 2.20, None),\n (90, \"Th\", \"Thorium\", 4.0, 3, 2.06, 2.20, 1.79),\n (91, \"Pa\", \"Protactinium\", 4.0, 3, 2.00, 2.20, 1.63),\n (92, \"U\", \"Uranium\", 4.0, 3, 1.96, 2.20, 1.56),\n (93, \"Np\", \"Neptunium\", 4.0, 3, 1.90, 2.20, 1.55),\n (94, \"Pu\", \"Plutonium\", 4.0, 3, 1.87, 2.20, 1.59),\n (95, \"Am\", \"Americium\", 4.0, 3, 1.80, 2.20, 1.73),\n (96, \"Cm\", \"Curium\", 4.0, 3, 1.69, 2.20, 1.74),\n (97, \"Bk\", \"Berkelium\", 4.0, 3, None, None, 1.70),\n (98, \"Cf\", \"Californium\", 4.0, 3, None, None, 1.86),\n (99, \"Es\", \"Einsteinium\", 4.0, 3, None, None, 1.86),\n (100, \"Fm\", \"Fermium\", 4.0, 3, None, None, None),\n (101, \"Md\", \"Mendelevium\", 4.0, 3, None, None, None),\n (102, \"No\", \"Nobelium\", 4.0, 3, None, None, None),\n (103, \"Lr\", \"Lawrencium\", 4.0, 3, None, None, None),\n (104, \"Rf\", \"Rutherfordium\", 4.0, 3, None, None, None),\n (105, \"Db\", \"Dubnium\", 2.0, 3, None, None, None),\n ]\n \"\"\"A list of atomic numbers, symbols, names, and other information, up\n to atomic number 105\"\"\"\n\n # scatter factor\n self.sf = [\n [0.493, 0.323, 0.140, 0.041, 10.511, 26.126, 3.142, 57.800, 0.003],\n [0.873, 0.631, 0.311, 0.178, 9.104, 3.357, 22.928, 0.982, 0.006],\n [1.128, 0.751, 0.618, 0.465, 3.955, 1.052, 85.391, 168.261, 0.038],\n [1.592, 1.128, 0.539, 0.703, 43.643, 1.862, 103.483, 0.542, 0.038],\n [2.055, 1.333, 1.098, 0.707, 23.219, 1.021, 60.350, 0.140, -0.193],\n [2.310, 1.020, 1.589, 0.865, 20.844, 10.208, 0.569, 51.651, 0.216],\n [12.213, 3.132, 2.013, 1.166, 0.006, 9.893, 28.997, 0.583, -11.529],\n [3.049, 2.287, 1.546, 0.867, 13.277, 5.701, 0.324, 32.909, 0.251],\n [3.539, 2.641, 1.517, 1.024, 10.283, 4.294, 0.262, 26.148, 0.278],\n [3.955, 3.112, 1.455, 1.125, 8.404, 3.426, 0.231, 21.718, 0.352],\n [4.763, 3.174, 1.267, 1.113, 3.285, 8.842, 0.314, 129.424, 0.676],\n [5.420, 2.174, 1.227, 2.307, 2.828, 79.261, 0.381, 7.194, 0.858],\n [6.420, 1.900, 1.594, 1.965, 3.039, 0.743, 31.547, 85.089, 1.115],\n [6.292, 3.035, 1.989, 1.541, 2.439, 32.334, 0.678, 81.694, 1.141],\n [6.435, 4.179, 1.780, 1.491, 1.907, 27.157, 0.526, 68.164, 1.115],\n [6.905, 5.203, 1.438, 1.586, 1.468, 22.215, 0.254, 56.172, 0.867],\n [11.460, 7.196, 6.256, 1.645, 0.010, 1.166, 18.519, 47.778, -9.557],\n [7.484, 6.772, 0.654, 1.644, 0.907, 14.841, 43.898, 33.393, 1.444],\n [8.219, 7.440, 1.052, 0.866, 12.795, 0.775, 213.187, 41.684, 1.423],\n [8.627, 7.387, 1.590, 1.021, 10.442, 0.660, 85.748, 178.437, 1.375],\n [9.189, 7.368, 1.641, 1.468, 9.021, 0.573, 136.108, 51.353, 1.333],\n [9.759, 7.356, 1.699, 1.902, 7.851, 0.500, 35.634, 116.105, 1.281],\n [10.297, 7.351, 2.070, 2.057, 6.866, 0.438, 26.894, 102.478, 1.220],\n [10.641, 7.354, 3.324, 1.492, 6.104, 0.392, 20.263, 98.740, 1.183],\n [11.282, 7.357, 3.019, 2.244, 5.341, 0.343, 17.867, 83.754, 1.090],\n [11.769, 7.357, 3.522, 2.305, 4.761, 0.307, 15.354, 76.881, 1.037],\n [12.284, 7.341, 4.003, 2.349, 4.279, 0.278, 13.536, 71.169, 1.012],\n [12.838, 7.292, 4.444, 2.380, 3.878, 0.257, 12.176, 66.342, 1.034],\n [13.338, 7.168, 5.616, 1.673, 3.583, 0.247, 11.397, 64.831, 1.191],\n [14.074, 7.032, 5.165, 2.410, 3.266, 0.233, 10.316, 58.710, 1.304],\n [15.235, 6.701, 4.359, 2.962, 3.067, 0.241, 10.781, 61.414, 1.719],\n [16.082, 6.375, 3.707, 3.683, 2.851, 0.252, 11.447, 54.763, 2.131],\n [16.672, 6.070, 3.431, 4.278, 2.635, 0.265, 12.948, 47.797, 2.531],\n [17.001, 5.820, 3.973, 4.354, 2.410, 0.273, 15.237, 43.816, 2.841],\n [17.179, 5.236, 5.638, 3.985, 2.172, 16.580, 0.261, 41.433, 2.956],\n [17.355, 6.729, 5.549, 3.537, 1.938, 16.562, 0.226, 39.397, 2.825],\n [17.178, 9.644, 5.140, 1.529, 1.789, 17.315, 0.275, 164.934, 3.487],\n [17.566, 9.818, 5.422, 2.669, 1.556, 14.099, 0.166, 132.376, 2.506],\n [17.776, 10.295, 5.726, 3.266, 1.403, 12.801, 0.261, 104.354, 1.912],\n [17.876, 10.948, 5.417, 3.657, 1.276, 11.916, 0.118, 87.663, 2.069],\n [17.614, 12.014, 4.042, 3.533, 1.189, 11.766, 0.205, 69.796, 3.756],\n [3.703, 17.236, 12.888, 3.743, 0.277, 1.096, 11.004, 61.658, 4.387],\n [19.130, 11.095, 4.649, 2.713, 0.864, 8.145, 21.571, 86.847, 5.404],\n [19.267, 12.918, 4.863, 1.568, 0.809, 8.435, 24.800, 94.293, 5.379],\n [19.296, 14.350, 4.734, 1.289, 0.752, 8.218, 25.875, 98.606, 5.328],\n [19.332, 15.502, 5.295, 0.606, 0.699, 7.989, 25.205, 76.899, 5.266],\n [19.281, 16.688, 4.805, 1.046, 0.645, 7.473, 24.660, 99.816, 5.179],\n [19.221, 17.644, 4.461, 1.603, 0.595, 6.909, 24.701, 87.482, 5.069],\n [19.162, 18.560, 4.295, 2.040, 0.548, 6.378, 25.850, 92.803, 4.939],\n [19.189, 19.101, 4.458, 2.466, 5.830, 0.503, 26.891, 83.957, 4.782],\n [19.642, 19.045, 5.037, 2.683, 5.303, 0.461, 27.907, 75.283, 4.591],\n [19.964, 19.014, 6.145, 2.524, 4.817, 0.421, 28.528, 70.840, 4.352],\n [20.147, 18.995, 7.514, 2.273, 4.347, 0.381, 27.766, 66.878, 4.071],\n [20.293, 19.030, 8.977, 1.990, 3.928, 0.344, 26.466, 64.266, 3.712],\n [20.389, 19.106, 10.662, 1.495, 3.569, 0.311, 24.388, 213.904, 3.335],\n [20.336, 19.297, 10.888, 2.696, 3.216, 0.276, 20.207, 167.202, 2.773],\n [20.578, 19.599, 11.373, 3.287, 2.948, 0.244, 18.773, 133.124, 2.147],\n [21.167, 19.770, 11.851, 3.330, 2.812, 0.227, 17.608, 127.113, 1.863],\n [22.044, 19.670, 12.386, 2.824, 2.774, 0.222, 16.767, 143.644, 2.058],\n [22.684, 19.685, 12.774, 2.851, 2.662, 0.211, 15.885, 137.903, 1.985],\n [23.340, 19.610, 13.123, 2.875, 2.563, 0.202, 15.101, 132.721, 2.029],\n [24.004, 19.426, 13.440, 2.896, 2.473, 0.196, 14.400, 128.007, 2.210],\n [24.627, 19.089, 13.760, 2.293, 2.388, 0.194, 13.755, 123.174, 2.575],\n [25.071, 19.080, 13.852, 3.545, 2.253, 0.182, 12.933, 101.398, 2.420],\n [25.898, 18.219, 14.317, 2.954, 2.243, 0.196, 12.665, 115.362, 3.583],\n [26.507, 17.638, 14.560, 2.966, 2.180, 0.202, 12.190, 111.874, 4.297],\n [26.905, 17.294, 14.558, 3.638, 2.071, 0.198, 11.441, 92.657, 4.568],\n [27.656, 16.428, 14.978, 2.982, 2.074, 0.224, 11.360, 105.703, 5.920],\n [28.182, 15.885, 15.154, 2.987, 2.029, 0.239, 10.998, 102.961, 6.756],\n [28.664, 15.434, 15.309, 2.990, 1.989, 0.257, 10.665, 100.417, 7.567],\n [28.948, 15.221, 15.100, 3.716, 1.902, 9.985, 0.261, 84.330, 7.976],\n [29.144, 15.173, 14.759, 4.300, 1.833, 9.600, 0.275, 72.029, 8.582],\n [29.202, 15.229, 14.514, 4.765, 1.773, 9.370, 0.296, 63.364, 9.244],\n [0.000, 0.000, 0.000, 0.000, 1.722, 9.231, 0.323, 57.725, 9.858],\n [28.762, 15.719, 14.556, 5.442, 1.672, 9.092, 0.350, 52.086, 10.472],\n [28.189, 16.155, 14.931, 5.676, 1.629, 8.979, 0.383, 48.165, 11.000],\n [27.305, 16.730, 15.611, 5.834, 1.593, 8.866, 0.418, 45.001, 11.472],\n [27.006, 17.764, 15.713, 5.784, 1.513, 8.812, 0.425, 38.610, 11.688],\n [16.882, 18.591, 25.558, 5.860, 0.461, 8.622, 1.483, 36.396, 12.066],\n [20.681, 19.042, 21.657, 5.968, 0.545, 8.448, 1.573, 38.325, 12.609],\n [27.545, 19.158, 15.538, 5.526, 0.655, 8.708, 1.963, 45.815, 13.175],\n [31.062, 13.064, 18.442, 5.970, 0.690, 2.358, 8.618, 47.258, 13.412],\n [33.369, 12.951, 16.588, 6.469, 0.704, 2.924, 8.794, 48.009, 13.578],\n [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000],\n [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000],\n [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000],\n [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000],\n [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000],\n [35.660, 23.103, 12.598, 4.087, 0.589, 3.652, 18.599, 117.020, 13.527],\n [35.564, 23.422, 12.747, 4.807, 0.563, 3.462, 17.831, 99.172, 13.431],\n [35.885, 23.295, 14.189, 4.173, 0.548, 3.415, 16.924, 105.251, 13.429],\n [0.000, 0.000, 0.000, 0.000, 0.530, 3.335, 16.143, 101.371, 13.393],\n [36.187, 23.596, 15.640, 4.186, 0.512, 3.254, 15.362, 97.491, 13.357],\n [36.526, 23.808, 16.771, 3.479, 0.499, 3.264, 14.946, 105.980, 13.381],\n ]\n \"\"\"A list of scatter factors for the elements\"\"\"\n\n self.z = None\n \"\"\"atomic number\"\"\"\n self.short_name = None\n \"\"\"atomic symbol\"\"\"\n self.long_name = None\n \"\"\"atomic name\"\"\"\n self.valence = None\n \"\"\"valence value\"\"\"\n self.valence_electrons = None\n \"\"\"number of valence electrons\"\"\"\n self.covalent_radius = None\n \"\"\"atomic radius used for distance checking within crystals\"\"\"\n self.vdw_radius = None\n \"\"\"atomic radius used for volume estimation within crystals\"\"\"\n self.metallic_radius = None\n \"\"\"atomic radius used for distance checking within metallic crystals\"\"\"\n\n pos = None\n\n try:\n int(self.input)\n self.z = self.input\n\n for i, el in enumerate(self.elements_list):\n if el[0] == self.z:\n pos = i\n self.short_name = el[1]\n self.long_name = el[2]\n break\n except ValueError:\n self.short_name = self.input\n for i, el in enumerate(self.elements_list):\n if el[1] == self.short_name:\n pos = i\n self.z = el[0]\n self.long_name = el[2]\n break\n\n if not self.z:\n self.short_name = None\n self.long_name = self.input\n for i, el in enumerate(self.elements_list):\n if el[2] == self.long_name:\n pos = i\n self.z = el[0]\n self.short_name = el[1]\n break\n if not self.z:\n self.long_name = None\n\n if pos is not None:\n self.valence = self.elements_list[pos][3]\n self.valence_electrons = self.elements_list[pos][4]\n self.covalent_radius = self.elements_list[pos][5]\n self.vdw_radius = self.elements_list[pos][6]\n self.metallic_radius = self.elements_list[pos][7]\n self.scatter = self.sf[pos]\n\n def get_all(self, pos):\n \"\"\"\n Return all [pos] elements in the full element list\n \n Args:\n pos: the index of the elements to retrieve\n \n Returns:\n a list containing only the [pos] elements of self.elements_list\n \"\"\"\n els = []\n for el in self.elements_list:\n els.append(el[pos])\n return els\n\n def get_sf(self, pos):\n \"\"\"\n Get the scattering factor for an element.\n \n Args:\n pos: the atomic number of the element\n\n Returns:\n the scattering factor of the element\n \"\"\"\n els = []\n for el in self.sf:\n els.append(el[pos])\n return els\n\n # TODO: add docstrings for miscellaneous functions\n def all_z(self):\n return self.get_all(0)\n\n def all_short_names(self):\n return self.get_all(1)\n\n def all_long_names(self):\n return self.get_all(2)\n\n def all_valences(self):\n return self.get_all(3)\n\n def all_valence_electrons(self):\n return self.get_all(4)\n\n def all_covalent_radii(self):\n return self.get_all(5)\n\n def all_vdw_radii(self):\n return self.get_all(6)\n\n def all_metallic_radii(self):\n return self.get_all(7)\n\n def get_sf(self):\n return self.get_sf()\n\n def number_from_specie(specie):\n if type(specie) == int or type(specie) == float:\n if specie <= 105 and specie >= 1:\n index = int(specie)\n else:\n print(specie)\n print(\"Error: Atomic number must be between 1 and 105.\")\n return\n elif type(specie) == str:\n try:\n el = Element(specie)\n index = el.z\n except:\n print(\"Error: Invalid atomic symbol, name, or number.\")\n return\n elif type(specie) == Element:\n try:\n index = specie.z\n except:\n print(\"Error: Element object has no atomic number 'z'.\")\n return\n else:\n try:\n el = Element(specie.number)\n index = el.z\n except:\n print(\"Error: Invalid atomic symbol, name, or number.\")\n return\n return index\n", "meta": {"hexsha": "424bff0b02d0f9fc7a6ac236c565709f9d32ef24", "size": 19193, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyxtal/database/element.py", "max_stars_repo_name": "ubikpt/PyXtal", "max_stars_repo_head_hexsha": "32da046a2bde542279824d6377aea116b679a2e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 127, "max_stars_repo_stars_event_min_datetime": "2018-09-21T22:27:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:11:49.000Z", "max_issues_repo_path": "pyxtal/database/element.py", "max_issues_repo_name": "ubikpt/PyXtal", "max_issues_repo_head_hexsha": "32da046a2bde542279824d6377aea116b679a2e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 171, "max_issues_repo_issues_event_min_datetime": "2018-08-06T07:10:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T00:59:53.000Z", "max_forks_repo_path": "pyxtal/database/element.py", "max_forks_repo_name": "ubikpt/PyXtal", "max_forks_repo_head_hexsha": "32da046a2bde542279824d6377aea116b679a2e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 50, "max_forks_repo_forks_event_min_datetime": "2018-08-12T22:50:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T07:52:47.000Z", "avg_line_length": 51.3181818182, "max_line_length": 83, "alphanum_fraction": 0.4649090814, "include": true, "reason": "from numpy", "num_tokens": 8904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.2227001388253088, "lm_q1q2_score": 0.12262033674293558}} {"text": "\"\"\"Utilities for coordinate-based meta-analysis estimators.\"\"\"\nimport logging\nimport os\n\nimport nibabel as nib\nimport numpy as np\nimport numpy.linalg as npl\nfrom scipy import ndimage\n\nfrom .. import references\nfrom ..due import due\nfrom ..extract import download_peaks2maps_model\nfrom ..utils import _determine_chunk_size\n\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"2\"\nLGR = logging.getLogger(__name__)\n\n\ndef model_fn(features, labels, mode, params):\n \"\"\"Run model function used internally by peaks2maps.\n\n .. deprecated:: 0.0.11\n `model_fn` will be removed in NiMARE 0.0.13.\n\n .. versionadded:: 0.0.4\n\n \"\"\"\n import tensorflow as tf\n from tensorflow.python.estimator.export.export_output import PredictOutput\n\n ngf = 64\n layers = []\n\n training_flag = mode == tf.estimator.ModeKeys.TRAIN\n\n input_images_placeholder = tf.expand_dims(features, -1)\n\n conv_args = {\n \"strides\": 2,\n \"kernel_size\": 4,\n \"padding\": \"valid\",\n \"activation\": tf.nn.leaky_relu,\n \"kernel_initializer\": tf.random_normal_initializer(0, 0.02),\n \"name\": \"conv\",\n \"use_bias\": False,\n }\n\n deconv_args = conv_args.copy()\n deconv_args[\"padding\"] = \"same\"\n deconv_args[\"name\"] = \"deconv\"\n\n batchnorm_args = {\n \"scale\": True,\n \"gamma_initializer\": tf.random_normal_initializer(1.0, 0.02),\n \"center\": True,\n \"beta_initializer\": tf.zeros_initializer(),\n \"name\": \"batchnorm\",\n \"training\": training_flag,\n }\n\n def pad_and_conv(input, out_channels, conv_args):\n padded_input = tf.pad(input, [[0, 0], [1, 1], [1, 1], [1, 1], [0, 0]], mode=\"CONSTANT\")\n convolved = tf.compat.v1.layers.conv3d(padded_input, out_channels, **conv_args)\n return convolved\n\n # encoder_1: [batch, 256, 256, in_channels] => [batch, 128, 128, ngf]\n with tf.compat.v1.variable_scope(\"encoder_1\"):\n this_args = conv_args.copy()\n output = pad_and_conv(input_images_placeholder, ngf, this_args)\n layers.append(output)\n\n layer_specs = [\n (ngf * 2, 0.2),\n # encoder_3: [batch, 64, 64, ngf * 2] => [batch, 32, 32, ngf * 4]\n (ngf * 2, 0.2),\n # encoder_3: [batch, 64, 64, ngf * 2] => [batch, 32, 32, ngf * 4]\n (ngf * 4, 0.2),\n # encoder_4: [batch, 32, 32, ngf * 4] => [batch, 16, 16, ngf * 8]\n (ngf * 8, 0.2),\n # encoder_5: [batch, 16, 16, ngf * 8] => [batch, 8, 8, ngf * 8]\n # ngf * 8,\n # # encoder_6: [batch, 8, 8, ngf * 8] => [batch, 4, 4, ngf * 8]\n ]\n\n for out_channels, dropout in layer_specs:\n with tf.compat.v1.variable_scope(\"encoder_%d\" % (len(layers) + 1)):\n # [batch, in_height, in_width, in_channels] => [batch, in_height/2, in_width/2,\n # out_channels]\n convolved = pad_and_conv(layers[-1], out_channels, conv_args)\n output = tf.compat.v1.layers.batch_normalization(convolved, **batchnorm_args)\n if dropout > 0.0:\n output = tf.compat.v1.layers.dropout(output, rate=dropout, training=training_flag)\n layers.append(output)\n\n layer_specs = [\n # (ngf * 8, 0.5),\n # # decoder_6: [batch, 4, 4, ngf * 8 * 2] => [batch, 8, 8, ngf * 8 * 2]\n (ngf * 8, 0.2),\n # decoder_5: [batch, 8, 8, ngf * 8 * 2] => [batch, 16, 16, ngf * 8 * 2]\n (ngf * 4, 0.2),\n # decoder_4: [batch, 16, 16, ngf * 8 * 2] => [batch, 32, 32, ngf * 4 * 2]\n (ngf * 2, 0.2),\n # decoder_3: [batch, 32, 32, ngf * 4 * 2] => [batch, 64, 64, ngf * 2 * 2]\n (ngf * 2, 0.2),\n # decoder_2: [batch, 64, 64, ngf * 2 * 2] => [batch, 128, 128, ngf * 2]\n ]\n\n num_encoder_layers = len(layers)\n for decoder_layer, (out_channels, dropout) in enumerate(layer_specs):\n skip_layer = num_encoder_layers - decoder_layer - 1\n with tf.compat.v1.variable_scope(\"decoder_%d\" % (skip_layer + 1)):\n if decoder_layer == 0:\n # first decoder layer doesn't have skip connections\n # since it is directly connected to the skip_layer\n input = layers[-1]\n else:\n input = tf.concat([layers[-1], layers[skip_layer]], axis=4)\n\n output = tf.compat.v1.layers.conv3d_transpose(input, out_channels, **deconv_args)\n output = tf.compat.v1.layers.batch_normalization(output, **batchnorm_args)\n\n if dropout > 0.0:\n output = tf.compat.v1.layers.dropout(output, rate=dropout, training=training_flag)\n\n layers.append(output)\n\n # decoder_1: [batch, 128, 128, ngf * 2] => [batch, 256, 256, generator_outputs_channels]\n with tf.compat.v1.variable_scope(\"decoder_1\"):\n input = tf.concat([layers[-1], layers[0]], axis=4)\n this_args = deconv_args.copy()\n this_args[\"activation\"] = None\n output = tf.compat.v1.layers.conv3d_transpose(input, 1, **this_args)\n layers.append(output)\n\n predictions = tf.squeeze(layers[-1], -1)\n\n if mode == tf.estimator.ModeKeys.PREDICT:\n temp = tf.compat.v1.saved_model.signature_constants\n return tf.estimator.EstimatorSpec(\n mode=mode,\n predictions=predictions,\n export_outputs={temp.DEFAULT_SERVING_SIGNATURE_DEF_KEY: PredictOutput(predictions)},\n )\n else:\n labels, filenames = labels\n loss = tf.losses.mean_squared_error(labels, predictions)\n\n # Add a scalar summary for the snapshot loss.\n # Create the gradient descent optimizer with the given learning rate.\n optimizer = tf.train.AdamOptimizer(params.learning_rate)\n # Use the optimizer to apply the gradients that minimize the loss\n # (and also increment the global step counter) as a single training step.\n extra_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(extra_update_ops):\n train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step())\n\n return tf.estimator.EstimatorSpec(\n mode=mode,\n predictions=predictions,\n loss=loss,\n train_op=train_op,\n export_outputs={\"output\": predictions},\n )\n\n\ndef _get_resize_arg(target_shape):\n \"\"\"Get resizing arguments, as used by peaks2maps.\n\n .. deprecated:: 0.0.11\n `_get_resize_arg` will be removed in NiMARE 0.0.13.\n\n .. versionadded:: 0.0.1\n\n \"\"\"\n mni_shape_mm = np.array([148.0, 184.0, 156.0])\n target_resolution_mm = np.ceil(mni_shape_mm / np.array(target_shape)).astype(np.int32)\n target_affine = np.array(\n [\n [4.0, 0.0, 0.0, -75.0],\n [0.0, 4.0, 0.0, -105.0],\n [0.0, 0.0, 4.0, -70.0],\n [0.0, 0.0, 0.0, 1.0],\n ]\n )\n target_affine[0, 0] = target_resolution_mm[0]\n target_affine[1, 1] = target_resolution_mm[1]\n target_affine[2, 2] = target_resolution_mm[2]\n return target_affine, list(target_shape)\n\n\ndef _get_generator(contrasts_coordinates, target_shape, affine, skip_out_of_bounds=False):\n \"\"\"Get generator, as used by peaks2maps.\"\"\"\n\n def generator():\n for contrast in contrasts_coordinates:\n encoded_coords = np.zeros(list(target_shape))\n for real_pt in contrast:\n vox_pt = np.rint(nib.affines.apply_affine(npl.inv(affine), real_pt)).astype(int)\n if skip_out_of_bounds and (vox_pt[0] >= 32 or vox_pt[1] >= 32 or vox_pt[2] >= 32):\n continue\n encoded_coords[vox_pt[0], vox_pt[1], vox_pt[2]] = 1\n yield (encoded_coords, encoded_coords)\n\n return generator\n\n\n@due.dcite(\n references.PEAKS2MAPS,\n description=\"Transforms coordinates of peaks to unthresholded maps using a deep \"\n \"convolutional neural net.\",\n)\ndef compute_p2m_ma(\n contrasts_coordinates, skip_out_of_bounds=True, tf_verbosity_level=None, model_dir=\"auto\"\n):\n \"\"\"Generate modeled activation (MA) maps using deep ConvNet model peaks2maps.\n\n .. deprecated:: 0.0.11\n `compute_p2m_ma` will be removed in NiMARE 0.0.13.\n\n Parameters\n ----------\n contrasts_coordinates : list of lists that are len == 3\n List of contrasts and their coordinates\n skip_out_of_bounds : bool, optional\n Remove coordinates outside of the bounding box of the peaks2maps model\n tf_verbosity_level : int\n Tensorflow verbosity logging level\n model_dir : str, optional\n Location of peaks2maps model. Default is \"auto\".\n\n Returns\n -------\n ma_values : array-like\n 1d array of modeled activation values.\n \"\"\"\n try:\n import tensorflow as tf\n except ImportError as e:\n if \"No module named 'tensorflow'\" in str(e):\n raise Exception(\n \"tensorflow not installed - see https://www.tensorflow.org/install/ \"\n \"for instructions\"\n )\n else:\n raise\n\n if tf_verbosity_level is None:\n tf_verbosity_level = tf.compat.v1.logging.FATAL\n target_shape = (32, 32, 32)\n affine, _ = _get_resize_arg(target_shape)\n tf.compat.v1.logging.set_verbosity(tf_verbosity_level)\n\n def generate_input_fn():\n dataset = tf.compat.v1.data.Dataset.from_generator(\n _get_generator(\n contrasts_coordinates, target_shape, affine, skip_out_of_bounds=skip_out_of_bounds\n ),\n (tf.float32, tf.float32),\n (tf.TensorShape(target_shape), tf.TensorShape(target_shape)),\n )\n dataset = dataset.batch(1)\n iterator = dataset.make_one_shot_iterator()\n return iterator.get_next()\n\n # download_peaks2maps_model expects None for \"auto\"\n model_dir = None if model_dir == \"auto\" else model_dir\n model_dir = download_peaks2maps_model(data_dir=model_dir)\n model = tf.estimator.Estimator(model_fn, model_dir=model_dir)\n\n results = model.predict(generate_input_fn)\n results = [result for result in results]\n assert len(results) == len(contrasts_coordinates), \"returned %d\" % len(results)\n\n niis = [nib.Nifti1Image(np.squeeze(result), affine) for result in results]\n return niis\n\n\ndef compute_kda_ma(\n shape,\n vox_dims,\n ijks,\n r,\n value=1.0,\n exp_idx=None,\n sum_overlap=False,\n memory_limit=None,\n memmap_filename=None,\n):\n \"\"\"Compute (M)KDA modeled activation (MA) map.\n\n .. versionchanged:: 0.0.8\n\n * [ENH] Add *memmap_filename* parameter for memory mapping arrays.\n\n .. versionadded:: 0.0.4\n\n Replaces the values around each focus in ijk with binary sphere.\n\n Parameters\n ----------\n shape : :obj:`tuple`\n Shape of brain image + buffer. Typically (91, 109, 91).\n vox_dims : array_like\n Size (in mm) of each dimension of a voxel.\n ijks : array-like\n Indices of foci. Each row is a coordinate, with the three columns\n corresponding to index in each of three dimensions.\n r : :obj:`int`\n Sphere radius, in mm.\n value : :obj:`int`\n Value for sphere.\n exp_idx : array_like\n Optional indices of experiments. If passed, must be of same length as\n ijks. Each unique value identifies all coordinates in ijk that come from\n the same experiment. If None passed, it is assumed that all coordinates\n come from the same experiment.\n sum_overlap : :obj:`bool`\n Whether to sum voxel values in overlapping spheres.\n memory_limit : :obj:`str` or None, optional\n Memory limit to apply to data. If None, no memory management will be applied.\n Otherwise, the memory limit will be used to (1) assign memory-mapped files and\n (2) restrict memory during array creation to the limit.\n Default is None.\n memmap_filename : :obj:`str`, optional\n If passed, use this file for memory mapping arrays\n\n Returns\n -------\n kernel_data : :obj:`numpy.array`\n 3d or 4d array. If `exp_idx` is none, a 3d array in the same shape as\n the `shape` argument is returned. If `exp_idx` is passed, a 4d array\n is returned, where the first dimension has size equal to the number of\n unique experiments, and the remaining 3 dimensions are equal to `shape`.\n \"\"\"\n squeeze = exp_idx is None\n if exp_idx is None:\n exp_idx = np.ones(len(ijks))\n\n uniq, exp_idx = np.unique(exp_idx, return_inverse=True)\n n_studies = len(uniq)\n\n kernel_shape = (n_studies,) + shape\n if memmap_filename:\n # Use a memmapped 4D array\n kernel_data = np.memmap(memmap_filename, dtype=type(value), mode=\"w+\", shape=kernel_shape)\n else:\n kernel_data = np.zeros(kernel_shape, dtype=type(value))\n\n n_dim = ijks.shape[1]\n xx, yy, zz = [slice(-r // vox_dims[i], r // vox_dims[i] + 0.01, 1) for i in range(n_dim)]\n cube = np.vstack([row.ravel() for row in np.mgrid[xx, yy, zz]])\n kernel = cube[:, np.sum(np.dot(np.diag(vox_dims), cube) ** 2, 0) ** 0.5 <= r]\n\n if memory_limit:\n chunk_size = _determine_chunk_size(limit=memory_limit, arr=ijks[0])\n\n for i, peak in enumerate(ijks):\n sphere = np.round(kernel.T + peak)\n idx = (np.min(sphere, 1) >= 0) & (np.max(np.subtract(sphere, shape), 1) <= -1)\n sphere = sphere[idx, :].astype(int)\n exp = exp_idx[i]\n if sum_overlap:\n kernel_data[exp][tuple(sphere.T)] += value\n else:\n kernel_data[exp][tuple(sphere.T)] = value\n\n if memmap_filename and i % chunk_size == 0:\n # Write changes to disk\n kernel_data.flush()\n\n if squeeze:\n kernel_data = np.squeeze(kernel_data, axis=0)\n\n return kernel_data\n\n\ndef compute_ale_ma(shape, ijk, kernel):\n \"\"\"Generate ALE modeled activation (MA) maps.\n\n Replaces the values around each focus in ijk with the contrast-specific\n kernel. Takes the element-wise maximum when looping through foci, which\n accounts for foci which are near to one another and may have overlapping\n kernels.\n\n Parameters\n ----------\n shape : tuple\n Shape of brain image + buffer. Typically (91, 109, 91) + (30, 30, 30).\n ijk : array-like\n Indices of foci. Each row is a coordinate, with the three columns\n corresponding to index in each of three dimensions.\n kernel : array-like\n 3D array of smoothing kernel. Typically of shape (30, 30, 30).\n\n Returns\n -------\n ma_values : array-like\n 1d array of modeled activation values.\n \"\"\"\n ma_values = np.zeros(shape)\n mid = int(np.floor(kernel.shape[0] / 2.0))\n mid1 = mid + 1\n for j_peak in range(ijk.shape[0]):\n i, j, k = ijk[j_peak, :]\n xl = max(i - mid, 0)\n xh = min(i + mid1, ma_values.shape[0])\n yl = max(j - mid, 0)\n yh = min(j + mid1, ma_values.shape[1])\n zl = max(k - mid, 0)\n zh = min(k + mid1, ma_values.shape[2])\n xlk = mid - (i - xl)\n xhk = mid - (i - xh)\n ylk = mid - (j - yl)\n yhk = mid - (j - yh)\n zlk = mid - (k - zl)\n zhk = mid - (k - zh)\n\n if (\n (xl >= 0)\n & (xh >= 0)\n & (yl >= 0)\n & (yh >= 0)\n & (zl >= 0)\n & (zh >= 0)\n & (xlk >= 0)\n & (xhk >= 0)\n & (ylk >= 0)\n & (yhk >= 0)\n & (zlk >= 0)\n & (zhk >= 0)\n ):\n ma_values[xl:xh, yl:yh, zl:zh] = np.maximum(\n ma_values[xl:xh, yl:yh, zl:zh], kernel[xlk:xhk, ylk:yhk, zlk:zhk]\n )\n return ma_values\n\n\n@due.dcite(references.ALE_KERNEL, description=\"Introduces sample size-dependent kernels to ALE.\")\ndef get_ale_kernel(img, sample_size=None, fwhm=None):\n \"\"\"Estimate 3D Gaussian and sigma (in voxels) for ALE kernel given sample size or fwhm.\"\"\"\n if sample_size is not None and fwhm is not None:\n raise ValueError('Only one of \"sample_size\" and \"fwhm\" may be specified')\n elif sample_size is None and fwhm is None:\n raise ValueError('Either \"sample_size\" or \"fwhm\" must be provided')\n elif sample_size is not None:\n uncertain_templates = (\n 5.7 / (2.0 * np.sqrt(2.0 / np.pi)) * np.sqrt(8.0 * np.log(2.0))\n ) # pylint: disable=no-member\n # Assuming 11.6 mm ED between matching points\n uncertain_subjects = (11.6 / (2 * np.sqrt(2 / np.pi)) * np.sqrt(8 * np.log(2))) / np.sqrt(\n sample_size\n ) # pylint: disable=no-member\n fwhm = np.sqrt(uncertain_subjects ** 2 + uncertain_templates ** 2)\n\n fwhm_vox = fwhm / np.sqrt(np.prod(img.header.get_zooms()))\n sigma_vox = (\n fwhm_vox * np.sqrt(2.0) / (np.sqrt(2.0 * np.log(2.0)) * 2.0)\n ) # pylint: disable=no-member\n\n data = np.zeros((31, 31, 31))\n mid = int(np.floor(data.shape[0] / 2.0))\n data[mid, mid, mid] = 1.0\n kernel = ndimage.filters.gaussian_filter(data, sigma_vox, mode=\"constant\")\n\n # Crop kernel to drop surrounding zeros\n mn = np.min(np.where(kernel > np.spacing(1))[0])\n mx = np.max(np.where(kernel > np.spacing(1))[0])\n kernel = kernel[mn : mx + 1, mn : mx + 1, mn : mx + 1]\n mid = int(np.floor(data.shape[0] / 2.0))\n return sigma_vox, kernel\n", "meta": {"hexsha": "f461535851ea35e07c2521eeb242706021f7d914", "size": 17158, "ext": "py", "lang": "Python", "max_stars_repo_path": "nimare/meta/utils.py", "max_stars_repo_name": "tsalo/NiMARE", "max_stars_repo_head_hexsha": "46e4e502e5736434afb8c707b3f54011fef4d63d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-09T17:33:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T17:33:15.000Z", "max_issues_repo_path": "nimare/meta/utils.py", "max_issues_repo_name": "tsalo/NiMARE", "max_issues_repo_head_hexsha": "46e4e502e5736434afb8c707b3f54011fef4d63d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-10-24T00:47:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-13T20:56:59.000Z", "max_forks_repo_path": "nimare/meta/utils.py", "max_forks_repo_name": "tsalo/NiMARE", "max_forks_repo_head_hexsha": "46e4e502e5736434afb8c707b3f54011fef4d63d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-01-14T14:51:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-20T19:59:18.000Z", "avg_line_length": 36.4288747346, "max_line_length": 98, "alphanum_fraction": 0.6085208066, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.23934934732271168, "lm_q1q2_score": 0.12247903535013603}} {"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"hyperscreen is an improved background rejection algorithm\nfor \"\"\"\n\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport colorama\nfrom tqdm import tqdm as progressbar\nimport sys\nimport os\n\nimport warnings\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LogNorm\n\nfrom astropy.io import fits\nfrom astropy.table import Table\n\n\nimport skimage.data as data\nimport skimage.segmentation as seg\nimport skimage.filters as filters\nimport skimage.draw as draw\nimport skimage.color as color\n\nimport pandas as pd\nimport numpy as np\nnp.seterr(divide='ignore')\n\ncolorama.init()\n\n\nclass HRCevt1:\n \"\"\"This is a conceptual class representation of a Chandra High Resolution Camera (HRC) Level 1 Event File\n\n :return: HRCevt1 object\n :rtype: pandas.DataFrame or astropy.table.table.Table\n \"\"\"\n\n def __init__(self, evt1file, verbose=False, as_astropy_table=False):\n \"\"\"The constructor method for the HRCevt1 class\n\n :param evt1file: A .fits (or fits.gz) file containing the level 1 event list. If downloaded from the Chandra database, this file always has a *evt1.fits extension. This event list includes all events telemetered.\n :type evt1file: .fits or .fits.gz\n :param verbose: Set verbose=True to make the constructor chatty on the command line, defaults to False\n :type verbose: bool, optional\n :param as_astropy_table: Set as_astropy_table to True in order to have the HRCevt1 constructor method return an Astropy Table object, rather than a Pandas DataFrame. Defaults to False.\n :type as_astropy_table: bool, optional\n \"\"\"\n\n # Define how chatty to be\n self.verbose = verbose\n\n if self.verbose is True:\n print(colorama.Fore.BLUE + '\\nParsing HRC EVT1 file...', end=\" \")\n # Do a standard read in of the EVT1 fits table\n self.filename = evt1file\n self.hdulist = fits.open(evt1file)\n self.data = Table(self.hdulist[1].data)\n self.header = self.hdulist[1].header\n self.gti = self.hdulist[2].data\n self.hdulist.close() # Don't forget to close your fits file!\n\n # Make sure the user isn't running this on an ACIS observation!\n if self.header[\"DETNAM\"][:4] == 'ACIS':\n raise Exception(\n \"ERROR: HRCevt1 objects can only be initialized for Chandra/HRC observations. This is a Chandra/ACIS observation.\")\n\n # Populate the fp, fb values for ever event\n if self.verbose is True:\n print(colorama.Fore.BLUE + 'Calculating fp, fb values...', end=\" \")\n fp_u, fb_u, fp_v, fb_v = self.calculate_fp_fb()\n\n # Populate the fp, fb values for ever event\n if self.verbose is True:\n print(colorama.Fore.BLUE + 'Applying GTI mask... ', end=\" \")\n self.gti.starts = self.gti['START']\n self.gti.stops = self.gti['STOP']\n\n self.gtimask = (self.data[\"time\"] > self.gti.starts[0]) & (\n self.data[\"time\"] < self.gti.stops[-1])\n\n # Populate the fp, fb values for every event\n if self.verbose is True:\n print(colorama.Fore.BLUE + 'Populating metadata columns...', end=\" \")\n self.data[\"fp_u\"] = fp_u\n self.data[\"fb_u\"] = fb_u\n self.data[\"fp_v\"] = fp_v\n self.data[\"fb_v\"] = fb_v\n\n # Make individual status bit columns with legible names\n self.data[\"AV3 corrected for ringing\"] = self.data[\"status\"][:, 0]\n self.data[\"AU3 corrected for ringing\"] = self.data[\"status\"][:, 1]\n self.data[\"Event impacted by prior event (piled up)\"] = self.data[\"status\"][:, 2]\n # Bit 4 (Python 3) is spare\n self.data[\"Shifted event time\"] = self.data[\"status\"][:, 4]\n self.data[\"Event telemetered in NIL mode\"] = self.data[\"status\"][:, 5]\n self.data[\"V axis not triggered\"] = self.data[\"status\"][:, 6]\n self.data[\"U axis not triggered\"] = self.data[\"status\"][:, 7]\n self.data[\"V axis center blank event\"] = self.data[\"status\"][:, 8]\n self.data[\"U axis center blank event\"] = self.data[\"status\"][:, 9]\n self.data[\"V axis width exceeded\"] = self.data[\"status\"][:, 10]\n self.data[\"U axis width exceeded\"] = self.data[\"status\"][:, 11]\n self.data[\"Shield PMT active\"] = self.data[\"status\"][:, 12]\n # Bit 14 (Python 13) is hardware spare\n self.data[\"Upper level discriminator not exceeded\"] = self.data[\"status\"][:, 14]\n self.data[\"Lower level discriminator not exceeded\"] = self.data[\"status\"][:, 15]\n self.data[\"Event in bad region\"] = self.data[\"status\"][:, 16]\n self.data[\"Amp total on V or U = 0\"] = self.data[\"status\"][:, 17]\n self.data[\"Incorrect V center\"] = self.data[\"status\"][:, 18]\n self.data[\"Incorrect U center\"] = self.data[\"status\"][:, 19]\n self.data[\"PHA ratio test failed\"] = self.data[\"status\"][:, 20]\n self.data[\"Sum of 6 taps = 0\"] = self.data[\"status\"][:, 21]\n self.data[\"Grid ratio test failed\"] = self.data[\"status\"][:, 22]\n self.data[\"ADC sum on V or U = 0\"] = self.data[\"status\"][:, 23]\n self.data[\"PI exceeding 255\"] = self.data[\"status\"][:, 24]\n self.data[\"Event time tag is out of sequence\"] = self.data[\"status\"][:, 25]\n self.data[\"V amp flatness test failed\"] = self.data[\"status\"][:, 26]\n self.data[\"U amp flatness test failed\"] = self.data[\"status\"][:, 27]\n self.data[\"V amp saturation test failed\"] = self.data[\"status\"][:, 28]\n self.data[\"U amp saturation test failed\"] = self.data[\"status\"][:, 29]\n self.data[\"V hyperbolic test failed\"] = self.data[\"status\"][:, 30]\n self.data[\"U hyperbolic test failed\"] = self.data[\"status\"][:, 31]\n self.data[\"Hyperbola test passed\"] = np.logical_not(np.logical_or(\n self.data['U hyperbolic test failed'], self.data['V hyperbolic test failed']))\n self.data[\"Hyperbola test failed\"] = np.logical_or(\n self.data['U hyperbolic test failed'], self.data['V hyperbolic test failed'])\n\n self.obsid = self.header[\"OBS_ID\"]\n self.obs_date = self.header[\"DATE\"]\n self.target = self.header[\"OBJECT\"]\n self.detector = self.header[\"DETNAM\"]\n self.grating = self.header[\"GRATING\"]\n self.exptime = self.header[\"EXPOSURE\"]\n\n self.numevents = len(self.data[\"time\"])\n self.goodtimeevents = len(self.data[\"time\"][self.gtimask])\n self.badtimeevents = self.numevents - self.goodtimeevents\n\n self.hyperbola_passes = np.sum(np.logical_or(\n self.data['U hyperbolic test failed'], self.data['V hyperbolic test failed']))\n self.hyperbola_failures = np.sum(np.logical_not(np.logical_or(\n self.data['U hyperbolic test failed'], self.data['V hyperbolic test failed'])))\n\n if self.hyperbola_passes + self.hyperbola_failures != self.numevents:\n warnings.warn(\"Number of Hyperbola Test Failures and Passes ({}) does not equal total number of events ({}).\".format(\n self.hyperbola_passes + self.hyperbola_failures, self.numevents))\n\n if self.verbose is True:\n print(colorama.Fore.GREEN + 'Done')\n\n if self.verbose is True:\n if as_astropy_table is True:\n read_type = \"Astropy Table\"\n else:\n read_type = \"Pandas DataFrame\"\n print(colorama.Fore.CYAN + 'Observation Details: ')\n print(colorama.Fore.CYAN + 'ObsID {} | {} | {} | {} ksec | {:,} counts (level 1 events)'.format(self.obsid,\n self.target, self.detector, np.round(self.exptime/1000, 2), self.numevents))\n print(colorama.Fore.RED + '\\nConverting EVT1 file to {}...'.format(read_type), end=\" \")\n\n if as_astropy_table is False:\n # Multidimensional columns don't grok with Pandas\n self.data.remove_column('status')\n self.data = self.data.to_pandas()\n\n if self.verbose is True:\n print(colorama.Fore.GREEN + 'Done')\n\n def __str__(self):\n \"\"\"This method returns the string representation of the HRCevt1 object. It is called when the print() or str() function is invoked on an HRCevt1 object.\n\n :return: A string describing the HRCevt1 object\n :rtype: str\n \"\"\"\n return \"HRC EVT1 object with {} events. Data is packaged as a Pandas Dataframe (or an Astropy Table if as_astropy_table=True on initialization.)\".format(self.numevents)\n\n def calculate_fp_fb(self):\n \"\"\"Method to calculate the Fine Position (f_p) and normalized central tap amplitude (fb) for the HRC U- and V- axes.\n\n :return: fp_u, fb_u, fp_v, fb_v; the calculated fine positions and normalized central tap amplitudes, respectively, for the HRC U- and V- axes of the I or S detector\n :rtype: float\n \"\"\"\n\n a_u = self.data[\"au1\"] # otherwise known as \"a1\"\n b_u = self.data[\"au2\"] # \"a2\"\n c_u = self.data[\"au3\"] # \"a3\"\n\n a_v = self.data[\"av1\"]\n b_v = self.data[\"av2\"]\n c_v = self.data[\"av3\"]\n\n with np.errstate(invalid='ignore'):\n # Do the U axis\n fp_u = ((c_u - a_u) / (a_u + b_u + c_u))\n fb_u = b_u / (a_u + b_u + c_u)\n\n # Do the V axis\n fp_v = ((c_v - a_v) / (a_v + b_v + c_v))\n fb_v = b_v / (a_v + b_v + c_v)\n\n return fp_u, fb_u, fp_v, fb_v\n\n def threshold(self, img, bins, softening=None):\n \"\"\"HyperScreen (a) separates events by both axis and tap, (b) creates an\n image (a 2D histogram, with bin sizes dependent on the total number of counts\n in the observation), then (c) performs efficient image segmentation on that image\n by applying Otsu's Method (https://en.wikipedia.org/wiki/Otsu%27s_method) to\n create a bespoke threshold for each tap image. This efficiently separates the 'boomerang'\n locus for 'real' events with the 'everything else' region for background events. This function\n performs operation (c).\n\n Arguments:\n img {[type]} -- [description]\n bins {[type]} -- [description]\n \"\"\"\n\n # You don't want to be verbose in this function; it's called many times\n\n thresh_img = img.copy()\n thresh_img[img == 0] = np.nan\n\n if softening is None:\n thresh = filters.threshold_otsu(img)\n elif isinstance(softening, float):\n otsu_thresh = filters.threshold_otsu(img)\n thresh = otsu_thresh - (otsu_thresh * softening)\n\n # \"If you don't ignore the warning, you'll get a warning\" ~~ G. Tremblay\n with np.errstate(invalid='ignore'):\n thresh_img[thresh_img < thresh] = np.nan\n thresh_img[:int(bins[1] / 2), :] = np.nan\n # thresh_img[:,int(bins[1]-5):] = np.nan\n\n return thresh_img\n\n def hyperscreen(self, softening=1.0):\n \"\"\"[summary]\n\n Returns:\n [type] -- [description]\n \"\"\"\n\n data = self.data[self.data['Hyperbola test passed']]\n\n # taprange = range(data['crsu'].min(), data['crsu'].max() + 1)\n taprange_u = range(data['crsu'].min() - 1, data['crsu'].max() + 1)\n taprange_v = range(data['crsv'].min() - 1, data['crsv'].max() + 1)\n\n if self.numevents < 100000:\n bins = [50, 50] # number of bins\n else:\n bins = [200, 200]\n\n # Instantiate these empty dictionaries to hold our results\n u_axis_survivals = {}\n v_axis_survivals = {}\n\n if self.verbose is False:\n progressbar_disable = True\n elif self.verbose is True:\n progressbar_disable = False\n\n if self.verbose is True:\n print(colorama.Fore.YELLOW + \"\\nApplying Otsu's Method to every Tap-specific boomerang across U-axis taps {} through {}\".format(taprange_u[0] + 1, taprange_u[-1] + 1))\n\n skiptaps_u = []\n skiptaps_v = []\n\n for tap in progressbar(taprange_u, disable=progressbar_disable, ascii=False):\n # Do the U axis\n tapmask_u = data[data['crsu'] == tap].index.values\n if len(tapmask_u) < 20:\n skiptaps_u.append((tap + 1, len(tapmask_u)))\n continue\n keep_u = np.isfinite(data['fb_u'][tapmask_u])\n\n hist_u, xbounds_u, ybounds_u = np.histogram2d(\n data['fb_u'][tapmask_u][keep_u], data['fp_u'][tapmask_u][keep_u], bins=bins)\n thresh_hist_u = self.threshold(\n hist_u, bins=bins, softening=softening)\n\n posx_u = np.digitize(data['fb_u'][tapmask_u], xbounds_u)\n posy_u = np.digitize(data['fp_u'][tapmask_u], ybounds_u)\n hist_mask_u = (posx_u > 0) & (posx_u <= bins[0]) & (\n posy_u > -1) & (posy_u <= bins[1])\n\n # Values of the histogram where the points are\n hhsub_u = thresh_hist_u[posx_u[hist_mask_u] -\n 1, posy_u[hist_mask_u] - 1]\n pass_fb_u = data['fb_u'][tapmask_u][hist_mask_u][np.isfinite(\n hhsub_u)]\n\n u_axis_survivals[\"U Axis Tap {:02d}\".format(\n tap)] = pass_fb_u.index.values\n\n if self.verbose is True:\n print(\"\\nThe following {} U-axis taps were skipped due to a (very) low number of counts: \".format(len(skiptaps_u)))\n for skipped_tap in skiptaps_u:\n tapnum, counts = skipped_tap\n print(\"Skipped U-axis Tap {}, which had {} count(s)\".format(tapnum, counts))\n print(colorama.Fore.MAGENTA + \"\\n... doing the same for the V axis taps {} through {}\".format(taprange_v[0] + 1, taprange_v[-1] + 1))\n\n for tap in progressbar(taprange_v, disable=progressbar_disable, ascii=False):\n # Now do the V axis:\n tapmask_v = data[data['crsv'] == tap].index.values\n if len(tapmask_v) < 20:\n skiptaps_v.append((tap + 1, len(tapmask_v)))\n continue\n keep_v = np.isfinite(data['fb_v'][tapmask_v])\n\n hist_v, xbounds_v, ybounds_v = np.histogram2d(\n data['fb_v'][tapmask_v][keep_v], data['fp_v'][tapmask_v][keep_v], bins=bins)\n thresh_hist_v = self.threshold(\n hist_v, bins=bins, softening=softening)\n\n posx_v = np.digitize(data['fb_v'][tapmask_v], xbounds_v)\n posy_v = np.digitize(data['fp_v'][tapmask_v], ybounds_v)\n hist_mask_v = (posx_v > 0) & (posx_v <= bins[0]) & (\n posy_v > -1) & (posy_v <= bins[1])\n\n # Values of the histogram where the points are\n hhsub_v = thresh_hist_v[posx_v[hist_mask_v] -\n 1, posy_v[hist_mask_v] - 1]\n pass_fb_v = data['fb_v'][tapmask_v][hist_mask_v][np.isfinite(\n hhsub_v)]\n\n v_axis_survivals[\"V Axis Tap {:02d}\".format(\n tap)] = pass_fb_v.index.values\n\n if self.verbose is True:\n print(\"\\nThe following {} V-axis taps were skipped due to a (very) low number of counts: \".format(len(skiptaps_v)))\n for skipped_tap in skiptaps_v:\n tapnum, counts = skipped_tap\n print(\"Skipped V-axis Tap {}, which had {} count(s)\".format(tapnum, counts))\n\n # Done looping over taps\n\n if self.verbose is True:\n print(colorama.Fore.BLUE + \"\\nCollecting events that pass both U- and V-axis HyperScreen tests...\", end=\" \")\n\n u_all_survivals = np.concatenate(\n [x for x in u_axis_survivals.values()])\n v_all_survivals = np.concatenate(\n [x for x in v_axis_survivals.values()])\n\n # If the event passes both U- and V-axis tests, it survives\n all_survivals = np.intersect1d(u_all_survivals, v_all_survivals)\n survival_mask = np.isin(self.data.index.values, all_survivals)\n failure_mask = np.logical_not(survival_mask)\n\n num_survivals = sum(survival_mask)\n num_failures = sum(failure_mask)\n\n percent_hyperscreen_rejected = round(\n ((num_failures / self.numevents) * 100), 2)\n\n # Do a sanity check to look for lost events. Shouldn't be any.\n if num_survivals + num_failures != self.numevents:\n print(\"WARNING: Total Number of survivals and failures does \\\n not equal total events in the EVT1 file. Something is wrong!\")\n\n legacy_hyperbola_test_failures = sum(\n self.data['Hyperbola test failed'])\n percent_legacy_hyperbola_test_rejected = round(\n ((legacy_hyperbola_test_failures / self.numevents) * 100), 2)\n\n percent_improvement_over_legacy_test = round(\n (percent_hyperscreen_rejected - percent_legacy_hyperbola_test_rejected), 2)\n\n if self.verbose is True:\n print(\"Done\")\n print(colorama.Fore.GREEN + \"HyperScreen rejected\" + colorama.Fore.YELLOW + \" {}% of all events ({:,} bad events / {:,} total events)\".format(percent_hyperscreen_rejected, sum(failure_mask), self.numevents) + colorama.Fore.GREEN +\n \"\\nThe Murray+ algorithm rejects\" + colorama.Fore.MAGENTA + \" {}% of all events ({:,} bad events / {:,} total events)\".format(percent_legacy_hyperbola_test_rejected, legacy_hyperbola_test_failures, self.numevents))\n\n print(colorama.Fore.GREEN + \"As long as the results pass sanity checks, this is a POTENTIAL improvement of \\n\" +\n colorama.Fore.BLUE + \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ POTENTIAL Improvement ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\" +\n colorama.Fore.WHITE + \" {}%\\n\".format(percent_improvement_over_legacy_test) +\n colorama.Fore.BLUE + \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\")\n\n hyperscreen_results_dict = {\"ObsID\": self.obsid,\n \"Target\": self.target,\n \"Exposure Time\": self.exptime,\n \"Detector\": self.detector,\n \"Number of Events\": self.numevents,\n \"Number of Good Time Events\": self.goodtimeevents,\n \"U Axis Survivals by Tap\": u_axis_survivals,\n \"V Axis Survivals by Tap\": v_axis_survivals,\n \"U Axis All Survivals\": u_all_survivals,\n \"V Axis All Survivals\": v_all_survivals,\n \"All Survivals (event indices)\": all_survivals,\n \"All Survivals (boolean mask)\": survival_mask,\n \"All Failures (boolean mask)\": failure_mask,\n \"Percent rejected by Tapscreen\": percent_hyperscreen_rejected,\n \"Percent rejected by Hyperbola\": percent_legacy_hyperbola_test_rejected,\n \"Percent improvement\": percent_improvement_over_legacy_test\n }\n\n return hyperscreen_results_dict\n\n def hyperbola(self, fb, a, b, h):\n \"\"\"Given the normalized central tap amplitude, a, b, and h,\n return an array of length len(fb) that gives a hyperbola.\n\n Arguments:\n fb {[type]} -- [description]\n a {[type]} -- [description]\n b {[type]} -- [description]\n h {[type]} -- [description]\n\n Returns:\n [type] -- [description]\n \"\"\"\n\n hyperbola = b * np.sqrt(((fb - h)**2 / a**2) - 1)\n\n return hyperbola\n\n def legacy_hyperbola_test(self, tolerance=0.035):\n \"\"\"[summary]\n\n Keyword Arguments:\n tolerance {float} -- [description] (default: {0.035})\n\n Returns:\n [type] -- [description]\n \"\"\"\n\n # Remind the user what tolerance they're using\n # print(\"{0: <25}| Using tolerance = {1}\".format(\" \", tolerance))\n\n # Set hyperbolic coefficients, depending on whether this is HRC-I or -S\n if self.detector == \"HRC-I\":\n a_u = 0.3110\n b_u = 0.3030\n h_u = 1.0580\n\n a_v = 0.3050\n b_v = 0.2730\n h_v = 1.1\n # print(\"{0: <25}| Using HRC-I hyperbolic coefficients: \".format(\" \"))\n # print(\"{0: <25}| Au={1}, Bu={2}, Hu={3}\".format(\" \", a_u, b_u, h_u))\n # print(\"{0: <25}| Av={1}, Bv={2}, Hv={3}\".format(\" \", a_v, b_v, h_v))\n\n if self.detector == \"HRC-S\":\n a_u = 0.2706\n b_u = 0.2620\n h_u = 1.0180\n\n a_v = 0.2706\n b_v = 0.2480\n h_v = 1.0710\n # print(\"{0: <25}| Using HRC-S hyperbolic coefficients: \".format(\" \"))\n # print(\"{0: <25}| Au={1}, Bu={2}, Hu={3}\".format(\" \", a_u, b_u, h_u))\n # print(\"{0: <25}| Av={1}, Bv={2}, Hv={3}\".format(\" \", a_v, b_v, h_v))\n\n # Set the tolerance boundary (\"width\" of the hyperbolic region)\n\n h_u_lowerbound = h_u * (1 + tolerance)\n h_u_upperbound = h_u * (1 - tolerance)\n\n h_v_lowerbound = h_v * (1 + tolerance)\n h_v_upperbound = h_v * (1 - tolerance)\n\n # Compute the Hyperbolae\n with np.errstate(invalid='ignore'):\n zone_u_fit = self.hyperbola(self.data[\"fb_u\"], a_u, b_u, h_u)\n zone_u_lowerbound = self.hyperbola(\n self.data[\"fb_u\"], a_u, b_u, h_u_lowerbound)\n zone_u_upperbound = self.hyperbola(\n self.data[\"fb_u\"], a_u, b_u, h_u_upperbound)\n\n zone_v_fit = self.hyperbola(self.data[\"fb_v\"], a_v, b_v, h_v)\n zone_v_lowerbound = self.hyperbola(\n self.data[\"fb_v\"], a_v, b_v, h_v_lowerbound)\n zone_v_upperbound = self.hyperbola(\n self.data[\"fb_v\"], a_v, b_v, h_v_upperbound)\n\n zone_u = [zone_u_lowerbound, zone_u_upperbound]\n zone_v = [zone_v_lowerbound, zone_v_upperbound]\n\n # Apply the masks\n # print(\"{0: <25}| Hyperbolic masks for U and V axes computed\".format(\"\"))\n\n with np.errstate(invalid='ignore'):\n # print(\"{0: <25}| Creating U-axis mask\".format(\"\"), end=\" |\")\n between_u = np.logical_not(np.logical_and(\n self.data[\"fp_u\"] < zone_u[1], self.data[\"fp_u\"] > -1 * zone_u[1]))\n not_beyond_u = np.logical_and(\n self.data[\"fp_u\"] < zone_u[0], self.data[\"fp_u\"] > -1 * zone_u[0])\n condition_u_final = np.logical_and(between_u, not_beyond_u)\n\n # print(\" Creating V-axis mask\")\n between_v = np.logical_not(np.logical_and(\n self.data[\"fp_v\"] < zone_v[1], self.data[\"fp_v\"] > -1 * zone_v[1]))\n not_beyond_v = np.logical_and(\n self.data[\"fp_v\"] < zone_v[0], self.data[\"fp_v\"] > -1 * zone_v[0])\n condition_v_final = np.logical_and(between_v, not_beyond_v)\n\n mask_u = condition_u_final\n mask_v = condition_v_final\n\n hyperzones = {\"zone_u_fit\": zone_u_fit,\n \"zone_u_lowerbound\": zone_u_lowerbound,\n \"zone_u_upperbound\": zone_u_upperbound,\n \"zone_v_fit\": zone_v_fit,\n \"zone_v_lowerbound\": zone_v_lowerbound,\n \"zone_v_upperbound\": zone_v_upperbound}\n\n hypermasks = {\"mask_u\": mask_u, \"mask_v\": mask_v}\n\n # print(\"{0: <25}| Hyperbolic masks created\".format(\"\"))\n # print(\"{0: <25}| \".format(\"\"))\n return hyperzones, hypermasks\n\n def boomerang(self, mask=None, show=True, plot_legacy_zone=True, title=None, cmap=None, savepath=None, create_subplot=False, ax=None, rasterized=True):\n \"\"\"[summary]\n \"\"\"\n # You can plot the image on axes of a subplot by passing\n # that axis to this function. Here are some switches to enable that.\n\n if create_subplot is False:\n self.fig, self.ax = plt.subplots(figsize=(12, 8))\n elif create_subplot is True:\n if ax is None:\n self.ax = plt.gca()\n else:\n self.ax = ax\n\n if cmap is None:\n cmap = 'plasma'\n\n if mask is not None:\n self.ax.scatter(self.data['fb_u'], self.data['fp_u'],\n c=self.data['sumamps'], cmap='bone', s=0.3, alpha=0.8, rasterized=rasterized, label='All Events')\n\n frame = self.ax.scatter(self.data['fb_u'][mask], self.data['fp_u'][mask],\n c=self.data['sumamps'][mask], cmap=cmap, s=0.5, rasterized=rasterized, label='HyperScreen Accepted Events')\n\n else:\n frame = self.ax.scatter(self.data['fb_u'], self.data['fp_u'],\n c=self.data['sumamps'], cmap=cmap, s=0.5, rasterized=rasterized)\n\n if plot_legacy_zone is True:\n hyperzones, hypermasks = self.legacy_hyperbola_test(\n tolerance=0.035)\n self.ax.plot(self.data[\"fb_u\"], hyperzones[\"zone_u_lowerbound\"],\n 'o', markersize=0.3, color='black', alpha=0.8, rasterized=rasterized, label='Murray Exclusion Hyperbola')\n self.ax.plot(self.data[\"fb_u\"], -1 * hyperzones[\"zone_u_lowerbound\"],\n 'o', markersize=0.3, color='black', alpha=0.8, rasterized=rasterized)\n\n self.ax.plot(self.data[\"fb_u\"], hyperzones[\"zone_u_upperbound\"],\n 'o', markersize=0.3, color='black', alpha=0.8, rasterized=rasterized)\n self.ax.plot(self.data[\"fb_u\"], -1 * hyperzones[\"zone_u_upperbound\"],\n 'o', markersize=0.3, color='black', alpha=0.8, rasterized=rasterized)\n\n self.ax.grid(False)\n\n if title is None:\n self.ax.set_title('{} | {} | ObsID {} | {} ksec | {:,} counts'.format(\n self.target, self.detector, self.obsid, round(self.exptime / 1000, 1), self.numevents))\n else:\n self.ax.set_title(title)\n\n self.ax.set_ylim(-1.1, 1.1)\n self.ax.set_xlim(-0.1, 1.1)\n\n self.ax.set_ylabel(r'Fine Position $f_p$ $(C-A)/(A + B + C)$')\n self.ax.set_xlabel(\n r'Normalized Central Tap Amplitude $f_b$ $B / (A+B+C)$')\n\n if create_subplot is False:\n self.cbar = plt.colorbar(frame, pad=-0.005)\n self.cbar.set_label(\"SUMAMPS\")\n\n if show is True:\n plt.show()\n\n if savepath is not None:\n plt.savefig(savepath, dpi=150, bbox_inches='tight')\n\n plt.close()\n\n def image(self, masked_x=None, masked_y=None, xlim=None, ylim=None, detcoords=False, title=None, cmap=None, show=True, rasterized=True, savepath=None, create_subplot=False, ax=None, nbins=(400, 400)):\n \"\"\"Create a quicklook image, in detector or sky coordinates, of the\n observation. The image will be binned to 400x400 by default.\n\n Keyword Arguments:\n masked_x {[type]} -- [description] (default: {None})\n masked_y {[type]} -- [description] (default: {None})\n xlim {[type]} -- [description] (default: {None})\n ylim {[type]} -- [description] (default: {None})\n detcoords {bool} -- [description] (default: {False})\n title {[type]} -- [description] (default: {None})\n cmap {[type]} -- [description] (default: {None})\n show {bool} -- [description] (default: {True})\n rasterized {bool} -- [description] (default: {True})\n savepath {[type]} -- [description] (default: {None})\n create_subplot {bool} -- [description] (default: {False})\n ax {[type]} -- [description] (default: {None})\n \"\"\"\n\n if masked_x is not None and masked_y is not None:\n x = masked_x\n y = masked_y\n img_data, yedges, xedges = np.histogram2d(y, x, nbins)\n else:\n if detcoords is False:\n x = self.data['x'][self.gtimask]\n y = self.data['y'][self.gtimask]\n elif detcoords is True:\n x = self.data['detx'][self.gtimask]\n y = self.data['dety'][self.gtimask]\n img_data, yedges, xedges = np.histogram2d(y, x, nbins)\n\n extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]\n\n # Create the Figure\n styleplots()\n\n # You can plot the image on axes of a subplot by passing\n # that axis to this function. Here are some switches to enable that.\n if create_subplot is False:\n self.fig, self.ax = plt.subplots()\n elif create_subplot is True:\n if ax is None:\n self.ax = plt.gca()\n else:\n self.ax = ax\n\n self.ax.grid(False)\n\n if cmap is None:\n cmap = 'viridis'\n\n self.ax.imshow(img_data, extent=extent, norm=LogNorm(),\n interpolation=None, rasterized=rasterized, cmap=cmap, origin='lower')\n\n if title is None:\n self.ax.set_title(\"ObsID {} | {} | {} | {:,} events\".format(\n self.obsid, self.target, self.detector, self.goodtimeevents))\n else:\n self.ax.set_title(\"{}\".format(title))\n if detcoords is False:\n self.ax.set_xlabel(\"Sky X\")\n self.ax.set_ylabel(\"Sky Y\")\n elif detcoords is True:\n self.ax.set_xlabel(\"Detector X\")\n self.ax.set_ylabel(\"Detector Y\")\n\n if xlim is not None:\n self.ax.set_xlim(xlim)\n if ylim is not None:\n self.ax.set_ylim(ylim)\n\n if show is True:\n plt.show(block=True)\n\n if savepath is not None:\n plt.savefig('{}'.format(savepath))\n print(\"Saved image to {}\".format(savepath))\n\n plt.close()\n\n\ndef styleplots(): # pragma: no cover\n \"\"\"Make the plots pretty.\n \"\"\"\n\n mpl.rcParams['agg.path.chunksize'] = 10000\n\n # Make things pretty\n plt.style.use('ggplot')\n\n labelsizes = 10\n\n plt.rcParams['font.size'] = labelsizes\n plt.rcParams['axes.titlesize'] = 12\n plt.rcParams['axes.labelsize'] = labelsizes\n plt.rcParams['xtick.labelsize'] = labelsizes\n plt.rcParams['ytick.labelsize'] = labelsizes\n", "meta": {"hexsha": "5c1b29a3b8391a801ec30a4dbfbffab505cff011", "size": 30429, "ext": "py", "lang": "Python", "max_stars_repo_path": "hyperscreen/hypercore.py", "max_stars_repo_name": "granttremblay/hyperscreen", "max_stars_repo_head_hexsha": "f39029cdd835ffefb9a9a483f264f5cd76b7f58c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-07-01T12:24:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-16T23:49:07.000Z", "max_issues_repo_path": "hyperscreen/hypercore.py", "max_issues_repo_name": "granttremblay/hyperscreen", "max_issues_repo_head_hexsha": "f39029cdd835ffefb9a9a483f264f5cd76b7f58c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2019-10-12T02:38:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-21T01:20:31.000Z", "max_forks_repo_path": "hyperscreen/hypercore.py", "max_forks_repo_name": "granttremblay/hyperscreen", "max_forks_repo_head_hexsha": "f39029cdd835ffefb9a9a483f264f5cd76b7f58c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.2925764192, "max_line_length": 242, "alphanum_fraction": 0.572414473, "include": true, "reason": "import numpy,from astropy", "num_tokens": 7636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.22270012850745968, "lm_q1q2_score": 0.12175865670690453}} {"text": "\"\"\"Photometric redshift analysis. Includes a wrapper to LEPHARE and BPZ.\n\n- LEPHARE: http://www.cfht.hawaii.edu/~arnouts/LEPHARE/lephare.html\n- BPZ: http://www.stsci.edu/~dcoe/BPZ\n\"\"\"\n\nfrom __future__ import print_function\nimport os\nimport sys\nimport subprocess\nimport numpy as N\nimport pylab as P\nfrom scipy.optimize import curve_fit\nfrom astropy.io import ascii\nfrom astropy.table import Table, hstack\nfrom astropy.coordinates import SkyCoord\nfrom . import utils as cutils\n\n\nclass LEPHARE(object):\n\n \"\"\"Wrapper to the LEPHARE photometric redshift code.\n\n http://www.cfht.hawaii.edu/~arnouts/LEPHARE/lephare.html\n \"\"\"\n\n def __init__(self, magnitudes, errors, zpara=None, spectro_file=None, **kwargs):\n \"\"\"\n Run the LEPHARE progam (zphota).\n\n :param list magnitudes: Magnitudes. A list of list\n :param list errors: Error on magnitudes. Same shape as the magnitude list.\n :param string zpara: default is $LEPHAREDIR/config/zphot_megacam.para\n :param dictionnary files: A dictioannry conating the names of the\n\n Kwargs include the following list of possible parameters\n\n :param string basename: Base name for all created files\n :param string cname: Name of the studied cluster. If basename if not given,\n it will be used as base name for all created file\n :param string filters: filter list\n :param list ra: list of ra\n :param list dec: list of dec\n :param list id: list of ID\n \"\"\"\n self.data = {'mag': magnitudes, 'err': errors}\n self.kwargs = kwargs\n self.config = os.environ[\"LEPHAREDIR\"] + \\\n \"/config/zphot_megacam.para\" if zpara is None else zpara\n\n self.spectro_file = spectro_file\n # Name of created files?\n prefix = \"\"\n if 'basename' in kwargs:\n prefix = kwargs['basename'] + \"_\"\n elif 'cname' in kwargs:\n prefix = kwargs['cname'] + \"_\"\n self.files = {}\n self.files['input'] = prefix + \"zphot.in\"\n self.files['output'] = prefix + \"zphot.out\"\n self.files['pdz_output'] = prefix + \"zphot\"\n self.files['all_input'] = self.files['input'].replace('.in', '.all')\n\n # Initialize lephare output variables\n self.lephare_out = None\n self.data_out = None\n\n self.write_input()\n\n def write_input(self):\n \"\"\"\n Create and write files needed to run LEPHARE.\n\n - the input data file for LEPHARE\n - a similar file containing the sources ID along with their RA DEC.\n \"\"\"\n f = open(self.files['input'], 'w')\n if self.spectro_file is None:\n # No spectroscopic redshift file provided in config.yaml\n # --> only need the SHORT format for LePhare input file\n if 'filters' in self.kwargs:\n f.write(\"# id \" + \" \".join([\"mag_%s\" % filt for filt in self.kwargs['filters']]) +\n \" \" + \" \".join([\"err_mag_%s\" % filt for filt in self.kwargs['filters']]) +\n \"\\n\")\n for i, mags in enumerate(N.concatenate([self.data['mag'], self.data['err']]).T):\n f.write(\"%i %s\\n\" %\n (i, \" \".join([\"%.3f\" % m for m in mags])))\n\n f.close()\n print(\"INFO: Input data saved in\", self.files['input'])\n else:\n # Spectroscopic redshift file provided in config.yaml\n # --> Need to write LePhare input file in the LONG format,\n # i.e with 'context' and 'spectroz' of matching galaxies\n zspec = ZSPEC(self.spectro_file, names=[\n 'object', 'ra', 'dec', 'zspec'])\n zspec.skycoords = SkyCoord(\n zspec.data['ra'], zspec.data['dec'], unit='deg')\n skycoords_cat = SkyCoord(\n self.kwargs['ra'], self.kwargs['dec'], unit='deg')\n idx, d2d, d3d = skycoords_cat.match_to_catalog_sky(zspec.skycoords)\n zp = zspec.data['zspec'][idx]\n # identify galaxies with bad match, i.e. dist > 300 mas\n bad = N.where(d2d.mas > 300)\n zp[bad] = -99\n print(\"INFO: Using \" + str(len(idx) - N.size(bad)) +\n \" galaxies for spectroz training\")\n if 'filters' in self.kwargs:\n f.write(\"# id \" + \" \".join([\"mag_%s\" % filt for filt in self.kwargs['filters']]) +\n \" \" + \" \".join([\"err_mag_%s\" % filt for filt in self.kwargs['filters']]) +\n \" context\" + \" zspec\" + \"\\n\")\n # tells LePhare to run using the u, g, r, i and z bands.\n context = 31\n for i, mags in enumerate(N.concatenate([self.data['mag'], self.data['err']]).T):\n f.write(\"%i %s %s\\n\" % (i, \" \".join([\"%.3f\" % m for m in mags]),\n \" \".join((\"%i\" % context, \"%.3f\" % zp[i]))))\n f.close()\n if 'ra' in self.kwargs:\n f = open(self.files['all_input'], 'w')\n if 'filters' in self.kwargs is not None:\n f.write(\"# id ID RA DEC \" +\n \" \".join([\"mag_%s\" % filt for filt in self.kwargs['filters']]) + \" \" +\n \" \".join([\"err_mag_%s\" % filt for filt in self.kwargs['filters']]) +\n \"\\n\")\n for i, mags in enumerate(N.concatenate([self.data['mag'], self.data['err']]).T):\n f.write(\"%i %i %f %f %s\\n\" % (i, self.kwargs['id'][i],\n self.kwargs['ra'][i], self.kwargs['dec'][i],\n \" \".join([\"%.3f\" % m for m in mags])))\n f.close()\n print(\"INFO: All data saved in\", self.files['all_input'])\n\n def check_config(self, config=None):\n \"\"\"\n Check that the SED and filters requested for the LePhare run do exist.\n\n If not: explains where the problem is and aborts.\n \"\"\"\n if config is not None:\n if os.path.exists(config):\n self.config = config\n else:\n raise ValueError(\"%s does not exist\" % config)\n with open(self.config) as f:\n for line in f:\n if \"ZPHOTLIB\" in line:\n libs = line.split()[1].split(\",\")\n path_to_lib = os.environ[\"LEPHAREWORK\"] + \"/lib_mag/\"\n\n for lib in libs:\n lib_tmp = path_to_lib + lib + \".bin\"\n if not os.path.exists(lib_tmp):\n print(\"\\nERROR: Requested library %s does not exist \" % lib_tmp)\n print(\"INFO: Available SED libraries are:\\n \")\n for f in os.listdir(path_to_lib):\n if f.endswith(\".bin\"):\n print(f)\n print(\"--> Correct the ZPHOTLIB variable in %s\" % self.config +\n \"or generate the missing LePhare SED libraries\")\n sys.exit()\n\n for counter, lib in enumerate(libs):\n lib_tmp = path_to_lib + lib + \".doc\"\n with open(lib_tmp) as f:\n for line in f:\n if \"FILTER_FILE\" in line:\n filt_tmp = line.split()[1]\n if counter == 0:\n filt_ref = filt_tmp\n if filt_tmp != filt_ref:\n print(\"\\nERROR: Requested SED libraries %s\" % libs +\n \" have been built using different filters. Either change the \" +\n \"requested libraries or re-generate them accordingly.\")\n sys.exit()\n\n path_to_filt = os.environ[\"LEPHAREWORK\"] + \"/filt/\"\n if not os.path.exists(path_to_filt + filt_ref):\n print(\"\\nERROR: The FILTER_FILE %s used by the SED libraries %s does not exists.\" %\n (path_to_filt + filt_ref, libs))\n sys.exit()\n\n def run(self, config=None):\n \"\"\"\n Run LEPHARE.\n\n Default config file is $LEPHAREDIR/config/zphot_megacam.para.\n Can be overwritten with the config argument\n \"\"\"\n if config is not None:\n if os.path.exists(config):\n self.config = config\n else:\n raise ValueError(\"%s does not exist\" % config)\n\n # build command line\n cmd = \"zphota\"\n cmd += \" -c \" + self.config\n cmd += \" -CAT_IN \" + self.files['input']\n cmd += \" -CAT_OUT \" + self.files['output']\n cmd += \" -PDZ_OUT \" + self.files['pdz_output']\n print(\"INFO: Will run '%s'\" % cmd)\n\n self.lephare_out = subprocess.check_output(\n cmd, stderr=subprocess.STDOUT, shell=True)\n print(\"INFO: LEPHARE output summary (full output in self.lephare_out)\")\n print(\n \"\\n\".join([\" \" + zo for zo in self.lephare_out.split(\"\\n\")[-6:]]))\n\n self.data_out = ZPHOTO(self.files['output'], self.files['pdz_output'], zcode_name='lephare',\n all_input=self.files['all_input'], **self.kwargs)\n\n\nclass BPZ(object):\n\n \"\"\"\n Wrapper to the BPZ photometric redshift code.\n\n http://www.stsci.edu/~dcoe/BPZ\n \"\"\"\n\n def __init__(self, magnitudes, errors, zpara=None, spectro_file=None, **kwargs):\n \"\"\"\n Run the BPZ progam (zphota).\n\n :param list magnitudes: Magnitudes. A list of list\n :param list errors: Error on magnitudes. Same shape as the magnitude list.\n\n Kwargs include the following list of possible parameters\n\n :param string basename: Base name for all created files\n :param string cname: Name of the studied cluster. If basename if not given,\n it will be used as base name for all created file\n :param string filters: filter list\n :param list ra: list of ra\n :param list dec: list of dec\n :param list id: list of ID\n \"\"\"\n self.data = {'mag': magnitudes, 'err': errors}\n self.kwargs = kwargs\n self.config = zpara\n self.spectro_file = spectro_file\n\n # Name of created files?\n prefix = \"\"\n if 'basename' in kwargs:\n prefix = kwargs['basename'] + \"_\"\n elif 'cname' in kwargs:\n prefix = kwargs['cname'] + \"_\"\n self.files = {}\n self.files['input'] = prefix + \"bpz.in\"\n self.files['flux_comparison'] = prefix + \"bpz.flux_comparison\"\n self.files['output'] = prefix + \"bpz.bpz\"\n self.files['pdz_output'] = prefix + \"bpz.probs\"\n self.files['columns'] = prefix + \"bpz.columns\"\n self.files['all_input'] = self.files['input'].replace('.in', '.all')\n\n # Initialize BPZ output variables\n self.bpz_out = None\n self.data_out = None\n\n self.write_input()\n self.build_columns_file()\n\n def write_input(self):\n \"\"\"\n Create and write files needed to run BPZ.\n\n - the input data file for BPZ\n - a similar file containing the sources ID along with their RA DEC.\n \"\"\"\n f = open(self.files['input'], 'w')\n if 'filters' in self.kwargs:\n f.write(\"# id \" + \" \".join([\"mag_%s\" % filt for filt in self.kwargs['filters']]) +\n \" \" + \" \".join([\"err_mag_%s\" % filt for filt in self.kwargs['filters']]) +\n \"\\n\")\n for i, mags in enumerate(N.concatenate([self.data['mag'], self.data['err']]).T):\n f.write(\"%i %s\\n\" % (i, \" \".join([\"%.3f\" % m for m in mags])))\n\n f.close()\n print(\"INFO: Input data saved in\", self.files['input'])\n if 'ra' in self.kwargs:\n f = open(self.files['all_input'], 'w')\n if 'filters' in self.kwargs is not None:\n f.write(\"# id ID RA DEC \" +\n \" \".join([\"mag_%s\" % filt for filt in self.kwargs['filters']]) + \" \" +\n \" \".join([\"err_mag_%s\" % filt for filt in self.kwargs['filters']]) +\n \"\\n\")\n for i, mags in enumerate(N.concatenate([self.data['mag'], self.data['err']]).T):\n f.write(\"%i %i %f %f %s\\n\" % (i, self.kwargs['id'][i],\n self.kwargs['ra'][i], self.kwargs['dec'][i],\n \" \".join([\"%.3f\" % m for m in mags])))\n f.close()\n print(\"INFO: All data saved in\", self.files['all_input'])\n\n# def build_columns_file(self, prefix='HSC-', sufix='',\n# filters=None, ref='i', z_s=False):\n def build_columns_file(self, prefix='CFHT_megacam_', sufix='p',\n filters=None, ref='i', z_s=False):\n \"\"\"Build and write the 'columns' file.\n\n Hardcoded for test purpose.\n \"\"\"\n if filters is None: # set the default values as the CFHT ones\n filters = ['u', 'g', 'r', 'i', 'z']\n# filters = ['g', 'r', 'i', 'z', 'Y']\n f = open(self.files['columns'], 'w')\n f.write(\"# Filter columns AB/Vega zp_error zp_offset\\n\")\n for i, filt in enumerate(filters):\n f.write(\"%s%s%s %i, %i AB 0.01 0.00\\n\" %\n (prefix, filt, sufix, i + 2, i + len(filters) + 2))\n if z_s:\n f.write(\"Z_S %i\\n\" % (len(filters) * 2 + 2))\n f.write(\"M_0 %i\\n\"\n % [j + 2 for j, filt in enumerate(filters) if filt == ref][0])\n f.write(\"ID 1\\n\")\n f.close()\n\n def run(self):\n \"\"\"\n Run BPZ.\n\n Configuration file must exist in the current directory.\n\n .. todo:: Build the configuration file on the fly (the .columns)\n \"\"\"\n if not os.getenv('BPZPATH'):\n mess = \"BPZPATH if not defined. Please install BPZ \"\n mess += \"(see http://www.stsci.edu/~dcoe/BPZ/install.html).\"\n raise IOError(mess)\n\n if not os.path.exists(self.files['columns']):\n raise IOError(\"%s does not exist\" % self.files['columns'])\n\n # build command line options from param file\n if self.config is not None:\n opt_arr = N.genfromtxt(self.config, dtype=None)\n option = ['-' + opt_arr[i, 0].decode() + ' ' + opt_arr[i, 1].decode()\n for i in N.arange(len(opt_arr))]\n options = ' '.join(e for e in option)\n else:\n options = ''\n\n # build command line\n# cmd = \"python $BPZPATH/bpz.py %s \" % self.files['input'] + options\n cmd = \"bpz_run.py %s \" % self.files['input'] + options\n print(\"INFO: Will run '%s'\" % cmd)\n\n self.bpz_out = subprocess.check_output(\n cmd, stderr=subprocess.STDOUT, shell=True)\n print(\"INFO: BPZ output summary (full output in self.bpz_out)\")\n# print(\"\\n\".join([\" \" + zo for zo in self.bpz_out.split(\"\\n\")[:20]]))\n\n self.data_out = ZPHOTO(self.files['output'], self.files['pdz_output'],\n zcode_name='bpz', all_input=self.files['all_input'],\n **self.kwargs)\n\n\nclass ZPHOTO(object):\n\n \"\"\"Read photoz code (LePhare, BPZ) output file and creates/saves astropy tables.\"\"\"\n\n def __init__(self, zphot_output, zphot_pdz_output, zcode_name=None, all_input=None, **kwargs):\n \"\"\"Read the photoz progam (LePhare, BPZ, ...) output.\"\"\"\n self.files = {}\n self.files['output'] = zphot_output\n self.files['pdz_output'] = zphot_pdz_output\n self.kwargs = kwargs\n if all_input is not None:\n self.files['input'] = all_input\n self.read_input()\n self.code = zcode_name\n self.read()\n\n def read(self):\n \"\"\"Read the output.\"\"\"\n f = open(self.files['output'], 'r')\n self.data_array = N.loadtxt(self.files['output'], unpack=True)\n\n if self.code == 'lephare':\n self.header = [l for l in f if l.startswith('#')]\n f.close()\n self.variables = N.loadtxt(os.getenv('LEPHAREDIR') +\n \"/config/zphot_output.para\", dtype='string')\n self.data_dict = {v: a for v, a in zip(\n self.variables, self.data_array)}\n self.nsources = len(self.data_dict['Z_BEST'])\n self.pdz_zbins = N.loadtxt(\n self.files['pdz_output'] + '.zph', unpack=True)\n self.pdz_val = N.loadtxt(\n self.files['pdz_output'] + '.pdz', unpack=True)\n\n elif self.code == 'bpz':\n self.header = [l for l in f if l.startswith('##')]\n f.seek(0)\n self.variables = [l[4:].replace(' ', '').split(\n '\\n')[0] for l in f if l.startswith('# ')]\n f.seek(0)\n # BPZ does not provide a zbins file.\n # Needs to create it from zmin, zmax and dz specified in output file\n zmin = float([line.split('=')[1]\n for line in f if 'ZMIN' in line][0])\n f.seek(0)\n zmax = float([line.split('=')[1]\n for line in f if 'ZMAX' in line][0])\n f.seek(0)\n dz = float([line.split('=')[1] for line in f if 'DZ' in line][0])\n f.close()\n\n self.data_dict = {v: a for v, a in zip(\n self.variables, self.data_array)}\n self.nsources = len(self.data_dict['Z_B'])\n self.pdz_zbins = N.arange(zmin, zmax + dz, dz)\n self.pdz_val = N.loadtxt(self.files['pdz_output'], unpack=True,\n usecols=N.arange(1, len(self.pdz_zbins) + 1))\n\n def save_zphot(self, file_out, path_output, overwrite=False):\n \"\"\"Save the output of photoz code (z_best, chi^2, pdz) into astropy table.\"\"\"\n # Duplicates the zbins vector for each object.\n # It is redundant information but astropy tables need each field to have the\n # same size. Or maybe I'm missing something.\n zbins = N.tile(self.pdz_zbins, (len(self.kwargs['id']), 1))\n\n # Converts LePhare or BPZ likelihood to actual probability density\n for i in N.arange(len(self.pdz_val.T)):\n norm = N.trapz(self.pdz_val[:, i], self.pdz_zbins)\n new_pdz_val = self.pdz_val[:, i] / norm\n self.pdz_val[:, i] = new_pdz_val\n\n # Creates astropy table to be saved in path_output of file_out\n new_tab = hstack([Table([self.kwargs['id']]), Table([self.kwargs['ra']]),\n Table([self.kwargs['dec']]), Table(self.data_dict),\n Table([zbins], names=['zbins']),\n Table([self.pdz_val.T], names=['pdz'])],\n join_type='inner')\n\n # Rename BPZ Z_B to Z_BEST to match LePhare\n if 'Z_B' in new_tab.keys():\n new_tab.rename_column('Z_B', 'Z_BEST')\n\n # overwrite keyword of data.write(file,path) does not only overwrites\n # the data in path, but the whole file, i.e. (we lose all other\n # paths in the process) --> overwrite_or_append (see above)\n\n cutils.overwrite_or_append(file_out, path_output, new_tab, overwrite=overwrite)\n\n print(\"INFO: \", self.code, \"data saved in\", file_out, \"as\", path_output)\n\n def read_input(self):\n \"\"\"Read the input.\"\"\"\n data = N.loadtxt(self.files['input'], unpack=True)\n f = open(self.files['input'], 'r')\n l = f.readlines()[0]\n self.input_data = {k: d for k, d in zip(l[2:-1].split(), data)}\n f.close()\n\n def hist(self, param, **kwargs):\n \"\"\"Plot histograms.\n\n Possible kwargs\n\n :params float minv: Lower value of the histogram\n :params float maxv: Upper value of the histogram\n :params int nbins: Number of bins. Default is 10.\n :params string xlabel: An xlbal for the figure\n :params string title: A title for the figure\n :params float zclust: Redshift of the studies cluster\n \"\"\"\n # Get the data and apply some cut if asked\n pval = self.data_dict[param]\n filt = N.array([1] * len(pval), dtype='bool')\n if 'minv' in kwargs:\n filt &= (pval >= kwargs['minv'])\n if 'maxv' in kwargs:\n filt &= (pval <= kwargs['maxv'])\n pval = pval[filt]\n\n # Plot the histogram\n fig = P.figure()\n ax = fig.add_subplot(111, ylabel='#')\n ax.hist(pval, bins=kwargs['nbins'] if 'nbins' in kwargs else 10)\n xlabel = kwargs['xlabel'] if 'xlabel' in kwargs else param\n ax.set_xlabel(xlabel)\n if 'title' in kwargs:\n ax.set_title(kwargs['title'])\n if 'zclust' in kwargs:\n ax.axvline(kwargs['zclust'], color='r',\n label='Cluster redshift (%.4f)' % kwargs['zclust'])\n ax.legend(loc='best')\n\n # Save the figure\n fig.savefig(self.files['output'].replace(\n '.out', '') + \"_\" + xlabel + \"_zphot_hist.png\")\n\n def plot(self, px, py, **kwargs):\n \"\"\"\n Plot x vs. y.\n\n Possible kwargs are:\n :params float minx: lower limit of the x axis\n :params float maxx: upper limit of the x axis\n :params float miny: lower limit of the y axis\n :params float maxy: upper limit of the y axis\n :params string xlabel: label of the x axis\n :params string ylabel: label of the y axis\n :params string title: title of the figure\n \"\"\"\n pvalx = self.data_dict[px]\n pvaly = self.data_dict[py]\n filt = N.array([1] * len(pvalx), dtype='bool')\n if 'minx' in kwargs and kwargs['minx'] is not None:\n filt &= (pvalx >= kwargs['minx'])\n if 'maxx' in kwargs and kwargs['maxx'] is not None:\n filt &= (pvalx <= kwargs['maxx'])\n if 'miny' in kwargs and kwargs['miny'] is not None:\n filt &= (pvaly >= kwargs['miny'])\n if 'maxy' in kwargs and kwargs['maxy'] is not None:\n filt &= (pvaly <= kwargs['maxy'])\n pvalx, pvaly = pvalx[filt], pvaly[filt]\n fig = P.figure()\n ax = fig.add_subplot(111)\n ax.scatter(pvalx, pvaly)\n if 'xlabel' in kwargs and kwargs['xlabel'] is not None:\n px = kwargs['xlabel']\n if 'ylabel' in kwargs and kwargs['ylabel'] is not None:\n py = kwargs['ylabel']\n ax.set_xlabel(px)\n ax.set_ylabel(py)\n if 'title' in kwargs and kwargs['title'] is not None:\n ax.set_title(kwargs['title'])\n\n if 'figname' in kwargs and kwargs['figname'] is not None:\n fig.savefig(self.files['output'].replace(\n '.out', '') + \"_%s_vs_%s_zphot.png\" % (py, px))\n else:\n fig.savefig(\"%s_vs_%s_zphot.png\" % (py, px))\n\n def plot_map(self, title=None, zmin=0, zmax=999):\n \"\"\"Plot the redshift sky-map.\"\"\"\n if not hasattr(self, 'input_data'):\n print(\"WARNING: No input data given. Cannot plot the redshift map.\")\n return\n\n ra, dec, redshift = self.input_data['RA'], self.input_data['DEC'], self.data_dict['Z_BEST']\n\n # redshift has to be >= 0\n filt = (redshift >= zmin) & (redshift < zmax)\n ra, dec, redshift = ra[filt], dec[filt], redshift[filt]\n\n fig = P.figure()\n ax = fig.add_subplot(111, xlabel='RA (deg)', ylabel='DEC (deg)')\n scat = ax.scatter(ra, dec, c=redshift, cmap=(P.cm.jet))\n cb = fig.colorbar(scat)\n cb.set_label('Photometric redshift')\n if title is not None:\n ax.set_title(title)\n ax.set_xlim(xmin=min(ra) - 0.001, xmax=max(ra) + 0.001)\n ax.set_ylim(ymin=min(dec) - 0.001, ymax=max(dec) + 0.001)\n fig.savefig(self.files['output'].replace(\n '.out', '') + \"_redshift_map.png\")\n\n\ndef dict_to_array(d, filters='ugriz'):\n \"\"\"Transform a dictionnary into a list of arrays.\"\"\"\n return N.array([N.array(d[f]) for f in filters])\n\n\nclass ZSPEC(object):\n\n \"\"\"Compare spectroscopic and photometric redshifts.\"\"\"\n\n def __init__(self, sfile, names, unit='deg'):\n \"\"\"Read the input data file and organize the data.\n\n :param str sfile: File containing the spectroscopic redshift\n :param list names: A list of names for the columns. You must use 'ra' and 'dec'\n for the coordinates.\n :param str unit: Unit of the given coordinates ('deg', 'rad'). Should be understandable by\n astropy.coordinates.SkyCoord\n\n The spectroscopic redshift must be named 'zspec'.\n \"\"\"\n self.sfile = sfile\n self.data = ascii.read(sfile, names=names)\n if 'ra' not in self.data.keys():\n raise IOError(\"RA coordinate must be called 'ra'\")\n elif 'dec' not in self.data.keys():\n raise IOError(\"DEC coordinate must be called 'dec'\")\n elif 'zspec' not in self.data.keys():\n raise IOError(\"Spectroscopic reshift must be 'zspec'\")\n\n # Check whether duplicate galaxies exist in the spectroz sample\n # and remove them. Ideally would average out the various occurances.\n # (To be done later)\n ra = ['{:.20}'.format(x) for x in self.data['ra']]\n dec = ['{:.20}'.format(x) for x in self.data['dec']]\n radec = N.core.defchararray.add(ra, dec)\n unique_radec, good = N.unique(radec, return_index=True)\n if len(unique_radec) < len(radec):\n print(\"INFO: There are \" + str(len(radec) - len(unique_radec)) +\n \" duplicate galaxies in spectroz sample. They are removed.\")\n bad = N.delete(N.arange(len(self.data)), good)\n self.data.remove_rows(bad)\n\n self.skycoords = SkyCoord(self.data['ra'], self.data['dec'], unit=unit)\n self.zphot = self.skycoords_phot = self.match = None\n\n def load_zphot(self, ra, dec, zphot, unit='deg'):\n \"\"\"Load the photometric informations and match them to the spectro ones.\n\n :param list ra: List of RA coordinates\n :param list dec: List of DEC coordinates\n :param list zphot: List of photometric redshift\n :param list unit: List of RA coordinates\n\n All lists must have the same length.\n \"\"\"\n assert len(ra) == len(dec) == len(zphot)\n self.zphot = Table([ra, dec, zphot], names=['ra', 'dec', 'zphot'])\n self.skycoords_phot = SkyCoord(ra, dec, unit=unit)\n idx, d2d, d3d = self.skycoords.match_to_catalog_sky(\n self.skycoords_phot)\n self.match = Table([idx, d2d.marcsec, d3d], names=['idx', 'd2d', 'd3d'],\n meta={'description': ['Indices into first catalog.',\n 'On-sky separation between the '\n 'closest match for each element',\n '3D distance between the closest'\n 'match for each element'],\n 'unit': ['', 'marcsec', '']})\n\n def plot(self, cut=300, path_to_png=None):\n \"\"\"Plot a sky-map of the matches.\"\"\"\n if self.match is None:\n raise IOError(\n \"ERROR: You must load the photometric data first (load_zphot).\")\n\n zspec = self.data['zspec']\n zphot = self.zphot['zphot'][self.match['idx']]\n sdist = N.array(self.match['d2d'])\n filt = sdist < cut\n zspec, zphot, sdist = [x[filt] for x in [zspec, zphot, sdist]]\n\n fig = P.figure(figsize=(15, 8))\n\n # z-phot as a function of z-spec\n ax = fig.add_subplot(121, xlabel='Z-spec', ylabel='Z-phot')\n ax.set_xlim([0, 1.5])\n ax.set_ylim([0, 3.5])\n scat = ax.scatter(zspec, zphot, c=sdist, cmap=(P.cm.copper))\n ax.plot(N.arange(int(max(zspec + 1))),\n N.arange(int(max(zspec + 1))), c='red')\n cb = fig.colorbar(scat)\n cb.set_label('On-sky distance (marcsec)')\n ax.set_title(\"%i galaxies\" % len(self.match[filt]))\n\n # z-phot - zspec as a function of sources on-sky distances\n ax = fig.add_subplot(122, xlabel='On-sky distance',\n ylabel='(Z-phot - Z-spec)')\n scat = ax.scatter(sdist, zphot - zspec, color='k')\n ax.set_title(\"%i galaxies\" % len(self.match[filt]))\n ax.set_xscale('log')\n ax.set_xlim([1., 1.e6])\n ax.set_ylim([-1., 3.5])\n\n if path_to_png is not None:\n fig.savefig(path_to_png)\n\n fig = P.figure()\n\n # radec scatter plot of all catalogue and zspec galaxies\n ax = fig.add_subplot(121, xlabel='ra', ylabel='dec')\n ax.scatter(self.skycoords_phot.ra, self.skycoords_phot.dec,\n color='k', label='Photo-z', s=15)\n ax.scatter(self.skycoords.ra, self.skycoords.dec,\n color='r', label='Spectro-z', s=12)\n\n # radec scatter plot of matched catalogue and zspec galaxies, within the cut criterion\n ax = fig.add_subplot(122, xlabel='ra', ylabel='dec')\n ax.scatter(self.skycoords_phot.ra[self.match['idx'][filt]],\n self.skycoords_phot.dec[self.match['idx'][filt]],\n color='k', label='Photo-z', s=5)\n ax.scatter(self.skycoords.ra[filt], self.skycoords.dec[filt],\n color='r', label='Spectro-z', s=5)\n\n if path_to_png is not None:\n fig.savefig(path_to_png.replace('.png', '_map.png'))\n\n P.show()\n\n def scatter(self, zclust, cluster=None, cut=0.1, stability=False):\n \"\"\"Redshift scatter in the cluster.\n\n Plot the spectroscopic redshift distribution and apply a gaussian fit.\n \"\"\"\n # Apply selection\n zspec = self.data['zspec'][N.abs(self.data['zspec'] - zclust) < cut]\n\n # The gaussian fit\n hist, bin_edges = N.histogram(zspec, bins=len(zspec) / 4)\n bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2\n\n # Use initial guess for the fitting coefficients (A, mu and sigma above)\n coeff = curve_fit(gauss, bin_centers, hist, p0=[\n N.max(hist[0]), zclust, 0.3])[0]\n\n # Plot\n fig = P.figure()\n ax = fig.add_subplot(111, xlabel='Z-spec', ylabel='#',\n title='' if cluster is None else cluster +\n ', %i object included (cut=%.2f)' % (len(zspec), cut))\n ax.hist(zspec, bins=len(zspec) / 4, histtype='stepfilled')\n ax.axvline(zclust, color='r', label='Z-cluster (%.3f)' % zclust, lw=2)\n ax.plot(bin_centers, gauss(bin_centers, *coeff),\n label='Gaussian fit (mean, std)=(%.3f, %.3f)' %\n (coeff[1], N.abs(coeff[2])), lw=2, color='k')\n ax.legend(loc='best')\n\n if stability:\n cuts = [0.5, 0.1, 0.05, 0.03]\n z, ze = zip(*[self.scatter(zclust, cluster=cluster, cut=c)\n for c in cuts])\n fig = P.figure()\n ax = fig.add_subplot(111, xlabel='Selection cut around cluste rredshift',\n ylabel='Estimated redshift',\n title='' if cluster is None else cluster +\n ', %i object included (cut=%.2f)' % (len(zspec), cut))\n ax.axhline(N.mean(z), label='Average value', color='r', lw=2)\n ax.errorbar(cuts, z, yerr=ze, label='Individual fits', color='k',\n capsize=20, elinewidth=3)\n ax.legend(loc='best')\n print(\"INFO: Stability over the followed range of selection cuts:\")\n print(\" \", cuts)\n print(\"INFO: Input redshift: %.4f\" % zclust)\n print(\"INFO: Average redshift: %.4f =/- %.4f\" %\n (N.mean(z), N.sqrt(N.std(z)**2 + N.mean(ze)**2)))\n P.show()\n return N.mean(z), N.sqrt(N.std(z)**2 + N.mean(ze)**2)\n P.show()\n return coeff[1], N.abs(coeff[2])\n\n\ndef gauss(x, *p):\n \"\"\"Model function to be used to fit a gaussian distribution.\"\"\"\n A, mu, sigma = p\n return A * N.exp(- (x - mu) ** 2 / (2. * sigma ** 2))\n", "meta": {"hexsha": "5322fac4c465a0c8ba7d42177c22293b71ffdcfd", "size": 32134, "ext": "py", "lang": "Python", "max_stars_repo_path": "clusters/zphot.py", "max_stars_repo_name": "nicolaschotard/Clusters", "max_stars_repo_head_hexsha": "75b2adf46375a4b797a93a0727b14e5f99da3f60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2016-10-31T18:26:07.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-15T03:54:54.000Z", "max_issues_repo_path": "clusters/zphot.py", "max_issues_repo_name": "nicolaschotard/Clusters", "max_issues_repo_head_hexsha": "75b2adf46375a4b797a93a0727b14e5f99da3f60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2016-12-06T14:23:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-12T07:07:26.000Z", "max_forks_repo_path": "clusters/zphot.py", "max_forks_repo_name": "nicolaschotard/Clusters", "max_forks_repo_head_hexsha": "75b2adf46375a4b797a93a0727b14e5f99da3f60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-11-06T14:10:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-29T13:19:42.000Z", "avg_line_length": 43.1908602151, "max_line_length": 100, "alphanum_fraction": 0.5358809983, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 7984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.23934935817440725, "lm_q1q2_score": 0.12154444378857679}} {"text": "#!/usr/bin/env python\n\n\"\"\" A set of tools for modelling the antenna reponse and for callibrating the amplitude vs frequency of the antennas\nbased on pyCRtools. see Schellart et al. Detecting cosmic rays with the LOFAR radio telescope, and Nelles et al. Calibrating the absolute amplitude scale for air showers measured at LOFAR\n\nNote: LBA_ant_calibrator still needs some work.\n\nauthor: Brian hare\n\"\"\"\n\n##internal\nimport glob\nfrom pickle import load\nimport datetime\nfrom os.path import dirname, abspath\n\n##external \nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy.interpolate import interp1d\nfrom scipy.interpolate import RegularGridInterpolator, pchip_interpolate, PchipInterpolator\nfrom scipy.io import loadmat\n\n\n\n##mine\nfrom LoLIM.utilities import processed_data_dir, MetaData_directory, RTD, SId_to_Sname, v_air\nimport LoLIM.transmogrify as tmf\nimport LoLIM.IO.metadata as md\n\n\n\n# def get_absolute_calibration(frequencies, freq_mode='30-90'):\n# \"\"\"this function returns the absolute calibration given a set of frequencies (in Hz). Note that this is the INVERSE of the factor in pyCRtools. You should multiply this by the jones matrix to set the absolute correction\n# Note this is spefically derived for 80m cable lengths, which is consistant with relative calibraiton below.\n \n# If frequency is outside 30-80 MHz. A is assumed to be constant outside 30-80. Cable lengths and RCU gain are correct between 10-90 MHz. Assumed to be constant outside 10-90.\n \n# Returns 0 where frequencies<0\n \n# freq-mode: can be '30-90' or '10-90'. This sets which RCU setting is used. This should probably be the same as the data set being used, but probably doesn't matter.\n# The calibration was derived with 30-80, which is default.\"\"\"\n \n# A = [\n \n# ]\n \n\n\nclass aartfaac_LBA_model:\n\n def __init__(self, model_loc=None, R=700, C=15e-12, mode=\"LBA_OUTER\"):\n if model_loc is None:\n model_loc = dirname(abspath(__file__)) + '/AARTFAAC_LBA_MODEL/'\n \n self.model_loc = model_loc\n self.antenna_mode = mode\n \n self.fine_model_loc = self.model_loc + \"LBA_core_fine\"\n self.course_model_loc = self.model_loc + \"LBA_core\"\n \n ## get base data, assume is same between models\n data_fine = loadmat( self.fine_model_loc , variable_names=['Positions', 'Theta', 'Phi', 'Freq', 'Zant', 'g_z'] ) ## Zant is antenna impedences, g_z is angular dependence\n self.AART_ant_positions = data_fine['Positions']\n self.AART_thetas = data_fine['Theta'][0] ## zenithal angle in degrees\n self.AART_Phis = data_fine['Phi'][0] ## azimuthal angle in degrees\n \n self.AART_fineFreqs = data_fine['Freq'][0]\n fine_gz = data_fine['g_z']\n fine_Zant = data_fine['Zant']\n \n data_course = loadmat( self.course_model_loc , variable_names=['Freq', 'Zant', 'g_z'] )\n self.AART_courseFreqs = data_course['Freq'][0]\n course_gz = data_course['g_z']\n course_Zant = data_course['Zant']\n \n \n \n \n \n ### figure out how to fold fine and course models together\n fineFreq_low = self.AART_fineFreqs[0]\n # fineFreq_high = self.AART_fineFreqs[-1]\n \n freqs = []\n course_range_1 = [0]\n fine_range = []\n course_range_2 = []\n \n ## first we search AART_courseFreqs to find highest frequency lower than fine-range, adding them to the frequency list\n for i in range(len(self.AART_courseFreqs)): \n Fc = self.AART_courseFreqs[i]\n if Fc < fineFreq_low:\n freqs.append(Fc)\n else:\n break\n course_range_1.append(i)\n fine_range.append(i)\n \n ## add all fine frequencies\n freqs += list(self.AART_fineFreqs)\n fine_range.append(len(freqs))\n course_range_2.append(len(freqs))\n \n ## find first course frequency greater than fine frequencies\n for i in range(i, len(self.AART_courseFreqs)):\n if self.AART_courseFreqs[i] > freqs[-1]:\n break\n \n ## add rest of course frequencies to list\n freqs += list(self.AART_courseFreqs[i:]) \n course_range_2.append(len(freqs))\n \n self.all_frequencies = np.array(freqs, dtype=np.double)\n self.course_frequencyRange_low = np.array(course_range_1)\n self.fine_frequencyRange = np.array(fine_range)\n self.course_frequencyRange_high = np.array(course_range_2)\n \n \n \n #### combine antenna impedences\n num_ants = len(fine_Zant)\n num_thetas = len(self.AART_thetas)\n num_phis = len(self.AART_Phis)\n num_freqs = len(self.all_frequencies)\n \n self.antenna_Z = np.empty([num_ants, num_ants, num_freqs ], dtype=np.complex)\n \n self.antenna_Z[:,:, :self.course_frequencyRange_low[1]] = course_Zant[:,:, :self.course_frequencyRange_low[1]]\n self.antenna_Z[:,:, self.fine_frequencyRange[0]:self.fine_frequencyRange[1]] = fine_Zant[:,:, :]\n self.antenna_Z[:,:, self.fine_frequencyRange[1]:] = course_Zant[:,:, self.fine_frequencyRange[1]-len(self.all_frequencies):]\n \n \n self.total_impedence = np.empty((num_ants, num_ants, num_freqs), dtype=np.complex)\n self.set_RC( R, C ) ## this sets self.total_impedence\n \n \n \n \n \n ### now we combine total G_z, which is voltage on antenna\n self.total_Gz = np.empty( (num_ants,2,num_thetas,num_phis,num_freqs), dtype=np.complex )\n \n # for ant_i in range(num_ants):\n # for pol_i in range(2):\n self.total_Gz[:,:, :,:, : self.course_frequencyRange_low[1]] = course_gz[:,:, :,:, : self.course_frequencyRange_low[1]]\n self.total_Gz[:,:, :,:, self.fine_frequencyRange[0] : self.fine_frequencyRange[1]] = fine_gz [:,:, :,:, : ]\n self.total_Gz[:,:, :,:, self.fine_frequencyRange[1] :] = course_gz[:,:, :,:, self.fine_frequencyRange[1]-len(self.all_frequencies): ]\n \n \n def get_LNA_filter(self):\n \"\"\"given the antenna mode, return two things. First is np.array of indecies of LNAs that are on, second is np.array of LNAs that are off\"\"\"\n \n station_ant_positions = []\n for station in ['CS002', 'CS003', 'CS004', 'CS005', 'CS006', 'CS007']:\n station_ant_positions.append( md.convertITRFToLocal( md.getItrfAntennaPosition(station, self.antenna_mode) )[::2, :] )\n \n found_indeces = []\n unfound_indeces = []\n \n AARFAACC_X_locations = self.AART_ant_positions[0]\n AARFAACC_Y_locations = self.AART_ant_positions[1]\n \n err2 = 0.1*0.1\n for AAR_i in range(len(AARFAACC_X_locations)):\n \n found = False\n for stat_ant_XYZ in station_ant_positions:\n for XYZ in stat_ant_XYZ:\n KX, KY, KZ = XYZ\n AX = AARFAACC_X_locations[AAR_i]\n AY = AARFAACC_Y_locations[AAR_i]\n R2 = (AX-KX)**2 + (AY-KY)**2\n if R2 90:\n zenith = 90\n \n while azimuth<0:\n azimuth += 360\n while azimuth>360:\n azimuth -= 360\n \n # good_frequency_filter = np.logical_and(frequencies>=self.freq_bounds[0], frequencies=self.freq_bounds[-1]:\n return_matrices[fi, 0,0] = freq_fill\n return_matrices[fi, 1,1] = freq_fill\n return_matrices[fi, 0,1] = 0.0\n return_matrices[fi, 1,0] = 0.0\n else:\n return_matrices[fi, 0,0] = J00( (zenith,azimuth,f) )\n return_matrices[fi, 0,1] = J01( (zenith,azimuth,f) )\n return_matrices[fi, 1,0] = J10( (zenith,azimuth,f) )\n return_matrices[fi, 1,1] = J11( (zenith,azimuth,f) )\n \n # print(fi)\n # M = return_matrices[fi]\n # print(\"J:\", M)\n # print( M[ 0,0]*M[ 1,1] - M[ 0,1]*M[ 1,0] )\n # print()\n \n return return_matrices\n \n def get_antenna_model(self, ant_i):\n \"\"\"note: ant_i should be internal index!\"\"\"\n \n \n X_ant_i = int(ant_i/2)*2\n \n KX, KY = self.AART_ant_positions[:, X_ant_i]\n \n num_thetas = len(self.AART_thetas)\n num_phis = len(self.AART_Phis)\n num_frequencies = len( self.all_frequencies)\n num_antennas = len( self.total_Gz )\n \n #### some setup\n ## phase shifter to remove geometric delay\n shifter = np.empty([num_thetas, num_phis, num_frequencies ], dtype=np.complex)\n for zi in range( num_thetas ):\n for ai in range( num_phis ):\n Zenith = self.AART_thetas[zi]/RTD\n Azimuth = self.AART_Phis[ai]/RTD\n dt = ( KX*np.sin(Zenith)*np.cos(Azimuth) + KY*np.sin(Zenith)*np.sin(Azimuth))/v_air\n np.exp( self.all_frequencies*(1j*2*np.pi*(-dt)), out=shifter[zi,ai] )\n \n\n \n ## frequency interpolation\n frequency_bin = 0.5e6\n minF = self.all_frequencies[0]\n maxF = self.all_frequencies[-1]\n num_interpolant_freqs = int((maxF+minF)/frequency_bin )\n interpolant_frequencies = np.linspace(minF, maxF, num_interpolant_freqs)\n \n ## memory\n tmp1 = np.empty( (num_antennas,num_frequencies), dtype=np.complex )\n tmp2 = np.empty(num_frequencies, dtype=np.complex )\n tmp3 = np.empty(num_frequencies, dtype=np.double )\n\n def make_interpolant(antenna, polarization):\n \"\"\" antenna is 0 or 1 for X or Y, pol is 0 or 1 for zenith or azimithal component\"\"\"\n nonlocal tmp1, tmp2, tmp3\n \n antenna = antenna + X_ant_i\n \n grid = np.empty([num_thetas, num_phis, len(interpolant_frequencies) ], dtype=np.complex)\n \n for theta_i in range(num_thetas):\n for phi_i in range(num_phis):\n \n ## dot product between voltages and impedences\n tmp1[:,:] = self.total_Gz[:, polarization,theta_i,phi_i, :] \n tmp1 *= self.total_impedence[antenna, :, :] # this shouldn't matter??\n # tmp1 *= self.total_impedence[:, antenna, :]\n \n \n \n np.sum( tmp1, axis=0, out = tmp2 )\n \n ## shift phase due to arival direction\n tmp2 *= shifter[theta_i,phi_i]\n \n ## interpolate amplitude and phase\n np.abs(tmp2, out=tmp3)\n interp_ampltude = pchip_interpolate(self.all_frequencies,tmp3, interpolant_frequencies)\n \n # if theta_i==0 and phi_i==0:\n # print('amp')\n # plt.plot( interpolant_frequencies, interp_ampltude, 'o' )\n # plt.plot( self.all_frequencies, tmp3, 'o' )\n # plt.show()\n \n angles = np.angle(tmp2)\n angles = np.unwrap(angles)\n \n interp_angle = pchip_interpolate(self.all_frequencies,angles, interpolant_frequencies)\n \n # if theta_i==0 and phi_i==0:\n # print('angle')\n # plt.plot( interpolant_frequencies, interp_angle, 'o' )\n # plt.plot( self.all_frequencies, angles, 'o' )\n # plt.show()\n \n\n \n ## now convert back to real and imag\n interp_angle = interp_angle*1j\n np.exp( interp_angle, out=grid[theta_i,phi_i] )\n grid[theta_i,phi_i] *= interp_ampltude\n \n ## correct for different in definition\n if polarization==0: ## zenith points in oppisite directions in two models??\n grid *= -1\n ## and final angle-frequency interpolant\n interpolant = RegularGridInterpolator((self.AART_thetas, self.AART_Phis, interpolant_frequencies), grid, bounds_error=False,fill_value=0.0)\n return interpolant\n \n J00_interpolant = make_interpolant(0, 0)\n J01_interpolant = make_interpolant(0, 1)\n J10_interpolant = make_interpolant(1, 0)\n J11_interpolant = make_interpolant(1, 1)\n \n return self.single_LBA_model([[J00_interpolant,J01_interpolant],[J10_interpolant,J11_interpolant]], [interpolant_frequencies[0],interpolant_frequencies[-1]])\n \n def get_average_antenna_model(self):\n \"\"\"return model averaged over antenna set\"\"\"\n \n if self.antenna_mode == \"LBA_OUTER\":\n start_i = 576\n end_i = 576*2\n elif self.antenna_mode == \"LBA_INNER\":\n start_i = 0\n end_i = 576\n else:\n print(\"unknown mode:\", self.antenna_mode )\n \n total_num_antennas = len( self.total_Gz )\n num_frequencies = len(self.all_frequencies)\n num_zeniths = len(self.AART_thetas)\n num_azimuths = len(self.AART_Phis)\n \n ### define a utility function for extracting grid data\n temp_matrix = np.empty( (num_zeniths, num_azimuths, num_frequencies), dtype=np.complex )\n shifterTMP = np.empty( [ num_frequencies ], dtype=np.complex)\n tmp1 = np.empty( (total_num_antennas,num_frequencies), dtype=np.complex )\n def get_ant_i(ant_i, pol_i):\n \"\"\"given internal antenna index, and polarization, fill temp_matrix with correct response\"\"\"\n nonlocal shifterTMP, tmp1, temp_matrix\n \n KX, KY = self.AART_ant_positions[:, ant_i]\n for zi, ze in enumerate(self.AART_thetas):\n for ai, az in enumerate(self.AART_Phis):\n \n ## dot product between voltages and impedences\n tmp1[:,:] = self.total_Gz[:, pol_i,zi,ai, :] \n tmp1 *= self.total_impedence[ant_i, :, :] # this shouldn't matter??\n # tmp1 *= self.total_impedence[:, antenna, :]\n \n np.sum( tmp1, axis=0, out = temp_matrix[zi,ai, : ] )\n \n ## caculate phase shifts\n Zenith = ze/RTD\n Azimuth = az/RTD\n dt = ( KX*np.sin(Zenith)*np.cos(Azimuth) + KY*np.sin(Zenith)*np.sin(Azimuth))/v_air\n shifterTMP[:] = self.all_frequencies\n shifterTMP *= -1j*2*np.pi*dt\n np.exp( shifterTMP, out=shifterTMP )\n \n ## apply the shits\n temp_matrix[zi,ai, : ] *= shifterTMP\n \n if pol_i==0: ## zenith points in oppisite directions in two models??\n temp_matrix *= -1\n \n ### now define a utility function for calculating the average, and interpolating\n \n ## frequency interpolation\n frequency_bin = 0.5e6\n minF = self.all_frequencies[0]\n maxF = self.all_frequencies[-1]\n num_interpolant_freqs = int((maxF+minF)/frequency_bin )\n interpolant_frequencies = np.linspace(minF, maxF, num_interpolant_freqs)\n \n temp_AVE_matrix = np.empty( (num_zeniths, num_azimuths, num_frequencies), dtype=np.complex )\n tmp3 = np.empty(num_frequencies, dtype=np.double )\n def calc_func(antenna_pol, field_pol):\n \"\"\"antenna_pol should be 0 or 1 for X or Y antenna, and field_pol is 0 or 1 for zenithal or azimuthal field\"\"\"\n nonlocal temp_AVE_matrix, tmp3\n \n ## first average\n Npairs = int( (end_i-start_i)/2 )\n for pair_i in range(Npairs):\n ant_i = 2*pair_i + antenna_pol + start_i\n get_ant_i(ant_i, field_pol) ## this fills temp_matrix\n temp_AVE_matrix += temp_matrix ## error prone, but should be okay\n \n if not np.all( np.isfinite(temp_AVE_matrix) ):\n print('YO problem!', pair_i, np.all( np.isfinite(temp_matrix) ) )\n quit()\n \n temp_AVE_matrix /= Npairs\n \n \n upsample_grid = np.empty([num_zeniths, num_azimuths, len(interpolant_frequencies) ], dtype=np.complex)\n \n ## now interpolate frequencies \n for zi, ze in enumerate(self.AART_thetas):\n for ai, az in enumerate(self.AART_Phis):\n \n np.abs(temp_AVE_matrix[zi,ai, : ], out=tmp3)\n interp_ampltude = pchip_interpolate(self.all_frequencies, tmp3, interpolant_frequencies)\n \n \n \n angles = np.angle(temp_AVE_matrix[zi,ai, : ])\n angles = np.unwrap(angles)\n \n interp_angle = pchip_interpolate(self.all_frequencies, angles, interpolant_frequencies)\n \n ## now convert back to real and imag\n interp_angle = interp_angle*1j\n np.exp( interp_angle, out = upsample_grid[zi,ai, :] )\n upsample_grid[zi,ai, :] *= interp_ampltude\n \n \n ## and final angle-frequency interpolant\n return RegularGridInterpolator((self.AART_thetas, self.AART_Phis, interpolant_frequencies), upsample_grid, bounds_error=False, fill_value=0.0)\n \n \n ### now we actually make the responses\n J00 = calc_func(0, 0)\n J01 = calc_func(0, 1)\n J10 = calc_func(1, 0)\n J11 = calc_func(1, 1)\n return self.single_LBA_model([[J00,J01],[J10,J11]], [interpolant_frequencies[0],interpolant_frequencies[-1]])\n \n \n \n def get_antenna_locs(self):\n \"\"\"return two arrays. First is X locations of all antennas. Second is Y locations. Each location is in pairs, the first is the X dipole, second is Y dipole\"\"\"\n return self.AART_ant_positions[0], self.AART_ant_positions[1]\n \n def get_grid_info(self):\n \"\"\"return info about the internal grid. returns three real-valued numpy arrays: frequencies [Hz], zenithal [degrees], and azimuthal [degrees]\"\"\"\n return self.all_frequencies, self.AART_thetas, self.AART_Phis\n \n def get_response_grid(self, antenna_i, frequency_i, ant_pol_i, field_pol_i):\n \"\"\"given an antenna_i, and frequency_i, return response of ant_pol_i (0 for X 1 for Y dipole) to field_pol_i (0 is zenithal, 1 is azimuthal). Response is a 2D matrix, first index is zenith angle, second is azimuthal\"\"\"\n \n total_antenna_i = int(antenna_i/2)*2 + ant_pol_i\n \n \n #### some setup\n KX, KY = self.AART_ant_positions[:, total_antenna_i]\n \n num_thetas = len(self.AART_thetas)\n num_phis = len(self.AART_Phis)\n \n frequency = self.all_frequencies[ frequency_i ]\n \n ret = np.empty([num_thetas, num_phis], dtype=np.complex)\n \n ## the calculation\n for zenith_i in range( num_thetas ):\n for azimuth_i in range( num_phis ):\n \n \n ## phase shifter to remove geometric delay\n Zenith = self.AART_thetas[zenith_i]/RTD\n Azimuth = self.AART_Phis[azimuth_i]/RTD\n dt = ( KX*np.sin(Zenith)*np.cos(Azimuth) + KY*np.sin(Zenith)*np.sin(Azimuth))/v_air\n phase_shift = np.exp( frequency*(1j*2*np.pi*(-dt)) )\n \n \n ## the antenna response\n response = np.dot( self.total_impedence[total_antenna_i, :, frequency_i] , self.total_Gz[:, field_pol_i, zenith_i, azimuth_i, frequency_i] )\n \n \n ret[ zenith_i, azimuth_i] = response*phase_shift\n \n \n \n if field_pol_i==0: ## zenith points in oppisite directions in two models??\n ret *= -1\n \n return ret\n\nclass aartfaac_average_LBA_model:\n\n def __init__(self, mode=\"LBA_OUTER\"):\n if mode == \"LBA_OUTER\":\n fname = MetaData_directory+\"/lofar/antenna_response_model/AARTFAAC_AVE_LBAOUTER_R700_C17.npz\"\n else:\n print('mode unknown:', mode)\n quit()\n\n data = np.load(fname)\n initial_frequencies = data['freqs']\n zeniths = data['zeniths']\n azimuths = data['azimuths']\n \n original_J00 = data['J00']\n original_J01 = data['J01']\n original_J10 = data['J10']\n original_J11 = data['J11']\n \n \n num_zeniths = len(zeniths)\n num_azimuths = len(azimuths)\n \n ## frequency interpolation\n frequency_bin = 0.5e6\n minF = initial_frequencies[0]\n maxF = initial_frequencies[-1]\n num_interpolant_freqs = int((maxF+minF)/frequency_bin )\n interpolant_frequencies = np.linspace(minF, maxF, num_interpolant_freqs)\n \n \n # print('arg', initial_frequencies.shape, original_J00.shape)\n \n tmp = np.empty(len(initial_frequencies), dtype=np.double )\n def upsample_and_interpolate(GRID):\n nonlocal tmp\n \n upsample_grid = np.empty([num_zeniths, num_azimuths, num_interpolant_freqs ], dtype=np.complex)\n \n ## now interpolate frequencies \n for zi, ze in enumerate(zeniths):\n for ai, az in enumerate(azimuths):\n \n np.abs(GRID[zi,ai, : ], out=tmp)\n interp_ampltude = pchip_interpolate(initial_frequencies, tmp, interpolant_frequencies)\n \n \n \n angles = np.angle(GRID[zi,ai, : ])\n angles = np.unwrap(angles)\n \n interp_angle = pchip_interpolate(initial_frequencies, angles, interpolant_frequencies)\n \n ## now convert back to real and imag\n interp_angle = interp_angle*1j\n np.exp( interp_angle, out = upsample_grid[zi,ai, :] )\n upsample_grid[zi,ai, :] *= interp_ampltude\n \n \n ## and final angle-frequency interpolant\n \n return RegularGridInterpolator((zeniths, azimuths, interpolant_frequencies), upsample_grid, bounds_error=False, fill_value=0.0)\n \n self.freq_bounds = [ interpolant_frequencies[0], interpolant_frequencies[-1] ]\n \n self.J00 = upsample_and_interpolate( original_J00 )\n self.J01 = upsample_and_interpolate( original_J01 )\n self.J10 = upsample_and_interpolate( original_J10 )\n self.J11 = upsample_and_interpolate( original_J11 )\n \n def Jones_Matrices(self, frequencies, zenith, azimuth, freq_fill=1.0):\n \"\"\" if frequencies is numpy array in Hz, zenith and azimuth in degrees, than return numpy array of jones matrices,\n that when doted with [zenithal,azimuthal] component of incidident E-field, then will give [X,Y] voltages on dipoles\"\"\"\n \n return_matrices = np.empty( (len(frequencies), 2,2), dtype=np.complex )\n \n if zenith<0:\n zenith = 0\n elif zenith > 90:\n zenith = 90\n \n while azimuth<0:\n azimuth += 360\n while azimuth>360:\n azimuth -= 360\n \n # good_frequency_filter = np.logical_and(frequencies>=self.freq_bounds[0], frequenciesself.freq_bounds[-1]:\n return_matrices[fi, 0,0] = freq_fill\n return_matrices[fi, 1,1] = freq_fill\n return_matrices[fi, 0,1] = 0.0\n return_matrices[fi, 1,0] = 0.0\n else:\n return_matrices[fi, 0,0] = self.J00( (zenith,azimuth,f) )\n return_matrices[fi, 0,1] = self.J01( (zenith,azimuth,f) )\n return_matrices[fi, 1,0] = self.J10( (zenith,azimuth,f) )\n return_matrices[fi, 1,1] = self.J11( (zenith,azimuth,f) )\n \n # print(fi)\n # M = return_matrices[fi]\n # print(\"J:\", M)\n # print( M[ 0,0]*M[ 1,1] - M[ 0,1]*M[ 1,0] )\n # print()\n \n return return_matrices\n \n def save_to_text(self):\n \n freq_grid = np.linspace(10,90, num=int((90-10)/1)+1 ) \n zenith_grid = np.linspace(0,90, num=int(90/5)+1 )\n azimuth_grid = np.linspace(0,360, num=int(360/10)+1 )\n \n J00_out = open('./J00_text.txt', 'w')\n J01_out = open('./J01_text.txt', 'w')\n J10_out = open('./J10_text.txt', 'w')\n J11_out = open('./J11_text.txt', 'w')\n \n J00_out.write('voltage on X-dipole to zenithal field. Azimuthal=0 points 45 degrees south from East.\\n')\n J00_out.write('f (MHz) Zenith(deg.) Azimuth(deg.) real(Vout) imag(Vout)\\n')\n \n J01_out.write('voltage on X-dipole to azimuthal field. Azimuthal=0 points 45 degrees south from East.\\n')\n J01_out.write('f (MHz) Zenith(deg.) Azimuth(deg.) real(Vout) imag(Vout)\\n')\n \n J10_out.write('voltage on Y-dipole to zenithal field\\. Azimuthal=0 points 45 degrees south from East.n')\n J10_out.write('f (MHz) Zenith(deg.) Azimuth(deg.) real(Vout) imag(Vout)\\n')\n \n J11_out.write('voltage on Y-dipole to azimuthal field. Azimuthal=0 points 45 degrees south from East.\\n')\n J11_out.write('f (MHz) Zenith(deg.) Azimuth(deg.) real(Vout) imag(Vout)\\n')\n \n for f in freq_grid:\n for z in zenith_grid:\n for a in azimuth_grid:\n jonesy = self.Jones_Matrices( [f*1e6],z,a+45 )\n start = str(f)+ ' ' + str(z)+' '+str(a)+' '\n J00_out.write(start+str(np.real(jonesy[0,0,0])) + ' ' + str(np.imag(jonesy[0,0,0])) +'\\n')\n J01_out.write(start+str(np.real(jonesy[0,0,1])) + ' ' + str(np.imag(jonesy[0,0,1])) +'\\n')\n J10_out.write(start+str(np.real(jonesy[0,1,0])) + ' ' + str(np.imag(jonesy[0,1,0])) +'\\n')\n J11_out.write(start+str(np.real(jonesy[0,1,1])) + ' ' + str(np.imag(jonesy[0,1,1])) +'\\n')\n \n \n \nclass calibrated_AARTFAAC_model:\n \"\"\"returns the AARTFAAC model multiplied by katies cal.\"\"\"\n \n def __init__(self):\n self.AARTFAAC = aartfaac_average_LBA_model()\n \n calibration = [42484.88872879, 41519.47733373, 39694.16854372, 38435.36963118,\n 36974.13596039, 35819.34454985, 35072.53901876, 33960.74197721,\n 32944.65142405, 32112.44688046, 31590.52174516, 30433.52586868,\n 29756.92041985, 28880.95581826, 28204.37711364, 27646.83132496,\n 27058.11219529, 26693.43614747, 25952.89684011, 25517.72346825,\n 25220.5602153 , 24782.62398452, 24349.88724441, 23755.78027908,\n 23289.45439997, 22800.30039329, 22176.17569116, 21619.22598549,\n 21341.84386379, 21368.96227069, 22032.38713345, 22127.96304476,\n 22678.25184787, 24670.14420208, 25703.00236409, 24792.9736945,\n 23817.8752368 , 22912.1048524 , 22393.11267467, 21844.38535201,\n 20831.10515113, 20220.27315072, 19223.64518551, 18099.23669312,\n 17569.76228552, 16298.99230863, 14845.6897604 , 13488.79405579,\n 11966.53709451, 10895.66530218, 9703.34502309]\n \n cal_frequencies = np.arange(30e6, 80.5e6, 1e6)\n self.calibration_interpolator = PchipInterpolator(cal_frequencies, calibration, extrapolate=True )\n\n def get_calibrator(self, frequencies):\n return self.calibration_interpolator( frequencies )\n\n def Jones_ONLY(self, frequencies, zenith, azimuth, freq_fill=1.0):\n return self.AARTFAAC.Jones_Matrices( frequencies, zenith, azimuth, freq_fill )\n\n def Jones_Matrices(self, frequencies, zenith, azimuth, freq_fill=1.0):\n \"\"\"return calibrated jones matrices\"\"\"\n JM = self.AARTFAAC.Jones_Matrices( frequencies, zenith, azimuth, freq_fill )\n C = self.get_calibrator( frequencies )\n JM[:, 0,0] *= C\n JM[:, 0,1] *= C\n JM[:, 1,0] *= C\n JM[:, 1,1] *= C\n return JM\n \n \n \n \ndef invert_2X2_matrix_list( matrices ):\n \"\"\" if matrices is an array of 2x2 matrices, then return the array of inverse matrices \"\"\"\n num = len(matrices)\n out = np.zeros( (num, 2,2), dtype=matrices.dtype)\n \n out[:, 0,0] = matrices[:, 1,1]\n out[:, 0,1] = -matrices[:, 0,1]\n out[:, 1,0] = -matrices[:, 1,0]\n out[:, 1,1] = matrices[:, 0,0]\n \n determinants = matrices[:, 0,0]*matrices[:, 1,1] - matrices[:, 0,1]*matrices[:, 1,0]\n \n out /= determinants[:, np.newaxis, np.newaxis]\n \n return out\n\ndef fourier_series( x, p):\n \"\"\"Evaluates a partial Fourier series\n\n F(x) \\\\approx \\\\frac{a_{0}}{2} + \\\\sum_{n=1}^{\\\\mathrm{order}} a_{n} \\\\sin(nx) + b_{n} \\\\cos(nx)\n \"\"\"\n\n r = p[0] / 2\n\n order = int( (len(p) - 1) / 2 )\n\n for i in range(order):\n\n n = i + 1\n\n r += p[2*i + 1] * np.sin(n * x) + p[2*i + 2] * np.cos(n * x)\n\n return r\n\ndef getGalaxyCalibrationData(antenna_noise_power, timestamp, antenna_type=\"outer\"):\n \"\"\"return factor to correct for amplitude shifts. Essenturally returns sqrt( P_{expected} / P_{measured} ). Where P is noise power. \n for antenna_type outer it returns factor for Y/X dipoles, for \"inner\" returns \"X/Y\". antenna_noise_power is an array of measured powers for each antenna. \n Even/odd indecies should be Y/X dipole for outer and oppisite for inner.\n timestamp should be posix timestamp\"\"\"\n \n \n longitude = 6.869837540/RTD\n \n ## this is in outer order: Y,X\n # coefficients_lba = [ np.array([ 0.01489468, -0.00129305, 0.00089477, -0.00020722, -0.00046507]), ## for Y antennas\n # np.array( [ 0.01347391, -0.00088765, 0.00059822, 0.00011678, -0.00039787] ) ] ## for X antennas\n coefficients_lba = [ np.array( [ 3.85712631e+01, -2.17182149e+00, 1.68114451e+00 , 4.24076969e-01, -9.24289199e-01, 2.11372242e-01, 1.09281884e-01, -1.74674795e-01, 3.70793388e-03] ), ## for Y antennas\n np.array( [38.13314007, -3.02861767 , 2.11558435, -0.30123627, -0.94641864, -0.14297615, 0.05037442, -0.04133833, -0.11443689]) ] ## for X antennas\n\n \n \n # Convert timestamp to datetime object\n t = datetime.datetime.utcfromtimestamp(timestamp)\n # Calculate JD(UT1)\n ut = tmf.gregorian2jd(t.year, t.month, float(t.day) + ((float(t.hour) + float(t.minute) / 60. + float(t.second) / 3600.) / 24.))\n # Calculate JD(TT)\n dtt = tmf.delta_tt_utc(tmf.date2jd(t.year, t.month, float(t.day) + ((float(t.hour) + float(t.minute) / 60. + float(t.second) / 3600.) / 24.)))\n tt = tmf.gregorian2jd(t.year, t.month, float(t.day) + ((float(t.hour) + float(t.minute) / 60. + (float(t.second) + dtt / 3600.)) / 24.))\n # Calculate Local Apparant Sidereal Time\n last = tmf.rad2circle(tmf.last(ut, tt, longitude))\n\n\n galactic_noise_power =[ fourier_series(last, coefficients_lba[0]), fourier_series(last, coefficients_lba[1]) ]\n \n antenna_noise_power[ antenna_noise_power==0 ] = np.nan\n \n if antenna_type == 'outer':\n Y_measured_powers = antenna_noise_power[0::2]\n X_measured_powers = antenna_noise_power[1::2]\n \n Y_expected_power = galactic_noise_power[0]\n X_expected_power = galactic_noise_power[1]\n \n else:\n X_measured_powers = antenna_noise_power[0::2]\n Y_measured_powers = antenna_noise_power[1::2]\n \n X_expected_power = galactic_noise_power[0]\n Y_expected_power = galactic_noise_power[1]\n \n \n ## note this should make new arrays\n Y_factors = Y_expected_power / Y_measured_powers\n X_factors = X_expected_power / X_measured_powers\n \n np.sqrt(Y_factors, out=Y_factors)\n np.sqrt(X_factors, out=X_factors)\n \n if antenna_type == 'outer':\n return Y_factors, X_factors\n else:\n return X_factors, Y_factors\n\n\n", "meta": {"hexsha": "49adf56867b4c8584529a0a2614fca6560861f5a", "size": 37390, "ext": "py", "lang": "Python", "max_stars_repo_path": "LIM_scripts/antenna_response.py", "max_stars_repo_name": "Bhare8972/LOFAR-LIM", "max_stars_repo_head_hexsha": "89f25be8c02cb8980c2e237da3eaac279d40a06a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-04-21T13:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-15T12:44:23.000Z", "max_issues_repo_path": "LIM_scripts/antenna_response.py", "max_issues_repo_name": "Bhare8972/LOFAR-LIM", "max_issues_repo_head_hexsha": "89f25be8c02cb8980c2e237da3eaac279d40a06a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LIM_scripts/antenna_response.py", "max_forks_repo_name": "Bhare8972/LOFAR-LIM", "max_forks_repo_head_hexsha": "89f25be8c02cb8980c2e237da3eaac279d40a06a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-11-06T18:34:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-04T14:16:57.000Z", "avg_line_length": 43.5273573923, "max_line_length": 226, "alphanum_fraction": 0.56854774, "include": true, "reason": "import numpy,from scipy", "num_tokens": 9639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.23934933647101647, "lm_q1q2_score": 0.12154443276733745}} {"text": "#!/usr/bin/env python\n\n\"\"\"Module to deal with trees\n\nSome more documentation\n\nFor now (and for some time), this module assumes that in the Trees folder,\nthere is only one set of tree_bricks (i.e. TreeMaker was run for only one set\nof tree_bricks).\n\nTODO:\n - everything\n - pep8\n\n\"\"\"\nimport matplotlib\nimport numpy as np\n#from matplotlib.backends.backend_pdf import PdfPages\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom scipy.io import FortranFile as FF\nimport yt\nfrom glob import glob\nimport os\nimport yt.utilities.fortran_utils as fpu\nfrom tqdm import tqdm\n\nfrom . import physics\nfrom .utils import find_outputs\n\n\nclass Forest(object):\n \"\"\"\n Read the outputs from TreeMaker and gather in a dataframe\n in self.trees\n units are:\n x,y,z -> Mpccm\n vx,vy,xz -> km/s (to check)\n m,mvir -> 1e11Msun\n r,rvir -> Mpc\n \"\"\"\n\n def __init__(self, Galaxy=False, path='.', big_run=False):\n paths = find_outputs(path+'/Outputs')\n self.prefix = path\n yt.funcs.mylog.setLevel(40)\n ds = yt.load(paths[-1])\n\n _sim = {}\n _sim['h'] = float(ds.cosmology.hubble_constant)\n _sim['Om'] = ds.omega_matter\n _sim['Ol'] = ds.omega_lambda\n _sim['Lbox'] = float(ds.length_unit.in_units('Mpccm'))\n\n treefolder = os.path.join(self.prefix, 'Trees')\n self.galaxies = False\n if Galaxy:\n treefolder = os.path.join(self.prefix, 'TreeStars')\n self.galaxies = True\n\n self.treefolder = treefolder\n self.sim = _sim\n self.ds = ds\n self.folder = treefolder\n self.snap = self._get_timestep_number()\n\n self.read_tree(big_run)\n\n def read_tree(self, big_run=False):\n \"\"\"\n \"\"\"\n\n if self.galaxies:\n tree_file = os.path.join(self.folder, 'tree.dat')\n self = self._read_tree(tree_file, 'd', big_run)\n else:\n tree_file = glob('{}/tree_file_???.001'.format(self.folder))[0]\n self = self._read_tree(tree_file, 'f', big_run)\n\n return\n\n def map_halo_ts_to_output(self, timestep):\n timestep = timestep.astype('int64')\n bricks = sorted(glob(os.path.join(self.treefolder, 'tree_bricks???')))\n mapping = np.empty(timestep.max(), dtype=np.int64)\n for istep in sorted(timestep.unique()):\n #ioutput = int(brick.split('bricks')[1])\n ioutput = int(bricks[istep-1].split('bricks')[1])\n mapping[istep-1] = ioutput\n\n return mapping[timestep-1]\n\n\n def get_all_progenitors(self, hnum, timestep=None):\n \"\"\"Return the reduced tree containing ONLY the progenitors of halo hid\n ==========\n * hid: ID of the halo at output timestep given by the halo/galaxy finder\n * timestep (None): timestep at which the ID must be taken, default is last timestep\n \"\"\"\n\n if timestep is None:\n ts = self.halo_ts.max()\n print('Care, this can be very long for galaxies. The get_main_progenitor is much faster')\n print('It is OK for Haloes')\n progenitors = self._get_progenitors(hnum, timestep=timestep)\n\n return progenitors\n\n def get_main_progenitor(self, hnum, timestep=None):\n \"\"\"Return the reduced tree containing ONLY the main progenitors of halo hid\n ==========\n * hid: ID of the halo at output timestep given by the halo/galaxy finder\n * timestep (None): timestep at which the ID must be taken, default is last timestep\n \"\"\"\n id_main = {}\n if timestep is None:\n ts = self.trees.halo_ts.max()\n else:\n ts = timestep\n\n list_progenitors = [(hnum, ts)]\n fatherMass = self.trees.loc[hnum,timestep].fatherMass\n fathersID = self.trees.loc[hnum,timestep].fathersID\n while (fathersID.size > 1):\n #update ts\n ts -= 1\n #remove background\n fatherMass = fatherMass[fathersID > 0]\n fathersID = fathersID[fathersID > 0]\n #main father is the one that contains most mass\n main_father = fathersID[fatherMass.argmax()]\n list_progenitors += [(main_father, ts)]\n fatherMass = self.trees.loc[main_father, ts].fatherMass\n fathersID = self.trees.loc[main_father, ts].fathersID\n main_progs = self.trees.loc[list_progenitors]\n\n return main_progs\n\n def get_main_children(self, hnum, timestep=None):\n \"\"\"Return the reduced tree containing ONLY the main children of halo hid\n ==========\n * hid: ID of the halo at output timestep given by the halo/galaxy finder\n * timestep (None): timestep at which the ID must be taken, default is last timestep\n \"\"\"\n # Get current timestep\n max_ts = self.trees.halo_ts.max()\n if timestep is None:\n ts = max_ts \n else:\n ts = timestep\n\n list_sons = [(hnum, ts)]\n while (ts < max_ts):\n main_son = self.trees.loc[hnum,ts].mainSon\n #update ts\n ts += 1\n list_sons += [(main_son, ts)]\n children = self.trees.loc[list_sons]\n\n return children\n\n def get_family(self, hnum, timestep=None):\n \"\"\"Return the reduced tree containing ONLY the main progenitors/children of halo hid\n ==========\n * hid: ID of the halo at output timestep given by the halo/galaxy finder\n * timestep (None): timestep at which the ID must be taken, default is last timestep\n \"\"\"\n # Get current timestep\n if timestep is None:\n ts = self.trees.halo_ts.max()\n else:\n ts = timestep\n\n child = self.get_main_children(hnum, timestep)\n fathers = self.get_main_progenitor(hnum, timestep)\n fathers = fathers.loc[fathers.halo_ts != ts]\n family = pd.concat((child, fathers))\n family = family.sort_index(level=1)\n\n return family\n\n def plot_all_trees(self, minmass=-1, maxmass=1e99, radius=1.0,\n output=None, loc='./'):\n \"\"\"\n See plot_halo_tree.\n Compute the above function for all halos with virial mass\n between `minmass` and `maxmass`. The width in Mpccm for the\n dynamics of the BH is radius. `loc` is the location to save the\n PDF.\n \"\"\"\n\n if output is None:\n output = str(minmass) + 'To' + str(maxmass) + '_r' + str(radius)\n\n # Normalize min/max mass to 1e11\n minmass /= 1.e11\n maxmass /= 1.e11\n\n # Select halos at the last timestep of the tree, with the right mass\n # Also selects halos with at least 1 progenitor...\n mask = ((self.trees.halo_ts == self.snap) &\n (self.trees.mvir > minmass) &\n (self.trees.mvir < maxmass) &\n (self.trees.first_prog != -1))\n\n tid = self.trees[mask].halo_id\n print('Total: {} halos'.format(len(tid)))\n\n pdf = PdfPages(loc + 'trees{}.pdf'.format(output))\n try:\n fig = self.fig\n except AttributeError:\n self.fig = plt.figure(figsize=(12, 12))\n self.fig.savefig(pdf, format='pdf', dpi=200)\n\n for ihalo in tid:\n self.plot_halo_tree(hid=int(ihalo), radius=radius, pdffile=pdf)\n plt.close()\n pdf.close()\n plt.close('all')\n\n return 'OK'\n\n def plot_halo_tree(self, hid=None, hnum=None, hts=None, radius=1.0,\n pdffile=None, loc='./'):\n \"\"\"\n Plot Mass/Merger history of a halo\n Parameters\n ----------\n * hid (None): halo_id of the halo you want to have the merger/mass history\n * hnum (None): halo_num of the halo you want to have the\n merger history, if used then the timestep of this halo must\n be given with hts\n * radius (1): width of the window to plot the dynamics of the halo\n * loc ('./'): where to save the plot\n \"\"\"\n\n # Define the selected halo\n if hid is None:\n hid = (self.trees.loc[(self.trees.halo_num == hnum) & (\n self.trees.halo_ts == hts)].halo_id).astype(int)\n halo = self.trees.ix[hid]\n sim = self.sim\n\n xh = halo['x'] # - sim['Lbox']/2 #/sim['Lbox'] + .5\n yh = halo['y'] # - sim['Lbox']/2 #/sim['Lbox'] + .5\n zh = halo['z'] # - sim['Lbox']/2 #/sim['Lbox'] + .5\n\n # Get progenitors\n progs = self._get_progenitors(hid)\n progs.loc[hid].descendent_id = -1\n main_progs = self.get_main_progenitor(hid)\n main_progs.loc[hid].descendent_id = -1\n\n # Recenter on selected halo and correct for periodic boundaries\n progs['x'] -= xh\n progs['y'] -= yh\n progs['z'] -= zh\n progs['x'].where(progs.x <= sim['Lbox'] / 2.,\n progs.x - sim['Lbox'], inplace=True)\n progs['y'].where(progs.y <= sim['Lbox'] / 2.,\n progs.y - sim['Lbox'], inplace=True)\n progs['z'].where(progs.z <= sim['Lbox'] / 2.,\n progs.z - sim['Lbox'], inplace=True)\n progs['x'].where(progs.x >= -sim['Lbox'] / 2.,\n progs.x + sim['Lbox'], inplace=True)\n progs['y'].where(progs.y >= -sim['Lbox'] / 2.,\n progs.y + sim['Lbox'], inplace=True)\n progs['z'].where(progs.z >= -sim['Lbox'] / 2.,\n progs.z + sim['Lbox'], inplace=True)\n main_progs['x'] -= xh\n main_progs['y'] -= yh\n main_progs['z'] -= zh\n main_progs['x'].where(main_progs.x <= sim['Lbox'] / 2.,\n main_progs.x - sim['Lbox'], inplace=True)\n main_progs['y'].where(main_progs.y <= sim['Lbox'] / 2.,\n main_progs.y - sim['Lbox'], inplace=True)\n main_progs['z'].where(main_progs.z <= sim['Lbox'] / 2.,\n main_progs.z - sim['Lbox'], inplace=True)\n main_progs['x'].where(main_progs.x >= -sim['Lbox'] / 2.,\n main_progs.x + sim['Lbox'], inplace=True)\n main_progs['y'].where(main_progs.y >= -sim['Lbox'] / 2.,\n main_progs.y + sim['Lbox'], inplace=True)\n main_progs['z'].where(main_progs.z >= -sim['Lbox'] / 2.,\n main_progs.z + sim['Lbox'], inplace=True)\n\n # Define plot range\n xc = (main_progs['x'].min() + main_progs['x'].max()) * .5\n yc = (main_progs['y'].min() + main_progs['y'].max()) * .5\n zc = (main_progs['z'].min() + main_progs['z'].max()) * .5\n xmin = ymin = zmin = -radius\n xmax = ymax = zmax = radius\n progs[['x', 'y', 'z']] -= [xc, yc, zc]\n main_progs[['x', 'y', 'z']] -= [xc, yc, zc]\n\n # Recenter other halos, and correct for periodic boundaries\n x = self.trees.x - (xc + xh)\n y = self.trees.y - (yc + yh)\n z = self.trees.z - (zc + zh)\n x.where(x <= sim['Lbox'] / 2., x - sim['Lbox'], inplace=True)\n y.where(y <= sim['Lbox'] / 2., y - sim['Lbox'], inplace=True)\n z.where(z <= sim['Lbox'] / 2., z - sim['Lbox'], inplace=True)\n x.where(x >= -sim['Lbox'] / 2., x + sim['Lbox'], inplace=True)\n y.where(y >= -sim['Lbox'] / 2., y + sim['Lbox'], inplace=True)\n z.where(z >= -sim['Lbox'] / 2., z + sim['Lbox'], inplace=True)\n\n # Select other halos within plot range\n others = ((x < radius) & (-radius < x) &\n (y < radius) & (-radius < y) &\n (z < radius) & (-radius < z))\n\n # Scalings\n scc = np.log10(progs.m)\n mainscc = np.log10(main_progs.m)\n sc = (scc - scc.min()) / (scc.max() - scc.min()) * 500.\n mainsc = (mainscc - scc.min()) / (mainscc.max() - scc.min()) * 500.\n\n osc = np.log10(self.trees[others].m)\n osc = (osc - scc.min()) / (scc.max() - scc.min()) * 500.\n ocol = self.trees[others].halo_ts\n ocol = .15 + .7 * (ocol - ocol.min()) / (ocol.max() - ocol.min())\n edg = np.where(self.trees[others].bush_id ==\n halo['bush_id'], 'orange', 'k')\n\n # Plot halos dynamics in the comoving space\n # try:\n # fig = self.fig\n # except AttributeError:\n self.fig = plt.figure(figsize=(12, 12))\n fig = self.fig\n # try:\n # ax = self.ax\n # except AttributeError:\n ax10 = self.fig.add_axes([0.07, 0.05, 0.4, 0.4])\n ax00 = self.fig.add_axes([0.07, 0.5, 0.4, 0.4])\n ax01 = self.fig.add_axes([0.55, 0.5, 0.4, 0.4])\n ax11 = self.fig.add_axes([0.55, 0.05, 0.4, 0.4])\n self.ax = [ax00, ax01, ax10, ax11]\n ax = self.ax\n\n self.ax[0].scatter(x[others], y[others], c=ocol, s=osc, cmap='Greys',\n vmin=0, vmax=1., edgecolor=edg,\n rasterized=True)\n self.ax[0].scatter(progs.x, progs.y, c=progs.halo_ts, s=sc,\n cmap='summer', rasterized=True)\n self.ax[0].scatter(main_progs.x, main_progs.y,\n c=main_progs.halo_ts, s=mainsc,\n cmap='magma', rasterized=True)\n self.ax[0].set_xlabel(r'$x$ (cMpc)')\n self.ax[0].set_ylabel(r'$y$ (cMpc)')\n self.ax[0].set_xlim(xmin, xmax)\n self.ax[0].set_ylim(ymin, ymax)\n\n self.ax[1].scatter(z[others], y[others], c=ocol, s=osc, cmap='Greys',\n vmin=0, vmax=1., edgecolor=edg,\n rasterized=True)\n self.ax[1].scatter(progs.z, progs.y, c=progs.halo_ts, s=sc,\n cmap='summer', rasterized=True)\n self.ax[1].scatter(main_progs.z, main_progs.y,\n c=main_progs.halo_ts, s=mainsc,\n cmap='magma', rasterized=True)\n self.ax[1].set_xlabel(r'$z$ (cMpc)')\n self.ax[1].set_ylabel(r'$y$ (cMpc)')\n self.ax[1].set_xlim(zmin, zmax)\n self.ax[1].set_ylim(ymin, ymax)\n\n self.ax[2].scatter(x[others], z[others], c=ocol, s=osc, cmap='Greys',\n vmin=0, vmax=1., edgecolor=edg,\n rasterized=True)\n self.ax[2].scatter(progs.x, progs.z, c=progs.halo_ts, s=sc,\n cmap='summer', rasterized=True)\n self.ax[2].scatter(main_progs.x, main_progs.z,\n c=main_progs.halo_ts, s=mainsc,\n cmap='magma', rasterized=True)\n self.ax[2].set_xlabel(r'$x$ (cMpc)')\n self.ax[2].set_ylabel(r'$z$ (cMpc)')\n self.ax[2].set_xlim(xmin, xmax)\n self.ax[2].set_ylim(zmin, zmax)\n\n # Draw some lines\n for progid in progs.halo_id:\n descid = progs.ix[progid].descendent_id\n if descid > 0:\n progenitor = progs.ix[progid]\n descendent = progs.ix[descid]\n px, py, pz = progenitor[['x', 'y', 'z']]\n dx, dy, dz = descendent[['x', 'y', 'z']]\n l0 = self.ax[0].plot([px, dx], [py, dy],\n lw=1, c='k', zorder=-1)\n l1 = self.ax[1].plot([pz, dz], [py, dy], lw=1, c='k',\n zorder=-1)\n l2 = self.ax[2].plot([px, dx], [pz, dz], lw=1, c='k',\n zorder=-1)\n\n title = \"Halo #{t:d}\\n(x, y, z) = ({x:3.3f}, {y:3.3f}, {z:3.3f})\"\n title = title.format(t=int(halo.halo_num),\n x=xh / sim['Lbox'] + .5,\n y=yh / sim['Lbox'] + .5,\n z=zh / sim['Lbox'] + .5)\n suptitle = self.fig.suptitle(title, fontsize=18)\n\n if not self.fig.texts:\n self.fig.texts.append(suptitle)\n if pdffile:\n self.fig.savefig(pdffile, format='pdf', dpi=200)\n else:\n plt.savefig(loc + 'halo_{:d}dynamics.png'.format(int(halo.halo_num)), dpi=100, format='png')\n\n # A bit of cleaning\n # for axx in self.ax:\n # axx.clear()\n #self.fig.texts = []\n fig.clf()\n # try:\n # fig = self.fig\n # except AttributeError:\n # self.fig = plt.figure(figsize=(12, 12))\n # try:\n # ax = self.ax\n # except AttributeError:\n ax10 = self.fig.add_axes([0.07, 0.05, 0.4, 0.4])\n ax00 = self.fig.add_axes([0.07, 0.5, 0.4, 0.4])\n ax01 = self.fig.add_axes([0.55, 0.5, 0.4, 0.4])\n ax11 = self.fig.add_axes([0.55, 0.05, 0.4, 0.4])\n self.ax = [ax00, ax01, ax10, ax11]\n ax = self.ax\n\n # Plot halo mass/merger history\n\n time = np.array([self.timestep['age'][int(hts) - 1]\n for hts in progs.halo_ts])\n maintime = np.array([self.timestep['age'][int(hts) - 1]\n for hts in main_progs.halo_ts])\n self.ax[0].scatter(time, progs.m * 1e11, c=progs.halo_ts,\n s=sc, cmap='summer', rasterized=True)\n self.ax[0].semilogy(\n [self.ds.cosmology.t_from_z(z) / (3600 * 24 * 365 * 1e9)\n for z in np.logspace(-10, 2, 1000)],\n 1e12 * physics.MofZ(halo.m * 1e11 / 1e12,\n np.logspace(-10, 2, 1000),\n 1 / self.timestep['aexp'][progs.loc[hid].halo_ts - 1] - 1),\n 'k')\n self.ax[0].scatter(maintime, main_progs.m * 1e11,\n c=main_progs.halo_ts, s=mainsc,\n cmap='magma', rasterized=True)\n self.ax[0].set_xlabel(r'$t$ (Gyr)')\n self.ax[0].set_ylabel(r'$M$ ($\\mathrm{M}_{\\odot}$)')\n self.ax[0].set_ylim(1e11 * progs.m.min() / 3.,\n 1e11 * progs.m.max() * 3.)\n self.ax[0].set_xlim(time.min(), time.max())\n self.ax[0].set_yscale('log')\n z = np.unique([int((1 / self.timestep['aexp'][int(hts) - 1] - 1) * 2) / 2.\n for hts in main_progs.halo_ts])\n z = z[1:-1]\n ax_z = self.ax[0].twiny()\n ax_z.set_xlim(self.ax[0].get_xlim())\n ax_z.set_xticks([float(self.ds.cosmology.t_from_z(\n zz) / (1e9 * 365 * 24 * 3600)) for zz in z])\n ax_z.set_xticklabels(z)\n ax_z.set_xlabel(\"redshift\")\n\n main_prog = self.get_main_progenitor(hid)\n minor_mergers = []\n major_mergers = []\n for current_id in main_prog.halo_id:\n if main_prog.halo_ts[current_id] != main_prog.halo_ts.min():\n halo_ts = main_prog.halo_ts[current_id]\n progs = self.get_all_progenitors(\n current_id, timestep=halo_ts - 1)\n mask_minor = ((progs.m / main_prog.m[current_id + 1] > 1. / 20) &\n (progs.m / main_prog.m[current_id + 1] < 1. / 4))\n minor_mergers += [len(progs.m[mask_minor])]\n mask_major = (progs.m / main_prog.m[current_id + 1] >= 1. / 4)\n major_mergers += [len(progs.m[mask_major]) - 1]\n\n scc = np.log10(main_prog.m)\n sc = (scc - scc.min()) / (scc.max() - scc.min()) * 500.\n time = np.array([self.timestep['age'][hts - 1]\n for hts in main_prog[main_prog.halo_ts !=\n self.trees.halo_ts[hid]].halo_ts])\n self.ax[2].plot(time, # np.cumsum(major_mergers)[-1] -\n np.cumsum(major_mergers),\n color='b', label='1:1 > mass ratio > 1:4 (sim)')\n\n self.ax[2].plot(time,\n [physics.N_merger_until_z(\n 0.25,\n halo.m * 1e11 / 1e12,\n self.ds.cosmology.z_from_t(t * 1e9 * 365 * 24 * 3600),\n self.ds.cosmology.z_from_t(time.max() * 1e9 * 365 * 24 * 3600))\n for t in time],\n color='b', linestyle='--',\n label='1:1 > mass ratio > 1:4 (theory)')\n\n self.ax[2].plot(time, # np.cumsum(minor_mergers)[-1] -\n np.cumsum(minor_mergers), color='r',\n label='1:4 > mass ratio > 1:20 (sim)')\n\n self.ax[2].plot(time,\n [physics.N_merger_until_z(\n 1. / 20,\n halo.m * 1e11 / 1e12,\n self.ds.cosmology.z_from_t(t * 1e9 * 365 * 24 * 3600),\n self.ds.cosmology.z_from_t(time.max() * 1e9 * 365 * 24 * 3600))\n - physics.N_merger_until_z(\n 1. / 4,\n halo.m * 1e11 / 1e12,\n self.ds.cosmology.z_from_t(t * 1e9 * 365 * 24 * 3600),\n self.ds.cosmology.z_from_t(time.max() * 1e9 * 365 * 24 * 3600))\n for t in time],\n color='r', linestyle='--',\n label='1:4 > mass ratio > 1:20 (theory)')\n # self.ax[2].scatter(time, [minor_mergers[m] for m in major_mergers],\n # c=main_prog[main_prog.halo_ts != main_prog.halo_ts.max()].halo_ts,\n # s=sc, cmap='summer', rasterized=True)\n # self.ax[2].scatter(time, [major_mergers[m] for m in major_mergers],\n # c=main_prog[main_prog.halo_ts != main_prog.halo_ts.max()].halo_ts,\n # s=sc, cmap='magma', rasterized=True, marker='*')\n self.ax[2].legend(loc='best')\n self.ax[2].set_ylabel('#merger left before t$_{max}$')\n self.ax[2].set_xlabel(r'$t$ (Gyr)')\n self.ax[2].set_xlim(time.min(), time.max())\n self.ax[2].set_ylim(ymin=0)\n z = np.unique([int(1 / self.timestep['aexp'][int(hts) - 1] - 1)\n for hts in main_progs.halo_ts])\n z = z[1:-1]\n ax_z = self.ax[2].twiny()\n ax_z.set_xlim(self.ax[0].get_xlim())\n ax_z.set_xticks([np.copy(self.ds.cosmology.t_from_z(\n zz) / (1e9 * 365 * 24 * 3600)) for zz in z])\n ax_z.set_xticklabels(z)\n\n title = \"Halo #{t:d}\\nFinal virial mass = {x:.2e} M$_\\odot$\"\n title = title.format(t=int(halo.halo_num),\n x=halo['mvir'] * 1e11)\n suptitle = self.fig.suptitle(title, fontsize=18)\n\n if not self.fig.texts:\n self.fig.texts.append(suptitle)\n if pdffile:\n self.fig.savefig(pdffile, format='pdf', dpi=200)\n else:\n plt.savefig('halo_{:d}.png'.format(\n int(halo.halo_num)), dpi=100, format='png')\n\n # A bit of cleaning\n # for axx in self.ax:\n # axx.clear()\n #self.fig.texts = []\n fig.clf()\n\n return hid\n\n def plot_accretion_history(self, hid, scale='mass'):\n \"\"\"Plot halo accretion history.\n\n Blah\n \"\"\"\n # Define the selected halo\n halo = self.trees.ix[hid]\n sim = self.sim\n\n # Get progenitors\n progs = self._get_progenitors(hid)\n\n # Scalings\n scc = np.log10(progs.m)\n sc = (scc - scc.min()) / (scc.max() - scc.min()) * 500.\n\n try:\n fig = self.fig\n except AttributeError:\n self.fig = plt.figure(figsize=(12, 12))\n try:\n ax = self.ax\n except AttributeError:\n self.ax = self.fig.add_subplot(111)\n\n time = np.array([self.timestep['age'][hts - 1]\n for hts in progs.halo_ts])\n self.ax.scatter(time, progs.m * 1e11, c=progs.halo_ts, s=sc,\n cmap='summer', rasterized=True)\n self.ax.set_xlabel(r'$t$ (Gyr)')\n self.ax.set_ylabel(r'$M$ ($\\mathrm{M}_{\\odot}$)')\n self.ax.set_ylim(1e11 * progs.m.min() / 3., 1e11 * progs.m.max() * 3.)\n self.ax.set_xlim(time.min(), time.max())\n self.ax.set_yscale('log')\n\n self.fig.tight_layout()\n self.fig.savefig('halo_{:d}_history.pdf'.format(\n int(halo.halo_num)), dpi=200, format='pdf')\n\n return hid\n\n # CONVENIENCE FUNCTIONS\n def _get_timestep_number(self):\n l = len(glob(os.path.join(self.folder, 'halos_results.???')))\n return l\n\n def get_ioutlist(self, inputfile='input_TreeMaker.dat'):\n \"\"\"Return the number of treebricks files from an input file\n\n The input_TreeMaker.dat file must be a list of:\n nsnaps some_number\n '/path/to/tree_bricks{n:03d}'\n '/path/to/tree_bricks{n+1:03d}'\n ...\n '/path/to/tree_bricks{n+nsnaps:03d}'\n ...\n\n What should be done:\n * Read all the /path/to/tree_bricks lines\n * For each line, get the tree_bricks number\n * Return the mapping between [1, nsnaps] and the tree_bricks list.\n \"\"\"\n import os.path\n\n with open(self.folder + inputfile, 'r') as ifile:\n lines = ifile.readlines()\n\n outputs = []\n\n # We know that the name of the tree_bricks file should be\n # \"tree_bricksXXX\"\n tbbasename = 'tree_bricks'\n # We can skip the first line, which should be \"nsnaps 1\"\n for path in lines[1:]:\n # Remove those nasty \"'\" and \\n\n tbname = os.path.basename(path[1:-2])\n assert tbname.startswith(tbbasename)\n outputs.append(int(tbname[len(tbbasename):]))\n\n return outputs\n\n def _get_progenitors(self, hid, timestep):\n if self.galaxies:\n progenitors = self.trees.loc[(self.trees.halo_num == hid) & (self.trees.halo_ts == timestep)]\n if len(progenitors) == 0:\n return\n else:\n if len(progenitors.fathersID.item()) == 1:\n return progenitors\n else:\n for fatherID in progenitors.fathersID.item():\n progenitors = pd.concat([progenitors, self._get_progenitors(fatherID, timestep-1)])\n return progenitors\n\n else:\n target = self.trees.loc[(self.trees.halo_num == hid) & (self.trees.halo_ts == timestep)].index\n print(target)\n mask = ((self.trees.halo_id >= self.trees.loc[target].halo_id.item()) &\n (self.trees.halo_id <= self.trees.loc[target].last_prog.item()))\n\n progenitors = self.trees.loc[mask].copy()\n return progenitors\n\n def _read_halo(self, F, precision, big_run=False):\n [ID] = fpu.read_vector(F, 'i')\n [BushID] = fpu.read_vector(F, 'i')\n [timestep] = fpu.read_vector(F, 'i')\n [level, hosthaloID, hostsubID, nbsub, nextsub] = fpu.read_vector(F, 'i')\n [m] = fpu.read_vector(F, precision)\n [dmacc] = fpu.read_vector(F, 'd')\n [x, y, z] = fpu.read_vector(F, precision)\n [vx, vy, vz] = fpu.read_vector(F, precision)\n [Lx, Ly, Lz] = fpu.read_vector(F, precision)\n [r, a, b, c] = fpu.read_vector(F, precision)\n [ek, ep, et] = fpu.read_vector(F, precision)\n [spin] = fpu.read_vector(F, precision)\n [nbfather] = fpu.read_vector(F, 'i')\n if nbfather == 0:\n fatherID = []\n fatherMass = []\n else:\n fatherID = fpu.read_vector(F, 'i')\n fatherMass = fpu.read_vector(F, precision)\n [nbsons] = fpu.read_vector(F, 'i')\n if nbsons == 0:\n sonsID = []\n mainSon = []\n else:\n sonsID = fpu.read_vector(F, 'i')\n mainSon = fpu.read_vector(F, 'i')[0]\n if self.galaxies:\n [rvir, mvir, tvir, cvel,Reff] = fpu.read_vector(F, precision)\n else:\n [rvir, mvir, tvir, cvel] = fpu.read_vector(F, precision)\n [rho_0, r_c] = fpu.read_vector(F, precision)\n if not big_run:\n fpu.read_vector(F, 'i') # ncont\n\n return (ID, timestep, level, hosthaloID, hostsubID, m,\n dmacc, x, y, z, vx, vy, vz, Lx, Ly, Lz, r, a, b,\n c, ek, ep, et, spin, rvir, mvir, tvir, cvel,\n fatherID, fatherMass, sonsID, mainSon, Reff)\n\n\n def _read_tree(self, tree_file, precision, big_run=False):\n Key_tree = [\n 'halo_num', 'tree_step', 'level', 'host_halo_id', 'host_sub_id', 'm',\n 'dmacc', 'x', 'y', 'z', 'vx', 'vy', 'vz', 'Lx', 'Ly', 'Lz', 'r',\n 'a', 'b', 'c', 'ek', 'ep', 'et', 'spin', 'rvir', 'mvir', 'tvir',\n 'cvel', 'fathersID', 'fatherMass', 'sonsID', 'mainSon']\n if self.galaxies:\n Key_tree += ['Reff']\n\n with open(tree_file, 'rb') as F:\n self.timestep = {}\n [self.timestep['nsteps']] = fpu.read_vector(F, 'i')\n n_halo_tot = fpu.read_vector(F, 'i')\n self.timestep['nhalos'] = n_halo_tot[:self.timestep['nsteps']]\n self.timestep['aexp'] = fpu.read_vector(F, precision)\n fpu.read_vector(F, precision)\n self.timestep['age'] = fpu.read_vector(F, precision)\n\n data = np.empty(shape=(n_halo_tot.sum(), len(Key_tree)), dtype=object)\n if (os.path.exists('{}/tree.hdf'.format(self.folder))):\n self.trees = pd.read_hdf('{}/tree.hdf'.format(self.folder))\n else:\n print('Reading the tree for the first time... be patient!')\n j = 0\n for istep in tqdm(range(self.timestep['nsteps'])):\n for ihalo in range(n_halo_tot[istep]+n_halo_tot[istep+self.timestep['nsteps']]):\n data[j] = self._read_halo(F, precision, big_run) \n j += 1\n\n dd = {k: data[:, i]\n for i, k in enumerate(Key_tree)}\n self.trees = pd.DataFrame(dd)\n for k in ['halo_num', 'tree_step', 'level', 'host_halo_id', 'host_sub_id']:\n self.trees[k] = self.trees[k].astype(np.int32)\n for k in ['m', 'dmacc', 'x', 'y', 'z', 'vx', 'vy', 'vz', 'Lx', 'Ly',\n 'Lz', 'r', 'a', 'b', 'c', 'ek', 'ep', 'et', 'spin', 'rvir',\n 'mvir', 'tvir', 'cvel']:\n self.trees[k] = self.trees[k].astype(np.float32)\n\n\n #process a bit the data\n self.timestep['aexp'] = 1/(1+self.ds.cosmology.z_from_t(self.ds.arr(self.timestep['age'],'Gyr'))) \n ####### Create halo_ts from the step in the tree\n self.trees['halo_ts'] = self.map_halo_ts_to_output(self.trees.tree_step)\n iout = self.trees.tree_step.values.astype(int)-1\n self.trees['aexp'] = self.timestep['aexp'][iout]\n aexp = self.trees['aexp']\n aexp_last = self.timestep['aexp'].max() \n \n factor = float(self.ds.length_unit.in_units('cm') / 3.08e24) * aexp / aexp_last \n self.trees['x'] = self.trees['x'] / factor + 0.5\n self.trees['y'] = self.trees['y'] / factor + 0.5\n self.trees['z'] = self.trees['z'] / factor + 0.5\n \n # Find outputs given halo_ts\n paths = find_outputs(self.prefix+'/Outputs')\n self.outputs = paths[-int(self.trees.halo_ts.max()):]\n step_first_gal = len(paths) - self.trees.halo_ts.max()\n self.trees.halo_ts += step_first_gal\n\n self.trees.m *= 1e11\n self.trees.dmacc *= 1e11\n\n self.trees.set_index(['halo_num','halo_ts'], drop=False, inplace=True)\n self.trees.to_hdf('{}/tree.hdf'.format(self.folder), 'hdf5')\n\n return self\n", "meta": {"hexsha": "dd735019cc2ad37440c313ac916219a6193347dc", "size": 31491, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyrats/trees.py", "max_stars_repo_name": "HugoPfister/Pyrats", "max_stars_repo_head_hexsha": "fc2cab0d1e14b8dd19b3eba361d47f053187ab47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyrats/trees.py", "max_issues_repo_name": "HugoPfister/Pyrats", "max_issues_repo_head_hexsha": "fc2cab0d1e14b8dd19b3eba361d47f053187ab47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyrats/trees.py", "max_forks_repo_name": "HugoPfister/Pyrats", "max_forks_repo_head_hexsha": "fc2cab0d1e14b8dd19b3eba361d47f053187ab47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1647058824, "max_line_length": 112, "alphanum_fraction": 0.5176717157, "include": true, "reason": "import numpy,from scipy", "num_tokens": 8801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.23651623106411432, "lm_q1q2_score": 0.12102928271755442}} {"text": "#!/usr/bin/env python\n\n##############################################\n# The MIT License (MIT)\n# Copyright (c) 2016 Kevin Walchko\n# see LICENSE for full details\n##############################################\n\nfrom __future__ import print_function\nfrom __future__ import division\nimport numpy as np\nfrom math import cos, sin, sqrt, pi\n# from math import radians as d2r\n# from Servo import Servo\n# import time\n\n\ndef rot_z_tuple(t, c):\n\t\"\"\"\n\tt - theta [radians]\n\tc - [x,y,z]\n\treturn - (x,y,z) tuple rotated about z-axis\n\t\"\"\"\n\tans = (\n\t\tc[0]*cos(t)-c[1]*sin(t),\n\t\tc[0]*sin(t)+c[1]*cos(t),\n\t\tc[2]\n\t)\n\n\treturn ans\n\n\n# make a static method in Gait? Nothing else uses it\ndef rot_z(t, c):\n\t\"\"\"\n\tt - theta [radians]\n\tc - [x,y,z]\n\treturn - [x,y,z] numpy array rotated about z-axis\n\t\"\"\"\n\tans = np.array([\n\t\tc[0]*cos(t)-c[1]*sin(t),\n\t\tc[0]*sin(t)+c[1]*cos(t),\n\t\tc[2]\n\t])\n\t# ans = np.array(rot_z_tuple(t, c))\n\n\treturn ans\n\n\nclass Gait(object):\n\t\"\"\"\n\tBase class for gaits. Gait only plan all foot locations for 1 complete cycle\n\tof the gait.\n\t\"\"\"\n\t# these are the offsets of each leg\n\tlegOffset = [0, 6, 3, 9]\n\t# frame rotations for each leg\n\tcmrot = [pi/4, -pi/4, -3*pi/4, 3*pi/4]\n\tframe = [-pi/4, pi/4, 3*pi/4, -3*pi/4] # this seem to work better ... wtf?\n\tmoveFoot = None\n\trest = None\n\tscale = 50.0\n\n\tdef __init__(self, rest):\n\t\t# the resting or idle position/orientation of a leg\n\t\tself.rest = rest\n\t\t# self.moveFoot = mf\n\t\t# self.write = w\n\n\tdef command(self, cmd):\n\t\t\"\"\"\n\t\tfunc is the quadruped move foot function for a specific leg\n\t\t\"\"\"\n\t\tx, y, rz = cmd\n\t\td = sqrt(x**2+y**2)\n\n\t\t# commands should be unit length, oneCyle scales it\n\t\tif 1.0 < d:\n\t\t\tx /= d\n\t\t\ty /= d\n\n\t\t# handle no movement command ... do else where?\n\t\tif d < 0.1 and abs(rz) < 0.1:\n\t\t\tx = y = 0.0\n\t\t\trz = 0.0\n\n\t\t\treturn None\n\n\t\t# if abs(rz) < 0.001:\n\t\t# \trz = 0.0\n\n\t\treturn self.oneCycle(x, y, rz)\n\n\tdef oneCycle(x, y, rz):\n\t\tprint('*** wrong function! ***')\n\t\treturn None\n\n\nclass DiscreteRippleGait(Gait):\n\t\"\"\"\n\tDiscrete 12 step gait\n\t\"\"\"\n\tsteps = 0\n\n\tdef __init__(self, h, r):\n\t\tGait.__init__(self, r)\n\t\tself.phi = [9/9, 6/9, 3/9, 0/9, 1/9, 2/9, 3/9, 4/9, 5/9, 6/9, 7/9, 8/9] # foot pos in gait sequence\n\t\tmaxl = h # lifting higher gives me errors\n\t\tminl = maxl/2\n\t\tself.z = [minl, maxl, minl, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] # leg height\n\t\tself.steps = len(self.phi)\n\n\tdef eachLeg(self, index, cmd):\n\t\t\"\"\"\n\t\tinterpolates the foot position of each leg\n\t\tcmd:\n\t\t\tlinear (mm)\n\t\t\tangle (rads)\n\t\t\"\"\"\n\t\trest = self.rest\n\t\ti = index\n\t\tphi = self.phi[i]\n\t\txx, yy, rzz = cmd\n\n\t\t# rotational commands -----------------------------------------------\n\t\tangle = rzz/2-rzz*phi\n\t\trest_rot = rot_z(-angle, rest)\n\n\t\t# create new move command\n\t\tmove = np.array([\n\t\t\txx/2 - phi*xx,\n\t\t\tyy/2 - phi*yy,\n\t\t\tself.z[i]\n\t\t])\n\n\t\t# new foot position: newpos = rot + move ----------------------------\n\t\tnewpos = move + rest_rot\n\t\t# print('New [](x,y,z): {:.2f}\\t{:.2f}\\t{:.2f}'.format(newpos[0], newpos[1], newpos[2]))\n\t\treturn newpos\n\n\tdef oneCycle(self, x, y, rz):\n\t\tscale = self.scale\n\t\tcmd = (scale*x, scale*y, rz)\n\t\tret = [] # 4 leg foot positions for the entire 12 count cycle is returned\n\n\t\tfor i in range(0, self.steps): # iteration, there are 12 steps in gait cycle\n\t\t\tfootPos = []\n\t\t\tfor legNum in [0, 2, 1, 3]: # order them diagonally\n\t\t\t\t# rcmd = self.calcRotatedOffset(cmd, legNum)\n\t\t\t\trcmd = rot_z_tuple(self.frame[legNum], cmd)\n\t\t\t\tindex = (i + self.legOffset[legNum]) % 12\n\t\t\t\tpos = self.eachLeg(index, rcmd) # move each leg appropriately\n\t\t\t\t# print('Foot[{}]: {:.2f} {:.2f} {:.2f}'.format(legNum, *(pos)))\n\t\t\t\t# if legNum == 0: print('New [{}](x,y,z): {:.2f}\\t{:.2f}\\t{:.2f}'.format(i, pos[0], pos[1], pos[2]))\n\t\t\t\tfootPos.append([index, legNum, pos]) # all in leg frame\n\t\t\t# print('footPos', footPos)\n\n\t\t\t# corr = Correction()\n\t\t\t# c = corr.calcCorrection(footPos)\n\t\t\t# feet = corr.rotateFeetCorrected(footPos, c)\n\n\t\t\tret.append(footPos) # 4 feet at index i: [index, legNum, footposition]\n\n# <<<<<<< HEAD:quadruped/Gait.py\n\t\treturn ret\n# =======\n# \t\t\tfeet = footPos\n# \t\t\t# print('----------------------------')\n# \t\t\tfor foot in feet:\n# \t\t\t\tlegNum = foot[1]\n# \t\t\t\tft = foot[2]\n# \t\t\t\tself.moveFoot(legNum, ft)\n# \t\t\t\t# print('Foot[{}]: {:.2f} {:.2f} {:.2f}'.format(legNum, *ft))\n#\n# \t\t\t# Servo.bulkWrite(Servo.ser)\n# \t\t\t# Servo.syncWrite(Servo.ser)\n# \t\t\tself.write()\n# \t\t\ttime.sleep(0.1)\n# >>>>>>> master:quadruped/quadruped/Gait.py\n\n\n# class ContinousRippleGait(Gait):\n# \talpha = 1.0\n#\n# \tdef __init__(self, h, r):\n# \t\tGait.__init__(self)\n# \t\tself.height = h\n# \t\tself.rest = r\n#\n# \t@staticmethod\n# \tdef phi(x):\n# \t\t\"\"\"\n# \t\tThe phase\n# \t\t\"\"\"\n# \t\tphi = 0.0\n# \t\tif x <= 3.0:\n# \t\t\tphi = 1/3*(3.0-x)\n# \t\telse:\n# \t\t\tphi = 1/9*(x-3)\n# \t\treturn phi\n#\n# \tdef z(self, x):\n# \t\t\"\"\"\n# \t\tLeg height\n#\n# \t\tduty cycle:\n# \t\t\t0-3: leg lifted\n# \t\t\t3-12: leg on ground\n# \t\t\tduty = (12-3)/12 = 0.75 = 75% a walking gait\n# \t\t\"\"\"\n# \t\theight = self.height\n# \t\tz = 0.0\n# \t\tif x <= 1:\n# \t\t\tz = height/1.0*x\n# \t\telif x <= 2.0:\n# \t\t\tz = height\n# \t\telif x <= 3.0:\n# \t\t\tz = -height/1.0*(x-2.0)+height\n# \t\treturn z\n#\n# \tdef eachLeg(self, index, cmd):\n# \t\t\"\"\"\n# \t\tinterpolates the foot position of each leg\n# \t\t\"\"\"\n# \t\trest = self.rest\n# \t\ti = (index*self.alpha) % 12\n# \t\tphi = self.phi(i)\n# \t\tz = self.z(i)\n#\n# \t\t# rotational commands -----------------------------------------------\n# \t\tangle = cmd['angle']/2-cmd['angle']*phi\n# \t\trest_rot = rot_z(-angle, rest)\n# \t\t# rest_rot[2] = 0 # let linear handle z height\n#\n# \t\t# linear commands ----------------------------------------------------\n# \t\tlinear = cmd['linear']\n# \t\txx = linear[0]\n# \t\tyy = linear[1]\n#\n# \t\t# create new move command\n# \t\tmove = np.array([\n# \t\t\txx/2 - phi*xx,\n# \t\t\tyy/2 - phi*yy,\n# \t\t\tz\n# \t\t])\n#\n# \t\t# new foot position: newpos = rot + move ----------------------------\n# \t\tnewpos = move + rest_rot\n# \t\treturn newpos\n", "meta": {"hexsha": "f5d9c605411f5be594d611647bb98d086b8c99e9", "size": 5830, "ext": "py", "lang": "Python", "max_stars_repo_path": "quadruped_old/quadruped/Gait.py", "max_stars_repo_name": "walchko/pyGeckoQuadruped", "max_stars_repo_head_hexsha": "e95ab53297a5f8e57da2d9344b59f2efde5724ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-02-08T00:47:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-03T07:34:05.000Z", "max_issues_repo_path": "quadruped_old/quadruped/Gait.py", "max_issues_repo_name": "walchko/pyGeckoQuadruped", "max_issues_repo_head_hexsha": "e95ab53297a5f8e57da2d9344b59f2efde5724ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-07-02T21:57:36.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-02T21:57:36.000Z", "max_forks_repo_path": "quadruped_old/quadruped/Gait.py", "max_forks_repo_name": "walchko/pyGeckoQuadruped", "max_forks_repo_head_hexsha": "e95ab53297a5f8e57da2d9344b59f2efde5724ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-08T23:32:29.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-08T23:32:29.000Z", "avg_line_length": 23.32, "max_line_length": 105, "alphanum_fraction": 0.5461406518, "include": true, "reason": "import numpy", "num_tokens": 2149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.19436780635202988, "lm_q1q2_score": 0.1202709955203497}} {"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\n\"\"\"Functions for performing aperture photometry on 2-D arrays.\"\"\"\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\nimport math\nimport abc\nimport numpy as np\nimport warnings\nimport astropy.units as u\nfrom astropy.io import fits\nfrom astropy.table import Table\nfrom astropy.coordinates import SkyCoord\nfrom astropy.extern import six\nfrom astropy.utils.misc import InheritDocstrings\nfrom astropy.utils.exceptions import AstropyUserWarning\nfrom .aperture_funcs import do_circular_photometry, do_elliptical_photometry, \\\n do_annulus_photometry\n\n__all__ = [\"Aperture\",\n \"CircularAperture\", \"CircularAnnulus\",\n \"EllipticalAperture\", \"EllipticalAnnulus\",\n \"RectangularAperture\",\n \"aperture_photometry\"]\n\n\ndef _make_annulus_path(patch_inner, patch_outer):\n import matplotlib.path as mpath\n verts_inner = patch_inner.get_verts()\n verts_outer = patch_outer.get_verts()\n codes_inner = (np.ones(len(verts_inner), dtype=mpath.Path.code_type) *\n mpath.Path.LINETO)\n codes_inner[0] = mpath.Path.MOVETO\n codes_outer = (np.ones(len(verts_outer), dtype=mpath.Path.code_type) *\n mpath.Path.LINETO)\n codes_outer[0] = mpath.Path.MOVETO\n codes = np.concatenate((codes_inner, codes_outer))\n verts = np.concatenate((verts_inner, verts_outer[::-1]))\n return mpath.Path(verts, codes)\n\n\nclass _ABCMetaAndInheritDocstrings(InheritDocstrings, abc.ABCMeta):\n pass\n\n\n@six.add_metaclass(_ABCMetaAndInheritDocstrings)\nclass Aperture(object):\n \"\"\"\n Abstract base class for an arbitrary 2-d aperture.\n\n Derived classes should contain whatever internal data is needed to\n define the aperture, and provide methods `do_photometry` and `extent`\n (and optionally, ``area``).\n \"\"\"\n\n @abc.abstractmethod\n def extent(self):\n \"\"\"\n Extent of apertures. In the case when part of an aperture's extent\n falls out of the actual data region, the\n `~photutils.Aperture.get_phot_extents` method redefines the extent\n which has data coverage.\n\n Returns\n -------\n x_min, x_max, y_min, y_max : lists of floats\n Extent of the apertures.\n \"\"\"\n\n @abc.abstractmethod\n def plot(self, ax=None, fill=False, **kwargs):\n \"\"\"\n Plot the aperture(s) on a matplotlib Axes instance.\n\n Parameters\n ----------\n ax : `matplotlib.axes.Axes` instance, optional\n If `None`, then the current ``Axes`` instance is used.\n\n fill : bool, optional\n Set whether to fill the aperture patch. The default is\n `False`.\n\n kwargs\n Any keyword arguments accepted by `matplotlib.patches.Patch`.\n \"\"\"\n\n @abc.abstractmethod\n def do_photometry(self, data, error=None, gain=None, pixelwise_error=True,\n method='exact', subpixels=5):\n \"\"\"Sum flux within aperture(s).\n\n Parameters\n ----------\n data : array_like\n The 2-d array on which to perform photometry.\n error : array_like, optional\n Error in each pixel, interpreted as Gaussian 1-sigma uncertainty.\n ``error`` has to have the same shape as ``data``.\n gain : array_like, optional\n Ratio of counts (e.g., electrons or photons) to units of the\n data (e.g., ADU), for the purpose of calculating Poisson error from\n the object itself. ``gain`` has to have the same shape as ``data``.\n pixelwise_error : bool, optional\n For error and/or gain arrays. If `True`, assume error and/or gain\n vary significantly within an aperture: sum contribution from each\n pixel. If `False`, assume error and gain do not vary significantly\n within an aperture.\n method : str, optional\n Method to threat masked pixels. For the currently supported methods\n see the documentation of `aperture_photometry`.\n subpixels : int, optional\n For the ``'subpixel'`` method, resample pixels by this factor (in\n each dimension). That is, each pixel is divided into\n ``subpixels ** 2`` subpixels.\n\n Returns\n -------\n flux : `~astropy.units.Quantity`\n Sum of the values withint the aperture(s). Unit is kept to be the\n unit of the input ``data``.\n\n fluxvar : `~astropy.units.Quantity`\n Corresponting uncertainity in the ``flux`` values. Returned only\n if input ``error`` is not `None`.\n \"\"\"\n\n def get_phot_extents(self, data):\n \"\"\"\n Get the photometry extents and check if the apertures is fully out\n of data.\n\n Parameters\n ----------\n data : array_like\n The 2-d array on which to perform photometry.\n\n Returns\n -------\n extents : dict\n The ``extents`` dictionary contains 3 elements:\n\n * ``'ood_filter'``\n A boolean array with `True` elements where the aperture is\n falling out of the data region.\n * ``'pixel_extent'``\n x_min, x_max, y_min, y_max : Refined extent of apertures with\n data coverage.\n * ``'phot_extent'``\n x_pmin, x_pmax, y_pmin, y_pmax: Extent centered to the 0, 0\n positions as required by the `~photutils.geometry` functions.\n \"\"\"\n\n extents = self.extent()\n\n # Check if an aperture is fully out of data\n ood_filter = np.logical_or(extents[:, 0] >= data.shape[1],\n extents[:, 1] <= 0)\n np.logical_or(ood_filter, extents[:, 2] >= data.shape[0],\n out=ood_filter)\n np.logical_or(ood_filter, extents[:, 3] <= 0, out=ood_filter)\n\n # TODO check whether it makes sense to have negative pixel\n # coordinate, one could imagine a stackes image where the reference\n # was a bit offset from some of the images? Or in those cases just\n # give Skycoord to the Aperture and it should deal with the\n # conversion for the actual case?\n x_min = np.maximum(extents[:, 0], 0)\n x_max = np.minimum(extents[:, 1], data.shape[1])\n y_min = np.maximum(extents[:, 2], 0)\n y_max = np.minimum(extents[:, 3], data.shape[0])\n\n x_pmin = x_min - self.positions[:, 0] - 0.5\n x_pmax = x_max - self.positions[:, 0] - 0.5\n y_pmin = y_min - self.positions[:, 1] - 0.5\n y_pmax = y_max - self.positions[:, 1] - 0.5\n\n # TODO: check whether any pixel is nan in data[y_min[i]:y_max[i],\n # x_min[i]:x_max[i])), if yes return something valid rather than nan\n\n return {'ood_filter': ood_filter,\n 'pixel_extent': [x_min, x_max, y_min, y_max],\n 'phot_extent': [x_pmin, x_pmax, y_pmin, y_pmax]}\n\n\nclass CircularAperture(Aperture):\n \"\"\"\n Circular aperture(s).\n\n Parameters\n ----------\n positions : tuple, or list, or array\n Center coordinates of the apertures as list or array of (x, y)\n pixelcoordinates.\n r : float\n The radius of the aperture.\n\n Raises\n ------\n ValueError : `~.exceptions.ValueError`\n If the radius is negative.\n \"\"\"\n\n def __init__(self, positions, r):\n try:\n self.r = float(r)\n except TypeError:\n raise TypeError('r must be numeric, received {0}'.format(type(r)))\n\n if r < 0:\n raise ValueError('r must be non-negative')\n\n if isinstance(positions, u.Quantity):\n positions = positions.value\n if isinstance(positions, (list, tuple, np.ndarray)):\n self.positions = np.atleast_2d(positions)\n else:\n raise TypeError(\"List or array of (x,y) pixel coordinates is \"\n \"expected got '{0}'.\".format(positions))\n\n if self.positions.ndim > 2:\n raise ValueError('{0}-d position array not supported. Only 2-d '\n 'arrays supported.'.format(self.positions.ndim))\n\n def extent(self):\n extents = []\n for x, y in self.positions:\n extents.append((int(x - self.r + 0.5), int(x + self.r + 1.5),\n int(y - self.r + 0.5), int(y + self.r + 1.5)))\n\n return np.array(extents)\n\n def area(self):\n \"\"\"\n Returns\n -------\n area : float\n Area of aperture.\n \"\"\"\n return math.pi * self.r ** 2\n\n def plot(self, ax=None, fill=False, **kwargs):\n import matplotlib.pyplot as plt\n import matplotlib.patches as mpatches\n kwargs['fill'] = fill\n if ax is None:\n ax = plt.gca()\n for position in self.positions:\n patch = mpatches.Circle(position, self.r, **kwargs)\n ax.add_patch(patch)\n\n def do_photometry(self, data, error=None, gain=None, pixelwise_error=True,\n method='exact', subpixels=5):\n extents = super(CircularAperture, self).get_phot_extents(data)\n\n if method not in ('center', 'subpixel', 'exact'):\n raise ValueError('{0} method not supported for aperture class '\n '{1}'.format(method, self.__class__.__name__))\n\n flux = do_circular_photometry(data, self.positions, extents,\n self.r, error=error, gain=gain,\n pixelwise_error=pixelwise_error,\n method=method,\n subpixels=subpixels)\n return flux\n\n\nclass CircularAnnulus(Aperture):\n \"\"\"\n Circular annulus aperture.\n\n Parameters\n ----------\n positions : tuple, or list, or array\n Center coordinates of the apertures as list or array of (x, y)\n pixelcoordinates.\n r_in : float\n The inner radius of the annulus.\n r_out : float\n The outer radius of the annulus.\n\n Raises\n ------\n ValueError : `~.exceptions.ValueError`\n If inner radius (``r_in``) is greater than outer radius (``r_out``).\n ValueError : `~.exceptions.ValueError`\n If inner radius is negative.\n \"\"\"\n\n def __init__(self, positions, r_in, r_out):\n try:\n self.r_in = r_in\n self.r_out = r_out\n except TypeError:\n raise TypeError(\"'r_in' and 'r_out' must be numeric, received {0} \"\n \"and {1}\".format((type(r_in), type(r_out))))\n\n if not (r_out > r_in):\n raise ValueError('r_out must be greater than r_in')\n if r_in < 0:\n raise ValueError('r_in must be non-negative')\n\n if isinstance(positions, u.Quantity):\n positions = positions.value\n if isinstance(positions, (list, tuple, np.ndarray)):\n self.positions = np.atleast_2d(positions)\n else:\n raise TypeError(\"List or array of (x,y) pixel coordinates is \"\n \"expected got '{0}'.\".format(positions))\n\n if self.positions.ndim > 2:\n raise ValueError('{0}-d position array not supported. Only 2-d '\n 'arrays supported.'.format(self.positions.ndim))\n\n def extent(self):\n extents = []\n centers = []\n for x, y in self.positions:\n extents.append((int(x - self.r_out + 0.5),\n int(x + self.r_out + 1.5),\n int(y - self.r_out + 0.5),\n int(y + self.r_out + 1.5)))\n centers.append((x, x, y, y))\n\n self._centers = np.array(centers)\n return np.array(extents)\n\n def area(self):\n \"\"\"\n Returns\n -------\n area : float\n Area of aperture.\n \"\"\"\n return math.pi * (self.r_out ** 2 - self.r_in ** 2)\n\n def do_photometry(self, data, error=None, gain=None, pixelwise_error=True,\n method='exact', subpixels=5):\n extents = super(CircularAnnulus, self).get_phot_extents(data)\n\n if method not in ('center', 'subpixel', 'exact'):\n raise ValueError('{0} method not supported for aperture class '\n '{1}'.format(method, self.__class__.__name__))\n\n flux = do_annulus_photometry(data, self.positions, 'circular', extents,\n (self.r_in, ), (self.r_out, ),\n error=error, gain=gain,\n pixelwise_error=pixelwise_error,\n method=method,\n subpixels=subpixels)\n\n return flux\n\n def plot(self, ax=None, fill=False, **kwargs):\n import matplotlib.pyplot as plt\n import matplotlib.patches as mpatches\n kwargs['fill'] = fill\n if ax is None:\n ax = plt.gca()\n resolution = 20\n for position in self.positions:\n patch_inner = mpatches.CirclePolygon(position, self.r_in,\n resolution=resolution)\n patch_outer = mpatches.CirclePolygon(position, self.r_out,\n resolution=resolution)\n path = _make_annulus_path(patch_inner, patch_outer)\n patch = mpatches.PathPatch(path, **kwargs)\n ax.add_patch(patch)\n\n\nclass EllipticalAperture(Aperture):\n \"\"\"\n An elliptical aperture.\n\n Parameters\n ----------\n positions : tuple, or list, or array\n Center coordinates of the apertures as list or array of (x, y)\n pixelcoordinates.\n a : float\n The semimajor axis.\n b : float\n The semiminor axis.\n theta : float\n The position angle of the semimajor axis in radians\n (counterclockwise).\n\n Raises\n ------\n ValueError : `~.exceptions.ValueError`\n If either axis (``a`` or ``b``) is negative.\n\n \"\"\"\n\n def __init__(self, positions, a, b, theta):\n try:\n self.a = float(a)\n self.b = float(b)\n self.theta = float(theta)\n except TypeError:\n raise TypeError(\"'a' and 'b' and 'theta' must be numeric, received\"\n \"{0} and {1} and {2}.\"\n .format((type(a), type(b), type(theta))))\n\n if a < 0 or b < 0:\n raise ValueError(\"'a' and 'b' must be non-negative.\")\n\n if isinstance(positions, u.Quantity):\n positions = positions.value\n if isinstance(positions, (list, tuple, np.ndarray)):\n self.positions = np.atleast_2d(positions)\n else:\n raise TypeError(\"List or array of (x,y) pixel coordinates is \"\n \"expected got '{0}'.\".format(positions))\n\n if self.positions.ndim > 2:\n raise ValueError('{0}-d position array not supported. Only 2-d '\n 'arrays supported.'.format(self.positions.ndim))\n\n def extent(self):\n r = max(self.a, self.b)\n extents = []\n centers = []\n for x, y in self.positions:\n extents.append((int(x - r + 0.5), int(x + r + 1.5),\n int(y - r + 0.5), int(y + r + 1.5)))\n centers.append((x, x, y, y))\n\n self._centers = np.array(centers)\n return np.array(extents)\n\n def area(self):\n \"\"\"\n Returns\n -------\n area : float\n Area of aperture.\n \"\"\"\n return math.pi * self.a * self.b\n\n def do_photometry(self, data, error=None, gain=None, pixelwise_error=True,\n method='exact', subpixels=5):\n extents = super(EllipticalAperture, self).get_phot_extents(data)\n\n if method not in ('center', 'subpixel', 'exact'):\n raise ValueError('{0} method not supported for aperture class '\n '{1}'.format(method, self.__class__.__name__))\n\n flux = do_elliptical_photometry(data, self.positions, extents,\n self.a, self.b, self.theta,\n error=error, gain=gain,\n pixelwise_error=pixelwise_error,\n method=method,\n subpixels=subpixels)\n return flux\n\n def plot(self, ax=None, fill=False, **kwargs):\n import matplotlib.pyplot as plt\n import matplotlib.patches as mpatches\n kwargs['fill'] = fill\n if ax is None:\n ax = plt.gca()\n theta_deg = self.theta * 180. / np.pi\n for position in self.positions:\n patch = mpatches.Ellipse(position, self.a, self.b, theta_deg,\n **kwargs)\n ax.add_patch(patch)\n\n\nclass EllipticalAnnulus(Aperture):\n \"\"\"\n An elliptical annulus aperture.\n\n Parameters\n ----------\n positions : tuple, or list, or array\n Center coordinates of the apertures as list or array of (x, y)\n pixelcoordinates.\n a_in : float\n The inner semimajor axis.\n a_out : float\n The outer semimajor axis.\n b_out : float\n The outer semiminor axis. (The inner semiminor axis is determined\n by scaling by a_in/a_out.)\n theta : float\n The position angle of the semimajor axis in radians.\n (counterclockwise).\n\n Raises\n ------\n ValueError : `~.exceptions.ValueError`\n If inner semimajor axis (``a_in``) is greater than outer semimajor\n axis (``a_out``).\n ValueError : `~.exceptions.ValueError`\n If either the inner semimajor axis (``a_in``) or the outer semiminor\n axis (``b_out``) is negative.\n \"\"\"\n\n def __init__(self, positions, a_in, a_out, b_out, theta):\n try:\n self.a_in = float(a_in)\n self.a_out = float(a_out)\n self.b_out = float(b_out)\n self.theta = float(theta)\n except TypeError:\n raise TypeError(\"'a_in' and 'a_out' and 'b_out' and 'theta' must \"\n \"be numeric, received {0} and {1} and {2} and {3}.\"\n .format((type(a_in), type(a_out),\n type(b_out), type(theta))))\n\n if not (a_out > a_in):\n raise ValueError(\"'a_out' must be greater than 'a_in'\")\n if a_in < 0 or b_out < 0:\n raise ValueError(\"'a_in' and 'b_out' must be non-negative\")\n\n self.b_in = a_in * b_out / a_out\n\n if isinstance(positions, u.Quantity):\n positions = positions.value\n if isinstance(positions, (list, tuple, np.ndarray)):\n self.positions = np.atleast_2d(positions)\n else:\n raise TypeError(\"List or array of (x,y) pixel coordinates is \"\n \"expected got '{0}'.\".format(positions))\n\n if self.positions.ndim > 2:\n raise ValueError('{0}-d position array not supported. Only 2-d '\n 'arrays supported.'.format(self.positions.ndim))\n\n def extent(self):\n r = max(self.a_out, self.b_out)\n extents = []\n centers = []\n for x, y in self.positions:\n extents.append((int(x - r + 0.5), int(x + r + 1.5),\n int(y - r + 0.5), int(y + r + 1.5)))\n centers.append((x, x, y, y))\n\n self._centers = np.array(centers)\n return np.array(extents)\n\n def area(self):\n \"\"\"\n Returns\n -------\n area : float\n Area of aperture.\n \"\"\"\n return math.pi * (self.a_out * self.b_out - self.a_in * self.b_in)\n\n def plot(self, ax=None, fill=False, **kwargs):\n import matplotlib.pyplot as plt\n import matplotlib.patches as mpatches\n kwargs['fill'] = fill\n if ax is None:\n ax = plt.gca()\n theta_deg = self.theta * 180. / np.pi\n for position in self.positions:\n patch_inner = mpatches.Ellipse(position, self.a_in, self.b_in,\n theta_deg, **kwargs)\n patch_outer = mpatches.Ellipse(position, self.a_out, self.b_out,\n theta_deg, **kwargs)\n path = _make_annulus_path(patch_inner, patch_outer)\n patch = mpatches.PathPatch(path, **kwargs)\n ax.add_patch(patch)\n\n def do_photometry(self, data, error=None, gain=None, pixelwise_error=True,\n method='exact', subpixels=5):\n extents = super(EllipticalAnnulus, self).get_phot_extents(data)\n\n if method not in ('center', 'subpixel', 'exact'):\n raise ValueError('{0} method not supported for aperture class '\n '{1}'.format(method, self.__class__.__name__))\n\n flux = do_annulus_photometry(data, self.positions, 'elliptical',\n extents,\n (self.a_in, self.b_in, self.theta),\n (self.a_out, self.b_out, self.theta),\n error=error, gain=gain,\n pixelwise_error=pixelwise_error,\n method=method, subpixels=subpixels)\n return flux\n\n\nclass RectangularAperture(Aperture):\n \"\"\"\n A rectangular aperture.\n\n Parameters\n ----------\n positions : tuple, or list, or array\n Center coordinates of the apertures as list or array of (x, y)\n pixelcoordinates.\n w : float\n The full width of the aperture (at theta = 0, this is the \"x\" axis).\n h : float\n The full height of the aperture (at theta = 0, this is the \"y\" axis).\n theta : float\n The position angle of the semimajor axis in radians\n (counterclockwise).\n\n Raises\n ------\n ValueError : `~.exceptions.ValueError`\n If either width (``w``) or height (``h``) is negative.\n \"\"\"\n\n def __init__(self, positions, w, h, theta):\n try:\n self.w = float(w)\n self.h = float(h)\n self.theta = float(theta)\n except TypeError:\n raise TypeError(\"'w' and 'h' and 'theta' must \"\n \"be numeric, received {0} and {1} and {2}.\"\n .format((type(w), type(h), type(theta))))\n if w < 0 or h < 0:\n raise ValueError(\"'w' and 'h' must be nonnegative.\")\n\n if isinstance(positions, u.Quantity):\n positions = positions.value\n if isinstance(positions, (list, tuple, np.ndarray)):\n self.positions = np.atleast_2d(positions)\n else:\n raise TypeError(\"List or array of (x,y) pixel coordinates is \"\n \"expected got '{0}'.\".format(positions))\n\n if self.positions.ndim > 2:\n raise ValueError('{0}-d position array not supported. Only 2-d '\n 'arrays supported.'.format(self.positions.ndim))\n\n def extent(self):\n r = max(self.h, self.w) * 2 ** -0.5\n # this is an overestimate by up to sqrt(2) unless theta = 45 deg\n extents = []\n centers = []\n for x, y in self.positions:\n extents.append((int(x - r + 0.5), int(x + r + 1.5),\n int(y - r + 0.5), int(y + r + 1.5)))\n centers.append((x, x, y, y))\n\n self._centers = np.array(centers)\n return np.array(extents)\n\n def area(self):\n \"\"\"\n Returns\n -------\n area : float\n Area of aperture.\n \"\"\"\n return self.w * self.h\n\n def plot(self, ax=None, fill=False, **kwargs):\n import matplotlib.pyplot as plt\n import matplotlib.patches as mpatches\n kwargs['fill'] = fill\n if ax is None:\n ax = plt.gca()\n hw = self.w / 2.\n hh = self.h / 2.\n sint = math.sin(self.theta)\n cost = math.cos(self.theta)\n dx = (hh * sint) - (hw * cost)\n dy = -(hh * cost) - (hw * sint)\n positions = self.positions + np.array([dx, dy])\n theta_deg = self.theta * 180. / np.pi\n for position in positions:\n patch = mpatches.Rectangle(position, self.w, self.h, theta_deg,\n **kwargs)\n ax.add_patch(patch)\n\n def do_photometry(self, data, error=None, gain=None, pixelwise_error=True,\n method='subpixel', subpixels=5):\n\n extents = super(RectangularAperture, self).get_phot_extents(data)\n\n if method not in ('center', 'subpixel', 'exact'):\n raise ValueError('{0} method not supported for aperture class '\n '{1}'.format(method, self.__class__.__name__))\n\n ood_filter = extents['ood_filter']\n x_min, x_max, y_min, y_max = extents['pixel_extent']\n x_pmin, x_pmax, y_pmin, y_pmax = extents['phot_extent']\n\n flux = u.Quantity(np.zeros(len(self.positions), dtype=np.float),\n unit=data.unit)\n\n # Check for invalid aperture\n if self.w == 0 or self.h == 0:\n return (flux, )\n\n # TODO: flag these objects\n if np.sum(ood_filter):\n flux[ood_filter] = np.nan\n warnings.warn(\"The aperture at position {0} does not have any \"\n \"overlap with the data\"\n .format(self.positions[ood_filter]),\n AstropyUserWarning)\n if np.sum(ood_filter) == len(self.positions):\n return (flux, )\n\n if error is not None:\n fluxvar = u.Quantity(np.zeros(len(self.positions), dtype=np.float),\n unit=error.unit ** 2)\n\n if method in ('center', 'subpixel'):\n if method == 'center': subpixels = 1\n if method == 'subpixel': from imageutils import downsample\n\n for i in range(len(flux)):\n x_size = ((x_pmax[i] - x_pmin[i]) /\n (data[:, x_min[i]:x_max[i]].shape[1] * subpixels))\n y_size = ((y_pmax[i] - y_pmin[i]) /\n (data[y_min[i]:y_max[i], :].shape[0] * subpixels))\n\n x_centers = np.arange(x_pmin[i] + x_size / 2.,\n x_pmax[i], x_size)\n y_centers = np.arange(y_pmin[i] + y_size / 2.,\n y_pmax[i], y_size)\n\n xx, yy = np.meshgrid(x_centers, y_centers)\n\n newx = (xx * math.cos(self.theta) +\n yy * math.sin(self.theta))\n newy = (yy * math.cos(self.theta) -\n xx * math.sin(self.theta))\n\n halfw = self.w / 2\n halfh = self.h / 2\n in_aper = (((-halfw < newx) & (newx < halfw) &\n (-halfh < newy) & (newy < halfh)).astype(float)\n / subpixels ** 2)\n\n if method == 'center':\n if not np.isnan(flux[i]):\n flux[i] = np.sum(data[y_min[i]:y_max[i],\n x_min[i]:x_max[i]] * in_aper)\n if error is not None:\n if pixelwise_error:\n subvariance = error[y_min[i]:y_max[i],\n x_min[i]:x_max[i]] ** 2\n if gain is not None:\n subvariance += (data[y_min[i]:y_max[i],\n x_min[i]:x_max[i]] /\n gain[y_min[i]:y_max[i],\n x_min[i]:x_max[i]])\n # Make sure variance is > 0\n fluxvar[i] = max(np.sum(subvariance * in_aper), 0)\n else:\n local_error = error[int((y_min[i] + y_max[i]) / 2 + 0.5),\n int((x_min[i] + x_max[i]) / 2 + 0.5)]\n fluxvar[i] = max(local_error ** 2 * np.sum(in_aper), 0)\n if gain is not None:\n local_gain = gain[int((y_min[i] + y_max[i]) / 2 + 0.5),\n int((x_min[i] + x_max[i]) / 2 + 0.5)]\n fluxvar[i] += flux[i] / local_gain\n else:\n if not np.isnan(flux[i]):\n if error is None:\n flux[i] = np.sum(data[y_min[i]:y_max[i],\n x_min[i]:x_max[i]] *\n downsample(in_aper, subpixels))\n else:\n fraction = downsample(in_aper, subpixels)\n flux[i] = np.sum(data[y_min[i]:y_max[i],\n x_min[i]:x_max[i]] * fraction)\n\n if pixelwise_error:\n subvariance = error[y_min[i]:y_max[i],\n x_min[i]:x_max[i]] ** 2\n if gain is not None:\n subvariance += (data[y_min[i]:y_max[i],\n x_min[i]:x_max[i]] /\n gain[y_min[i]:y_max[i],\n x_min[i]:x_max[i]])\n # Make sure variance is > 0\n fluxvar[i] = max(np.sum(subvariance * fraction), 0)\n else:\n local_error = error[int((y_min[i] + y_max[i]) / 2 + 0.5),\n int((x_min[i] + x_max[i]) / 2 + 0.5)]\n fluxvar[i] = max(local_error ** 2 * np.sum(fraction), 0)\n if gain is not None:\n local_gain = gain[int((y_min[i] + y_max[i]) / 2 + 0.5),\n int((x_min[i] + x_max[i]) / 2 + 0.5)]\n fluxvar[i] += flux[i] / local_gain\n\n elif method == 'exact':\n raise NotImplementedError(\"'exact' method not yet supported for \"\n \"RectangularAperture\")\n else:\n raise ValueError('{0} method not supported for aperture class '\n '{1}'.format(method, self.__class__.__name__))\n\n if error is None:\n return (flux, )\n else:\n return (flux, np.sqrt(fluxvar))\n\n\ndef aperture_photometry(data, positions, apertures, unit=None, wcs=None,\n error=None, gain=None, mask=None, method='exact',\n subpixels=5, pixelcoord=True, pixelwise_error=True,\n mask_method='skip'):\n \"\"\"\n Sum flux within an aperture at the given position(s).\n\n Parameters\n ----------\n data : array_like, `~astropy.io.fits.ImageHDU`, `~astropy.io.fits.HDUList`\n The 2-d array on which to perform photometry. Units are used during\n the photometry, either provided along with the data array, or stored\n in the header keyword ``'BUNIT'``.\n positions : list, tuple, nd.array or `~astropy.coordinates.SkyCoord`\n Positions of the aperture centers, either in pixel or sky\n coordinates. If positions is `~astropy.coordinates.SkyCoord` or\n ``pixelcoord`` is `False` a wcs transformation is also needed to\n convert the input positions to pixel positions. If ``positions`` are\n sky positions but not an `~astropy.coordinates.SkyCoord` object, it\n need to be in the same celestial frame as the wcs transformation.\n apertures : tuple\n First element of the tuple is the mode, the currently supported ones\n are: ``'circular'``, ``'elliptical'``, ``'circular_annulus'``,\n ``'elliptical_annulus'``, ``'rectangular'``. The remaining (1 to 4)\n elements are the parameters for the given mode. Check the\n documentation of the relevant ``Aperture`` classes for more\n information.\n unit : `~astropy.units.UnitBase` instance, str\n An object that represents the unit associated with ``data``. Must\n be an `~astropy.units.UnitBase` object or a string parseable by the\n :mod:`~astropy.units` package. An error is raised if ``data``\n already has a different unit.\n wcs : `~astropy.wcs.WCS`, optional\n Use this as the wcs transformation when either ``pixelcoord`` is\n `False` or ``positions`` is `~astropy.coordinates.SkyCoord`. It\n overrides any wcs transformation passed along with ``data`` either\n in the header or in an attribute.\n error : float or array_like, optional\n Error in each pixel, interpreted as Gaussian 1-sigma uncertainty.\n gain : float or array_like, optional\n Ratio of counts (e.g., electrons or photons) to units of the data\n (e.g., ADU), for the purpose of calculating Poisson error from the\n object itself. If ``gain`` is `None` (default), ``error`` is assumed to\n include all uncertainty in each pixel. If ``gain`` is given, ``error``\n is assumed to be the \"background error\" only (not accounting for\n Poisson error in the flux in the apertures).\n mask : array_like (bool), optional\n Mask to apply to the data.\n method : str, optional\n Method to use for determining overlap between the aperture and pixels.\n Options include ['center', 'subpixel', 'exact'], but not all options\n are available for all types of apertures. More precise methods will\n generally be slower.\n\n * ``'center'``\n A pixel is considered to be entirely in or out of the aperture\n depending on whether its center is in or out of the aperture.\n * ``'subpixel'``\n A pixel is divided into subpixels and the center of each\n subpixel is tested (as above). With ``subpixels`` set to 1, this\n method is equivalent to 'center'. Note that for subpixel\n sampling, the input array is only resampled once for each\n object.\n * ``'exact'`` (default)\n The exact overlap between the aperture and each pixel is\n calculated.\n subpixels : int, optional\n For the ``'subpixel'`` method, resample pixels by this factor (in\n each dimension). That is, each pixel is divided into\n ``subpixels ** 2`` subpixels.\n pixelcoord : bool, optional\n If `True` (default), assume ``positions`` are pixel positions. If\n `False`, assume the input positions are sky coordinates and uses the\n wcs transformation (provided either via ``wcs`` or along with\n ``data``) to convert them to pixel positions.\n pixelwise_error : bool, optional\n For error and/or gain arrays. If `True`, assume error and/or gain\n vary significantly within an aperture: sum contribution from each\n pixel. If `False`, assume error and gain do not vary significantly\n within an aperture. Use the single value of error and/or gain at\n the center of each aperture as the value for the entire aperture.\n Default is `True`.\n mask_method : str, optional\n Method to treat masked pixels. Currently supported methods:\n\n * ``'skip'``\n Leave out the masked pixels from all calculations.\n * ``'interpolation'``\n The value of the masked pixels are replaced by the mean value of\n the neighbouring non-masked pixels.\n\n Returns\n -------\n phot_table : `~astropy.table.Table`\n A table of the photometry with the following columns:\n\n * ``'aperture_sum'``: Sum of the values within the aperture.\n * ``'aperture_sum_err'``: Corresponding uncertainty in\n ``'aperture_sum'`` values. Returned only if input ``error`` is not\n `None`.\n * ``'pixel_center'``: pixel coordinate pairs of the center of the\n apertures. Unit is pixel.\n * ``'input_center'``: input coordinate pairs as they were given in the\n ``positions`` parameter.\n\n The metadata of the table stores the version numbers of both astropy\n and photutils, as well as the calling arguments.\n aux_dict : dict\n Auxilary dictionary storing all the auxilary information\n available. The element are the following:\n\n * ``'apertures'``\n The `~photutils.Aperture` object containing the apertures to use\n during the photometry.\n\n \"\"\"\n dataunit = None\n datamask = None\n wcs_transformation = wcs\n\n if isinstance(data, (fits.PrimaryHDU, fits.ImageHDU)):\n header = data.header\n data = data.data\n\n if 'BUNIT' in header:\n dataunit = header['BUNIT']\n\n # TODO check how a mask can be stored in the header, it seems like\n # full pixel masks are not supported by the FITS standard, look for\n # real life examples (e.g. header value stores the fits number of\n # fits extension where the pixelmask is stored?)\n if 'MASK' in header:\n datamask = header.mask\n\n elif isinstance(data, fits.HDUList):\n # TODO: do it in a 2d array, and thus get the light curves as a\n # side-product? Although it's not usual to store time series as\n # HDUList\n\n for i in range(len(data)):\n if data[i].data is not None:\n warnings.warn(\"Input data is a HDUList object, photometry is \"\n \"only run for the {0}. HDU.\"\n .format(i), AstropyUserWarning)\n return aperture_photometry(data[i], positions, apertures, unit,\n wcs, error, gain, mask, method,\n subpixels, pixelcoord,\n pixelwise_error, mask_method)\n\n # this is basically for NDData inputs and alike\n elif hasattr(data, 'data') and not isinstance(data, np.ndarray):\n if data.wcs is not None and wcs_transformation is None:\n wcs_transformation = data.wcs\n datamask = data.mask\n\n if hasattr(data, 'unit'):\n dataunit = data.unit\n\n if unit is not None and dataunit is not None:\n if unit != dataunit:\n raise u.UnitsError('Unit of input data ({0}) and unit given by '\n 'unit argument ({1}) are not identical.'.\n format(dataunit, unit))\n data = u.Quantity(data, unit=dataunit, copy=False)\n elif unit is None:\n if dataunit is not None:\n data = u.Quantity(data, unit=dataunit, copy=False)\n else:\n data = u.Quantity(data, copy=False)\n else:\n data = u.Quantity(data, unit=unit, copy=False)\n\n if datamask is None:\n data.mask = datamask\n\n # Check input array type and dimension.\n if np.iscomplexobj(data):\n raise TypeError('Complex type not supported')\n if data.ndim != 2:\n raise ValueError('{0}-d array not supported. '\n 'Only 2-d arrays supported.'.format(data.ndim))\n\n # Deal with the mask if it exist\n if mask is not None or datamask is not None:\n if mask is None:\n mask = datamask\n else:\n mask = np.asarray(mask)\n if np.iscomplexobj(mask):\n raise TypeError('Complex type not supported')\n if mask.ndim != 2:\n raise ValueError('{0}-d array not supported. '\n 'Only 2-d arrays supported.'\n .format(mask.ndim))\n if mask.shape != data.shape:\n raise ValueError('Shapes of mask array and data array '\n 'must match')\n\n if datamask is not None:\n mask *= datamask\n\n if mask_method == 'skip':\n data *= ~mask\n\n if mask_method == 'interpolation':\n for i, j in zip(*np.nonzero(mask)):\n y0, y1 = max(i - 1, 0), min(i + 2, data.shape[0])\n x0, x1 = max(j - 1, 0), min(j + 2, data.shape[1])\n data[i, j] = np.mean(data[y0:y1, x0:x1][~mask[y0:y1, x0:x1]])\n\n # Check whether we really need to calculate pixelwise errors, even if\n # requested. (If neither error nor gain is an array, we don't need to.)\n if ((error is None) or\n (np.isscalar(error) and gain is None) or\n (np.isscalar(error) and np.isscalar(gain))):\n pixelwise_error = False\n\n # Check error shape.\n if error is not None:\n if isinstance(error, u.Quantity):\n if np.isscalar(error.value):\n error = u.Quantity(np.broadcast_arrays(error, data),\n unit=error.unit)[0]\n elif np.isscalar(error):\n error = u.Quantity(np.broadcast_arrays(error, data),\n unit=data.unit)[0]\n else:\n error = u.Quantity(error, unit=data.unit, copy=False)\n\n if error.shape != data.shape:\n raise ValueError('shapes of error array and data array must'\n ' match')\n\n # Check gain shape.\n if gain is not None:\n # Gain doesn't do anything without error set, so raise an exception.\n # (TODO: instead, should we just set gain = None and ignore it?)\n if error is None:\n raise ValueError('gain requires error')\n\n if isinstance(gain, u.Quantity):\n if np.isscalar(gain.value):\n gain = u.Quantity(np.broadcast_arrays(gain, data),\n unit=gain.unit)[0]\n\n elif np.isscalar(gain):\n gain = np.broadcast_arrays(gain, data)[0]\n if gain.shape != data.shape:\n raise ValueError('shapes of gain array and data array must match')\n\n # Check that 'subpixels' is an int and is 1 or greater.\n if method == 'subpixel':\n subpixels = int(subpixels)\n if subpixels < 1:\n raise ValueError('subpixels: an integer greater than 0 is '\n 'required')\n\n if not pixelcoord or isinstance(positions, SkyCoord):\n\n from astropy.wcs import wcs\n\n try:\n from astropy.wcs.utils import wcs_to_celestial_frame\n except ImportError: # Astropy < 1.0\n from .extern.wcs_utils import wcs_to_celestial_frame\n\n if wcs_transformation is None:\n wcs_transformation = wcs.WCS(header)\n\n # TODO this should be simplified once wcs_world2pix() supports\n # SkyCoord objects as input\n if isinstance(positions, SkyCoord):\n # Check which frame the wcs uses\n framename = wcs_to_celestial_frame(wcs_transformation).name\n frame = getattr(positions, framename)\n component_names = list(frame.representation_component_names.keys())[0:2]\n if len(positions.shape) > 0:\n positions_repr = u.Quantity(zip(getattr(frame,\n component_names[0]).deg,\n getattr(frame,\n component_names[1]).deg),\n unit=u.deg)\n else:\n positions_repr = (u.Quantity((getattr(frame,\n component_names[0]).deg,\n getattr(frame,\n component_names[1]).deg),\n unit=u.deg), )\n elif not isinstance(positions, u.Quantity):\n # TODO figure out the unit of the input positions for this case\n # TODO revise this once wcs_world2pix() accepts more input formats\n if len(positions) > 1 and not isinstance(positions, tuple):\n positions_repr = u.Quantity(positions, copy=False)\n else:\n positions_repr = (u.Quantity(positions, copy=False), )\n pixelpositions = u.Quantity(wcs_transformation.wcs_world2pix\n (positions_repr, 0), unit=u.pixel,\n copy=False)\n else:\n positions = u.Quantity(positions, unit=u.pixel, copy=False)\n pixelpositions = positions\n\n if apertures[0] == 'circular':\n ap = CircularAperture(pixelpositions.value, apertures[1])\n elif apertures[0] == 'circular_annulus':\n ap = CircularAnnulus(pixelpositions.value, *apertures[1:3])\n elif apertures[0] == 'elliptical':\n ap = EllipticalAperture(pixelpositions.value, *apertures[1:4])\n elif apertures[0] == 'elliptical_annulus':\n ap = EllipticalAnnulus(pixelpositions.value, *apertures[1:5])\n elif apertures[0] == 'rectangular':\n if method == 'exact':\n warnings.warn(\"'exact' method is not implemented, defaults to \"\n \"'subpixel' instead\", AstropyUserWarning)\n method = 'subpixel'\n ap = RectangularAperture(pixelpositions.value, *apertures[1:4])\n\n # Prepare version return data\n from astropy import __version__\n astropy_version = __version__\n\n from photutils import __version__\n photutils_version = __version__\n\n photometry_result = ap.do_photometry(data, method=method,\n subpixels=subpixels,\n error=error, gain=gain,\n pixelwise_error=pixelwise_error)\n if error is None:\n phot_col_names = ('aperture_sum', )\n else:\n phot_col_names = ('aperture_sum', 'aperture_sum_err')\n\n # Note: if wcs_transformation is None, 'pixel_center' will be the same\n # as 'input_center'\n\n # check whether single or multiple positions\n if len(pixelpositions) > 1 and pixelpositions[0].size >= 2:\n coord_columns = (pixelpositions, positions)\n else:\n coord_columns = ((pixelpositions,), (positions,))\n\n coord_col_names = ('pixel_center', 'input_center')\n\n return (Table(data=(photometry_result + coord_columns),\n names=(phot_col_names + coord_col_names),\n meta={'name': 'Aperture photometry results',\n 'version': 'astropy: {0}, photutils: {1}'\n .format(astropy_version, photutils_version),\n 'calling_args': ('method={0}, subpixels={1}, '\n 'error={2}, gain={3}, '\n 'pixelwise_error={4}')\n .format(method, subpixels, error is not None,\n gain is not None, pixelwise_error)}),\n {'apertures': ap})\n", "meta": {"hexsha": "7c9d8ac2b497972e18706dc174f5fa59af72a1a5", "size": 47398, "ext": "py", "lang": "Python", "max_stars_repo_path": "photutils/aperture_core.py", "max_stars_repo_name": "hamogu/photutils", "max_stars_repo_head_hexsha": "d032c703260482aa57fc76c1adb7d244b376c39a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "photutils/aperture_core.py", "max_issues_repo_name": "hamogu/photutils", "max_issues_repo_head_hexsha": "d032c703260482aa57fc76c1adb7d244b376c39a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-02-19T14:00:04.000Z", "max_issues_repo_issues_event_max_datetime": "2016-02-19T14:00:04.000Z", "max_forks_repo_path": "photutils/aperture_core.py", "max_forks_repo_name": "hamogu/photutils", "max_forks_repo_head_hexsha": "d032c703260482aa57fc76c1adb7d244b376c39a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9662921348, "max_line_length": 91, "alphanum_fraction": 0.5363095489, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 10473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.20689405859634893, "lm_q1q2_score": 0.1202681556980033}} {"text": "#!/usr/bin/env python\n__doc__ = \"\"\"\nCalculate Root-mean-square deviation (RMSD) between structure A and B, in XYZ\nor PDB format, using transformation and rotation.\n\nFor more information, usage, example and citation read more at\nhttps://github.com/charnley/rmsd\n\"\"\"\n\n__version__ = \"1.4\"\n\nimport argparse\nimport copy\nimport gzip\nimport pathlib\nimport re\nimport sys\n\nimport numpy as np\nfrom scipy.optimize import linear_sum_assignment\nfrom scipy.spatial import distance_matrix\nfrom scipy.spatial.distance import cdist\n\ntry:\n import qml\nexcept ImportError:\n qml = None\n\n\nMETHOD_KABSCH = \"kabsch\"\nMETHOD_QUATERNION = \"quaternion\"\nMETHOD_NOROTATION = \"none\"\nROTATION_METHODS = [METHOD_KABSCH, METHOD_QUATERNION, METHOD_NOROTATION]\n\n\nREORDER_NONE = \"none\"\nREORDER_QML = \"qml\"\nREORDER_HUNGARIAN = \"hungarian\"\nREORDER_INERTIA_HUNGARIAN = \"inertia-hungarian\"\nREORDER_BRUTE = \"brute\"\nREORDER_DISTANCE = \"distance\"\nREORDER_METHODS = [\n REORDER_NONE,\n REORDER_QML,\n REORDER_HUNGARIAN,\n REORDER_INERTIA_HUNGARIAN,\n REORDER_BRUTE,\n REORDER_DISTANCE,\n]\n\n\nAXIS_SWAPS = np.array(\n [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 1, 0], [2, 0, 1]]\n)\n\nAXIS_REFLECTIONS = np.array(\n [\n [1, 1, 1],\n [-1, 1, 1],\n [1, -1, 1],\n [1, 1, -1],\n [-1, -1, 1],\n [-1, 1, -1],\n [1, -1, -1],\n [-1, -1, -1],\n ]\n)\n\nELEMENT_WEIGHTS = {\n 1: 1.00797,\n 2: 4.00260,\n 3: 6.941,\n 4: 9.01218,\n 5: 10.81,\n 6: 12.011,\n 7: 14.0067,\n 8: 15.9994,\n 9: 18.998403,\n 10: 20.179,\n 11: 22.98977,\n 12: 24.305,\n 13: 26.98154,\n 14: 28.0855,\n 15: 30.97376,\n 16: 32.06,\n 17: 35.453,\n 19: 39.0983,\n 18: 39.948,\n 20: 40.08,\n 21: 44.9559,\n 22: 47.90,\n 23: 50.9415,\n 24: 51.996,\n 25: 54.9380,\n 26: 55.847,\n 28: 58.70,\n 27: 58.9332,\n 29: 63.546,\n 30: 65.38,\n 31: 69.72,\n 32: 72.59,\n 33: 74.9216,\n 34: 78.96,\n 35: 79.904,\n 36: 83.80,\n 37: 85.4678,\n 38: 87.62,\n 39: 88.9059,\n 40: 91.22,\n 41: 92.9064,\n 42: 95.94,\n 43: 98,\n 44: 101.07,\n 45: 102.9055,\n 46: 106.4,\n 47: 107.868,\n 48: 112.41,\n 49: 114.82,\n 50: 118.69,\n 51: 121.75,\n 53: 126.9045,\n 52: 127.60,\n 54: 131.30,\n 55: 132.9054,\n 56: 137.33,\n 57: 138.9055,\n 58: 140.12,\n 59: 140.9077,\n 60: 144.24,\n 61: 145,\n 62: 150.4,\n 63: 151.96,\n 64: 157.25,\n 65: 158.9254,\n 66: 162.50,\n 67: 164.9304,\n 68: 167.26,\n 69: 168.9342,\n 70: 173.04,\n 71: 174.967,\n 72: 178.49,\n 73: 180.9479,\n 74: 183.85,\n 75: 186.207,\n 76: 190.2,\n 77: 192.22,\n 78: 195.09,\n 79: 196.9665,\n 80: 200.59,\n 81: 204.37,\n 82: 207.2,\n 83: 208.9804,\n 84: 209,\n 85: 210,\n 86: 222,\n 87: 223,\n 88: 226.0254,\n 89: 227.0278,\n 91: 231.0359,\n 90: 232.0381,\n 93: 237.0482,\n 92: 238.029,\n 94: 242,\n 95: 243,\n 97: 247,\n 96: 247,\n 102: 250,\n 98: 251,\n 99: 252,\n 108: 255,\n 109: 256,\n 100: 257,\n 101: 258,\n 103: 260,\n 104: 261,\n 107: 262,\n 105: 262,\n 106: 263,\n 110: 269,\n 111: 272,\n 112: 277,\n}\n\nELEMENT_NAMES = {\n 1: \"H\",\n 2: \"He\",\n 3: \"Li\",\n 4: \"Be\",\n 5: \"B\",\n 6: \"C\",\n 7: \"N\",\n 8: \"O\",\n 9: \"F\",\n 10: \"Ne\",\n 11: \"Na\",\n 12: \"Mg\",\n 13: \"Al\",\n 14: \"Si\",\n 15: \"P\",\n 16: \"S\",\n 17: \"Cl\",\n 18: \"Ar\",\n 19: \"K\",\n 20: \"Ca\",\n 21: \"Sc\",\n 22: \"Ti\",\n 23: \"V\",\n 24: \"Cr\",\n 25: \"Mn\",\n 26: \"Fe\",\n 27: \"Co\",\n 28: \"Ni\",\n 29: \"Cu\",\n 30: \"Zn\",\n 31: \"Ga\",\n 32: \"Ge\",\n 33: \"As\",\n 34: \"Se\",\n 35: \"Br\",\n 36: \"Kr\",\n 37: \"Rb\",\n 38: \"Sr\",\n 39: \"Y\",\n 40: \"Zr\",\n 41: \"Nb\",\n 42: \"Mo\",\n 43: \"Tc\",\n 44: \"Ru\",\n 45: \"Rh\",\n 46: \"Pd\",\n 47: \"Ag\",\n 48: \"Cd\",\n 49: \"In\",\n 50: \"Sn\",\n 51: \"Sb\",\n 52: \"Te\",\n 53: \"I\",\n 54: \"Xe\",\n 55: \"Cs\",\n 56: \"Ba\",\n 57: \"La\",\n 58: \"Ce\",\n 59: \"Pr\",\n 60: \"Nd\",\n 61: \"Pm\",\n 62: \"Sm\",\n 63: \"Eu\",\n 64: \"Gd\",\n 65: \"Tb\",\n 66: \"Dy\",\n 67: \"Ho\",\n 68: \"Er\",\n 69: \"Tm\",\n 70: \"Yb\",\n 71: \"Lu\",\n 72: \"Hf\",\n 73: \"Ta\",\n 74: \"W\",\n 75: \"Re\",\n 76: \"Os\",\n 77: \"Ir\",\n 78: \"Pt\",\n 79: \"Au\",\n 80: \"Hg\",\n 81: \"Tl\",\n 82: \"Pb\",\n 83: \"Bi\",\n 84: \"Po\",\n 85: \"At\",\n 86: \"Rn\",\n 87: \"Fr\",\n 88: \"Ra\",\n 89: \"Ac\",\n 90: \"Th\",\n 91: \"Pa\",\n 92: \"U\",\n 93: \"Np\",\n 94: \"Pu\",\n 95: \"Am\",\n 96: \"Cm\",\n 97: \"Bk\",\n 98: \"Cf\",\n 99: \"Es\",\n 100: \"Fm\",\n 101: \"Md\",\n 102: \"No\",\n 103: \"Lr\",\n 104: \"Rf\",\n 105: \"Db\",\n 106: \"Sg\",\n 107: \"Bh\",\n 108: \"Hs\",\n 109: \"Mt\",\n 110: \"Ds\",\n 111: \"Rg\",\n 112: \"Cn\",\n 114: \"Uuq\",\n 116: \"Uuh\",\n}\n\nNAMES_ELEMENT = {value: key for key, value in ELEMENT_NAMES.items()}\n\n\ndef str_atom(atom):\n \"\"\"\n Convert atom type from integer to string\n\n Parameters\n ----------\n atoms : string\n\n Returns\n -------\n atoms : integer\n\n \"\"\"\n atom = ELEMENT_NAMES[atom]\n return atom\n\n\ndef int_atom(atom):\n \"\"\"\n Convert atom type from string to integer\n\n Parameters\n ----------\n atoms : string\n\n Returns\n -------\n atoms : integer\n\n \"\"\"\n\n atom = atom.capitalize()\n return NAMES_ELEMENT[atom]\n\n\ndef rmsd(V, W):\n \"\"\"\n Calculate Root-mean-square deviation from two sets of vectors V and W.\n\n Parameters\n ----------\n V : array\n (N,D) matrix, where N is points and D is dimension.\n W : array\n (N,D) matrix, where N is points and D is dimension.\n\n Returns\n -------\n rmsd : float\n Root-mean-square deviation between the two vectors\n \"\"\"\n diff = np.array(V) - np.array(W)\n N = len(V)\n return np.sqrt((diff * diff).sum() / N)\n\n\ndef kabsch_rmsd(P, Q, W=None, translate=False):\n \"\"\"\n Rotate matrix P unto Q using Kabsch algorithm and calculate the RMSD.\n An optional vector of weights W may be provided.\n\n Parameters\n ----------\n P : array\n (N,D) matrix, where N is points and D is dimension.\n Q : array\n (N,D) matrix, where N is points and D is dimension.\n W : array or None\n (N) vector, where N is points.\n translate : bool\n Use centroids to translate vector P and Q unto each other.\n\n Returns\n -------\n rmsd : float\n root-mean squared deviation\n \"\"\"\n\n if translate:\n Q = Q - centroid(Q)\n P = P - centroid(P)\n\n if W is not None:\n return kabsch_weighted_rmsd(P, Q, W)\n\n P = kabsch_rotate(P, Q)\n return rmsd(P, Q)\n\n\ndef kabsch_rotate(P, Q):\n \"\"\"\n Rotate matrix P unto matrix Q using Kabsch algorithm.\n\n Parameters\n ----------\n P : array\n (N,D) matrix, where N is points and D is dimension.\n Q : array\n (N,D) matrix, where N is points and D is dimension.\n\n Returns\n -------\n P : array\n (N,D) matrix, where N is points and D is dimension,\n rotated\n\n \"\"\"\n U = kabsch(P, Q)\n\n # Rotate P\n P = np.dot(P, U)\n return P\n\n\ndef kabsch_fit(P, Q, W=None):\n \"\"\"\n Rotate and translate matrix P unto matrix Q using Kabsch algorithm.\n An optional vector of weights W may be provided.\n\n Parameters\n ----------\n P : array\n (N,D) matrix, where N is points and D is dimension.\n Q : array\n (N,D) matrix, where N is points and D is dimension.\n W : array or None\n (N) vector, where N is points.\n\n Returns\n -------\n P : array\n (N,D) matrix, where N is points and D is dimension,\n rotated and translated.\n\n \"\"\"\n if W is not None:\n P = kabsch_weighted_fit(P, Q, W, rmsd=False)\n else:\n QC = centroid(Q)\n Q = Q - QC\n P = P - centroid(P)\n P = kabsch_rotate(P, Q) + QC\n return P\n\n\ndef kabsch(P, Q):\n \"\"\"\n Using the Kabsch algorithm with two sets of paired point P and Q, centered\n around the centroid. Each vector set is represented as an NxD\n matrix, where D is the the dimension of the space.\n The algorithm works in three steps:\n - a centroid translation of P and Q (assumed done before this function\n call)\n - the computation of a covariance matrix C\n - computation of the optimal rotation matrix U\n For more info see http://en.wikipedia.org/wiki/Kabsch_algorithm\n Parameters\n ----------\n P : array\n (N,D) matrix, where N is points and D is dimension.\n Q : array\n (N,D) matrix, where N is points and D is dimension.\n Returns\n -------\n U : matrix\n Rotation matrix (D,D)\n \"\"\"\n\n # Computation of the covariance matrix\n C = np.dot(np.transpose(P), Q)\n\n # Computation of the optimal rotation matrix\n # This can be done using singular value decomposition (SVD)\n # Getting the sign of the det(V)*(W) to decide\n # whether we need to correct our rotation matrix to ensure a\n # right-handed coordinate system.\n # And finally calculating the optimal rotation matrix U\n # see http://en.wikipedia.org/wiki/Kabsch_algorithm\n V, S, W = np.linalg.svd(C)\n d = (np.linalg.det(V) * np.linalg.det(W)) < 0.0\n\n if d:\n S[-1] = -S[-1]\n V[:, -1] = -V[:, -1]\n\n # Create Rotation matrix U\n U = np.dot(V, W)\n\n return U\n\n\ndef kabsch_weighted(P, Q, W=None):\n \"\"\"\n Using the Kabsch algorithm with two sets of paired point P and Q.\n Each vector set is represented as an NxD matrix, where D is the\n dimension of the space.\n An optional vector of weights W may be provided.\n\n Note that this algorithm does not require that P and Q have already\n been overlayed by a centroid translation.\n\n The function returns the rotation matrix U, translation vector V,\n and RMS deviation between Q and P', where P' is:\n\n P' = P * U + V\n\n For more info see http://en.wikipedia.org/wiki/Kabsch_algorithm\n\n Parameters\n ----------\n P : array\n (N,D) matrix, where N is points and D is dimension.\n Q : array\n (N,D) matrix, where N is points and D is dimension.\n W : array or None\n (N) vector, where N is points.\n\n Returns\n -------\n U : matrix\n Rotation matrix (D,D)\n V : vector\n Translation vector (D)\n RMSD : float\n Root mean squared deviation between P and Q\n \"\"\"\n # Computation of the weighted covariance matrix\n CMP = np.zeros(3)\n CMQ = np.zeros(3)\n C = np.zeros((3, 3))\n if W is None:\n W = np.ones(len(P)) / len(P)\n W = np.array([W, W, W]).T\n # NOTE UNUSED psq = 0.0\n # NOTE UNUSED qsq = 0.0\n iw = 3.0 / W.sum()\n n = len(P)\n for i in range(3):\n for j in range(n):\n for k in range(3):\n C[i, k] += P[j, i] * Q[j, k] * W[j, i]\n CMP = (P * W).sum(axis=0)\n CMQ = (Q * W).sum(axis=0)\n PSQ = (P * P * W).sum() - (CMP * CMP).sum() * iw\n QSQ = (Q * Q * W).sum() - (CMQ * CMQ).sum() * iw\n C = (C - np.outer(CMP, CMQ) * iw) * iw\n\n # Computation of the optimal rotation matrix\n # This can be done using singular value decomposition (SVD)\n # Getting the sign of the det(V)*(W) to decide\n # whether we need to correct our rotation matrix to ensure a\n # right-handed coordinate system.\n # And finally calculating the optimal rotation matrix U\n # see http://en.wikipedia.org/wiki/Kabsch_algorithm\n V, S, W = np.linalg.svd(C)\n d = (np.linalg.det(V) * np.linalg.det(W)) < 0.0\n\n if d:\n S[-1] = -S[-1]\n V[:, -1] = -V[:, -1]\n\n # Create Rotation matrix U, translation vector V, and calculate RMSD:\n U = np.dot(V, W)\n msd = (PSQ + QSQ) * iw - 2.0 * S.sum()\n if msd < 0.0:\n msd = 0.0\n rmsd = np.sqrt(msd)\n V = np.zeros(3)\n for i in range(3):\n t = (U[i, :] * CMQ).sum()\n V[i] = CMP[i] - t\n V = V * iw\n return U, V, rmsd\n\n\ndef kabsch_weighted_fit(P, Q, W=None, rmsd=False):\n \"\"\"\n Fit P to Q with optional weights W.\n Also returns the RMSD of the fit if rmsd=True.\n\n Parameters\n ----------\n P : array\n (N,D) matrix, where N is points and D is dimension.\n Q : array\n (N,D) matrix, where N is points and D is dimension.\n W : vector\n (N) vector, where N is points\n rmsd : Bool\n If True, rmsd is returned as well as the fitted coordinates.\n\n Returns\n -------\n P' : array\n (N,D) matrix, where N is points and D is dimension.\n RMSD : float\n if the function is called with rmsd=True\n \"\"\"\n R, T, RMSD = kabsch_weighted(Q, P, W)\n PNEW = np.dot(P, R.T) + T\n if rmsd:\n return PNEW, RMSD\n else:\n return PNEW\n\n\ndef kabsch_weighted_rmsd(P, Q, W=None):\n \"\"\"\n Calculate the RMSD between P and Q with optional weighhts W\n\n Parameters\n ----------\n P : array\n (N,D) matrix, where N is points and D is dimension.\n Q : array\n (N,D) matrix, where N is points and D is dimension.\n W : vector\n (N) vector, where N is points\n\n Returns\n -------\n RMSD : float\n \"\"\"\n R, T, w_rmsd = kabsch_weighted(P, Q, W)\n return w_rmsd\n\n\ndef quaternion_rmsd(P, Q):\n \"\"\"\n Rotate matrix P unto Q and calculate the RMSD\n based on doi:10.1016/1049-9660(91)90036-O\n\n Parameters\n ----------\n P : array\n (N,D) matrix, where N is points and D is dimension.\n Q : array\n (N,D) matrix, where N is points and D is dimension.\n\n Returns\n -------\n rmsd : float\n \"\"\"\n rot = quaternion_rotate(P, Q)\n P = np.dot(P, rot)\n return rmsd(P, Q)\n\n\ndef quaternion_transform(r):\n \"\"\"\n Get optimal rotation\n note: translation will be zero when the centroids of each molecule are the\n same\n \"\"\"\n Wt_r = makeW(*r).T\n Q_r = makeQ(*r)\n rot = Wt_r.dot(Q_r)[:3, :3]\n return rot\n\n\ndef makeW(r1, r2, r3, r4=0):\n \"\"\"\n matrix involved in quaternion rotation\n \"\"\"\n W = np.asarray(\n [\n [r4, r3, -r2, r1],\n [-r3, r4, r1, r2],\n [r2, -r1, r4, r3],\n [-r1, -r2, -r3, r4],\n ]\n )\n return W\n\n\ndef makeQ(r1, r2, r3, r4=0):\n \"\"\"\n matrix involved in quaternion rotation\n \"\"\"\n Q = np.asarray(\n [\n [r4, -r3, r2, r1],\n [r3, r4, -r1, r2],\n [-r2, r1, r4, r3],\n [-r1, -r2, -r3, r4],\n ]\n )\n return Q\n\n\ndef quaternion_rotate(X, Y):\n \"\"\"\n Calculate the rotation\n\n Parameters\n ----------\n X : array\n (N,D) matrix, where N is points and D is dimension.\n Y: array\n (N,D) matrix, where N is points and D is dimension.\n\n Returns\n -------\n rot : matrix\n Rotation matrix (D,D)\n \"\"\"\n N = X.shape[0]\n W = np.asarray([makeW(*Y[k]) for k in range(N)])\n Q = np.asarray([makeQ(*X[k]) for k in range(N)])\n Qt_dot_W = np.asarray([np.dot(Q[k].T, W[k]) for k in range(N)])\n # NOTE UNUSED W_minus_Q = np.asarray([W[k] - Q[k] for k in range(N)])\n A = np.sum(Qt_dot_W, axis=0)\n eigen = np.linalg.eigh(A)\n r = eigen[1][:, eigen[0].argmax()]\n rot = quaternion_transform(r)\n return rot\n\n\ndef centroid(X):\n \"\"\"\n Centroid is the mean position of all the points in all of the coordinate\n directions, from a vectorset X.\n\n https://en.wikipedia.org/wiki/Centroid\n\n C = sum(X)/len(X)\n\n Parameters\n ----------\n X : array\n (N,D) matrix, where N is points and D is dimension.\n\n Returns\n -------\n C : float\n centroid\n \"\"\"\n C = X.mean(axis=0)\n return C\n\n\ndef hungarian_vectors(p_vecs, q_vecs, sigma=1e-0, use_kernel=True):\n \"\"\"\n\n Hungarian cost assignment of a similiarty molecule kernel.\n\n Note: Assumes p and q are atoms of same type\n\n Parameters\n ----------\n p_vecs : array\n (N,L) matrix, where N is no. of atoms and L is representation length\n q_vecs : array\n (N,L) matrix, where N is no. of atoms and L is representation length\n\n Returns\n -------\n indices_b : array\n (N) view vector of reordered assignment\n\n \"\"\"\n\n if use_kernel:\n # Calculate cost matrix from similarity kernel\n K = qml.kernels.laplacian_kernel(p_vecs, q_vecs, sigma)\n K *= -1.0\n K += 1.0\n\n else:\n K = distance_matrix(p_vecs, q_vecs)\n\n # Perform Hungarian analysis on distance matrix between atoms of 1st\n # structure and trial structure\n indices_a, indices_b = linear_sum_assignment(K)\n\n return indices_b\n\n\ndef reorder_similarity(p_atoms, q_atoms, p_coord, q_coord, use_kernel=True):\n \"\"\"\n Re-orders the input atom list and xyz coordinates using QML similarity\n the Hungarian method for assignment.\n\n Parameters\n ----------\n p_atoms : array\n (N,1) matrix, where N is points holding the atoms' names\n p_atoms : array\n (N,1) matrix, where N is points holding the atoms' names\n p_coord : array\n (N,D) matrix, where N is points and D is dimension\n q_coord : array\n (N,D) matrix, where N is points and D is dimension\n\n Returns\n -------\n view_reorder : array\n (N,1) matrix, reordered indexes of atom alignment based on the\n coordinates of the atoms\n \"\"\"\n\n if qml is None:\n raise ImportError(\n \"QML is not installed. Package is avaliable from\"\n \"\\n github.com/qmlcode/qml\"\n \"\\n pip install qml\"\n )\n\n if isinstance(p_atoms[0], str):\n p_atoms = [int_atom(atom) for atom in p_atoms]\n q_atoms = [int_atom(atom) for atom in q_atoms]\n p_atoms = np.array(p_atoms)\n q_atoms = np.array(q_atoms)\n\n elements = np.unique(p_atoms)\n n_atoms = p_atoms.shape[0]\n distance_cut = 20.0\n\n parameters = {\n \"elements\": elements,\n \"pad\": n_atoms,\n \"rcut\": distance_cut,\n \"acut\": distance_cut,\n }\n\n p_vecs = qml.representations.generate_fchl_acsf(\n p_atoms, p_coord, **parameters\n )\n\n q_vecs = qml.representations.generate_fchl_acsf(\n q_atoms, q_coord, **parameters\n )\n\n # generate full view from q shape to fill in atom view on the fly\n view_reorder = np.zeros(q_atoms.shape, dtype=int)\n\n for atom in elements:\n\n (p_atom_idx,) = np.where(p_atoms == atom)\n (q_atom_idx,) = np.where(q_atoms == atom)\n\n p_vecs_atom = p_vecs[p_atom_idx]\n q_vecs_atom = q_vecs[q_atom_idx]\n\n view = hungarian_vectors(\n p_vecs_atom, q_vecs_atom, use_kernel=use_kernel\n )\n view_reorder[p_atom_idx] = q_atom_idx[view]\n\n return view_reorder\n\n\ndef reorder_distance(p_atoms, q_atoms, p_coord, q_coord):\n \"\"\"\n Re-orders the input atom list and xyz coordinates by atom type and then by\n distance of each atom from the centroid.\n\n Parameters\n ----------\n atoms : array\n (N,1) matrix, where N is points holding the atoms' names\n coord : array\n (N,D) matrix, where N is points and D is dimension\n\n Returns\n -------\n atoms_reordered : array\n (N,1) matrix, where N is points holding the ordered atoms' names\n coords_reordered : array\n (N,D) matrix, where N is points and D is dimension (rows re-ordered)\n \"\"\"\n\n # Find unique atoms\n unique_atoms = np.unique(p_atoms)\n\n # generate full view from q shape to fill in atom view on the fly\n view_reorder = np.zeros(q_atoms.shape, dtype=int)\n\n for atom in unique_atoms:\n\n (p_atom_idx,) = np.where(p_atoms == atom)\n (q_atom_idx,) = np.where(q_atoms == atom)\n\n A_coord = p_coord[p_atom_idx]\n B_coord = q_coord[q_atom_idx]\n\n # Calculate distance from each atom to centroid\n A_norms = np.linalg.norm(A_coord, axis=1)\n B_norms = np.linalg.norm(B_coord, axis=1)\n\n reorder_indices_A = np.argsort(A_norms)\n reorder_indices_B = np.argsort(B_norms)\n\n # Project the order of P onto Q\n translator = np.argsort(reorder_indices_A)\n view = reorder_indices_B[translator]\n view_reorder[p_atom_idx] = q_atom_idx[view]\n\n return view_reorder\n\n\ndef hungarian(A, B):\n \"\"\"\n Hungarian reordering.\n\n Assume A and B are coordinates for atoms of SAME type only\n \"\"\"\n\n # should be kabasch here i think\n distances = cdist(A, B, \"euclidean\")\n\n # Perform Hungarian analysis on distance matrix between atoms of 1st\n # structure and trial structure\n indices_a, indices_b = linear_sum_assignment(distances)\n\n return indices_b\n\n\ndef reorder_hungarian(p_atoms, q_atoms, p_coord, q_coord):\n \"\"\"\n Re-orders the input atom list and xyz coordinates using the Hungarian\n method (using optimized column results)\n\n Parameters\n ----------\n p_atoms : array\n (N,1) matrix, where N is points holding the atoms' names\n p_atoms : array\n (N,1) matrix, where N is points holding the atoms' names\n p_coord : array\n (N,D) matrix, where N is points and D is dimension\n q_coord : array\n (N,D) matrix, where N is points and D is dimension\n\n Returns\n -------\n view_reorder : array\n (N,1) matrix, reordered indexes of atom alignment based on the\n coordinates of the atoms\n\n \"\"\"\n\n # Find unique atoms\n unique_atoms = np.unique(p_atoms)\n\n # generate full view from q shape to fill in atom view on the fly\n view_reorder = np.zeros(q_atoms.shape, dtype=int)\n view_reorder -= 1\n\n for atom in unique_atoms:\n (p_atom_idx,) = np.where(p_atoms == atom)\n (q_atom_idx,) = np.where(q_atoms == atom)\n\n A_coord = p_coord[p_atom_idx]\n B_coord = q_coord[q_atom_idx]\n\n view = hungarian(A_coord, B_coord)\n view_reorder[p_atom_idx] = q_atom_idx[view]\n\n return view_reorder\n\n\ndef reorder_inertia_hungarian(p_atoms, q_atoms, p_coord, q_coord):\n \"\"\"\n Align the principal intertia axis and then re-orders the input atom list\n and xyz coordinates using the Hungarian method (using optimized column\n results)\n\n Parameters\n ----------\n p_atoms : array\n (N,1) matrix, where N is points holding the atoms' names\n p_atoms : array\n (N,1) matrix, where N is points holding the atoms' names\n p_coord : array\n (N,D) matrix, where N is points and D is dimension\n q_coord : array\n (N,D) matrix, where N is points and D is dimension\n\n Returns\n -------\n view_reorder : array\n (N,1) matrix, reordered indexes of atom alignment based on the\n coordinates of the atoms\n\n \"\"\"\n # get the principal axis of P and Q\n p_axis = get_principal_axis(p_atoms, p_coord)\n q_axis = get_principal_axis(q_atoms, q_coord)\n\n # rotate Q onto P considering that the axis are parallel and antiparallel\n U1 = rotation_matrix_vectors(p_axis, q_axis)\n U2 = rotation_matrix_vectors(p_axis, -q_axis)\n q_coord1 = np.dot(q_coord, U1)\n q_coord2 = np.dot(q_coord, U2)\n\n q_review1 = reorder_hungarian(p_atoms, q_atoms, p_coord, q_coord1)\n q_review2 = reorder_hungarian(p_atoms, q_atoms, p_coord, q_coord2)\n q_coord1 = q_coord1[q_review1]\n q_coord2 = q_coord2[q_review2]\n\n rmsd1 = kabsch_rmsd(p_coord, q_coord1)\n rmsd2 = kabsch_rmsd(p_coord, q_coord2)\n\n if rmsd1 < rmsd2:\n return q_review1\n else:\n return q_review2\n\n\ndef generate_permutations(elements, n):\n \"\"\"\n Heap's algorithm for generating all n! permutations in a list\n https://en.wikipedia.org/wiki/Heap%27s_algorithm\n\n \"\"\"\n c = [0] * n\n yield elements\n i = 0\n while i < n:\n if c[i] < i:\n if i % 2 == 0:\n elements[0], elements[i] = elements[i], elements[0]\n else:\n elements[c[i]], elements[i] = elements[i], elements[c[i]]\n yield elements\n c[i] += 1\n i = 0\n else:\n c[i] = 0\n i += 1\n\n\ndef brute_permutation(A, B):\n \"\"\"\n Re-orders the input atom list and xyz coordinates using the brute force\n method of permuting all rows of the input coordinates\n\n Parameters\n ----------\n A : array\n (N,D) matrix, where N is points and D is dimension\n B : array\n (N,D) matrix, where N is points and D is dimension\n\n Returns\n -------\n view : array\n (N,1) matrix, reordered view of B projected to A\n \"\"\"\n\n rmsd_min = np.inf\n view_min = None\n\n # Sets initial ordering for row indices to [0, 1, 2, ..., len(A)], used in\n # brute-force method\n\n num_atoms = A.shape[0]\n initial_order = list(range(num_atoms))\n\n for reorder_indices in generate_permutations(initial_order, num_atoms):\n\n # Re-order the atom array and coordinate matrix\n coords_ordered = B[reorder_indices]\n\n # Calculate the RMSD between structure 1 and the Hungarian re-ordered\n # structure 2\n rmsd_temp = kabsch_rmsd(A, coords_ordered)\n\n # Replaces the atoms and coordinates with the current structure if the\n # RMSD is lower\n if rmsd_temp < rmsd_min:\n rmsd_min = rmsd_temp\n view_min = copy.deepcopy(reorder_indices)\n\n return view_min\n\n\ndef reorder_brute(p_atoms, q_atoms, p_coord, q_coord):\n \"\"\"\n Re-orders the input atom list and xyz coordinates using all permutation of\n rows (using optimized column results)\n\n Parameters\n ----------\n p_atoms : array\n (N,1) matrix, where N is points holding the atoms' names\n q_atoms : array\n (N,1) matrix, where N is points holding the atoms' names\n p_coord : array\n (N,D) matrix, where N is points and D is dimension\n q_coord : array\n (N,D) matrix, where N is points and D is dimension\n\n Returns\n -------\n view_reorder : array\n (N,1) matrix, reordered indexes of atom alignment based on the\n coordinates of the atoms\n\n \"\"\"\n\n # Find unique atoms\n unique_atoms = np.unique(p_atoms)\n\n # generate full view from q shape to fill in atom view on the fly\n view_reorder = np.zeros(q_atoms.shape, dtype=int)\n view_reorder -= 1\n\n for atom in unique_atoms:\n (p_atom_idx,) = np.where(p_atoms == atom)\n (q_atom_idx,) = np.where(q_atoms == atom)\n\n A_coord = p_coord[p_atom_idx]\n B_coord = q_coord[q_atom_idx]\n\n view = brute_permutation(A_coord, B_coord)\n view_reorder[p_atom_idx] = q_atom_idx[view]\n\n return view_reorder\n\n\ndef check_reflections(\n p_atoms,\n q_atoms,\n p_coord,\n q_coord,\n reorder_method=reorder_hungarian,\n rotation_method=kabsch_rmsd,\n keep_stereo=False,\n):\n \"\"\"\n Minimize RMSD using reflection planes for molecule P and Q\n\n Warning: This will affect stereo-chemistry\n\n Parameters\n ----------\n p_atoms : array\n (N,1) matrix, where N is points holding the atoms' names\n q_atoms : array\n (N,1) matrix, where N is points holding the atoms' names\n p_coord : array\n (N,D) matrix, where N is points and D is dimension\n q_coord : array\n (N,D) matrix, where N is points and D is dimension\n\n Returns\n -------\n min_rmsd\n min_swap\n min_reflection\n min_review\n\n \"\"\"\n\n min_rmsd = np.inf\n min_swap = None\n min_reflection = None\n min_review = None\n tmp_review = None\n swap_mask = [1, -1, -1, 1, -1, 1]\n reflection_mask = [1, -1, -1, -1, 1, 1, 1, -1]\n\n for swap, i in zip(AXIS_SWAPS, swap_mask):\n for reflection, j in zip(AXIS_REFLECTIONS, reflection_mask):\n\n # skip enantiomers\n if keep_stereo and i * j == -1:\n continue\n\n tmp_atoms = copy.copy(q_atoms)\n tmp_coord = copy.deepcopy(q_coord)\n tmp_coord = tmp_coord[:, swap]\n tmp_coord = np.dot(tmp_coord, np.diag(reflection))\n tmp_coord -= centroid(tmp_coord)\n\n # Reorder\n if reorder_method is not None:\n tmp_review = reorder_method(\n p_atoms, tmp_atoms, p_coord, tmp_coord\n )\n\n tmp_coord = tmp_coord[tmp_review]\n tmp_atoms = tmp_atoms[tmp_review]\n\n # Rotation\n if rotation_method is None:\n this_rmsd = rmsd(p_coord, tmp_coord)\n else:\n this_rmsd = rotation_method(p_coord, tmp_coord)\n\n if this_rmsd < min_rmsd:\n min_rmsd = this_rmsd\n min_swap = swap\n min_reflection = reflection\n min_review = tmp_review\n\n if not (p_atoms == q_atoms[min_review]).all():\n print(\"error: Not aligned\")\n quit()\n\n return min_rmsd, min_swap, min_reflection, min_review\n\n\ndef rotation_matrix_vectors(v1, v2):\n \"\"\"\n Returns the rotation matrix that rotates v1 onto v2\n using Rodrigues' rotation formula.\n (see https://math.stackexchange.com/a/476311)\n ----------\n v1 : array\n Dim 3 float array\n v2 : array\n Dim 3 float array\n\n Return\n ------\n output : 3x3 matrix\n Rotation matrix\n \"\"\"\n\n if (v1 == v2).all():\n rot = np.eye(3)\n\n # return a rotation of pi around the y-axis\n elif (v1 == -v2).all():\n rot = np.array([[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]])\n\n else:\n v = np.cross(v1, v2)\n s = np.linalg.norm(v)\n c = np.vdot(v1, v2)\n\n vx = np.array(\n [[0.0, -v[2], v[1]], [v[2], 0.0, -v[0]], [-v[1], v[0], 0.0]]\n )\n\n rot = np.eye(3) + vx + np.dot(vx, vx) * ((1.0 - c) / (s * s))\n\n return rot\n\n\ndef get_cm(atoms, V):\n \"\"\"\n Get the center of mass of V.\n ----------\n atoms : list\n List of atomic types\n V : array\n (N,3) matrix of atomic coordinates\n\n Return\n ------\n output : (3) array\n The CM vector\n \"\"\"\n\n if isinstance(atoms[0], str):\n atoms = [int_atom(atom) for atom in atoms]\n\n weights = [ELEMENT_WEIGHTS[x] for x in atoms]\n\n center_of_mass = np.average(V, axis=0, weights=weights)\n\n return center_of_mass\n\n\ndef get_inertia_tensor(atoms, V):\n \"\"\"\n Get the tensor of intertia of V.\n ----------\n atoms : list\n List of atomic types\n V : array\n (N,3) matrix of atomic coordinates\n\n Return\n ------\n output : 3x3 float matrix\n The tensor of inertia\n \"\"\"\n\n if isinstance(atoms[0], str):\n atoms = [int_atom(atom) for atom in atoms]\n\n CV = V - get_cm(atoms, V)\n\n Ixx = 0.0\n Iyy = 0.0\n Izz = 0.0\n Ixy = 0.0\n Ixz = 0.0\n Iyz = 0.0\n\n for sp, acoord in zip(atoms, CV):\n amass = ELEMENT_WEIGHTS[sp]\n Ixx += amass * (acoord[1] * acoord[1] + acoord[2] * acoord[2])\n Iyy += amass * (acoord[0] * acoord[0] + acoord[2] * acoord[2])\n Izz += amass * (acoord[0] * acoord[0] + acoord[1] * acoord[1])\n Ixy += -amass * acoord[0] * acoord[1]\n Ixz += -amass * acoord[0] * acoord[2]\n Iyz += -amass * acoord[1] * acoord[2]\n\n return np.array([[Ixx, Ixy, Ixz], [Ixy, Iyy, Iyz], [Ixz, Iyz, Izz]])\n\n\ndef get_principal_axis(atoms, V):\n \"\"\"\n Get the molecule's principal axis.\n ----------\n atoms : list\n List of atomic types\n V : array\n (N,3) matrix of atomic coordinates\n\n Return\n ------\n output : array\n Array of dim 3 containing the principal axis\n \"\"\"\n inertia = get_inertia_tensor(atoms, V)\n\n eigval, eigvec = np.linalg.eig(inertia)\n\n return eigvec[np.argmax(eigval)]\n\n\ndef set_coordinates(atoms, V, title=\"\", decimals=8):\n \"\"\"\n Print coordinates V with corresponding atoms to stdout in XYZ format.\n Parameters\n ----------\n atoms : list\n List of atomic types\n V : array\n (N,3) matrix of atomic coordinates\n title : string (optional)\n Title of molecule\n decimals : int (optional)\n number of decimals for the coordinates\n\n Return\n ------\n output : str\n Molecule in XYZ format\n\n \"\"\"\n N, D = V.shape\n\n if not isinstance(atoms[0], str):\n atoms = [str_atom(atom) for atom in atoms]\n\n fmt = \"{:<2}\" + (\" {:15.\" + str(decimals) + \"f}\") * 3\n\n out = list()\n out += [str(N)]\n out += [title]\n\n for i in range(N):\n atom = atoms[i]\n out += [fmt.format(atom, V[i, 0], V[i, 1], V[i, 2])]\n\n return \"\\n\".join(out)\n\n\ndef print_coordinates(atoms, V, title=\"\"):\n \"\"\"\n Print coordinates V with corresponding atoms to stdout in XYZ format.\n\n Parameters\n ----------\n atoms : list\n List of element types\n V : array\n (N,3) matrix of atomic coordinates\n title : string (optional)\n Title of molecule\n\n \"\"\"\n print(set_coordinates(atoms, V, title=title))\n\n\ndef get_coordinates(filename, fmt, is_gzip=False, return_atoms_as_int=False):\n \"\"\"\n Get coordinates from filename in format fmt. Supports XYZ and PDB.\n Parameters\n ----------\n filename : string\n Filename to read\n fmt : string\n Format of filename. Either xyz or pdb.\n Returns\n -------\n atoms : list\n List of atomic types\n V : array\n (N,3) where N is number of atoms\n \"\"\"\n if fmt == \"xyz\":\n get_func = get_coordinates_xyz\n\n elif fmt == \"pdb\":\n get_func = get_coordinates_pdb\n\n else:\n exit(\"Could not recognize file format: {:s}\".format(fmt))\n\n val = get_func(\n filename, is_gzip=is_gzip, return_atoms_as_int=return_atoms_as_int\n )\n\n return val\n\n\ndef get_coordinates_pdb(filename, is_gzip=False, return_atoms_as_int=False):\n \"\"\"\n Get coordinates from the first chain in a pdb file\n and return a vectorset with all the coordinates.\n\n Parameters\n ----------\n filename : string\n Filename to read\n\n Returns\n -------\n atoms : list\n List of atomic types\n V : array\n (N,3) where N is number of atoms\n \"\"\"\n\n # PDB files tend to be a bit of a mess. The x, y and z coordinates\n # are supposed to be in column 31-38, 39-46 and 47-54, but this is\n # not always the case.\n # Because of this the three first columns containing a decimal is used.\n # Since the format doesn't require a space between columns, we use the\n # above column indices as a fallback.\n\n x_column = None\n V = list()\n\n # Same with atoms and atom naming.\n # The most robust way to do this is probably\n # to assume that the atomtype is given in column 3.\n\n atoms = list()\n\n if is_gzip:\n openfunc = gzip.open\n openarg = \"rt\"\n else:\n openfunc = open\n openarg = \"r\"\n\n with openfunc(filename, openarg) as f:\n lines = f.readlines()\n for line in lines:\n if line.startswith(\"TER\") or line.startswith(\"END\"):\n break\n if line.startswith(\"ATOM\"):\n tokens = line.split()\n # Try to get the atomtype\n try:\n atom = tokens[2][0]\n if atom in (\"H\", \"C\", \"N\", \"O\", \"S\", \"P\"):\n atoms.append(atom)\n else:\n # e.g. 1HD1\n atom = tokens[2][1]\n if atom == \"H\":\n atoms.append(atom)\n else:\n raise Exception\n\n except ValueError:\n msg = (\n f\"error: Parsing atomtype for the following line:\"\n f\" \\n{line}\"\n )\n exit(msg)\n\n if x_column is None:\n try:\n # look for x column\n for i, x in enumerate(tokens):\n if (\n \".\" in x\n and \".\" in tokens[i + 1]\n and \".\" in tokens[i + 2]\n ):\n x_column = i\n break\n\n except IndexError:\n msg = (\n \"error: Parsing coordinates \"\n \"for the following line:\"\n f\"\\n{line}\"\n )\n exit(msg)\n\n # Try to read the coordinates\n try:\n V.append(\n np.asarray(\n tokens[x_column : x_column + 3], dtype=float\n )\n )\n\n except ValueError:\n # If that doesn't work, use hardcoded indices\n try:\n x = line[30:38]\n y = line[38:46]\n z = line[46:54]\n V.append(np.asarray([x, y, z], dtype=float))\n except ValueError:\n msg = (\n \"error: Parsing input \"\n \"for the following line:\"\n f\"\\n{line}\"\n )\n exit(msg)\n\n if return_atoms_as_int:\n atoms = [int_atom(atom) for atom in atoms]\n\n V = np.asarray(V)\n atoms = np.asarray(atoms)\n\n assert V.shape[0] == atoms.size\n\n return atoms, V\n\n\ndef get_coordinates_xyz(filename, is_gzip=False, return_atoms_as_int=False):\n \"\"\"\n Get coordinates from filename and return a vectorset with all the\n coordinates, in XYZ format.\n\n Parameters\n ----------\n filename : string\n Filename to read\n\n Returns\n -------\n atoms : list\n List of atomic types\n V : array\n (N,3) where N is number of atoms\n \"\"\"\n\n if is_gzip:\n openfunc = gzip.open\n openarg = \"rt\"\n else:\n openfunc = open\n openarg = \"r\"\n\n f = openfunc(filename, openarg)\n V = list()\n atoms = list()\n n_atoms = 0\n\n # Read the first line to obtain the number of atoms to read\n try:\n n_atoms = int(f.readline())\n except ValueError:\n exit(\"error: Could not obtain the number of atoms in the .xyz file.\")\n\n # Skip the title line\n f.readline()\n\n # Use the number of atoms to not read beyond the end of a file\n for lines_read, line in enumerate(f):\n\n if lines_read == n_atoms:\n break\n\n values = line.split()\n\n if len(values) < 4:\n atom = re.findall(r\"[a-zA-Z]+\", line)[0]\n atom = atom.upper()\n numbers = re.findall(r\"[-]?\\d+\\.\\d*(?:[Ee][-\\+]\\d+)?\", line)\n numbers = [float(number) for number in numbers]\n else:\n atom = values[0]\n numbers = [float(number) for number in values[1:]]\n\n # The numbers are not valid unless we obtain exacly three\n if len(numbers) >= 3:\n V.append(np.array(numbers)[:3])\n atoms.append(atom)\n else:\n msg = (\n f\"Reading the .xyz file failed in line {lines_read + 2}.\"\n \"Please check the format.\"\n )\n exit(msg)\n\n f.close()\n\n try:\n # I've seen examples where XYZ are written with integer atoms types\n atoms = [int(atom) for atom in atoms]\n atoms = [str_atom(atom) for atom in atoms]\n\n except ValueError:\n # Correct atom spelling\n atoms = [atom.capitalize() for atom in atoms]\n\n if return_atoms_as_int:\n atoms = [int_atom(atom) for atom in atoms]\n\n atoms = np.array(atoms)\n V = np.array(V)\n return atoms, V\n\n\ndef parse_arguments(args=None):\n\n description = __doc__\n\n version_msg = f\"\"\"\nrmsd {__version__}\n\nSee https://github.com/charnley/rmsd for citation information\n\n\"\"\"\n\n epilog = \"\"\"\n\"\"\"\n\n valid_reorder_methods = \", \".join(REORDER_METHODS)\n valid_rotation_methods = \", \".join(ROTATION_METHODS)\n\n parser = argparse.ArgumentParser(\n usage=\"calculate_rmsd [options] FILE_A FILE_B\",\n description=description,\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=epilog,\n )\n\n # Input structures\n parser.add_argument(\n \"structure_a\",\n metavar=\"FILE_A\",\n type=str,\n help=\"structures in .xyz or .pdb format\",\n )\n parser.add_argument(\"structure_b\", metavar=\"FILE_B\", type=str)\n\n # Admin\n parser.add_argument(\n \"-v\", \"--version\", action=\"version\", version=version_msg\n )\n\n # Rotation\n parser.add_argument(\n \"-r\",\n \"--rotation\",\n action=\"store\",\n default=\"kabsch\",\n help=(\n \"select rotation method. Valid methods are \"\n f\"{valid_rotation_methods}. \"\n \"Default is Kabsch.\"\n ),\n metavar=\"METHOD\",\n )\n\n # Reorder arguments\n parser.add_argument(\n \"-e\",\n \"--reorder\",\n action=\"store_true\",\n help=\"align the atoms of molecules\",\n )\n parser.add_argument(\n \"--reorder-method\",\n action=\"store\",\n default=\"hungarian\",\n metavar=\"METHOD\",\n help=(\n \"select reorder method. Valid method are \"\n f\"{valid_reorder_methods}. \"\n \"Default is Hungarian.\"\n ),\n )\n parser.add_argument(\n \"-ur\",\n \"--use-reflections\",\n action=\"store_true\",\n help=(\n \"scan through reflections in planes \"\n \"(eg Y transformed to -Y -> X, -Y, Z) \"\n \"and axis changes, (eg X and Z coords exchanged -> Z, Y, X). \"\n \"This will affect stereo-chemistry.\"\n ),\n )\n parser.add_argument(\n \"-urks\",\n \"--use-reflections-keep-stereo\",\n action=\"store_true\",\n help=(\n \"scan through reflections in planes \"\n \"(eg Y transformed to -Y -> X, -Y, Z) \"\n \"and axis changes, (eg X and Z coords exchanged -> Z, Y, X). \"\n \"Stereo-chemistry will be kept.\"\n ),\n )\n\n # Filter\n index_group = parser.add_mutually_exclusive_group()\n index_group.add_argument(\n \"-nh\",\n \"--ignore-hydrogen\",\n \"--no-hydrogen\",\n action=\"store_true\",\n help=\"ignore hydrogens when calculating RMSD\",\n )\n index_group.add_argument(\n \"--remove-idx\",\n nargs=\"+\",\n type=int,\n help=\"index list of atoms NOT to consider\",\n metavar=\"IDX\",\n )\n index_group.add_argument(\n \"--add-idx\",\n nargs=\"+\",\n type=int,\n help=\"index list of atoms to consider\",\n metavar=\"IDX\",\n )\n\n parser.add_argument(\n \"--format\",\n action=\"store\",\n help=\"format of input files. valid format are xyz and pdb\",\n metavar=\"FMT\",\n )\n parser.add_argument(\n \"--format-is-gzip\",\n action=\"store_true\",\n default=False,\n help=argparse.SUPPRESS,\n )\n\n parser.add_argument(\n \"-p\",\n \"--output\",\n \"--print\",\n action=\"store_true\",\n help=(\n \"print out structure B, \"\n \"centered and rotated unto structure A's coordinates \"\n \"in XYZ format\"\n ),\n )\n\n if args is None:\n args = parser.parse_args()\n else:\n args = parser.parse_args(args)\n\n # Check illegal combinations\n if (\n args.output\n and args.reorder\n and (args.ignore_hydrogen or args.add_idx or args.remove_idx)\n ):\n print(\n \"error: Cannot reorder atoms and print structure, \"\n \"when excluding atoms (such as --ignore-hydrogen)\"\n )\n sys.exit()\n\n if (\n args.use_reflections\n and args.output\n and (args.ignore_hydrogen or args.add_idx or args.remove_idx)\n ):\n print(\n \"error: Cannot use reflections on atoms and print, \"\n \"when excluding atoms (such as --ignore-hydrogen)\"\n )\n sys.exit()\n\n # Check methods\n args.rotation = args.rotation.lower()\n if args.rotation not in ROTATION_METHODS:\n print(\n f\"error: Unknown rotation method: '{args.rotation}'. \"\n f\"Please use {valid_rotation_methods}\"\n )\n sys.exit()\n\n # Check reorder methods\n args.reorder_method = args.reorder_method.lower()\n if args.reorder_method not in REORDER_METHODS:\n print(\n f'error: Unknown reorder method: \"{args.reorder_method}\". '\n f\"Please use {valid_reorder_methods}\"\n )\n sys.exit()\n\n # Check fileformat\n if args.format is None:\n filename = args.structure_a\n suffixes = pathlib.Path(filename).suffixes\n\n if len(suffixes) == 0:\n ext = None\n\n elif suffixes[-1] == \".gz\":\n args.format_is_gzip = True\n ext = suffixes[-2].strip(\".\")\n\n else:\n ext = suffixes[-1].strip(\".\")\n\n args.format = ext\n\n return args\n\n\ndef main(args=None):\n\n # Parse arguments\n args = parse_arguments(args)\n\n # As default, load the extension as format\n # Parse pdb.gz and xyz.gz as pdb and xyz formats\n p_all_atoms, p_all = get_coordinates(\n args.structure_a,\n args.format,\n is_gzip=args.format_is_gzip,\n return_atoms_as_int=True,\n )\n\n q_all_atoms, q_all = get_coordinates(\n args.structure_b,\n args.format,\n is_gzip=args.format_is_gzip,\n return_atoms_as_int=True,\n )\n\n p_size = p_all.shape[0]\n q_size = q_all.shape[0]\n\n if not p_size == q_size:\n print(\"error: Structures not same size\")\n sys.exit()\n\n if np.count_nonzero(p_all_atoms != q_all_atoms) and not args.reorder:\n msg = \"\"\"\nerror: Atoms are not in the same order.\n\nUse --reorder to align the atoms (can be expensive for large structures).\n\nPlease see --help or documentation for more information or\nhttps://github.com/charnley/rmsd for further examples.\n\"\"\"\n print(msg)\n sys.exit()\n\n # Set local view\n p_view = None\n q_view = None\n\n if args.ignore_hydrogen:\n assert type(p_all_atoms[0]) != str\n assert type(q_all_atoms[0]) != str\n p_view = np.where(p_all_atoms != 1)\n q_view = np.where(q_all_atoms != 1)\n\n elif args.remove_idx:\n index = range(p_size)\n index = set(index) - set(args.remove_idx)\n index = list(index)\n p_view = index\n q_view = index\n\n elif args.add_idx:\n p_view = args.add_idx\n q_view = args.add_idx\n\n # Set local view\n if p_view is None:\n p_coord = copy.deepcopy(p_all)\n q_coord = copy.deepcopy(q_all)\n p_atoms = copy.deepcopy(p_all_atoms)\n q_atoms = copy.deepcopy(q_all_atoms)\n\n else:\n p_coord = copy.deepcopy(p_all[p_view])\n q_coord = copy.deepcopy(q_all[q_view])\n p_atoms = copy.deepcopy(p_all_atoms[p_view])\n q_atoms = copy.deepcopy(q_all_atoms[q_view])\n\n # Recenter to centroid\n p_cent = centroid(p_coord)\n q_cent = centroid(q_coord)\n p_coord -= p_cent\n q_coord -= q_cent\n\n # set rotation method\n if args.rotation.lower() == METHOD_KABSCH:\n rotation_method = kabsch_rmsd\n elif args.rotation.lower() == METHOD_QUATERNION:\n rotation_method = quaternion_rmsd\n else:\n rotation_method = None\n\n # set reorder method\n if not args.reorder:\n reorder_method = None\n elif args.reorder_method == REORDER_QML:\n reorder_method = reorder_similarity\n elif args.reorder_method == REORDER_HUNGARIAN:\n reorder_method = reorder_hungarian\n elif args.reorder_method == REORDER_INERTIA_HUNGARIAN:\n reorder_method = reorder_inertia_hungarian\n elif args.reorder_method == REORDER_BRUTE:\n reorder_method = reorder_brute\n elif args.reorder_method == REORDER_DISTANCE:\n reorder_method = reorder_distance\n\n # Save the resulting RMSD\n result_rmsd = None\n\n if args.use_reflections:\n\n result_rmsd, _, _, q_review = check_reflections(\n p_atoms,\n q_atoms,\n p_coord,\n q_coord,\n reorder_method=reorder_method,\n rotation_method=rotation_method,\n )\n\n elif args.use_reflections_keep_stereo:\n\n result_rmsd, _, _, q_review = check_reflections(\n p_atoms,\n q_atoms,\n p_coord,\n q_coord,\n reorder_method=reorder_method,\n rotation_method=rotation_method,\n keep_stereo=True,\n )\n\n elif args.reorder:\n\n q_review = reorder_method(p_atoms, q_atoms, p_coord, q_coord)\n q_coord = q_coord[q_review]\n q_atoms = q_atoms[q_review]\n\n if not all(p_atoms == q_atoms):\n print(\n \"error: Structure not aligned. \"\n \"Please submit bug report at \"\n \"http://github.com/charnley/rmsd\"\n )\n sys.exit()\n\n # print result\n if args.output:\n\n if args.reorder:\n\n if q_review.shape[0] != q_all.shape[0]:\n print(\n \"error: Reorder length error. \"\n \"Full atom list needed for --print\"\n )\n quit()\n\n q_all = q_all[q_review]\n q_all_atoms = q_all_atoms[q_review]\n\n # Get rotation matrix\n U = kabsch(q_coord, p_coord)\n\n # recenter all atoms and rotate all atoms\n q_all -= q_cent\n q_all = np.dot(q_all, U)\n\n # center q on p's original coordinates\n q_all += p_cent\n\n # done and done\n xyz = set_coordinates(\n q_all_atoms, q_all, title=f\"{args.structure_b} - modified\"\n )\n print(xyz)\n\n else:\n\n if result_rmsd:\n pass\n\n elif rotation_method is None:\n result_rmsd = rmsd(p_coord, q_coord)\n\n else:\n result_rmsd = rotation_method(p_coord, q_coord)\n\n print(\"{0}\".format(result_rmsd))\n\n\nif __name__ == \"__main__\":\n main()\n", "meta": {"hexsha": "0f2408ca20c9f8c6ae392e08d974a240a805808f", "size": 49677, "ext": "py", "lang": "Python", "max_stars_repo_path": "rmsd/calculate_rmsd.py", "max_stars_repo_name": "jkha-unist/rmsd", "max_stars_repo_head_hexsha": "60c996d51aafce17929ae1f157d72ea4e2fcbbf2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rmsd/calculate_rmsd.py", "max_issues_repo_name": "jkha-unist/rmsd", "max_issues_repo_head_hexsha": "60c996d51aafce17929ae1f157d72ea4e2fcbbf2", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rmsd/calculate_rmsd.py", "max_forks_repo_name": "jkha-unist/rmsd", "max_forks_repo_head_hexsha": "60c996d51aafce17929ae1f157d72ea4e2fcbbf2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.543972332, "max_line_length": 78, "alphanum_fraction": 0.5540189625, "include": true, "reason": "import numpy,from scipy", "num_tokens": 13754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.23651623106411435, "lm_q1q2_score": 0.12010574822895896}} {"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\"\"\"\nDefine geometry for ACIS radiator and sunshade and perform raytrace\ncalculation of Earth illumination on the radiator surface.\n\"\"\"\nimport hashlib\nimport functools\nfrom contextlib import ExitStack\n\nfrom Quaternion import Quat\nimport numpy as np\nfrom numpy.random import RandomState\n\nprng = RandomState()\n\n_RANDOM_SALT = 1\n\ndef set_random_salt(salt):\n \"\"\"\n Set the internal ``_RANDOM_SALT`` module attribute to ``salt``.\n\n If set to ``None`` then the system random seed will be used everywhere and\n the results of ``calc_earth_vis`` will not be deterministic (i.e. they will\n vary slightly from one run to the next).\n\n If set otherwise then the ``calc_earth_vis`` function will return precisely\n the same results for the same input arguments and same value of ``salt``.\n Different ``salt`` values will generate different random variations of the\n results. This is done by making an MD5 digest of random salt and the\n function arguments and using this to generate an integer which sets the\n random seed.\n\n Any object type is allowed for ``salt``, the only thing that matters is\n is that it has a unique string representation.\n\n :param salt: any object with a unique str representation, repr(salt)\n \"\"\"\n global _RANDOM_SALT\n _RANDOM_SALT = salt\n\ndef _encode_data(val):\n with ExitStack() as stack:\n # Numpy 1.14 improved printing of arrays but this changes the encoded\n # array data here. For compatibility with the 1.12 formatting that forms\n # the basis of regression testing, use the old style here. np.printoptions\n # was added in numpy 1.15, so if that is found then we must use the legacy\n # print method. Note that legacy=\"1.12\" does not seem to work.\n if hasattr(np, 'printoptions'):\n stack.enter_context(np.printoptions(legacy=\"1.13\"))\n return np.array_str(np.array(val, ndmin=1)).encode(\"utf8\")\n\ndef _make_reproducible(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n if _RANDOM_SALT is not None:\n md5 = hashlib.md5()\n md5.update(repr(_RANDOM_SALT).encode(\"utf8\"))\n for val in args:\n md5.update(_encode_data(val))\n for val in kwargs.values():\n md5.update(_encode_data(val))\n digest = md5.hexdigest()\n seed = int(digest[:7], 16)\n prng.seed(seed)\n\n out = func(*args, **kwargs)\n return out\n return wrapper\n\n\ndef make_taco():\n \"\"\"Define geometry for ACIS radiator sun-shade (aka the space taco) in mm.\"\"\"\n y_pnts = np.array([-689.0, -333, -63, 553, 689]) + TACO_Y_OFF\n z_pnts = np.array([0.0, 777, 777, 421, 0]) - RAD_Z_OFF\n\n y_edge = np.arange(max(y_pnts))\n z_edge = interpolate(z_pnts, y_pnts, y_edge)\n\n return z_edge\n\n\n@_make_reproducible\ndef calc_earth_vis(p_chandra_eci=None,\n chandra_att=None,\n max_reflect=10,\n p_earth_body=None):\n \"\"\"Calculate the relative Earth visibility for the ACIS radiator given\n the Chandra orbit position ``p_chandra_eci`` and attitude ``chandra_att``.\n Alternately one can directly supply ``p_earth_body`` as a numpy array\n representing the position of the Earth in Chandra body coordinates.\n\n The relative visibility is normalized so that 1.0 represents the entire\n radiator having visibility toward the surface point and being exactly\n normal toward the surface.\n\n Total illumination gives the effective solid angle (steradians) of the\n visible Earth from the radiator perspective. It is averaged over the\n different points on the radiator.\n\n :param p_chandra_eci: Chandra orbital position [x, y, z] (meters)\n :param chandra_att: Chandra attitude [ra, dec, roll] (deg)\n :param max_reflect: number of reflections to compute (default=10)\n :param p_earth_body: optional 3-vector [x, y, z] (meters) of Earth\n in Chandra body coordinates (instead of p_chandra_eci and\n chandra_att inputs)\n\n :returns: relative visibility, total illumination, projected rays\n \"\"\"\n\n if p_earth_body is None:\n # Calculate position of earth in ECI and Chandra body coords.\n q_att = Quat(chandra_att)\n\n # For T = attitude transformation matrix then p_body = T^-1 p_eci\n p_earth_body = np.dot(q_att.transform.transpose(), -np.array(p_chandra_eci))\n else:\n p_earth_body = np.asarray(p_earth_body) # no-op if already an array\n\n illum = np.zeros(max_reflect+1)\n out_rays = []\n\n # If Earth disk is entirely below the \"horizon\" of the ACIS radiator then illum=0\n if p_earth_body[2] < -RAD_EARTH:\n return [], illum, out_rays\n\n # Quaternion to transform x-axis to the body-earth vector\n q_earth = quat_x_v2(p_earth_body)\n open_angle = np.arcsin(RAD_EARTH / np.sqrt(np.sum(p_earth_body**2)))\n\n rays, earth_solid_angle = sphere_rand(open_angle)\n n_rays = len(rays)\n rays_to_earth = np.dot(q_earth.transform, rays.transpose()).transpose() # shape (n_rays, 3)\n\n # Accept only rays with a positive Z component and make sure no X component is < 1e-6\n rays_to_earth = rays_to_earth[rays_to_earth[:, 2] > 0.0, :]\n n_rays_to_earth = len(rays_to_earth)\n if n_rays_to_earth % 2 == 1: # Ugh, make sure this list has even length\n rays_to_earth = rays_to_earth[:-1, :]\n n_rays_to_earth -= 1\n\n vis = np.zeros((max_reflect+1, n_rays))\n if len(rays_to_earth) == 0:\n return vis, illum, out_rays\n\n rays_to_earth_x = np.abs(rays_to_earth[:, 0])\n rays_to_earth_x[rays_to_earth_x < 1e-6] = 1e-6\n\n # Main ray-trace loop. Calculate ray visibility for an increasing number\n # of reflections. Rays that get blocked after N reflections are candidates\n # for getting out after N+1 reflections.\n\n # Radiator size: 17 inches wide (X) by 19 inches long (Y), centered within\n # SIM shaded structure.\n\n rad_x = prng.uniform(low=0.0, high=215.9, size=n_rays_to_earth // 2)\n rad_y = prng.uniform(low=-241.3, high=241.3, size=n_rays_to_earth // 2) + TACO_Y_OFF\n rad_x = np.append(rad_x, -rad_x)\n rad_y = np.append(rad_y, rad_y)\n rad_z = np.zeros(n_rays_to_earth)\n rays_x = rays_to_earth_x\n rays_y = rays_to_earth[:, 1]\n rays_z = rays_to_earth[:, 2]\n\n for refl in range(max_reflect + 1):\n if len(rays_x) == 0:\n break\n taco_x = TACO_X_OFF * (refl + 1)\n dx = (taco_x - rad_x) / rays_x\n\n # Find rays that intersect shade within Y limits of the shade (0, N_TACO mm)\n ray_taco_iys = np.array(rad_y + rays_y * dx, dtype=int)\n y_ok = (ray_taco_iys >= 0) & (ray_taco_iys < N_TACO)\n y_not_ok = ~y_ok\n ray_taco_iys[y_not_ok] = 0\n\n # From those rays find ones below the TACO_Z_EDGES curve\n ray_taco_zs = rays_z * dx\n z_ok = ray_taco_zs > TACO_Z_EDGES[ray_taco_iys]\n y_z_ok = (y_ok & z_ok) | y_not_ok\n\n # Calculate the delta-visibility for good rays (cos(incidence_angle) = Z component)\n d_vis = rays_z[y_z_ok] * REFLECT_ATTEN**refl\n # vis[refl, rays_i[y_z_ok]] += d_vis\n illum[refl] += earth_solid_angle * np.sum(d_vis) / n_rays\n\n blocked = ~y_z_ok\n rays_x = rays_x[blocked]\n rays_y = rays_y[blocked]\n rays_z = rays_z[blocked]\n # rays_i = rays_i[blocked]\n rad_x = rad_x[blocked]\n rad_y = rad_y[blocked]\n\n return vis, illum, out_rays\n\ndef interpolate(yin, xin, xout):\n \"\"\"\n Interpolate the curve defined by (xin, yin) at points xout. The array\n xin must be monotonically increasing. The output has the same data type as\n the input yin.\n\n :param yin: y values of input curve\n :param xin: x values of input curve\n :param xout: x values of output interpolated curve\n\n @:rtype: numpy array with interpolated curve\n \"\"\"\n lenxin = len(xin)\n\n i1 = np.searchsorted(xin, xout)\n i1[ i1==0 ] = 1\n i1[ i1==lenxin ] = lenxin-1\n\n x0 = xin[i1-1]\n x1 = xin[i1]\n y0 = yin[i1-1]\n y1 = yin[i1]\n\n return (xout - x0) / (x1 - x0) * (y1 - y0) + y0\n\ndef norm(vec):\n return vec / np.sqrt(np.sum(vec**2))\n\ndef quat_x_v2(v2):\n \"\"\"Generate quaternion that rotates X-axis into v2 by the shortest path\"\"\"\n x = np.array([1.,0,0])\n v2 = norm(np.array(v2))\n dot = np.dot(x, v2)\n if abs(dot) > 1-1e-8:\n x = norm(np.array([1., 0., 1e-5]))\n dot = np.dot(v2, x)\n angle = np.arccos(dot)\n axis = norm(np.cross(x, v2))\n sin_a = np.sin(angle / 2)\n cos_a = np.cos(angle / 2)\n return Quat([axis[0] * sin_a,\n axis[1] * sin_a,\n axis[2] * sin_a,\n cos_a])\n\ndef sphere_grid(ngrid, open_angle):\n \"\"\"Calculate approximately uniform spherical grid of rays containing\n ``ngrid`` points and extending over the opening angle ``open_angle``\n (radians).\n\n :returns: numpy array of unit length rays, grid area (steradians)\n \"\"\"\n from math import sin, cos, radians, pi, sqrt\n\n grid_area = 2*pi*(1-cos(open_angle))\n if ngrid <= 1:\n return np.array([[1., 0., 0.]]), grid_area\n\n gridsize = sqrt(grid_area / ngrid)\n\n grid = []\n theta0 = pi/2-open_angle\n n_d = int(round(open_angle / gridsize))\n d_d = open_angle / n_d\n\n for i_d in range(0, n_d+1):\n dec = i_d * d_d + pi/2 - open_angle\n if abs(i_d) != n_d:\n n_r = int(round( 2*pi * cos(dec) / d_d))\n d_r = 2*pi / n_r\n else:\n n_r = 1\n d_r = 1\n for i_r in range(0, n_r):\n ra = i_r * d_r\n # This has x <=> z (switched) from normal formulation to make the\n # grid centered about the x-axis\n grid.append((sin(dec), sin(ra) * cos(dec), cos(ra) * cos(dec)))\n\n # (x, y, z) = zip(*grid) (python magic)\n return np.array(grid), grid_area\n\n\n@_make_reproducible\ndef sphere_rand(open_angle, min_ngrid=100, max_ngrid=10000):\n \"\"\"Calculate approximately uniform spherical grid of rays containing\n ``ngrid`` points and extending over the opening angle ``open_angle``\n (radians).\n\n :returns: numpy array of unit length rays, grid area (steradians)\n \"\"\"\n from math import sin, cos, radians, pi, sqrt\n\n xmin = cos(open_angle)\n grid_area = 2*pi*(1-xmin)\n\n idx_xmin = np.searchsorted(SPHERE_X, xmin)\n if N_SPHERE - idx_xmin < min_ngrid:\n idx_xmin = N_SPHERE - min_ngrid\n\n ngrid = int(min_ngrid + (max_ngrid-min_ngrid) * (1-xmin))\n idx_sphere = prng.randint(idx_xmin, N_SPHERE, ngrid)\n\n return SPHERE_XYZ[idx_sphere, :], grid_area\n\n\n@_make_reproducible\ndef random_hemisphere(nsample):\n x = prng.uniform(low=0.3, high=1.0, size=nsample)\n x.sort() # x is not random\n t = 2*np.pi * prng.uniform(size=nsample)\n r = np.sqrt(1-x**2)\n z = r * np.cos(t)\n y = r * np.sin(t)\n return np.array([x, y, z]).transpose()\n\n\nRAD_EARTH = 6371e3\nRAD_Z_OFF = 36\nTACO_X_OFF = 230\nTACO_Y_OFF = 689\n\nREFLECT_ATTEN = 0.9\nTACO_Z_EDGES = make_taco()\nN_TACO = len(TACO_Z_EDGES)\n\nN_SPHERE = 1500000\nSPHERE_XYZ = random_hemisphere(N_SPHERE)\nSPHERE_X = SPHERE_XYZ[:, 0].copy()\n", "meta": {"hexsha": "37391b0ea1f44767f760d3af616cd06e05610108", "size": 11219, "ext": "py", "lang": "Python", "max_stars_repo_path": "acis_taco/acis_taco.py", "max_stars_repo_name": "jzuhone/acis_taco", "max_stars_repo_head_hexsha": "dae1be0988fc52f63491c42ac6f27d4766c39029", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "acis_taco/acis_taco.py", "max_issues_repo_name": "jzuhone/acis_taco", "max_issues_repo_head_hexsha": "dae1be0988fc52f63491c42ac6f27d4766c39029", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-01-10T16:03:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T22:29:05.000Z", "max_forks_repo_path": "acis_taco/acis_taco.py", "max_forks_repo_name": "jzuhone/acis_taco", "max_forks_repo_head_hexsha": "dae1be0988fc52f63491c42ac6f27d4766c39029", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-12-11T17:21:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-11T17:21:31.000Z", "avg_line_length": 34.52, "max_line_length": 96, "alphanum_fraction": 0.6448881362, "include": true, "reason": "import numpy,from numpy", "num_tokens": 3242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.21206881431678096, "lm_q1q2_score": 0.11922010397960799}} {"text": "#!/usr/bin/python2.7\n\nfrom __future__ import division\nimport os\nimport numpy\nimport scipy\nimport matplotlib\nimport pandas\nimport statsmodels\nimport patsy\nimport sys\nimport argparse\nimport matplotlib.pyplot as plt\nimport re\n\nfrom random import shuffle,random,randint,choice,seed\nfrom collections import Counter\nfrom os import system\nfrom pandas import DataFrame\nfrom pandas import *\n# import rpy2.robjects as robjects\n# from rpy2.robjects.packages import importr\n# from rpy2.robjects import pandas2ri\n# pandas2ri.activate()\nfrom Bio import SeqIO\n#import ggplot #added by alistair 01/05/18\n#from ggplot import *\nfrom subprocess import call\nfrom Bio.SeqRecord import SeqRecord\n\n# utils = importr(\"utils\")\n# plyr = importr(\"plyr\")\n# seqinr = importr(\"seqinr\")\n\n#Constant values\n\n#nt list\nnts = ['A','C','G','T']\n\n#Translation Table\ntt = {\"TTT\":\"F|Phe\",\"TTC\":\"F|Phe\",\"TTA\":\"L|Leu\",\"TTG\":\"L|Leu\",\"TCT\":\"S|Ser\",\"TCC\":\"S|Ser\",\"TCA\":\"S|Ser\",\"TCG\":\"S|Ser\", \"TAT\":\"Y|Tyr\",\"TAC\":\"Y|Tyr\",\"TAA\":\"*|Stp\",\"TAG\":\"*|Stp\",\"TGT\":\"C|Cys\",\"TGC\":\"C|Cys\",\"TGA\":\"*|Stp\",\"TGG\":\"W|Trp\", \"CTT\":\"L|Leu\",\"CTC\":\"L|Leu\",\"CTA\":\"L|Leu\",\"CTG\":\"L|Leu\",\"CCT\":\"P|Pro\",\"CCC\":\"P|Pro\",\"CCA\":\"P|Pro\",\"CCG\":\"P|Pro\",\"CAT\":\"H|His\",\"CAC\":\"H|His\",\"CAA\":\"Q|Gln\",\"CAG\":\"Q|Gln\",\"CGT\":\"R|Arg\",\"CGC\":\"R|Arg\",\"CGA\":\"R|Arg\",\"CGG\":\"R|Arg\", \"ATT\":\"I|Ile\",\"ATC\":\"I|Ile\",\"ATA\":\"I|Ile\",\"ATG\":\"M|Met\",\"ACT\":\"T|Thr\",\"ACC\":\"T|Thr\",\"ACA\":\"T|Thr\",\"ACG\":\"T|Thr\", \"AAT\":\"N|Asn\",\"AAC\":\"N|Asn\",\"AAA\":\"K|Lys\",\"AAG\":\"K|Lys\",\"AGT\":\"S|Ser\",\"AGC\":\"S|Ser\",\"AGA\":\"R|Arg\",\"AGG\":\"R|Arg\",\"GTT\":\"V|Val\",\"GTC\":\"V|Val\",\"GTA\":\"V|Val\",\"GTG\":\"V|Val\",\"GCT\":\"A|Ala\",\"GCC\":\"A|Ala\",\"GCA\":\"A|Ala\",\"GCG\":\"A|Ala\", \"GAT\":\"D|Asp\",\"GAC\":\"D|Asp\",\"GAA\":\"E|Glu\",\"GAG\":\"E|Glu\",\"GGT\":\"G|Gly\",\"GGC\":\"G|Gly\",\"GGA\":\"G|Gly\",\"GGG\":\"G|Gly\"}\n#Following functions or their combinations produce randomized or scrambled nucleotide sequence from input sequence.\n#Amino-acid sequence of derived sequence is identical to the input sequence, but nucleotide composition (GC-, nucleotide, or dinucleotide content) may differ slightly for randomized sequences.\n\ndef gc3(seq):#this function creates sequence with GC-content close to the GC-content of the input sequence, but counts of nucleotides may differ from input sequence.\n gc=at=0\n for num in xrange(2,len(seq),3):#first calculating A+T and G+C of the input sequence in third codon position\n if seq[num]=='A'or seq[num]=='T':\n at+=1\n elif seq[num]=='G'or seq[num]=='C':\n gc+=1\n at=at/(len(seq)/3.)\n gc=gc/(len(seq)/3.)\n\n seq1=[]\n for num in xrange(2,len(seq),3):#list \"seq1\" will contain the first two nt of codon, third codon position will containe flags for subsequent randomization. Flags ('_Y_','_R_','_H_',or '_N_') correspond to IUPAC single-letter code, Y-Pyrimindine(C or T), R-Purine(A or G), H-Not G(A or C or T), N-any.\n seq1+=seq[num-2:num],\n if (seq[num]=='T'or seq[num]=='C')and(seq[num-2:num]=='TT'or seq[num-2:num]=='TA'or seq[num-2:num]=='TG'or seq[num-2:num]=='CA'or seq[num-2:num]=='AA'or seq[num-2:num]=='AG'or seq[num-2:num]=='GA'):\n seq1+='_Y_',\n elif (seq[num]=='A'or seq[num]=='G')and(seq[num-2:num]=='TT'or seq[num-2:num]=='CA'or seq[num-2:num]=='AA'or seq[num-2:num]=='AG'or seq[num-2:num]=='GA'):\n seq1+='_R_',\n elif seq[num-2:num+1]=='ATT'or seq[num-2:num+1]=='ATC'or seq[num-2:num+1]=='ATA':\n seq1+='_H_',\n elif (seq[num]=='A'or seq[num]=='G'or seq[num]=='T'or seq[num]=='C')and(seq[num-2:num]=='TC'or seq[num-2:num]=='CT'or seq[num-2:num]=='CC'or seq[num-2:num]=='CG'or seq[num-2:num]=='AC'or seq[num-2:num]=='GT'or seq[num-2:num]=='GC'or seq[num-2:num]=='GG'):\n seq1+='_N_',\n else: seq1+=seq[num],\n seq2=''#\"seq2\" will contain the derived sequence, approproate nucleotide is chosen for flags in \"seq1\", according to GC-content\n for i in seq1:\n if i == '_Y_':\n x=random()\n if x<=gc:\n seq2+='C'\n elif gcT or T->C shuffling preserves the aminoacid sequence (i.e. PHE, SER etc.).\n #C and T from the original sequence in this case would be extracted into list \"Y\"\n shuffle(Y)#shuffling of list \"Y\". For example, before shuffling \"Y\" is ['C','T','C']; after - ['T','C','C']or['C','C','T']or['C','T','C']\n seq2=''\n for i in xrange(len(seq1)):\n if seq1[i]=='_Y_':seq2+=Y.pop(0)#now elements of \"Y\" are inserted back into the sequence instead of '_Y_', but in a different order compared to the input sequence\n else:seq2+=seq1[i]\n seq=seq2\n\n R=[]#similar to the previous step, but A and G are shuffled\n seq1=[]\n for num in xrange(2,len(seq),3):\n if (seq[num]=='A' or seq[num]=='G')and(seq[num-2:num]=='TT'or seq[num-2:num]=='TC'or seq[num-2:num]=='CT'or seq[num-2:num]=='CC'or seq[num-2:num]=='CA'or seq[num-2:num]=='CG'or seq[num-2:num]=='AC'or seq[num-2:num]=='AA'or seq[num-2:num]=='AG'or seq[num-2:num]=='GT'or seq[num-2:num]=='GC'or seq[num-2:num]=='GA'or seq[num-2:num]=='GG'):\n R+=seq[num],\n seq1+=seq[num-2:num],'_R_',\n else:seq1+=seq[num-2:num+1],\n shuffle(R)\n seq2=''\n for i in xrange(len(seq1)):\n if seq1[i]=='_R_':seq2+=R.pop(0)\n else:seq2+=seq1[i]\n seq=seq2\n\n\n H=[]#similar to the previous step, but A,C, and T are shuffled. Affected aminoacids are ILE (three codons), four-codon and four-codon portion of six-codon aminoacids.\n seq1=[]\n for num in xrange(2,len(seq),3):\n if (seq[num]=='A'or seq[num]=='C'or seq[num]=='T')and(seq[num-2:num]=='TC'or seq[num-2:num]=='CT'or seq[num-2:num]=='CC'or seq[num-2:num]=='CG'or seq[num-2:num]=='AT'or seq[num-2:num]=='AC'or seq[num-2:num]=='GT'or seq[num-2:num]=='GC'or seq[num-2:num]=='GG'):\n H+=seq[num],\n seq1+=seq[num-2:num],'_H_',\n else:seq1+=seq[num-2:num+1],\n shuffle(H)\n seq2=''\n for i in xrange(len(seq1)):\n if seq1[i]=='_H_':seq2+=H.pop(0)\n else:seq2+=seq1[i]\n seq=seq2\n\n N=[]#Shuffling of all four nucleotides, where possible. Affected aminoacids are four-codons and four-codon portion of six-codon aminoacids.\n seq1=[]\n for num in xrange(2,len(seq),3):\n if (seq[num]=='A'or seq[num]=='C'or seq[num]=='T'or seq[num]=='G')and(seq[num-2:num]=='TC'or seq[num-2:num]=='CT'or seq[num-2:num]=='CC'or seq[num-2:num]=='CG'or seq[num-2:num]=='AC'or seq[num-2:num]=='GT'or seq[num-2:num]=='GC'or seq[num-2:num]=='GG'):\n N+=seq[num],\n seq1+=seq[num-2:num],'_N_',\n else:seq1+=seq[num-2:num+1],\n shuffle(N)\n seq2=''\n for i in xrange(len(seq1)):\n if seq1[i]=='_N_':seq2+=N.pop(0)\n else:seq2+=seq1[i]\n seq=seq2\n return seq\n\ndef dn23(seq):#this function creates a randomized sequence, with dinucleotide frequences in codon position 2-3 close to those of the input sequence.\n aa=ag=ac=at=ga=gg=gc=gt=ca=cg=cc=ct=ta=tg=tc=tt=0\n for num in xrange(2,len(seq),3):#first calculating dinucleotide frequences in codon position 2-3\n if seq[num-1]=='A':\n if seq[num]=='A':\n aa+=1\n elif seq[num]=='G':\n ag+=1\n elif seq[num]=='C':\n ac+=1\n elif seq[num]=='T':\n at+=1\n elif seq[num-1]=='G':\n if seq[num]=='A':\n ga+=1\n elif seq[num]=='G':\n gg+=1\n elif seq[num]=='C':\n gc+=1\n elif seq[num]=='T':\n gt+=1\n elif seq[num-1]=='C':\n if seq[num]=='A':\n ca+=1\n elif seq[num]=='G':\n cg+=1\n elif seq[num]=='C':\n cc+=1\n elif seq[num]=='T':\n ct+=1\n elif seq[num-1]=='T':\n if seq[num]=='A':\n ta+=1\n elif seq[num]=='G':\n tg+=1\n elif seq[num]=='C':\n tc+=1\n elif seq[num]=='T':\n tt+=1\n aa,ag,ac,at,ga,gg,gc,gt,ca,cg,cc,ct,ta,tg,tc,tt=aa/(len(seq)/3.),ag/(len(seq)/3.),ac/(len(seq)/3.),at/(len(seq)/3.),ga/(len(seq)/3.),gg/(len(seq)/3.),gc/(len(seq)/3.),gt/(len(seq)/3.),ca/(len(seq)/3.),cg/(len(seq)/3.),cc/(len(seq)/3.),ct/(len(seq)/3.),ta/(len(seq)/3.),tg/(len(seq)/3.),tc/(len(seq)/3.),tt/(len(seq)/3.)\n seq2=''\n for num in xrange(2,len(seq),3):#now each codon is replaced with a synonimous codon according to the dinucleotide frequences in codon position 2-3\n seq2+=seq[num-2:num]\n if seq[num-1]=='A'and seq[num-2:num+1]!='TAA'and seq[num-2:num+1]!='TAG':\n if seq[num]=='T'or seq[num]=='C':\n space=at+ac\n AT,AC=at/space,ac/space\n x=random()\n if x<=AT:\n seq2+='T'\n elif ATC)\n CTYC=[]\n\n TAT,TAA,TAG,TAC,TGT,TGA,TGG,TGC=[],[],[],[],[],[],[],[]#these lists will contain the third R-nucleotide of ILE and VAL to exchange with the first position of Leu\n TAG_arg=[]#only 'A' to 'C'. Arginine has AGY and CGN codons, first position can be shuffled.\n\n seq1+=seq[:2]\n for num in xrange(2,len(seq)-2,1):\n #seq1+=seq[num-2:num]\n if num%3==2 and seq[num-2:num]=='CT' and (seq[num]=='C' or seq[num]=='T'):\n if seq[num+1]=='A':\n CTYA+=seq[num],\n seq1+='CTYA',\n elif seq[num+1]=='G':\n if seq[num]=='C':#T/C separation because of ARG, (A->C)\n CTCG+=seq[num],\n seq1+='CTYG',\n elif seq[num]=='T':\n CTTG+=seq[num],\n seq1+='CTYG',\n elif seq[num+1]=='C':\n CTYC+=seq[num],\n seq1+='CTYC',\n elif seq[num+1]=='T':\n CTYT+=seq[num],\n seq1+='CTYT',\n else:\n seq1+=seq[num],\n elif num%3==2 and (seq[num-2:num+1]=='GTA'or seq[num-2:num+1]=='ATA'):\n if seq[num+1]=='A':\n TAA+=seq[num],\n seq1+='TAA',\n elif seq[num+1]=='G':\n TAG+=seq[num],\n seq1+='TAG',\n elif seq[num+1]=='C':\n TAC+=seq[num],\n seq1+='TAC',\n elif seq[num+1]=='T':\n TAT+=seq[num],\n seq1+='TAT',\n else:\n seq1+=seq[num],\n elif num%3==2 and seq[num-2:num+1]=='GTG':\n if seq[num+1]=='A':\n TGA+=seq[num],\n seq1+='TGA',\n elif seq[num+1]=='G':\n TGG+=seq[num],\n seq1+='TGG',\n elif seq[num+1]=='C':\n TGC+=seq[num],\n seq1+='TGC',\n elif seq[num+1]=='T':\n TGT+=seq[num],\n seq1+='TGT',\n else:\n seq1+=seq[num],\n elif num%3==0 and (seq[num:num+3]=='AGA' or seq[num:num+3]=='AGG') and seq[num-1]=='T'and seq[num-2:num]!='TT'and seq[num-3:num]!='CTT':\n TAG_arg+=seq[num],\n seq1+='TAG_arg',\n else:\n seq1+=seq[num],\n seq1+=seq[-2:]\n\n #now replacing the third position Y with R in LEU\n CTAG=[]\n change_num=min(len(CTCG),len(TAG_arg))\n CTAG,TAG_arg[:change_num],CTCG=TAG_arg[:change_num],CTCG[:change_num],CTCG[-1*(len(CTCG)-change_num):]\n CTYG=CTCG+CTTG\n shuffle(CTYG)\n change_num=min(len(CTYG),len(TAG)) #first TAN,\n CTYG[:change_num],TAG[:change_num]=TAG[:change_num],CTYG[:change_num] #then TGN,\n CTYG.reverse() #important,\n change_num=min(len(CTYG),len(TGG)) #Arginine,\n CTYG[:change_num],TGG[:change_num]=TGG[:change_num],CTYG[:change_num] #first TAN,\n CTYG+=CTAG #then TGN,\n #important,\n change_num=min(len(CTYT),len(TAT)) #first TAN,\n CTYT[:change_num],TAT[:change_num]=TAT[:change_num],CTYT[:change_num] #then TGN,\n CTYT.reverse() #important,\n change_num=min(len(CTYT),len(TGT)) #first TAN,\n CTYT[:change_num],TGT[:change_num]=TGT[:change_num],CTYT[:change_num] #then TGN,\n #important,\n #first TAN,\n change_num=min(len(CTYA),len(TAA)) #then TGN,\n CTYA[:change_num],TAA[:change_num]=TAA[:change_num],CTYA[:change_num] #important,\n CTYA.reverse() #Arginine,\n change_num=min(len(CTYA),len(TGA)) #then TGN,\n CTYA[:change_num],TGA[:change_num]=TGA[:change_num],CTYA[:change_num] #important,\n #first TAN,\n #then TGN,\n change_num=min(len(CTYC),len(TAC)) #important,\n CTYC[:change_num],TAC[:change_num]=TAC[:change_num],CTYC[:change_num] #first TAN,\n CTYC.reverse() #important,\n change_num=min(len(CTYC),len(TGC)) #Arginine,\n CTYC[:change_num],TGC[:change_num]=TGC[:change_num],CTYC[:change_num] #important\n\n shuffle(CTYT),shuffle(CTYA),shuffle(CTYG),shuffle(CTYC),shuffle(TAT),shuffle(TAA),shuffle(TAG),shuffle(TAC),shuffle(TGT),shuffle(TGA),shuffle(TGG),shuffle(TGC),shuffle(TAG_arg)\n\n seq2=''\n for i in xrange(len(seq1)):\n if seq1[i]=='CTYT':seq2+=CTYT.pop(0)\n elif seq1[i]=='CTYC':seq2+=CTYC.pop(0)\n elif seq1[i]=='CTYA':seq2+=CTYA.pop(0)\n elif seq1[i]=='CTYG':seq2+=CTYG.pop(0)\n elif seq1[i]=='TAG':seq2+=TAG.pop(0)\n elif seq1[i]=='TAA':seq2+=TAA.pop(0)\n elif seq1[i]=='TAC':seq2+=TAC.pop(0)\n elif seq1[i]=='TAT':seq2+=TAT.pop(0)\n elif seq1[i]=='TGG':seq2+=TGG.pop(0)\n elif seq1[i]=='TGA':seq2+=TGA.pop(0)\n elif seq1[i]=='TGC':seq2+=TGC.pop(0)\n elif seq1[i]=='TGT':seq2+=TGT.pop(0)\n elif seq1[i]=='TAG_arg':seq2+=TAG_arg.pop(0)\n else:seq2+=seq1[i]\n seq=seq2#convertion of CTY to CTR is finished\n\n #now shuffling the first nucleotide of TTR and CTR LEU codons, and the third Y of other codons\n seq1=[]\n TYT,AYT,GYT,CYT=[],[],[],[]\n seq1+=seq[:2]\n\n for num in xrange(2,len(seq)-2,1):\n if ((seq[num]=='T' or seq[num]=='C') and seq[num+1]=='T' and num%3==2 and seq[num+1:num+4]!='TTA' and seq[num+1:num+4]!='TTG' and seq[num+1:num+4]!='CTA' and seq[num+1:num+4]!='CTG') or (num%3==0 and (seq[num:num+3]=='TTA' or seq[num:num+3]=='TTG' or seq[num:num+3]=='CTA' or seq[num:num+3]=='CTG')):\n if seq[num-1]=='T':\n seq1+='TYT',\n TYT+=seq[num],\n elif seq[num-1]=='C':\n seq1+='CYT',\n CYT+=seq[num],\n elif seq[num-1]=='A':\n seq1+='AYT',\n AYT+=seq[num],\n elif seq[num-1]=='G':\n seq1+='GYT',\n GYT+=seq[num],\n else:\n seq1+=seq[num]\n else:\n seq1+=seq[num]\n seq1+=seq[-2:]\n\n shuffle(TYT),shuffle(GYT),shuffle(AYT),shuffle(CYT)\n seq2=''\n for i in xrange(len(seq1)):\n if seq1[i]=='TYT':seq2+=TYT.pop(0)\n elif seq1[i]=='AYT':seq2+=AYT.pop(0)\n elif seq1[i]=='GYT':seq2+=GYT.pop(0)\n elif seq1[i]=='CYT':seq2+=CYT.pop(0)\n else:seq2+=seq1[i]\n seq=seq2#shuffling is finished\n\n\n #SER\n seq1=[]\n\n TCRC,TCRA,TCRG,TCRT=[],[],[],[]#SER has TCN and AGY codons, first TCR will be converted to TCY\n CYC,CYA,CYG,CYT=[],[],[],[]\n\n for num in xrange(2,len(seq)-2,3):\n seq1+=seq[num-2:num]\n if seq[num-2:num+1]=='TCA' or seq[num-2:num+1]=='TCG':\n if seq[num+1]=='C':\n TCRC+=seq[num],\n seq1+='TCRC',\n elif seq[num+1]=='G':\n TCRG+=seq[num],\n seq1+='TCRG',\n elif seq[num+1]=='A':\n TCRA+=seq[num],\n seq1+='TCRA',\n elif seq[num+1]=='T':\n TCRT+=seq[num],\n seq1+='TCRT',\n else:\n seq1+=seq[num],\n elif (seq[num-2:num]=='CC'or seq[num-2:num]=='AC' or seq[num-2:num]=='GC')and(seq[num]=='T'or seq[num]=='C'):\n if seq[num+1]=='C':\n CYC+=seq[num],\n seq1+='CYC',\n elif seq[num+1]=='G':\n CYG+=seq[num],\n seq1+='CYG',\n elif seq[num+1]=='A':\n CYA+=seq[num],\n seq1+='CYA',\n elif seq[num+1]=='T':\n CYT+=seq[num],\n seq1+='CYT',\n else:\n seq1+=seq[num],\n else:\n seq1+=seq[num],\n seq1+=seq[-3:]\n\n change_num=min(len(TCRC),len(CYC))\n TCRC[:change_num],CYC[:change_num]=CYC[:change_num],TCRC[:change_num]\n\n change_num=min(len(TCRA),len(CYA))\n TCRA[:change_num],CYA[:change_num]=CYA[:change_num],TCRA[:change_num]\n\n change_num=min(len(TCRG),len(CYG))\n TCRG[:change_num],CYG[:change_num]=CYG[:change_num],TCRG[:change_num]\n\n change_num=min(len(TCRT),len(CYT))\n TCRT[:change_num],CYT[:change_num]=CYT[:change_num],TCRT[:change_num]\n\n shuffle(TCRC),shuffle(TCRA),shuffle(TCRG),shuffle(TCRT),shuffle(CYC),shuffle(CYA),shuffle(CYG),shuffle(CYT)\n\n seq2=''\n for i in xrange(len(seq1)):\n if seq1[i]=='TCRC':seq2+=TCRC.pop(0)\n elif seq1[i]=='TCRA':seq2+=TCRA.pop(0)\n elif seq1[i]=='TCRG':seq2+=TCRG.pop(0)\n elif seq1[i]=='TCRT':seq2+=TCRT.pop(0)\n elif seq1[i]=='CYT':seq2+=CYT.pop(0)\n elif seq1[i]=='CYA':seq2+=CYA.pop(0)\n elif seq1[i]=='CYG':seq2+=CYG.pop(0)\n elif seq1[i]=='CYC':seq2+=CYC.pop(0)\n else:seq2+=seq1[i]\n\n seq=seq2#convertion is finished\n\n\n #ATCY,AAGY conversion to BTCY,BAGY\n seq1=[]\n AAA_R,GAA_N,GAA_R,CAA_N,TAA_R,TAA_N,TAA_H,AAT_R,GAT_N,GAT_R,CAT_N,TAT_R,TAT_N,TAT_H=[],[],[],[],[],[],[],[],[],[],[],[],[],[]\n AGA_R,GBA_N,GGA_R,TGA_R,TBA_N,TYA_H,AGT_R,GBT_N,GGT_R,CBT_N,TGT_R,TBT_N,TYT_H,CBA_N=[],[],[],[],[],[],[],[],[],[],[],[],[],[]\n\n for num in xrange(2,len(seq)-2,3):\n seq1+=seq[num-2:num]\n if seq[num:num+4]=='AAGC'or seq[num:num+4]=='AAGT':\n if seq[num-2:num]=='CA'or seq[num-2:num]=='AA'or seq[num-2:num]=='GA':\n AAA_R+=seq[num],\n seq1+='AAA_R',\n elif seq[num-2:num]=='CG'or seq[num-2:num]=='GG':\n GAA_N+=seq[num],\n seq1+='GAA_N',\n elif seq[num-2:num]=='AG':\n GAA_R+=seq[num],\n seq1+='GAA_R',\n elif seq[num-2:num]=='CC'or seq[num-2:num]=='AC'or seq[num-2:num]=='GC':\n CAA_N+=seq[num],\n seq1+='CAA_N',\n elif seq[num-2:num]=='TT':\n TAA_R+=seq[num],\n seq1+='TAA_R',\n elif seq[num-2:num]=='CT'or seq[num-2:num]=='GT':\n TAA_N+=seq[num],\n seq1+='TAA_N',\n elif seq[num-2:num]=='AT':\n TAA_H+=seq[num],\n seq1+='TAA_H',\n else:\n seq1+=seq[num]\n elif seq[num:num+4]=='ATCC'or seq[num:num+4]=='ATCT':\n if seq[num-2:num]=='CA'or seq[num-2:num]=='AA'or seq[num-2:num]=='GA':\n AAT_R+=seq[num],\n seq1+='AAT_R',\n elif seq[num-2:num]=='CG'or seq[num-2:num]=='GG':\n GAT_N+=seq[num],\n seq1+='GAT_N',\n elif seq[num-2:num]=='AG':\n GAT_R+=seq[num],\n seq1+='GAT_R',\n elif seq[num-2:num]=='CC'or seq[num-2:num]=='AC'or seq[num-2:num]=='GC':\n CAT_N+=seq[num],\n seq1+='CAT_N',\n elif seq[num-2:num]=='TT':\n TAT_R+=seq[num],\n seq1+='TAT_R',\n elif seq[num-2:num]=='CT'or seq[num-2:num]=='GT':\n TAT_N+=seq[num],\n seq1+='TAT_N',\n elif seq[num-2:num]=='AT':\n TAT_H+=seq[num],\n seq1+='TAT_H',\n else:\n seq1+=seq[num]\n elif seq[num+1:num+4]!='AGC'and seq[num+1:num+4]!='AGT'and seq[num+1]=='A'and seq[num]!='A':\n if seq[num-2:num+1]=='CAG'or seq[num-2:num+1]=='AAG'or seq[num-2:num+1]=='GAG':\n AGA_R+=seq[num],\n seq1+='AGA_R',\n elif seq[num-2:num]=='CG'or seq[num-2:num]=='GG':\n GBA_N+=seq[num],\n seq1+='GBA_N',\n elif seq[num-2:num+1]=='AGG':\n GGA_R+=seq[num],\n seq1+='GGA_R',\n elif seq[num-2:num]=='CC'or seq[num-2:num]=='AC'or seq[num-2:num]=='GC':\n CBA_N+=seq[num],\n seq1+='CBA_N',\n elif seq[num-2:num+1]=='TTG':\n TGA_R+=seq[num],\n seq1+='TGA_R',\n elif seq[num-2:num]=='CT'or seq[num-2:num]=='GT':\n TBA_N+=seq[num],\n seq1+='TBA_N',\n elif seq[num-2:num]=='AT'and seq[num]!='G':\n TYA_H+=seq[num],\n seq1+='TYA_H',\n else:\n seq1+=seq[num]\n elif seq[num+1:num+4]!='TCC'and seq[num+1:num+4]!='TCT'and seq[num+1]=='T'and seq[num]!='A':\n if seq[num-2:num+1]=='CAG'or seq[num-2:num+1]=='AAG'or seq[num-2:num+1]=='GAG':\n AGT_R+=seq[num],\n seq1+='AGT_R',\n elif seq[num-2:num]=='CG'or seq[num-2:num]=='GG':\n GBT_N+=seq[num],\n seq1+='GBT_N',\n elif seq[num-2:num+1]=='AGG':\n GGT_R+=seq[num],\n seq1+='GGT_R',\n elif seq[num-2:num]=='CC'or seq[num-2:num]=='AC'or seq[num-2:num]=='GC':\n CBT_N+=seq[num],\n seq1+='CBT_N',\n elif seq[num-2:num+1]=='TTG':\n TGT_R+=seq[num],\n seq1+='TGT_R',\n elif seq[num-2:num]=='CT'or seq[num-2:num]=='GT':\n TBT_N+=seq[num],\n seq1+='TBT_N',\n elif seq[num-2:num]=='AT'and seq[num]!='G':\n TYT_H+=seq[num],\n seq1+='TYT_H',\n else:\n seq1+=seq[num]\n else:\n seq1+=seq[num]\n seq1+=seq[-3:]\n\n\n change_num=min(len(AAA_R),len(AGA_R))\n AAA_R[:change_num],AGA_R[:change_num]=AGA_R[:change_num],AAA_R[:change_num]\n\n change_num=min(len(GAA_R),len(GGA_R))\n GAA_R[:change_num],GGA_R[:change_num]=GGA_R[:change_num],GAA_R[:change_num]\n\n change_num=min(len(TAA_R),len(TGA_R))\n TAA_R[:change_num],TGA_R[:change_num]=TGA_R[:change_num],TAA_R[:change_num]\n\n change_num=min(len(AAT_R),len(AGT_R))\n AAT_R[:change_num],AGT_R[:change_num]=AGT_R[:change_num],AAT_R[:change_num]\n\n change_num=min(len(GAT_R),len(GGT_R))\n GAT_R[:change_num],GGT_R[:change_num]=GGT_R[:change_num],GAT_R[:change_num]\n\n change_num=min(len(TAT_R),len(TGT_R))\n TAT_R[:change_num],TGT_R[:change_num]=TGT_R[:change_num],TAT_R[:change_num]\n\n change_num=min(len(TAT_H),len(TYT_H))\n TAT_H[:change_num],TYT_H[:change_num]=TYT_H[:change_num],TAT_H[:change_num]\n\n change_num=min(len(TAA_H),len(TYA_H))\n TAA_H[:change_num],TYA_H[:change_num]=TYA_H[:change_num],TAA_H[:change_num]\n\n change_num=min(len(CAA_N),len(CBA_N))\n CAA_N[:change_num],CBA_N[:change_num]=CBA_N[:change_num],CAA_N[:change_num]\n\n change_num=min(len(GAA_N),len(GBA_N))\n GAA_N[:change_num],GBA_N[:change_num]=GBA_N[:change_num],GAA_N[:change_num]\n\n change_num=min(len(TAA_N),len(TBA_N))\n TAA_N[:change_num],TBA_N[:change_num]=TBA_N[:change_num],TAA_N[:change_num]\n\n change_num=min(len(GAT_N),len(GBT_N))\n GAT_N[:change_num],GBT_N[:change_num]=GBT_N[:change_num],GAT_N[:change_num]\n\n change_num=min(len(CAT_N),len(CBT_N))\n CAT_N[:change_num],CBT_N[:change_num]=CBT_N[:change_num],CAT_N[:change_num]\n\n change_num=min(len(TAT_N),len(TBT_N))\n TAT_N[:change_num],TBT_N[:change_num]=TBT_N[:change_num],TAT_N[:change_num]\n\n shuffle(AAA_R),shuffle(GAA_N),shuffle(GAA_R),shuffle(CAA_N),shuffle(TAA_R),shuffle(TAA_N),shuffle(TAA_H),shuffle(AAT_R),shuffle(GAT_N),shuffle(GAT_R),shuffle(CAT_N),shuffle(TAT_R),shuffle(TAT_N),shuffle(TAT_H),shuffle(AGA_R),shuffle(GBA_N),shuffle(GGA_R),shuffle(TGA_R),shuffle(TBA_N),shuffle(TYA_H),shuffle(AGT_R),shuffle(GBT_N),shuffle(GGT_R),shuffle(CBT_N),shuffle(TGT_R),shuffle(TBT_N),shuffle(TYT_H),shuffle(CBA_N)\n\n\n seq2=''\n for i in xrange(len(seq1)):\n if seq1[i]=='AAA_R':seq2+=AAA_R.pop(0)\n elif seq1[i]=='GAA_N':seq2+=GAA_N.pop(0)\n elif seq1[i]=='GAA_R':seq2+=GAA_R.pop(0)\n elif seq1[i]=='CAA_N':seq2+=CAA_N.pop(0)\n elif seq1[i]=='TAA_R':seq2+=TAA_R.pop(0)\n elif seq1[i]=='TAA_N':seq2+=TAA_N.pop(0)\n elif seq1[i]=='TAA_H':seq2+=TAA_H.pop(0)\n elif seq1[i]=='AAT_R':seq2+=AAT_R.pop(0)\n elif seq1[i]=='GAT_N':seq2+=GAT_N.pop(0)\n elif seq1[i]=='GAT_R':seq2+=GAT_R.pop(0)\n elif seq1[i]=='CAT_N':seq2+=CAT_N.pop(0)\n elif seq1[i]=='TAT_R':seq2+=TAT_R.pop(0)\n elif seq1[i]=='TAT_N':seq2+=TAT_N.pop(0)\n elif seq1[i]=='TAT_H':seq2+=TAT_H.pop(0)\n elif seq1[i]=='AGA_R':seq2+=AGA_R.pop(0)\n elif seq1[i]=='GBA_N':seq2+=GBA_N.pop(0)\n elif seq1[i]=='GGA_R':seq2+=GGA_R.pop(0)\n elif seq1[i]=='TGA_R':seq2+=TGA_R.pop(0)\n elif seq1[i]=='TBA_N':seq2+=TBA_N.pop(0)\n elif seq1[i]=='TYA_H':seq2+=TYA_H.pop(0)\n elif seq1[i]=='AGT_R':seq2+=AGT_R.pop(0)\n elif seq1[i]=='GBT_N':seq2+=GBT_N.pop(0)\n elif seq1[i]=='GGT_R':seq2+=GGT_R.pop(0)\n elif seq1[i]=='CBT_N':seq2+=CBT_N.pop(0)\n elif seq1[i]=='TGT_R':seq2+=TGT_R.pop(0)\n elif seq1[i]=='TBT_N':seq2+=TBT_N.pop(0)\n elif seq1[i]=='TYT_H':seq2+=TYT_H.pop(0)\n elif seq1[i]=='CBA_N':seq2+=CBA_N.pop(0)\n else:seq2+=seq1[i]\n seq=seq2#ATCY,AAGY conversion to BTCY,BAGY is finished\n\n\n seq1=[]#tAGT SER codon could be converted to tTCT, preserving overall dinucleotide content, if in other positions in sequence\n #tTg will be replaced with tAG, and tCt will be replaced with tGt, and vice versa.\n #Using the same logic, SER codons ending with Y could be replaced, according to the third nucleotide of previous codon.\n\n GTG,GAG=[],[]#G_SER\n CTG,CAG=[],[]#C_SER\n TTG,TAG=[],[]#T_SER\n\n TCC,TGC=[],[]#SER_C\n TCT,TGT=[],[]#SER_T\n\n GAGC,CAGC,TAGC,GAGT,CAGT,TAGT=[],[],[],[],[],[]\n GTCC,CTCC,TTCC,GTCT,CTCT,TTCT=[],[],[],[],[],[]\n\n for num in xrange(2,len(seq)-3,3):\n if seq[num-2:num]=='AG'and(seq[num]=='C'or seq[num]=='T')and(seq[num-3]=='G'or seq[num-3]=='C'or seq[num-3]=='T'):\n if seq[num-3]=='G':\n if seq[num]=='C':\n seq1+='GAGC','C'\n GAGC+=seq[num-2:num],\n elif seq[num]=='T':\n seq1+='GAGT','T'\n GAGT+=seq[num-2:num],\n elif seq[num-3]=='C':\n if seq[num]=='C':\n seq1+='CAGC','C'\n CAGC+=seq[num-2:num],\n elif seq[num]=='T':\n seq1+='CAGT','T'\n CAGT+=seq[num-2:num],\n elif seq[num-3]=='T':\n if seq[num]=='C':\n seq1+='TAGC','C'\n TAGC+=seq[num-2:num],\n elif seq[num]=='T':\n seq1+='TAGT','T'\n TAGT+=seq[num-2:num],\n elif seq[num-2:num]=='TC'and(seq[num]=='C'or seq[num]=='T')and(seq[num-3]=='G'or seq[num-3]=='C'or seq[num-3]=='T'):\n if seq[num-3]=='G':\n if seq[num]=='C':\n seq1+='GTCC','C'\n GTCC+=seq[num-2:num],\n elif seq[num]=='T':\n seq1+='GTCT','T'\n GTCT+=seq[num-2:num],\n elif seq[num-3]=='C':\n if seq[num]=='C':\n seq1+='CTCC','C'\n CTCC+=seq[num-2:num],\n elif seq[num]=='T':\n seq1+='CTCT','T'\n CTCT+=seq[num-2:num],\n elif seq[num-3]=='T':\n if seq[num]=='C':\n seq1+='TTCC','C'\n TTCC+=seq[num-2:num],\n elif seq[num]=='T':\n seq1+='TTCT','T'\n TTCT+=seq[num-2:num],\n elif seq[num-1:num+2]=='GTG'and(seq[num-2:num]=='CG'or seq[num-2:num]=='GG'):\n seq1+=seq[num-2:num],'GTG',\n GTG+=seq[num],\n elif seq[num-1:num+2]=='GAG'and(seq[num-2:num]=='CG'or seq[num-2:num]=='GG'):\n seq1+=seq[num-2:num],'GAG',\n GAG+=seq[num],\n elif seq[num-1:num+2]=='CTG'and(seq[num-2:num]=='AC'or seq[num-2:num]=='GC'or seq[num-2:num]=='CC'):\n seq1+=seq[num-2:num],'CTG',\n CTG+=seq[num],\n elif seq[num-1:num+2]=='CAG'and(seq[num-2:num]=='AC'or seq[num-2:num]=='GC'or seq[num-2:num]=='CC'):\n seq1+=seq[num-2:num],'CAG',\n CAG+=seq[num],\n elif seq[num-1:num+2]=='TTG'and(seq[num-2:num]=='AT'or seq[num-2:num]=='GT'or seq[num-2:num]=='CT'):\n seq1+=seq[num-2:num],'TTG',\n TTG+=seq[num],\n elif seq[num-1:num+2]=='TAG'and(seq[num-2:num]=='AT'or seq[num-2:num]=='GT'or seq[num-2:num]=='CT'):\n seq1+=seq[num-2:num],'TAG',\n TAG+=seq[num],\n elif seq[num-1:num+2]=='TCC'and(seq[num-2:num]=='GT'or seq[num-2:num]=='CT'):\n seq1+=seq[num-2:num],'TCC',\n TCC+=seq[num],\n elif seq[num-1:num+2]=='TGC'and(seq[num-2:num]=='GT'or seq[num-2:num]=='CT'):\n seq1+=seq[num-2:num],'TGC',\n TGC+=seq[num],\n elif seq[num-1:num+2]=='TCT'and(seq[num-2:num]=='GT'or seq[num-2:num]=='CT')and seq[num+1:num+4]!='TCC'and seq[num+1:num+4]!='TCT':\n seq1+=seq[num-2:num],'TCT',\n TCT+=seq[num],\n elif seq[num-1:num+2]=='TGT'and(seq[num-2:num]=='GT'or seq[num-2:num]=='CT')and seq[num+1:num+4]!='TCC'and seq[num+1:num+4]!='TCT':\n seq1+=seq[num-2:num],'TGT',\n TGT+=seq[num],\n else:\n seq1+=seq[num-2:num+1]\n seq1+=seq[-3:]\n\n gAGc=min(len(GAGC),len(GTG),len(TCC))\n gTCc=min(len(GTCC),len(GAG),len(TGC))\n\n gAGt=min(len(GAGT),len(GTG),len(TCT))\n gTCt=min(len(GTCT),len(GAG),len(TGT))\n\n cAGc=min(len(CAGC),len(CTG),len(TCC))\n cTCc=min(len(CTCC),len(CAG),len(TGC))\n\n cAGt=min(len(CAGT),len(CTG),len(TCT))\n cTCt=min(len(CTCT),len(CAG),len(TGT))\n\n tAGc=min(len(TAGC),len(TTG),len(TCC))\n tTCc=min(len(TTCC),len(TAG),len(TGC))\n\n tAGt=min(len(TAGC),len(TTG),len(TCT))\n tTCt=min(len(TTCC),len(TAG),len(TGT))\n\n if gAGc+gAGt>len(GTG):\n gAGc,gAGt=round(gAGc*(len(GTG)/float(gAGc+gAGt))),round(gAGt*(len(GTG)/float(gAGc+gAGt)))\n gAGc,gAGt=int(gAGc),int(gAGt)\n if gTCc+gTCt>len(GAG):\n gTCc,gTCt=round(gTCc*(len(GAG)/float(gTCc+gTCt))),round(gTCt*(len(GAG)/float(gTCc+gTCt)))\n gTCc,gTCt=int(gTCc),int(gTCt)\n\n if cAGc+cAGt>len(CTG):\n cAGc,cAGt=round(cAGc*(len(CTG)/float(cAGc+cAGt))),round(cAGt*(len(CTG)/float(cAGc+cAGt)))\n cAGc,cAGt=int(cAGc),int(cAGt)\n if cTCc+cTCt>len(CAG):\n cTCc,cTCt=round(cTCc*(len(CAG)/float(cTCc+cTCt))),round(cTCt*(len(CAG)/float(cTCc+cTCt)))\n cTCc,cTCt=int(cTCc),int(cTCt)\n\n if tAGc+tAGt>len(TTG):\n tAGc,tAGt=round(tAGc*(len(TTG)/float(tAGc+tAGt))),round(tAGt*(len(TTG)/float(tAGc+tAGt)))\n tAGc,tAGt=int(tAGc),int(tAGt)\n if tTCc+tTCt>len(TAG):\n tTCc,tTCt=round(tTCc*(len(TAG)/float(tTCc+tTCt))),round(tTCt*(len(TAG)/float(tTCc+tTCt)))\n tTCc,tTCt=int(tTCc),int(tTCt)\n\n\n\n if gAGc+cAGc+tAGc>len(TCC):\n gAGc,cAGc,tAGc=round(gAGc*(len(TCC)/float(gAGc+cAGc+tAGc))),round(cAGc*(len(TCC)/float(gAGc+cAGc+tAGc))),round(tAGc*(len(TCC)/float(gAGc+cAGc+tAGc)))\n gAGc,cAGc,tAGc=int(gAGc),int(cAGc),int(tAGc)\n\n if gAGt+cAGt+tAGt>len(TCT):\n gAGt,cAGt,tAGt=round(gAGt*(len(TCT)/float(gAGt+cAGt+tAGt))),round(cAGt*(len(TCT)/float(gAGt+cAGt+tAGt))),round(tAGt*(len(TCT)/float(gAGt+cAGt+tAGt)))\n gAGt,cAGt,tAGt=int(gAGt),int(cAGt),int(tAGt)\n\n if gTCc+cTCc+tTCc>len(TGC):\n gTCc,cTCc,tTCc=round(gTCc*(len(TGC)/float(gTCc+cTCc+tTCc))),round(cTCc*(len(TGC)/float(gTCc+cTCc+tTCc))),round(tTCc*(len(TGC)/float(gTCc+cTCc+tTCc)))\n gTCc,cTCc,tTCc=int(gTCc),int(cTCc),int(tTCc)\n\n if gTCt+cTCt+tTCt>len(TGT):\n gTCt,cTCt,tTCt=round(gTCt*(len(TGT)/float(gTCt+cTCt+tTCt))),round(cTCt*(len(TGT)/float(gTCt+cTCt+tTCt))),round(tTCt*(len(TGT)/float(gTCt+cTCt+tTCt)))\n gTCt,cTCt,tTCt=int(gTCt),int(cTCt),int(tTCt)\n\n #GAGC,GTG,TCC\n change_num=randint(0,gAGc)\n for i in xrange(change_num):\n GAGC[i]='TC'\n del GTG[0];GTG.append('A')\n del TCC[0];TCC.append('G')\n\n #GTCC,GAG,TGC\n change_num=randint(0,gTCc)\n for i in xrange(change_num):\n GTCC[i]='AG'\n del GAG[0];GAG.append('T')\n del TGC[0];TGC.append('C')\n\n #GAGT,GTG,TCT\n change_num=randint(0,gAGt)\n for i in xrange(change_num):\n GAGT[i]='TC'\n del GTG[0];GTG.append('A')\n del TCT[0];TCT.append('G')\n\n #GTCT,GAG,TGT\n change_num=randint(0,gTCt)\n for i in xrange(change_num):\n GTCT[i]='AG'\n del GAG[0];GAG.append('T')\n del TGT[0];TGT.append('C')\n\n #CAGC,CTG,TCC\n change_num=randint(0,cAGc)\n for i in xrange(change_num):\n CAGC[i]='TC'\n del CTG[0];CTG.append('A')\n del TCC[0];TCC.append('G')\n\n #CTCC,CAG,TGC\n change_num=randint(0,cTCc)\n for i in xrange(change_num):\n CTCC[i]='AG'\n del CAG[0];CAG.append('T')\n del TGC[0];TGC.append('C')\n\n #CAGT,CTG,TCT\n change_num=randint(0,cAGt)\n for i in xrange(change_num):\n CAGT[i]='TC'\n del CTG[0];CTG.append('A')\n del TCT[0];TCT.append('G')\n\n #CTCT,CAG,TGT\n change_num=randint(0,cTCt)\n for i in xrange(change_num):\n CTCT[i]='AG'\n del CAG[0];CAG.append('T')\n del TGT[0];TGT.append('C')\n\n #TAGC,TTG,TCC\n change_num=randint(0,tAGc)\n for i in xrange(change_num):\n TAGC[i]='TC'\n del TTG[0];TTG.append('A')\n del TCC[0];TCC.append('G')\n\n #TTCC,TAG,TGC\n change_num=randint(0,tTCc)\n for i in xrange(change_num):\n TTCC[i]='AG'\n del TAG[0];TAG.append('T')\n del TGC[0];TGC.append('C')\n\n #TAGC,TTG,TCT\n change_num=randint(0,tAGt)\n for i in xrange(change_num):\n TAGC[i]='TC'\n del TTG[0];TTG.append('A')\n del TCT[0];TCT.append('G')\n\n #tTCt=min(len(TTCC),len(TAG),len(TGT))\n change_num=randint(0,tTCt)\n for i in xrange(change_num):\n TTCC[i]='AG'\n del TAG[0];TAG.append('T')\n del TGT[0];TGT.append('C')\n\n shuffle(GTG),shuffle(GAG),shuffle(CTG),shuffle(CAG),shuffle(TTG),shuffle(TAG),shuffle(TCC),shuffle(TGC),shuffle(TCT),shuffle(TGT)\n shuffle(GAGC),shuffle(CAGC),shuffle(TAGC),shuffle(GAGT),shuffle(CAGT),shuffle(TAGT)\n shuffle(GTCC),shuffle(CTCC),shuffle(TTCC),shuffle(GTCT),shuffle(CTCT),shuffle(TTCT)\n\n seq2=''\n for i in xrange(len(seq1)):\n if seq1[i]=='GTG':seq2+=GTG.pop(0)\n elif seq1[i]=='GAG':seq2+=GAG.pop(0)\n elif seq1[i]=='CTG':seq2+=CTG.pop(0)\n elif seq1[i]=='CAG':seq2+=CAG.pop(0)\n elif seq1[i]=='TTG':seq2+=TTG.pop(0)\n elif seq1[i]=='TAG':seq2+=TAG.pop(0)\n elif seq1[i]=='TCC':seq2+=TCC.pop(0)\n elif seq1[i]=='TGC':seq2+=TGC.pop(0)\n elif seq1[i]=='TCT':seq2+=TCT.pop(0)\n elif seq1[i]=='TGT':seq2+=TGT.pop(0)\n elif seq1[i]=='GAGC':seq2+=GAGC.pop(0)\n elif seq1[i]=='CAGC':seq2+=CAGC.pop(0)\n elif seq1[i]=='TAGC':seq2+=TAGC.pop(0)\n elif seq1[i]=='GAGT':seq2+=GAGT.pop(0)\n elif seq1[i]=='CAGT':seq2+=CAGT.pop(0)\n elif seq1[i]=='TAGT':seq2+=TAGT.pop(0)\n elif seq1[i]=='GTCC':seq2+=GTCC.pop(0)\n elif seq1[i]=='CTCC':seq2+=CTCC.pop(0)\n elif seq1[i]=='TTCC':seq2+=TTCC.pop(0)\n elif seq1[i]=='GTCT':seq2+=GTCT.pop(0)\n elif seq1[i]=='CTCT':seq2+=CTCT.pop(0)\n elif seq1[i]=='TTCT':seq2+=TTCT.pop(0)\n else:seq2+=seq1[i]\n seq=seq2\n\n\n #ARG\n #shuffling of the first codon position of aginine codons requires convertion of CGY to CGR.\n #then the first codon positions of AGR and CGR are shuffled with the third codon position of other codons\n #aminoacid sequence and overall dinucleotide content are maintained\n\n seq1=[]\n\n GYA,GYT,GYC,GYG=[],[],[],[]\n\n GRA=[]#only gly\n GRT,GRC,GRG=[],[],[]\n\n for num in xrange(2,len(seq)-3,3):\n seq1+=seq[num-2:num]\n if seq[num-2:num]=='CG' and(seq[num]=='C'or seq[num]=='T'):\n if seq[num+1]=='A':\n GYA+=seq[num],\n seq1+='GYA',\n elif seq[num+1]=='T':\n GYT+=seq[num],\n seq1+='GYT',\n elif seq[num+1]=='C':\n GYC+=seq[num],\n seq1+='GYC',\n elif seq[num+1]=='G':\n GYG+=seq[num],\n seq1+='GYG',\n else:\n seq1+=seq[num],\n elif seq[num-2:num]=='GG' and(seq[num]=='A'or seq[num]=='G'):#only gly\n if seq[num+1]=='A':\n GRA+=seq[num],\n seq1+='GRA',\n elif seq[num+1]=='T':\n GRT+=seq[num],\n seq1+='GRT',\n elif seq[num+1]=='C':\n GRC+=seq[num],\n seq1+='GRC',\n elif seq[num+1]=='G':\n GRG+=seq[num],\n seq1+='GRG',\n else:\n seq1+=seq[num],\n else:\n seq1+=seq[num],\n seq1+=seq[-3:]\n\n change_num=min(len(GYA),len(GRA))\n GYA[:change_num],GRA[:change_num]=GRA[:change_num],GYA[:change_num]\n\n change_num=min(len(GYT),len(GRT))\n GYT[:change_num],GRT[:change_num]=GRT[:change_num],GYT[:change_num]\n\n change_num=min(len(GYC),len(GRC))\n GYC[:change_num],GRC[:change_num]=GRC[:change_num],GYC[:change_num]\n\n change_num=min(len(GYG),len(GRG))\n GYG[:change_num],GRG[:change_num]=GRG[:change_num],GYG[:change_num]\n\n shuffle(GYA),shuffle(GYT),shuffle(GYC),shuffle(GYG),shuffle(GRA),shuffle(GRG),shuffle(GRC),shuffle(GRT)\n\n seq2=''\n for i in xrange(len(seq1)):\n if seq1[i]=='GYA':seq2+=GYA.pop(0)\n elif seq1[i]=='GRA':seq2+=GRA.pop(0)\n elif seq1[i]=='GYT':seq2+=GYT.pop(0)\n elif seq1[i]=='GRT':seq2+=GRT.pop(0)\n elif seq1[i]=='GYC':seq2+=GYC.pop(0)\n elif seq1[i]=='GRC':seq2+=GRC.pop(0)\n elif seq1[i]=='GYG':seq2+=GYG.pop(0)\n elif seq1[i]=='GRG':seq2+=GRG.pop(0)\n else:seq2+=seq1[i]\n\n seq=seq2\n seq1=[]\n\n CGTG,CGCG,GTG,GCG,GAG=[],[],[],[],[]\n\n seq1+=seq[:2]\n for num in xrange(2,len(seq)-2,1):\n if seq[num-2:num+2]=='CGCG' and num%3==2:\n CGCG+=seq[num],\n seq1+='CGYG',\n elif seq[num-2:num+2]=='CGTG' and num%3==2:\n CGTG+=seq[num],\n seq1+='CGYG',\n elif seq[num-1:num+2]=='GTG' and seq[num-2]!='C' and num%3==2:\n GTG+=seq[num],\n seq1+='GTG',\n elif seq[num-1:num+2]=='GCG' and seq[num-2]!='C' and num%3==2:\n GCG+=seq[num],\n seq1+='GCG',\n elif (seq[num-1:num+3]=='GAGA' or seq[num-1:num+3]=='GAGG')and num%3==0:\n GAG+=seq[num],\n seq1+='GAG',\n else:\n seq1+=seq[num],\n seq1+=seq[-2:]\n\n CGYG=[]\n change_num=min(len(CGTG),len(GCG))\n CGYG[:change_num],GCG[:change_num]=GCG[:change_num],CGTG[:change_num]\n CGTG_num=change_num\n\n CGYG+=CGCG\n change_num=min(len(CGYG),len(GAG))\n CGYG[:change_num],GAG[:change_num]=GAG[:change_num],CGYG[:change_num]\n CGYG+=CGTG[CGTG_num:]\n\n shuffle(CGYG),shuffle(GTG),shuffle(GCG),shuffle(GAG)\n\n seq2=''\n for i in xrange(len(seq1)):\n if seq1[i]=='CGYG':seq2+=CGYG.pop(0)\n elif seq1[i]=='GTG':seq2+=GTG.pop(0)\n elif seq1[i]=='GCG':seq2+=GCG.pop(0)\n elif seq1[i]=='GAG':seq2+=GAG.pop(0)\n else:seq2+=seq1[i]\n seq=seq2\n\n seq1=[]\n TMG,AMG,GMG,CMG=[],[],[],[]\n seq1+=seq[:2],\n for num in xrange(2,len(seq)-2,1):\n if (num%3==0 and(seq[num:num+3]=='CGA' or seq[num:num+3]=='CGG' or seq[num:num+3]=='AGA' or seq[num:num+3]=='AGG'))or(num%3==2 and (seq[num:num+2]=='CG' or seq[num:num+2]=='AG')and((seq[num-1]=='T'and seq[num-2]!='T')or seq[num-1]=='C'or seq[num-2:num]=='GG')):\n if seq[num-1]=='T':\n seq1+='TMG',\n TMG+=seq[num],\n elif seq[num-1]=='C':\n seq1+='CMG',\n CMG+=seq[num],\n elif seq[num-1]=='A':\n seq1+='AMG',\n AMG+=seq[num],\n elif seq[num-1]=='G':\n seq1+='GMG',\n GMG+=seq[num],\n else:\n seq1+=seq[num]\n else:\n seq1+=seq[num]\n seq1+=seq[-2:]\n shuffle(TMG),shuffle(GMG),shuffle(AMG),shuffle(CMG)\n seq2=''\n for i in xrange(len(seq1)):\n if seq1[i]=='TMG':seq2+=TMG.pop(0)\n elif seq1[i]=='AMG':seq2+=AMG.pop(0)\n elif seq1[i]=='GMG':seq2+=GMG.pop(0)\n elif seq1[i]=='CMG':seq2+=CMG.pop(0)\n else:seq2+=seq1[i]\n return seq2\n\ndef get_difference(seq1,seq2):\n assert len(seq1) == len(seq2)\n return sum(seq1 != seq2 for seq1, seq2 in zip(seq1,seq2))\n\ndef make_protein_record(nuc_record):\n \"\"\"Returns a new SeqRecord with the translated sequence (default table).\"\"\"\n return SeqRecord(seq = nuc_record.seq.translate(to_stop=True), \\\n id = \"trans_\" + nuc_record.id, \\\n description = \"translation of CDS, using default table\")\n\n\n# main script body that calls the above subroutines\n\n#Shuffle Script\n# -*- coding: cp1251 -*-\n\n#Input Data\nparser = argparse.ArgumentParser(description='CodonShuffle.')\nparser.add_argument('-i', nargs='?', help='Input Filename', required=True, dest=\"input_file_name\")\nparser.add_argument('-s', choices=['dn23', 'dn31', 'dn231', 'n3'], nargs='?', help='Type of shuffle', default=\"dn23\", dest=\"random_type\")\nparser.add_argument('-r', nargs='?', help='Number of replications (int)', default='1000', dest=\"reps\", type=int)\nparser.add_argument('-m', choices=['CAI', 'CPB', 'DN', 'ENC', 'VFOLD', 'UFOLD', 'all'], nargs='*', help='Control Features [select one, multiple, or all]', default='all', dest=\"modules\")\nparser.add_argument('-g', dest=\"graphics\", help='Generate Feature Plots', action=\"store_true\")\nparser.add_argument('--seed', type=int, nargs='?', dest='randomseed', help='Optional integer for random seed', const=99)\nargs = parser.parse_args()\n\nif args.randomseed is not None:\n seed(args.randomseed)\n\ntypes_of_rnd=args.random_type\n\ninfile=open(args.input_file_name,'r')\nnames_list=[]\ndata={}\nfor line in infile:\n if line[0]=='>':\n strain=line\n data[strain]=''\n names_list+=strain,\n else:\n for liter in line:\n if liter!='\\n' and liter!='-' and liter!='~':\n data[strain]+=liter\ninfile.close()\n\n\nout_names=[]\nfor strain in names_list:\n seq_name=''\n for liter in strain:\n if liter =='\\\\' or liter =='/' or liter ==' ' or liter =='-' or liter ==',' or liter=='|' or liter==':': # compatible file names\n seq_name+='_'\n else:\n seq_name+=liter\n inseq_file=open(seq_name[1:-1]+'.fas','w')\n inseq_file.write(strain+data[strain]+'\\n')\n inseq_file.close()\n# bat_enc='chips -seqall '+seq_name[1:-1]+'.fas -nosum -outfile '+seq_name[1:-1]+'.enc -auto\\n'\n# system(bat_enc)\n\n outfile=open(seq_name[1:-1]+'_'+args.random_type+'.fas','w') #Create the file with wild type in the first position\n outfile.write(strain+data[strain]+'\\n')\n outfile.close()\n\n\n outfile=open(seq_name[1:-1]+'_'+args.random_type+'.fas','a') #Append permuted sequence\n for i in xrange(args.reps):\n outseq=data[strain]\n if args.random_type =='gc3':\n outseq=gc3(outseq)\n elif args.random_type == 'dn23':\n outseq=dn23(outseq)\n elif args.random_type=='dn31':\n outseq=third(outseq)\n elif args.random_type=='dn231':\n outseq=third(exchange6deg(outseq))\n elif args.random_type=='n3':\n outseq=third_simple(outseq)\n outfile.write('>replicate_'+str(i+1)+'\\n'+outseq+'\\n')\n outfile.close()\n# bat_enc='chips -seqall '+seq_name[1:-1]+'_'+args.random_type+'.fas -nosum -outfile '+seq_name[1:-1]+'_'+args.random_type+'.enc -auto\\n'\n# system(bat_enc)\n\nfirst_tot_out_string=`args.reps`+'_replicas\\nstrain\\t\\tstrain_Nc\\t'\n#if 'gc3'in types_of_rnd:first_tot_out_string+='\\tmean_Nc_gc3\\tsd\\t'\nif 'n3'in types_of_rnd:first_tot_out_string+='\\tmean_Nc_n3\\tsd\\t'\nif 'all'in types_of_rnd:first_tot_out_string+='\\tmean_Nc_all\\tsd\\t'\nif 'dn23'in types_of_rnd:first_tot_out_string+='\\tmean_Nc_dn23\\tsd\\t'\nif 'dn31'in types_of_rnd:first_tot_out_string+='\\tmean_Nc_dn31\\tsd\\t'\nif 'dn231'in types_of_rnd:first_tot_out_string+='\\tmean_Nc_dn231\\tsd\\t'\n\n# tot_out=open(args.input_file_name[:-4]+'.out','w') #output file writing\n# tot_out.write(first_tot_out_string+'\\n')\n# for strain in names_list:\n# seq_name=''\n# for liter in strain:\n# if liter =='\\\\' or liter =='/' or liter ==' ' or liter =='-' or liter ==',' or liter=='|':\n# seq_name+='_'\n# else:\n# seq_name+=liter\n# enc_in=open(seq_name[1:-1]+'.enc','r')\n# inseq_enc=0.\n# for i in enc_in:\n# if strain[1:-1] in i:\n# inseq_enc=float(i.split(' Nc = ')[1])\n# enc_in.close()\n#\n# out_string=strain[1:-1]+'\\t\\t'+`inseq_enc`+'\\t\\t'\n# enc_in=open(seq_name[1:-1]+'_'+args.random_type+'.enc','r')\n# enc=[]\n# for i in enc_in:\n# enc+=float(i.split(' Nc = ')[1]),\n# enc_in.close()\n#\n# mean_enc=sum(enc)/len(enc)\n# dd=0\n# for i in enc:d=(i-mean_enc)**2;dd+=d\n# sd_enc=(dd/(len(enc)-1))**(0.5)\n# out_string+=`mean_enc`+'\\t'+`sd_enc`+'\\t\\t'\n# out_string+='\\n'\n# tot_out.write(out_string)\n# tot_out.close()\n\n#filename.input(first_tot_out_string+'\\n', inplace=1) #Add the wild type sequence in the variable\n\nfilename = seq_name[1:-1]+'_'+args.random_type+'.fas'\n\nfinal_table=pandas.DataFrame()\n\n#Calculate Sequence distance\nprint \"Calculating Hamming distance\"\nseq_records=[]\n\ninseq_file=open(filename,'rU')\noutnt_file=open(filename+'.hamming', 'w')\n\nfor seq_record in SeqIO.parse(inseq_file, \"fasta\"):\n seq_records.append(seq_record.seq)\n\nn = len(seq_records)\nleast_squares = pandas.DataFrame(numpy.zeros(n))\n\nmy_array = np.zeros((n,n))\nfor i in range(0,n):\n for j in range(i+1,n):\n difference = get_difference(seq_records[i], seq_records[j])\n outnt_file.write(str(difference)+'\\n')\n my_array[i, j] = difference\n my_array[j, i] = difference\n#nuc_dist = my_array.iloc[:,0]\noutnt_file.close()\n\nif args.graphics:\n hamming_graphname = filename+'.hamming.pdf'\n hamming_table = pandas.read_csv(filename+'.hamming', sep='\\t', names=['distance'])\n hamming_graph = ggplot(hamming_table, aes('distance'))+geom_density() +labs(\"Hamming distance\",\"Frequency\")+ggtitle(seq_name[1:-1]+'_'+args.random_type+' (Hamming)') #Get the name of the script\n #ggsave(hamming_graph, hamming_graphname)\n hamming_graph.save(hamming_graphname)\n\n\nif 'CAI' in args.modules or 'all' in args.modules:\n #Run CAI and read result table\n print \"Calculating CAI\"\n cainame = seq_name[1:-1]+'_'+args.random_type+'.cai'\n call([\"./lib/EMBOSS-6.6.0/emboss/cai\", \"-seqall=\"+filename, \"-outfile=\"+cainame, \"-cfile=EChick.cut\"]) #Insert path before cai in this line (CAI)\n u_cols = ['a', 'sequence', 'b', 'cai']\n cai_table = pandas.read_csv(cainame, sep=' ', names=u_cols)\n cai_table = cai_table.drop('a', 1)\n cai_table = cai_table.drop('b', 1)\n cai_table_z = ((cai_table['cai'] - cai_table['cai'].mean()) / cai_table['cai'].std())\n cai_table_wt_z = cai_table_z.iloc[0]\n cai_table_wt_z_rep = np.repeat(cai_table_wt_z, len(cai_table_z))\n cai_table_z_ls = (cai_table_wt_z_rep-cai_table_z)**2\n\n least_squares = least_squares.add(cai_table_z_ls, axis=0)\n# final_table=final_table.append(cai_table['cai'])\n final_table.insert(0, \"Cai\", cai_table['cai'])\n\n\n if args.graphics:\n cai_graphname = cainame +'.pdf'\n u_cols = ['a', 'sequence', 'b', 'cai']\n cai_table = pandas.read_csv(cainame, sep=' ', names=u_cols)\n cai_table = cai_table.drop('a', 1)\n cai_table = cai_table.drop('b', 1)\n\n cai_graph = ggplot(cai_table, aes('cai'))+geom_density() +labs(\"CAI\",\"Frequency\")+ geom_vline(xintercept = [cai_table['cai'].iloc[0]] , colour=\"red\", linetype = \"dashed\") +ggtitle(seq_name[1:-1]+'_'+args.random_type+' (CAI)') #Get the name of the script\n #ggsave(cai_graph, cai_graphname)\n cai_graph.save(cai_graphname)\n\n\n\n\nif 'ENC' in args.modules or 'all' in args.modules:\n # Run ENC and result table\n print \"Calculating ENC\"\n call([\"./lib/codonW/codonw\", filename, \"-enc\", \"-nomenu\", \"-nowarn\", \"-silent\"]) #Insert path before codonw in this line (ENC)\n enc_filename = seq_name[1:-1]+'_'+args.random_type+'.out'\n enc_table = pandas.read_csv(enc_filename, sep='\\t')\n enc_table = enc_table.drop('Unnamed: 2',1)\n enc_table_z = ((enc_table['Nc'] - enc_table['Nc'].mean()) / enc_table['Nc'].std())\n enc_table_wt_z = enc_table_z.iloc[0]\n enc_table_wt_z_rep = np.repeat(enc_table_wt_z, len(enc_table_z))\n enc_table_z_ls = (enc_table_wt_z_rep-enc_table_z)**2\n\n least_squares = least_squares.add(enc_table_z_ls, axis=0)\n# final_table=final_table.append(enc_table['Nc'])\n final_table.insert(0, \"ENC\", enc_table['Nc'])\n\n if args.graphics:\n enc_filename = seq_name[1:-1]+'_'+args.random_type+'.out'\n enc_graphname = enc_filename+'.enc.pdf'\n enc_table = pandas.read_csv(enc_filename, sep='\\t')\n enc_table = enc_table.drop('Unnamed: 2',1)\n enc_graph = ggplot(enc_table, aes('Nc'))+geom_density() +labs(\"ENC\",\"Frequency\")+ geom_vline(xintercept = [enc_table['Nc'].iloc[0]] , colour=\"red\", linetype = \"dashed\") +ggtitle(seq_name[1:-1]+'_'+args.random_type+' (ENC)') #Get the name of the script\n #ggsave(enc_graph, enc_graphname)\n enc_graph.save(enc_graphname)\n\nif 'VFOLD' in args.modules or 'all' in args.modules:\n#Read FOLD (minimum free energy) table\n print \"Calculating VFOLD\"\n foldname = seq_name[1:-1]+'_'+args.random_type+'.fold'\n mfename = seq_name[1:-1]+'_'+args.random_type+'.mfe'\n i = open(filename, \"r\")\n o = open(foldname, \"w\")\n call([\"./lib/ViennaRNA-2.1.9/Progs/RNAfold\", \"--noPS\"], stdin=i, stdout=o) #Insert path before RNAfold in this line (MFOLD)\n i.close\n o.close\n# os.system(\"cat Poliovirus_1_Mahoney_P1_dn23.fold | sed 'N;N;s/\\\\n/ /g' | cut -f 4 -d ' ' | tr -d '()' > \" + mfename)\n\n # handle small energies by removing whitespace\n with open(foldname, 'r') as sources:\n lines = sources.readlines()\n with open(foldname, 'w') as sources:\n for line in lines:\n sources.write(re.sub('[(] +-', '(-', line))\n\n fold_tb = open(foldname, \"r\").read().split()\n fold_file=open(filename+'fold_table_mfe.txt', 'w')\n for i in range(3, len(fold_tb)-3, 4):\n fold_mfe = fold_tb[3]+'\\n'+fold_tb[i+4]\n fold_file.write(str(fold_mfe)+'\\n')\n fold_file.close()\n\n fold_table = pandas.read_csv(filename+'fold_table_mfe.txt', names=['mfe'])\n fold_table['mfe'] = fold_table['mfe'].map(lambda x: x.lstrip('(').rstrip(')'))\n fold_table['mfe']=fold_table.apply(lambda row: float(row['mfe']), axis=1)\n fold_table_z = ((fold_table['mfe'] - fold_table['mfe'].mean()) / fold_table['mfe'].std())\n fold_table_wt_z = fold_table_z.iloc[0]\n fold_table_wt_z_rep = np.repeat(fold_table_wt_z, len(fold_table_z))\n fold_table_z_ls = (fold_table_wt_z_rep-fold_table_z)**2\n\n least_squares = least_squares.add(fold_table_z_ls, axis=0)\n# final_table=final_table.append(fold_table['mfe'])\n final_table.insert(0, \"VFOLD (mfe)\", fold_table['mfe'])\n\n if args.graphics:\n fold_graphname = seq_name[1:-1]+'_'+args.random_type+'.fold.pdf'\n# fold_table = pandas.read_csv(mfename, names=['mfe'])\n fold_graph = ggplot(fold_table, aes('mfe'))+geom_density() +labs(\"MFE\",\"Frequency\")+ geom_vline(xintercept = [fold_table['mfe'].iloc[0]] , colour=\"red\", linetype = \"dashed\") +ggtitle(seq_name[1:-1]+'_'+args.random_type+' (FOLD)') #Get the name of the script\n #ggsave(fold_graph, fold_graphname)\n fold_graph.save(fold_graphname)\n\nif 'UFOLD' in args.modules:\n#Read FOLD (minimum free energy) table\n print \"Calculating UFOLD\"\n foldname = seq_name[1:-1]+'_'+args.random_type+'.fold'\n mfename = seq_name[1:-1]+'_'+args.random_type+'.fasta.dG'\n i = open(filename, \"r\")\n o = open(foldname, \"w\")\n call([\"hybrid-ss\", \"-E\", \"--output=\"+mfename, filename]) #Insert path before hybrid-ss in this line (UNAFOLD)\n i.close\n o.close\n# os.system(\"cat Poliovirus_1_Mahoney_P1_dn23.fold | sed 'N;N;s/\\\\n/ /g' | cut -f 4 -d ' ' | tr -d '()' > \" + mfename)\n\n ufold_table = pandas.read_csv(mfename, sep='\t')\n ufold_table_z = ((fold_table['-RT ln Z'] - fold_table['-RT ln Z'].mean()) / fold_table['-RT ln Z'].std())\n ufold_table_wt_z = ufold_table_z.iloc[0]\n ufold_table_wt_z_rep = np.repeat(ufold_table_wt_z, len(ufold_table_z))\n ufold_table_z_ls = (fold_table_wt_z_rep-fold_table_z)**2\n\n least_squares = least_squares.add(fold_table_z_ls, axis=0)\n# final_table=final_table.append(ufold_table['-RT ln Z'])\n final_table.insert(0, \"UFOLD (mfe)\", ufold_table['-RT ln Z'])\n\n if args.graphics:\n fold_graphname = seq_name[1:-1]+'_'+args.random_type+'.fold.pdf'\n fold_table = pandas.read_csv(mfename, mfename, sep='\t')\n fold_graph = ggplot(fold_table, aes('-RT ln Z'))+geom_density() +labs(\"MFE\",\"Frequency\")+ geom_vline(xintercept = [fold_table['-RT ln Z'].iloc[0]] , colour=\"red\", linetype = \"dashed\") +ggtitle(seq_name[1:-1]+'_'+args.random_type+' (FOLD)') #Get the name of the script\n #ggsave(fold_graph, fold_graphname)\n fold_graph.save(fold_graphname)\n\nif 'DN' in args.modules or 'all' in args.modules:\n print \"Calculating DN\"\n dnname = seq_name[1:-1]+'_'+args.random_type+'.dn'\n dn_file=open(dnname, 'w')\n\n dn_file.write(\"id\");\n for nt1 in nts:\n for nt2 in nts:\n dinut = nt1+nt2\n dn_file.write(\"\\t\"+dinut)\n dn_file.write(\"\\n\")\n\n for nuc_rec in SeqIO.parse(filename, \"fasta\"):\n nucs = [str(nuc_rec.seq[i:i+1]) for i in range(0,len(nuc_rec.seq),1)]\n dinucs = [str(nuc_rec.seq[i:i+2]) for i in range(0,len(nuc_rec.seq)-1,1)]\n\n nuc_counts = Counter(nucs)\n dinuc_counts = Counter(dinucs)\n seq_len = len(nuc_rec.seq)\n\n dn_file.write(nuc_rec.id)\n for nt1 in nts:\n for nt2 in nts:\n dinut = nt1+nt2\n if (dinut in dinuc_counts):\n freq = (dinuc_counts[dinut] / (seq_len - 1)) / ( (nuc_counts[nt1] / seq_len) * (nuc_counts[nt2] / seq_len))\n #print(nt1 + \" \" + nt2 + \" \" + str(freq) + \" \" + str(dinuc_counts[dinut]) + \" \" + str(nuc_counts[nt1]) + \" \" + str(nuc_counts[nt2]) + \"\\n\")\n dn_file.write(\"\\t\"+str(freq))\n else:\n dn_file.write(\"\\t0\")\n dn_file.write(\"\\n\")\n dn_file.close()\n\n dnlsname = seq_name[1:- 1]+'_'+args.random_type+'.dnls'\n# dn_least_file=open(dnlsname, 'w')\n dn_table = pandas.read_csv(dnname, sep='\t')\n dn_table_AA_wt = dn_table.iloc[0,1]\n dn_table_AA_wt_rep = np.repeat(dn_table_AA_wt, len(dn_table['AA']))\n dn_table_AC_wt = dn_table.iloc[0,2]\n dn_table_AC_wt_rep = np.repeat(dn_table_AC_wt, len(dn_table['AC']))\n dn_table_AG_wt = dn_table.iloc[0,3]\n dn_table_AG_wt_rep = np.repeat(dn_table_AG_wt, len(dn_table['AG']))\n dn_table_AT_wt = dn_table.iloc[0,4]\n dn_table_AT_wt_rep = np.repeat(dn_table_AT_wt, len(dn_table['AT']))\n dn_table_CA_wt = dn_table.iloc[0,5]\n dn_table_CA_wt_rep = np.repeat(dn_table_CA_wt, len(dn_table['CA']))\n dn_table_CC_wt = dn_table.iloc[0,6]\n dn_table_CC_wt_rep = np.repeat(dn_table_CC_wt, len(dn_table['CC']))\n dn_table_CG_wt = dn_table.iloc[0,7]\n dn_table_CG_wt_rep = np.repeat(dn_table_CG_wt, len(dn_table['CG']))\n dn_table_CT_wt = dn_table.iloc[0,8]\n dn_table_CT_wt_rep = np.repeat(dn_table_CT_wt, len(dn_table['CT']))\n dn_table_GA_wt = dn_table.iloc[0,9]\n dn_table_GA_wt_rep = np.repeat(dn_table_GA_wt, len(dn_table['GA']))\n dn_table_GC_wt = dn_table.iloc[0,10]\n dn_table_GC_wt_rep = np.repeat(dn_table_GC_wt, len(dn_table['GC']))\n dn_table_GG_wt = dn_table.iloc[0,11]\n dn_table_GG_wt_rep = np.repeat(dn_table_GG_wt, len(dn_table['GG']))\n dn_table_GT_wt = dn_table.iloc[0,12]\n dn_table_GT_wt_rep = np.repeat(dn_table_GT_wt, len(dn_table['GT']))\n dn_table_TA_wt = dn_table.iloc[0,13]\n dn_table_TA_wt_rep = np.repeat(dn_table_TA_wt, len(dn_table['TA']))\n dn_table_TC_wt = dn_table.iloc[0,14]\n dn_table_TC_wt_rep = np.repeat(dn_table_TC_wt, len(dn_table['TC']))\n dn_table_TG_wt = dn_table.iloc[0,15]\n dn_table_TG_wt_rep = np.repeat(dn_table_TG_wt, len(dn_table['TG']))\n dn_table_TT_wt = dn_table.iloc[0,16]\n dn_table_TT_wt_rep = np.repeat(dn_table_TT_wt, len(dn_table['TT']))\n\n dn_table_least = np.sqrt((dn_table_AA_wt_rep-dn_table['AA'])**2+(dn_table_AC_wt_rep-dn_table['AC'])**2+(dn_table_AG_wt_rep-dn_table['AG'])**2+(dn_table_AT_wt_rep-dn_table['AT'])**2+(dn_table_CA_wt_rep-dn_table['CA'])**2+(dn_table_CC_wt_rep-dn_table['CC'])**2+(dn_table_CG_wt_rep-dn_table['CG'])**2+(dn_table_CT_wt_rep-dn_table['CT'])**2+(dn_table_GA_wt_rep-dn_table['GA'])**2+(dn_table_GC_wt_rep-dn_table['GC'])**2+(dn_table_GG_wt_rep-dn_table['GG'])**2+(dn_table_GT_wt_rep-dn_table['GT'])**2+(dn_table_TA_wt_rep-dn_table['TA'])**2+(dn_table_TC_wt_rep-dn_table['TC'])**2+(dn_table_TG_wt_rep-dn_table['TG'])**2+(dn_table_TT_wt_rep-dn_table['TT'])**2)\n dn_table_least.to_csv(dnlsname, sep=\"\\t\")\n# dn_least_file.write(dn_table_least)\n# dn_least_file.close()\n dn_table_least_z = ((dn_table_least - dn_table_least.mean()) / dn_table_least.std())\n dn_table_least_z_wt = dn_table_least_z.iloc[0]\n dn_table_least_z_wt_rep = np.repeat(dn_table_least_z_wt, len(dn_table_least_z))\n dn_table_least_z_ls = (dn_table_least_z_wt_rep-dn_table_least_z)**2\n\n\n least_squares = least_squares.add(dn_table_least_z_ls, axis=0)\n u_cols = ['Replication', 'DN_least_square']\n dn_table_ls = pandas.read_csv(dnlsname, sep='\t', names=u_cols)\n# final_table=final_table.append(dn_table_ls['DN_least_square'])\n final_table.insert(0, \"DN_least_square\", dn_table_ls['DN_least_square'])\n final_table.insert(1, \"DN (TT)\", dn_table['TT'])\n final_table.insert(1, \"DN (TG)\", dn_table['TG'])\n final_table.insert(1, \"DN (TC)\", dn_table['TC'])\n final_table.insert(1, \"DN (TA)\", dn_table['TA'])\n final_table.insert(1, \"DN (GT)\", dn_table['GT'])\n final_table.insert(1, \"DN (GG)\", dn_table['GG'])\n final_table.insert(1, \"DN (GC)\", dn_table['GC'])\n final_table.insert(1, \"DN (GA)\", dn_table['GA'])\n final_table.insert(1, \"DN (CT)\", dn_table['CT'])\n final_table.insert(1, \"DN (CG)\", dn_table['CG'])\n final_table.insert(1, \"DN (CC)\", dn_table['CC'])\n final_table.insert(1, \"DN (CA)\", dn_table['CA'])\n final_table.insert(1, \"DN (AT)\", dn_table['AT'])\n final_table.insert(1, \"DN (AG)\", dn_table['AG'])\n final_table.insert(1, \"DN (AC)\", dn_table['AC'])\n final_table.insert(1, \"DN (AA)\", dn_table['AA'])\n\n if args.graphics:\n dnls_graphname = dnlsname + '.pdf'\n\n #--bug in python ggplot for this, use rpy2 instead--\n dn_table_least = pandas.read_csv(dnlsname, sep='\t', names=['Rep', 'DN'])\n dn_graph = ggplot(dn_table_least,aes('DN')) + geom_density() + xlab(\"Dinucleotide\") + ylab('Dinucleotide Least Squares')+ geom_vline(xintercept = [dn_table_least['DN'].iloc[0]] , colour=\"red\", linetype = \"dashed\") +ggtitle(seq_name[1:-1]+'_'+args.random_type+' (DN)')\n #ggsave(dn_graph, dnls_graphname)\n dn_graph.save(dnls_graphname)\n\n dn_table = pandas.read_csv(dnname, sep=\"\t\")\n fig, ax = plt.subplots()\n dn_table.boxplot(return_type='axes')\n ax.set_title(seq_name[1:- 1]+'_'+args.random_type+' (Dinucleotide Frequency)')\n ax.set_xlabel('Dinucleotide')\n ax.set_ylabel('Dinuc obser/Dinuc expec')\n fig.savefig(seq_name[1:-1]+'_'+args.random_type+'_dn.pdf')\n plt.close(fig)\n\n# r = robjects.r\n# r.library(\"ggplot2\")\n# r.library(\"reshape2\")\n# robjects.r('dn_table=read.csv(\"Poliovirus_1_Mahoney_P1_dn23.dn\", sep=\"\\t\", header=T)')\n# r.pdf(dn_graphname)\n# robjects.r('p<-ggplot(melt(dn_table, \"id\"), aes(variable, value)) + geom_boxplot() + xlab(\"dinucleotide\") + ylab(\"dinucleotide weight\")')\n# robjects.r('print(p)')\n# robjects.r['dev.off']()\n\nif 'CPB' in args.modules or 'all' in args.modules:\n #CPB, from Coleman et al 2008, pmid: 18583614\n\n #DNA to protein to CPB analysis\n #proteins = list((make_protein_record(nuc_rec) for nuc_rec in \\\n # SeqIO.parse(filename, \"fasta\")))\n #SeqIO.write(proteins, filename+\"_prot\", \"fasta\")\n\n print \"Calculating CPB\"\n cpbname = seq_name[1:-1]+'_'+args.random_type+'.cpb'\n cpb_file=open(cpbname,'w')\n\n #Human CPS from Coleman et al 2008, pmid: 18583614\n #cps_human = pandas.read_csv(\"Coleman_CPS.csv\", sep=';')\n cps_gallus = pandas.read_csv(\"CPSmmc4gallus.csv\", sep=',')\n #Delete column\n #cps_human = cps_human.drop('Aapair', 1)\n #cps_human = cps_human.drop('Expected', 1)\n #cps_human = cps_human.drop('Observed', 1)\n #cps_human = cps_human.drop('Observed/Expected', 1)\n cps_gallus = cps_gallus.sort_values(['CodonPair'], ascending=True)\n\n\n for nuc_rec in SeqIO.parse(filename, \"fasta\"):\n prot_rec = make_protein_record(nuc_rec)\n codons = [str(nuc_rec.seq[i:i+3]) for i in range(0,len(nuc_rec.seq)-3,3)]\n dicodons = [str(nuc_rec.seq[i:i+6]) for i in range(0,len(nuc_rec.seq)-3,3)]\n aas = [str(prot_rec.seq[i:i+1]) for i in range(0,len(prot_rec.seq),1)]\n diaas = [str(prot_rec.seq[i:i+2]) for i in range(0,len(prot_rec.seq)-1,1)]\n\n codon_counts = Counter(codons)\n dicodon_counts = Counter(dicodons)\n aa_counts = Counter(aas)\n diaa_counts = Counter(diaas)\n\n cps = []\n for cp in dicodons:\n cod1 = cp[:3]\n cod2 = cp[3:]\n if cod1 in ['TAG', 'TGA', 'TAA'] or cod2 in ['TAG', 'TGA', 'TAA']:\n continue #skip stop codons\n aa1 = tt[cod1].split('|')[0]\n aa2 = tt[cod2].split('|')[0]\n ap = aa1+aa2\n #score = np.log(dicodons.count(cp) / ( ((codons.count(cod1) * codons.count(cod2)) / (aas.count(aa1) * aas.count(aa2))) * diaas.count(ap)))\n #score = np.log(dicodon_counts[cp] / ( ((codon_counts[cod1] * codon_counts[cod2]) / (aa_counts[aa1] * aa_counts[aa2])) * diaa_counts[ap]))\n numerator_cps = dicodon_counts[cp]\n denominator_cps = ((codon_counts[cod1] * codon_counts[cod2]) / (aa_counts[aa1] * aa_counts[aa2])) * diaa_counts[ap]\n with np.errstate(divide='ignore', invalid='ignore'):\n div_cps = np.true_divide(numerator_cps,denominator_cps)\n score = np.log(div_cps)\n cps.append(score)\n dicodon_df = pandas.DataFrame.from_dict(dicodon_counts, orient='index').reset_index()\n dicodon_df = dicodon_df.sort_values(['index'], ascending=True)\n dicodon_df.columns = ['CodonPair', 'Obs']\n cps_tb_final = pandas.merge(cps_gallus, dicodon_df, on='CodonPair', how='inner')\n cps_tb_final['CPS'] = cps_tb_final['CPS'].replace({',','.'}, regex=True)\n cps_tb_final['CPS'] = cps_tb_final['CPS'].astype(float)\n cps_tb_final['result'] = cps_tb_final.CPS * cps_tb_final.Obs\n cpb = sum(cps_tb_final['result'])/sum(cps_tb_final['Obs'])\n print str(cpb)\n cpb_file.write(str(cpb)+\"\\n\")\n cpb_file.close()\n\n u_cols = ['cpb']\n cpb_table = pandas.read_csv(cpbname, sep=' ', names=u_cols)\n cpb_table_z = ((cpb_table['cpb'] - cpb_table['cpb'].mean()) / cpb_table['cpb'].std())\n cpb_table_wt_z = cpb_table_z.iloc[0]\n cpb_table_wt_z_rep = np.repeat(cpb_table_wt_z, len(cpb_table_z))\n cpb_table_z_ls = (cpb_table_wt_z_rep-cpb_table_z)**2\n\n least_squares = least_squares.add(cpb_table_z_ls, axis=0)\n# final_table=final_table.append(cpb_table['cpb'])\n final_table.insert(0, \"CPB\", cpb_table['cpb'])\n\n if args.graphics:\n cpb_graphname = cpbname +'.pdf'\n u_cols = ['cpb']\n cpb_table = pandas.read_csv(cpbname, sep=' ', names=u_cols)\n cpb_graph = ggplot(cpb_table, aes('cpb'))+geom_density() +labs(\"CPB\",\"Frequency\")+ geom_vline(xintercept = [cpb_table['cpb'].iloc[0]] , colour=\"red\", linetype = \"dashed\") +ggtitle(seq_name[1:-1]+'_'+args.random_type+' (CPB)') #Get the name of the script\n #ggsave(cpb_graph, cpb_graphname)\n cpb_graph.save(cpb_graphname)\n\n#Calculation least square\n\nprint \"Calculating Least Squares\"\nleast_squares = np.sqrt(least_squares)\nleast_squares.columns = ['distance']\n\nleast_table_name = seq_name[1:-1]+'_'+args.random_type+'_least_square.txt'\nleast_squares.to_csv(least_table_name, sep=\"\\t\")\n#final_table=final_table.append(least_squares['distance'])\nfinal_table.insert(0, \"Distance(ls)\", least_squares['distance'])\n#least_table_file=open(least_table_name,'w')\n#least_table_file.write(least_squares)\n#least_table_file.close()\n#least_table = sqrt()\n\n\n# Create final graph and table\n\nprint \"Making final table\"\nnuc_distance_name=filename+'_distance_table.txt'\nnuc_distance_file=open(nuc_distance_name,'w')\nnuc_distance_table = np.zeros((n,n))\nfor j in range(1,n):\n difference = get_difference(seq_records[0], seq_records[j])\n nuc_distance_file.write(str(difference)+'\\n')\n my_array[0, j] = difference\nnuc_distance_file.close()\n\ncol_name = ['Nucleotide_difference']\nnew_nuc_distance_table = pandas.read_csv(nuc_distance_name, sep=' ', names=col_name)\n\n\n\nnew_nuc_distance_table.loc[-1]=[0]\nnew_nuc_distance_table.index = new_nuc_distance_table.index + 1\nnew_nuc_distance_table = new_nuc_distance_table.sort_index()\nnew_table=pandas.DataFrame()\nnew_table.insert(0, \"Distance\", least_squares['distance'])\nnew_table.insert(1, \"Nucleotide_difference\", new_nuc_distance_table['Nucleotide_difference'])\n\nnew_table_name = seq_name[1:-1]+'_'+args.random_type+'new_table_final_graph.txt'\nnew_table.to_csv(new_table_name, sep=\"\\t\")\n\n#final_table=final_table.append(new_nuc_distance_table['Nucleotide_difference'])\nfinal_table.insert(1, \"Nucleotide_difference\", new_nuc_distance_table['Nucleotide_difference'])\n\nfinal_tb_name = seq_name[1:-1]+'_'+args.random_type+'_final_table.txt'\nfinal_table.to_csv(final_tb_name, sep='\\t')\n\nif args.graphics:\n final_graphname = filename +'final_graph.pdf'\n final_graph = ggplot(new_table, aes('Distance', 'Nucleotide_difference'))+geom_point()+labs(\"Least Square Distance\",\"Hamming Distance (nt)\")+ggtitle(seq_name[1:-1]+'_'+args.random_type)\n #ggsave(final_graph, final_graphname)\n final_graph.save(final_graphname)\n", "meta": {"hexsha": "e03915a3c23a9caae810cb471854317e2f3ec252", "size": 85962, "ext": "py", "lang": "Python", "max_stars_repo_path": "CodonShuffle.py", "max_stars_repo_name": "alegione/CodonShuffle", "max_stars_repo_head_hexsha": "bd6674b2eb21ee144a39d6d1e9b7264aba887240", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CodonShuffle.py", "max_issues_repo_name": "alegione/CodonShuffle", "max_issues_repo_head_hexsha": "bd6674b2eb21ee144a39d6d1e9b7264aba887240", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CodonShuffle.py", "max_forks_repo_name": "alegione/CodonShuffle", "max_forks_repo_head_hexsha": "bd6674b2eb21ee144a39d6d1e9b7264aba887240", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.3041338583, "max_line_length": 907, "alphanum_fraction": 0.5360624462, "include": true, "reason": "import numpy,import scipy,import statsmodels", "num_tokens": 26667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.23651623644570763, "lm_q1q2_score": 0.11918199097530707}} {"text": "#!/usr/bin/env python3\n\"\"\" Aligner for faceswap.py \"\"\"\n\n#import logging\nfrom threading import Lock\n\nimport cv2\nimport numpy as np\n\n#logger = logging.get#logger(__name__) # pylint: disable=invalid-name\n\n\n_MEAN_FACE = np.array([[0.010086, 0.106454], [0.085135, 0.038915], [0.191003, 0.018748],\n [0.300643, 0.034489], [0.403270, 0.077391], [0.596729, 0.077391],\n [0.699356, 0.034489], [0.808997, 0.018748], [0.914864, 0.038915],\n [0.989913, 0.106454], [0.500000, 0.203352], [0.500000, 0.307009],\n [0.500000, 0.409805], [0.500000, 0.515625], [0.376753, 0.587326],\n [0.435909, 0.609345], [0.500000, 0.628106], [0.564090, 0.609345],\n [0.623246, 0.587326], [0.131610, 0.216423], [0.196995, 0.178758],\n [0.275698, 0.179852], [0.344479, 0.231733], [0.270791, 0.245099],\n [0.192616, 0.244077], [0.655520, 0.231733], [0.724301, 0.179852],\n [0.803005, 0.178758], [0.868389, 0.216423], [0.807383, 0.244077],\n [0.729208, 0.245099], [0.264022, 0.780233], [0.350858, 0.745405],\n [0.438731, 0.727388], [0.500000, 0.742578], [0.561268, 0.727388],\n [0.649141, 0.745405], [0.735977, 0.780233], [0.652032, 0.864805],\n [0.566594, 0.902192], [0.500000, 0.909281], [0.433405, 0.902192],\n [0.347967, 0.864805], [0.300252, 0.784792], [0.437969, 0.778746],\n [0.500000, 0.785343], [0.562030, 0.778746], [0.699747, 0.784792],\n [0.563237, 0.824182], [0.500000, 0.831803], [0.436763, 0.824182]])\n\n_MEAN_FACE_3D = np.array([[4.056931, -11.432347, 1.636229], # 8 chin LL\n [1.833492, -12.542305, 4.061275], # 7 chin L\n [0.0, -12.901019, 4.070434], # 6 chin C\n [-1.833492, -12.542305, 4.061275], # 5 chin R\n [-4.056931, -11.432347, 1.636229], # 4 chin RR\n [6.825897, 1.275284, 4.402142], # 33 L eyebrow L\n [1.330353, 1.636816, 6.903745], # 29 L eyebrow R\n [-1.330353, 1.636816, 6.903745], # 34 R eyebrow L\n [-6.825897, 1.275284, 4.402142], # 38 R eyebrow R\n [1.930245, -5.060977, 5.914376], # 54 nose LL\n [0.746313, -5.136947, 6.263227], # 53 nose L\n [0.0, -5.485328, 6.76343], # 52 nose C\n [-0.746313, -5.136947, 6.263227], # 51 nose R\n [-1.930245, -5.060977, 5.914376], # 50 nose RR\n [5.311432, 0.0, 3.987654], # 13 L eye L\n [1.78993, -0.091703, 4.413414], # 17 L eye R\n [-1.78993, -0.091703, 4.413414], # 25 R eye L\n [-5.311432, 0.0, 3.987654], # 21 R eye R\n [2.774015, -7.566103, 5.048531], # 43 mouth L\n [0.509714, -7.056507, 6.566167], # 42 mouth top L\n [0.0, -7.131772, 6.704956], # 41 mouth top C\n [-0.509714, -7.056507, 6.566167], # 40 mouth top R\n [-2.774015, -7.566103, 5.048531], # 39 mouth R\n [-0.589441, -8.443925, 6.109526], # 46 mouth bottom R\n [0.0, -8.601736, 6.097667], # 45 mouth bottom C\n [0.589441, -8.443925, 6.109526]]) # 44 mouth bottom L\n\n_EXTRACT_RATIOS = dict(legacy=0.375, face=0.5, head=0.625)\n\n\ndef get_matrix_scaling(matrix):\n \"\"\" Given a matrix, return the cv2 Interpolation method and inverse interpolation method for\n applying the matrix on an image.\n\n Parameters\n ----------\n matrix: :class:`numpy.ndarray`\n The transform matrix to return the interpolator for\n\n Returns\n -------\n tuple\n The interpolator and inverse interpolator for the given matrix. This will be (Cubic, Area)\n for an upscale matrix and (Area, Cubic) for a downscale matrix\n \"\"\"\n x_scale = np.sqrt(matrix[0, 0] * matrix[0, 0] + matrix[0, 1] * matrix[0, 1])\n y_scale = (matrix[0, 0] * matrix[1, 1] - matrix[0, 1] * matrix[1, 0]) / x_scale\n avg_scale = (x_scale + y_scale) * 0.5\n if avg_scale >= 1.:\n interpolators = cv2.INTER_CUBIC, cv2.INTER_AREA\n else:\n interpolators = cv2.INTER_AREA, cv2.INTER_CUBIC\n #logger.trace(\"interpolator: %s, inverse interpolator: %s\", interpolators[0], interpolators[1])\n return interpolators\n\n\ndef transform_image(image, matrix, size, padding=0):\n \"\"\" Perform transformation on an image, applying the given size and padding to the matrix.\n\n Parameters\n ----------\n image: :class:`numpy.ndarray`\n The image to transform\n matrix: :class:`numpy.ndarray`\n The transformation matrix to apply to the image\n size: int\n The final size of the transformed image\n padding: int, optional\n The amount of padding to apply to the final image. Default: `0`\n\n Returns\n -------\n :class:`numpy.ndarray`\n The transformed image\n \"\"\"\n '''logger.trace(\"image shape: %s, matrix: %s, size: %s. padding: %s\",\n image.shape, matrix, size, padding)'''\n # transform the matrix for size and padding\n mat = matrix * (size - 2 * padding)\n mat[:, 2] += padding\n\n # transform image\n interpolators = get_matrix_scaling(mat)\n retval = cv2.warpAffine(image, mat, (size, size), flags=interpolators[0])\n #logger.trace(\"transformed matrix: %s, final image shape: %s\", mat, image.shape)\n return retval\n\n\nclass AlignedFace():\n \"\"\" Class to align a face.\n\n Holds the aligned landmarks and face image, as well as associated matrices and information\n about an aligned face.\n\n Parameters\n ----------\n landmarks: :class:`numpy.ndarray`\n The original 68 point landmarks that pertain to the given image for this face\n image: :class:`numpy.ndarray`, optional\n The original frame that contains the face that is to be aligned. Pass `None` if the aligned\n face is not to be generated, and just the co-ordinates should be calculated.\n centering: [\"legacy\", \"face\", \"head\"], optional\n The type of extracted face that should be loaded. \"legacy\" places the nose in the center of\n the image (the original method for aligning). \"face\" aligns for the nose to be in the\n center of the face (top to bottom) but the center of the skull for left to right. \"head\"\n aligns for the center of the skull (in 3D space) being the center of the extracted image,\n with the crop holding the full head. Default: `\"face\"`\n size: int, optional\n The size in pixels, of each edge of the final aligned face. Default: `64`\n coverage_ratio: float, optional\n The amount of the aligned image to return. A ratio of 1.0 will return the full contents of\n the aligned image. A ratio of 0.5 will return an image of the given size, but will crop to\n the central 50%% of the image.\n dtype: str, optional\n Set a data type for the final face to be returned as. Passing ``None`` will return a face\n with the same data type as the original :attr:`image`. Default: ``None``\n is_aligned_face: bool, optional\n Indicates that the :attr:`image` is an aligned face rather than a frame.\n Default: ``False``\n \"\"\"\n def __init__(self, landmarks, image=None, centering=\"face\", size=64, coverage_ratio=1.0,\n dtype=None, is_aligned=False):\n '''logger.trace(\"Initializing: %s (image shape: %s, centering: '%s', size: %s, \"\n \"coverage_ratio: %s, dtype: %s, is_aligned: %s)\", self.__class__.__name__,\n image if image is None else image.shape, centering, size, coverage_ratio,\n dtype, is_aligned)'''\n self._frame_landmarks = landmarks\n self._centering = centering\n self._size = size\n self._dtype = dtype\n self._is_aligned = is_aligned\n self._matrices = dict(legacy=_umeyama(landmarks[17:], _MEAN_FACE, True)[0:2],\n face=None,\n head=None)\n self._padding = self._padding_from_coverage(size, coverage_ratio)\n\n self._cache = self._set_cache()\n\n self._face = self._extract_face(image)\n '''logger.trace(\"Initialized: %s (matrix: %s, padding: %s, face shape: %s)\",\n self.__class__.__name__, self._matrices[\"legacy\"], self._padding,\n self._face if self._face is None else self._face.shape)'''\n\n @property\n def size(self):\n \"\"\" int: The size (in pixels) of one side of the square extracted face image. \"\"\"\n return self._size\n\n @property\n def padding(self):\n \"\"\" int: The amount of padding (in pixels) that is applied to each side of the\n extracted face image for the selected extract type. \"\"\"\n return self._padding[self._centering]\n\n @property\n def matrix(self):\n \"\"\" :class:`numpy.ndarray`: The 3x2 transformation matrix for extracting and aligning the\n core face area out of the original frame, with no padding or sizing applied. The returned\n matrix is offset for the given :attr:`centering`. \"\"\"\n if self._matrices[self._centering] is None:\n matrix = self._matrices[\"legacy\"].copy()\n matrix[:, 2] -= self.pose.offset[self._centering]\n self._matrices[self._centering] = matrix\n #logger.trace(\"original matrix: %s, new matrix: %s\", self._matrices[\"legacy\"], matrix)\n return self._matrices[self._centering]\n\n @property\n def pose(self):\n \"\"\" :class:`lib.align.PoseEstimate`: The estimated pose in 3D space. \"\"\"\n with self._cache[\"pose\"][1]:\n if self._cache[\"pose\"][0] is None:\n lms = cv2.transform(np.expand_dims(self._frame_landmarks, axis=1),\n self._matrices[\"legacy\"]).squeeze()\n self._cache[\"pose\"][0] = PoseEstimate(lms)\n return self._cache[\"pose\"][0]\n\n @property\n def adjusted_matrix(self):\n \"\"\" :class:`numpy.ndarray`: The 3x2 transformation matrix for extracting and aligning the\n core face area out of the original frame with padding and sizing applied. \"\"\"\n with self._cache[\"adjusted_matrix\"][1]:\n if self._cache[\"adjusted_matrix\"][0] is None:\n matrix = self.matrix.copy()\n mat = matrix * (self._size - 2 * self.padding)\n mat[:, 2] += self.padding\n #logger.trace(\"adjusted_matrix: %s\", mat)\n self._cache[\"adjusted_matrix\"][0] = mat\n return self._cache[\"adjusted_matrix\"][0]\n\n @property\n def face(self):\n \"\"\" :class:`numpy.ndarray`: The aligned face at the given :attr:`size` at the specified\n :attr:`coverage` in the given :attr:`dtype`. If an :attr:`image` has not been provided\n then an the attribute will return ``None``. \"\"\"\n return self._face\n\n @property\n def original_roi(self):\n \"\"\" :class:`numpy.ndarray`: The location of the extracted face box within the original\n frame. \"\"\"\n with self._cache[\"original_roi\"][1]:\n if self._cache[\"original_roi\"][0] is None:\n roi = np.array([[0, 0],\n [0, self._size - 1],\n [self._size - 1, self._size - 1],\n [self._size - 1, 0]])\n roi = np.rint(self.transform_points(roi, invert=True)).astype(\"int32\")\n #logger.trace(\"original roi: %s\", roi)\n self._cache[\"original_roi\"][0] = roi\n return self._cache[\"original_roi\"][0]\n\n @property\n def landmarks(self):\n \"\"\" :class:`numpy.ndarray`: The 68 point facial landmarks aligned to the extracted face\n box. \"\"\"\n with self._cache[\"landmarks\"][1]:\n if self._cache[\"landmarks\"][0] is None:\n lms = self.transform_points(self._frame_landmarks)\n #logger.trace(\"aligned landmarks: %s\", lms)\n self._cache[\"landmarks\"][0] = lms\n return self._cache[\"landmarks\"][0]\n\n @property\n def interpolators(self):\n \"\"\" tuple: (`interpolator` and `reverse interpolator`) for the :attr:`adjusted matrix`. \"\"\"\n with self._cache[\"interpolators\"][1]:\n if self._cache[\"interpolators\"][0] is None:\n interpolators = get_matrix_scaling(self.adjusted_matrix)\n #logger.trace(\"interpolators: %s\", interpolators)\n self._cache[\"interpolators\"][0] = interpolators\n return self._cache[\"interpolators\"][0]\n\n @classmethod\n def _set_cache(cls):\n \"\"\" Set the cache items.\n\n Items are cached so that they are only created the first time they are called.\n Each item includes a threading lock to make cache creation thread safe.\n\n Returns\n -------\n dict\n The Aligned Face cache\n \"\"\"\n return dict(pose=[None, Lock()],\n original_roi=[None, Lock()],\n landmarks=[None, Lock()],\n adjusted_matrix=[None, Lock()],\n interpolators=[None, Lock()],\n cropped_roi=[dict(), Lock()],\n cropped_size=[dict(), Lock()],\n cropped_slices=[dict(), Lock()])\n\n def transform_points(self, points, invert=False):\n \"\"\" Perform transformation on a series of (x, y) co-ordinates in world space into\n aligned face space.\n\n Parameters\n ----------\n points: :class:`numpy.ndarray`\n The points to transform\n invert: bool, optional\n ``True`` to reverse the transformation (i.e. transform the points into world space from\n aligned face space). Default: ``False``\n\n Returns\n -------\n :class:`numpy.ndarray`\n The transformed points\n \"\"\"\n retval = np.expand_dims(points, axis=1)\n mat = cv2.invertAffineTransform(self.adjusted_matrix) if invert else self.adjusted_matrix\n retval = cv2.transform(retval, mat, retval.shape).squeeze()\n '''logger.trace(\"invert: %s, Original points: %s, transformed points: %s\",\n invert, points, retval)'''\n return retval\n\n def _extract_face(self, image):\n \"\"\" Extract the face from a source image and populate :attr:`face`. If an image is not\n provided then ``None`` is returned.\n\n Parameters\n ----------\n image: :class:`numpy.ndarray` or ``None``\n The original frame to extract the face from. ``None`` if the face should not be\n extracted\n\n Returns\n -------\n :class:`numpy.ndarray` or ``None``\n The extracted face at the given size, with the given coverage of the given dtype or\n ``None`` if no image has been provided.\n \"\"\"\n if image is None:\n #logger.debug(\"_extract_face called without a loaded image. Returning empty face.\")\n if self._is_aligned:\n raise ValueError(\"An aligned face must be provided if calling with \"\n \"'is_aligned=True'\")\n return None\n if self._is_aligned and self._centering != \"head\": # Crop out the sub face from full head\n image = self._convert_centering(image)\n\n if self._is_aligned and image.shape[0] != self._size: # Resize the given aligned face\n interp = cv2.INTER_CUBIC if image.shape[0] < self._size else cv2.INTER_AREA\n retval = cv2.resize(image, (self._size, self._size), interpolation=interp)\n elif self._is_aligned:\n retval = image\n else:\n retval = transform_image(image, self.matrix, self._size, self.padding)\n retval = retval if self._dtype is None else retval.astype(self._dtype)\n return retval\n\n def _convert_centering(self, image):\n \"\"\" When the face being loaded is pre-aligned, the loaded image will have 'head' centering\n so it needs to be cropped out to the appropriate centering.\n\n This function temporarily converts this object to a full head aligned face, extracts the\n sub-cropped face to the correct centering, revers the sub crop and returns the cropped\n face.\n\n Parameters\n ----------\n image: :class:`numpy.ndarray`\n The original head-centered aligned image\n\n Returns\n -------\n :class:`numpy.ndarray`\n The aligned image with the correct centering\n \"\"\"\n # Input image is sized up because of integer rounding\n src_size = self.size - (self._size * _EXTRACT_RATIOS[self._centering])\n head_size = 2 * int(np.rint(src_size / (1 - _EXTRACT_RATIOS[\"head\"]) / 2))\n if head_size != image.shape[0]:\n interp = cv2.INTER_CUBIC if image.shape[0] < head_size else cv2.INTER_AREA\n image = cv2.resize(image, (head_size, head_size), interpolation=interp)\n\n # store requested size + centering whilst temporary converting to full head extract\n old_centering = self._centering\n old_size = self.size\n self._centering = \"head\"\n self._size = image.shape[0]\n\n # crop the requested centering from image\n size = self.get_cropped_size(old_centering)\n out = np.zeros((size, size, image.shape[-1]), dtype=image.dtype)\n slices = self.get_cropped_slices(old_centering)\n out[slices[\"out\"][0], slices[\"out\"][1], :] = image[slices[\"in\"][0], slices[\"in\"][1], :]\n\n # Revert back to the correct centering and size and reset the cache\n self._centering = old_centering\n self._size = old_size\n self._cache = self._set_cache()\n '''logger.trace(\"Cropped from aligned extract: (centering: %s, in shape: %s, out shape: %s)\",\n old_centering, image.shape, out.shape)'''\n return out\n\n @classmethod\n def _padding_from_coverage(cls, size, coverage_ratio):\n \"\"\" Return the image padding for a face from coverage_ratio set against a\n pre-padded training image.\n\n Parameters\n ----------\n size: int\n The final size of the aligned image in pixels\n coverage_ratio: float\n The ratio of the final image to pad to\n\n Returns\n -------\n dict\n The padding required, in pixels for 'head', 'face' and 'legacy' face types\n \"\"\"\n retval = {_type: round((size * (coverage_ratio - (1 - _EXTRACT_RATIOS[_type]))) / 2)\n for _type in (\"legacy\", \"face\", \"head\")}\n #logger.trace(retval)\n return retval\n\n def get_cropped_roi(self, centering):\n \"\"\" Obtain the region of interest within an aligned face set to centered coverage for\n an alternative centering\n\n Parameters\n ----------\n centering: [\"legacy\", \"face\"]\n The type of centering to obtain the region of interest for. \"legacy\" places the nose\n in the center of the image (the original method for aligning). \"face\" aligns for the\n nose to be in the center of the face (top to bottom) but the center of the skull for\n left to right.\n\n Returns\n -------\n :class:`numpy.ndarray`\n The (`left`, `top`, `right`, `bottom` location of the region of interest within an\n aligned face centered on the head for the given centering\n \"\"\"\n if self._centering != \"head\":\n raise ValueError(\"Sub ROI can only be obtained from an aligned face with 'head' \"\n \"centering\")\n with self._cache[\"cropped_roi\"][1]:\n if centering not in self._cache[\"cropped_roi\"][0]:\n offset = self.pose.offset.get(centering, np.float32((0, 0))) # legacy = 0,0\n offset -= self.pose.offset[\"head\"]\n offset *= ((self._size - self._padding[\"head\"]) / 2)\n\n center = np.rint(offset + self._size / 2).astype(\"int32\")\n padding = self.get_cropped_size(centering) // 2\n roi = np.array([center - padding, center + padding]).ravel()\n '''logger.trace(\"centering: '%s', center: %s, padding: %s, sub roi: %s\",\n centering, center, padding, roi)'''\n self._cache[\"cropped_roi\"][0][centering] = roi\n return self._cache[\"cropped_roi\"][0][centering]\n\n def get_cropped_size(self, centering):\n \"\"\" Obtain the size of a cropped face from a full head centered image.\n\n Parameters\n ----------\n centering: [\"legacy\", \"face\"]\n The type of centering to obtain the region of interest for. \"legacy\" places the nose\n in the center of the image (the original method for aligning). \"face\" aligns for the\n nose to be in the center of the face (top to bottom) but the center of the skull for\n left to right.\n\n Returns\n -------\n int\n The pixel size of a sub-crop image from a full head aligned image\n\n Notes\n -----\n The ROI in relation to the source image is calculated by rounding the padding of one side\n to the nearest integer then applying this padding to the center of the crop, so the size\n is calculated in the same way.\n \"\"\"\n if self._centering != \"head\":\n raise ValueError(\"Sub ROI can only be obtained from an aligned face with 'head' \"\n \"centering\")\n with self._cache[\"cropped_size\"][1]:\n if not self._cache[\"cropped_size\"][0].get(centering):\n src_size = self.size - (self._size * _EXTRACT_RATIOS[\"head\"])\n size = 2 * int(np.rint(src_size / (1 - _EXTRACT_RATIOS[centering]) / 2))\n #logger.trace(\"centering: %s, size: %s, crop_size: %s\", centering, self._size, size)\n self._cache[\"cropped_size\"][0][centering] = size\n return self._cache[\"cropped_size\"][0][centering]\n\n def get_cropped_slices(self, centering):\n \"\"\" Obtain the slices to turn a full head extract into an alternatively centered extract.\n\n Parameters\n ----------\n centering: [\"legacy\", \"face\"]\n The type of centering to obtain the region of interest for. \"legacy\" places the nose\n in the center of the image (the original method for aligning). \"face\" aligns for the\n nose to be in the center of the face (top to bottom) but the center of the skull for\n left to right.\n\n Returns\n -------\n dict\n The slices for an input full head image and output cropped image\n \"\"\"\n if self._centering != \"head\":\n raise ValueError(\"Cropped slices can only be obtained from an aligned face with \"\n \"'head' centering\")\n with self._cache[\"cropped_slices\"][1]:\n if not self._cache[\"cropped_slices\"][0].get(centering):\n size = self.get_cropped_size(centering)\n roi = self.get_cropped_roi(centering)\n slice_in = [slice(max(roi[1], 0), roi[3]), slice(max(roi[0], 0), roi[2])]\n slice_out = [slice(max(roi[1] * -1, 0), size - max(0, roi[3] - self.size)),\n slice(max(roi[0] * -1, 0), size - max(0, roi[2] - self.size))]\n self._cache[\"cropped_slices\"][0][centering] = {\"in\": slice_in, \"out\": slice_out}\n '''logger.trace(\"centering: %s, cropped_slices: %s\",\n centering, self._cache[\"cropped_slices\"][0][centering])'''\n return self._cache[\"cropped_slices\"][0][centering]\n\n\nclass PoseEstimate():\n \"\"\" Estimates pose from a generic 3D head model for the given 2D face landmarks.\n\n Parameters\n ----------\n landmarks: :class:`numpy.ndarry`\n The original 68 point landmarks aligned to 0.0 - 1.0 range\n\n References\n ----------\n Head Pose Estimation using OpenCV and Dlib - https://www.learnopencv.com/tag/solvepnp/\n 3D Model points - http://aifi.isr.uc.pt/Downloads/OpenGL/glAnthropometric3DModel.cpp\n \"\"\"\n def __init__(self, landmarks):\n self._distortion_coefficients = np.zeros((4, 1)) # Assuming no lens distortion\n self._xyz_2d = None\n\n self._camera_matrix = self._get_camera_matrix()\n self._rotation, self._translation = self._solve_pnp(landmarks)\n self._offset = self._get_offset()\n\n @property\n def xyz_2d(self):\n \"\"\" :class:`numpy.ndarray` projected (x, y) coordinates for each x, y, z point at a\n constant distance from adjusted center of the skull (0.5, 0.5) in the 2D space. \"\"\"\n if self._xyz_2d is None:\n xyz = cv2.projectPoints(np.float32([[6, 0, -2.3], [0, 6, -2.3], [0, 0, 3.7]]),\n self._rotation,\n self._translation,\n self._camera_matrix,\n self._distortion_coefficients)[0].squeeze()\n self._xyz_2d = xyz - self._offset[\"head\"]\n return self._xyz_2d\n\n @property\n def offset(self):\n \"\"\" dict: The amount to offset a standard 0.0 - 1.0 umeyama transformation matrix for a\n from the center of the face (between the eyes) or center of the head (middle of skull)\n rather than the nose area. \"\"\"\n return self._offset\n\n @classmethod\n def _get_camera_matrix(cls):\n \"\"\" Obtain an estimate of the camera matrix based off the original frame dimensions.\n\n Returns\n -------\n :class:`numpy.ndarray`\n An estimated camera matrix\n \"\"\"\n focal_length = 4\n camera_matrix = np.array([[focal_length, 0, 0.5],\n [0, focal_length, 0.5],\n [0, 0, 1]], dtype=\"double\")\n #logger.trace(\"camera_matrix: %s\", camera_matrix)\n return camera_matrix\n\n def _solve_pnp(self, landmarks):\n \"\"\" Solve the Perspective-n-Point for the given landmarks.\n\n Takes 2D landmarks in world space and estimates the rotation and translation vectors\n in 3D space.\n\n Parameters\n ----------\n landmarks: :class:`numpy.ndarry`\n The original 68 point landmark co-ordinates relating to the original frame\n\n Returns\n -------\n rotation: :class:`numpy.ndarray`\n The solved rotation vector\n translation: :class:`numpy.ndarray`\n The solved translation vector\n \"\"\"\n points = landmarks[[6, 7, 8, 9, 10, 17, 21, 22, 26, 31, 32, 33, 34,\n 35, 36, 39, 42, 45, 48, 50, 51, 52, 54, 56, 57, 58]]\n _, rotation, translation = cv2.solvePnP(_MEAN_FACE_3D,\n points,\n self._camera_matrix,\n self._distortion_coefficients,\n flags=cv2.SOLVEPNP_ITERATIVE)\n #logger.trace(\"points: %s, rotation: %s, translation: %s\", points, rotation, translation)\n return rotation, translation\n\n def _get_offset(self):\n \"\"\" Obtain the offset between the original center of the extracted face to the new center\n of the head in 2D space.\n\n Returns\n -------\n :class:`numpy.ndarray`\n The x, y offset of the new center from the old center.\n \"\"\"\n points = dict(head=(0, 0, -2.3), face=(0, -1.5, 4.2))\n offset = dict()\n for key, pnts in points.items():\n center = cv2.projectPoints(np.float32([pnts]),\n self._rotation,\n self._translation,\n self._camera_matrix,\n self._distortion_coefficients)[0].squeeze()\n #logger.trace(\"center %s: %s\", key, center)\n offset[key] = center - (0.5, 0.5)\n #logger.trace(\"offset: %s\", offset)\n return offset\n\n\ndef _umeyama(source, destination, estimate_scale):\n \"\"\"Estimate N-D similarity transformation with or without scaling.\n\n Imported, and slightly adapted, directly from:\n https://github.com/scikit-image/scikit-image/blob/master/skimage/transform/_geometric.py\n\n\n Parameters\n ----------\n source: :class:`numpy.ndarray`\n (M, N) array source coordinates.\n destination: :class:`numpy.ndarray`\n (M, N) array destination coordinates.\n estimate_scale: bool\n Whether to estimate scaling factor.\n\n Returns\n -------\n :class:`numpy.ndarray`\n (N + 1, N + 1) The homogeneous similarity transformation matrix. The matrix contains\n NaN values only if the problem is not well-conditioned.\n\n References\n ----------\n .. [1] \"Least-squares estimation of transformation parameters between two\n point patterns\", Shinji Umeyama, PAMI 1991, :DOI:`10.1109/34.88573`\n \"\"\"\n # pylint:disable=invalid-name,too-many-locals\n num = source.shape[0]\n dim = source.shape[1]\n\n # Compute mean of source and destination.\n src_mean = source.mean(axis=0)\n dst_mean = destination.mean(axis=0)\n\n # Subtract mean from source and destination.\n src_demean = source - src_mean\n dst_demean = destination - dst_mean\n\n # Eq. (38).\n A = dst_demean.T @ src_demean / num\n\n # Eq. (39).\n d = np.ones((dim,), dtype=np.double)\n if np.linalg.det(A) < 0:\n d[dim - 1] = -1\n\n T = np.eye(dim + 1, dtype=np.double)\n\n U, S, V = np.linalg.svd(A)\n\n # Eq. (40) and (43).\n rank = np.linalg.matrix_rank(A)\n if rank == 0:\n return np.nan * T\n if rank == dim - 1:\n if np.linalg.det(U) * np.linalg.det(V) > 0:\n T[:dim, :dim] = U @ V\n else:\n s = d[dim - 1]\n d[dim - 1] = -1\n T[:dim, :dim] = U @ np.diag(d) @ V\n d[dim - 1] = s\n else:\n T[:dim, :dim] = U @ np.diag(d) @ V\n\n if estimate_scale:\n # Eq. (41) and (42).\n scale = 1.0 / src_demean.var(axis=0).sum() * (S @ d)\n else:\n scale = 1.0\n\n T[:dim, dim] = dst_mean - scale * (T[:dim, :dim] @ src_mean.T)\n T[:dim, :dim] *= scale\n\n return T\n", "meta": {"hexsha": "43a7c058b2915e76a2c22accb179dbbcbf4d7717", "size": 30737, "ext": "py", "lang": "Python", "max_stars_repo_path": "facelib/fs_align/aligned_face.py", "max_stars_repo_name": "chuanli11/GFPGAN", "max_stars_repo_head_hexsha": "4adbf820cef782c7d33113be35e5f1a49f2a3793", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "facelib/fs_align/aligned_face.py", "max_issues_repo_name": "chuanli11/GFPGAN", "max_issues_repo_head_hexsha": "4adbf820cef782c7d33113be35e5f1a49f2a3793", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "facelib/fs_align/aligned_face.py", "max_forks_repo_name": "chuanli11/GFPGAN", "max_forks_repo_head_hexsha": "4adbf820cef782c7d33113be35e5f1a49f2a3793", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.2896253602, "max_line_length": 101, "alphanum_fraction": 0.5676871523, "include": true, "reason": "import numpy", "num_tokens": 7776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.2309197735148081, "lm_q1q2_score": 0.1190668341584832}} {"text": "import os\nimport warnings\n\nimport numpy\nfrom six import integer_types\n\nimport theano\nfrom theano import Op, Apply, tensor, config, Variable\nfrom theano.scalar import as_scalar, constant, Log\nfrom theano.tensor import as_tensor_variable\nfrom theano.gradient import DisconnectedType, grad_not_implemented\nfrom theano.gof import Optimizer, local_optimizer, COp\nfrom theano.gof.cmodule import GCC_compiler\nfrom theano.gof.type import CDataType, Generic\nfrom theano.compile import optdb\nfrom theano.compile.ops import shape_i\nfrom theano.tensor.nnet import LogSoftmax, SoftmaxGrad\nfrom theano.tensor.nnet.abstract_conv import (AbstractConv2d,\n AbstractConv2d_gradWeights,\n AbstractConv2d_gradInputs,\n get_conv_output_shape)\nfrom theano.tensor.signal.pool import (\n Pool, MaxPoolGrad, AveragePoolGrad)\nfrom . import pygpu\nfrom .type import get_context, gpu_context_type, list_contexts, GpuArrayType\nfrom .basic_ops import (as_gpuarray_variable, infer_context_name,\n gpu_contiguous, GpuAllocEmpty, empty_like)\nfrom .elemwise import GpuElemwise\n\n# These don't exist in gpuarray\n# GpuDownsampleFactorMax, GpuDownsampleFactorMaxGrad\nfrom .nnet import GpuSoftmax\nfrom .opt import gpu_seqopt, register_opt, conv_groupopt, op_lifter\nfrom .opt_util import alpha_merge, output_merge, inplace_allocempty\n\n\ndef raise_no_cudnn(msg=\"CuDNN is required for convolution and pooling\"):\n raise RuntimeError(msg)\n\n\ndef _dnn_check_compile():\n preambule = \"\"\"\n#include \n#include \n#include \n\"\"\"\n\n # No need for the context in here since we won't execute that code\n body = \"\"\"\ncudnnHandle_t _handle = NULL;\ncudnnStatus_t err;\nif ((err = cudnnCreate(&_handle)) != CUDNN_STATUS_SUCCESS) {\n fprintf(stderr, \"could not create cuDNN handle: %s\",\n cudnnGetErrorString(err));\n return 1;\n}\n\"\"\"\n\n params = [\"-l\", \"cudnn\", \"-I\" + os.path.dirname(__file__)]\n if config.dnn.include_path:\n params.append(\"-I\" + config.dnn.include_path)\n if config.dnn.library_path:\n params.append(\"-L\" + config.dnn.library_path)\n if config.nvcc.compiler_bindir:\n params.extend(['--compiler-bindir', config.nvcc.compiler_bindir])\n # Do not run here the test program. It would run on the\n # default gpu, not the one selected by the user. If mixed\n # GPU are installed or if the GPUs are configured in\n # exclusive mode, this cause bad detection.\n avail, out, err = GCC_compiler.try_flags(\n params, preambule=preambule, body=body,\n try_run=False, output=True)\n\n if not avail:\n return False, (\"Theano cannot compile with cuDNN. \"\n \"We got this error:\\n\" + str(err))\n return True, None\n\n\ndef _dnn_check_version():\n v = version()\n if v < 3007:\n return False, (\n \"You have an old release of CuDNN (or a release candidate) \"\n \"that isn't supported. Please update to at least v3 final \"\n \"version.\")\n\n return True, None\n\n\ndef dnn_present():\n if dnn_present.avail is not None:\n return dnn_present.avail\n if config.dnn.enabled == \"False\":\n dnn_present.msg = \"disabled by dnn.enabled flag\"\n dnn_present.avail = False\n\n if pygpu is None:\n dnn_present.msg = \"PyGPU not available\"\n dnn_present.avail = False\n return False\n\n dnn_present.avail, dnn_present.msg = _dnn_check_compile()\n if dnn_present.avail:\n dnn_present.avail, dnn_present.msg = _dnn_check_version()\n if not dnn_present.avail:\n raise RuntimeError(dnn_present.msg)\n\n if config.dnn.enabled == \"True\":\n if not dnn_present.avail:\n raise RuntimeError(\n \"You enabled CuDNN, but we aren't able to use it: %s\" %\n dnn_present.msg)\n\n return dnn_present.avail\n\ndnn_present.avail = None\ndnn_present.msg = None\n\n\ndef dnn_available(context_name):\n if not dnn_present():\n dnn_available.msg = dnn_present.msg\n return False\n\n ctx = get_context(context_name)\n\n if not ctx.kind == 'cuda':\n dnn_available.msg = \"Not on a CUDA device.\"\n return False\n\n # This is a hack because bin_id is in the from of\n # \"_\" for cuda devices.\n if ctx.bin_id[-2:] < b'30':\n dnn_available.msg = \"Device not supported by cuDNN\"\n return False\n\n return True\n\ndnn_available.msg = None\n\n\nclass DnnBase(COp):\n \"\"\"\n Creates a handle for cudnn and pulls in the cudnn libraries and headers.\n\n \"\"\"\n # dnn does not know about broadcasting, so we do not need to assert\n # the input broadcasting pattern.\n check_broadcast = False\n params_type = gpu_context_type\n\n def get_params(self, node):\n return node.outputs[0].type.context\n\n def __init__(self, files=None, c_func=None):\n if files is None:\n files = []\n COp.__init__(self, [\"dnn_base.c\"] + files, c_func)\n\n def c_headers(self):\n return ['cudnn.h', 'cudnn_helper.h', 'gpuarray_helper.h',\n 'gpuarray/types.h', 'gpuarray/array.h', 'gpuarray/util.h',\n 'gpuarray/ext_cuda.h', 'gpuarray_api.h', 'numpy_compat.h']\n\n def c_header_dirs(self):\n return [os.path.dirname(__file__), pygpu.get_include(),\n config.dnn.include_path]\n\n def c_libraries(self):\n return ['cudnn', 'gpuarray']\n\n def c_lib_dirs(self):\n return [config.dnn.library_path]\n\n def c_compile_args(self):\n return ['-Wl,-rpath,' + config.dnn.library_path]\n\n def c_code_cache_version(self):\n return (super(DnnBase, self).c_code_cache_version(), version())\n\n\nclass DnnVersion(Op):\n __props__ = ()\n\n def c_headers(self):\n return ['cudnn.h']\n\n def c_header_dirs(self):\n return [config.dnn.include_path]\n\n def c_libraries(self):\n return ['cudnn']\n\n def c_lib_dirs(self):\n return [config.dnn.library_path]\n\n def c_compile_args(self):\n return ['-Wl,-rpath,' + config.dnn.library_path]\n\n def c_support_code(self):\n return \"\"\"\n#if PY_MAJOR_VERSION >= 3\n#define PyInt_FromLong PyLong_FromLong\n#endif\n\"\"\"\n\n def make_node(self):\n return Apply(self, [], [Generic()()])\n\n def c_code(self, node, name, inputs, outputs, sub):\n o = outputs[0]\n return \"\"\"\n %(o)s = PyTuple_Pack(2, PyInt_FromLong(CUDNN_VERSION), PyInt_FromLong(cudnnGetVersion()));\n \"\"\" % locals()\n\n def do_constant_folding(self, node):\n # Needed as we do not want to cache this information.\n return False\n\n def c_code_cache_version(self):\n # Not needed, but make it clear that we do not want to cache this.\n return None\n\n\ndef version(raises=True):\n \"\"\"\n Return the current cuDNN version we link with.\n\n This also does a check that the header version matches the runtime version.\n\n :raises: If True, raise an exception if CuDNN is not present or badly installed.\n Otherwise, return -1.\n \"\"\"\n if not dnn_present():\n if raises:\n raise Exception(\n \"We can't determine the cudnn version as it is not available\",\n dnn_available.msg)\n else:\n return -1\n\n if version.v is None:\n f = theano.function([], DnnVersion()(),\n theano.Mode(optimizer=None),\n profile=False)\n v = f()\n if v[0] != v[1]:\n raise RuntimeError(\"Mixed dnn version. The header is version %s \"\n \"while the library is version %s.\" % v)\n version.v = v[1]\n return version.v\nversion.v = None\n\n\nclass GpuDnnConvDesc(COp):\n \"\"\"\n This Op builds a convolution descriptor for use in the other convolution\n operations.\n\n See the doc of :func:`dnn_conv` for a description of the parameters\n\n \"\"\"\n\n __props__ = ('border_mode', 'subsample', 'conv_mode', 'precision')\n\n def c_headers(self):\n return ['cudnn.h', 'cudnn_helper.h']\n\n def c_header_dirs(self):\n return [os.path.dirname(__file__), config.dnn.include_path]\n\n def c_libraries(self):\n return ['cudnn']\n\n def c_lib_dirs(self):\n return [config.dnn.library_path]\n\n def do_constant_folding(self, node):\n return False\n\n def __init__(self, border_mode, subsample=(1, 1), conv_mode='conv',\n precision=\"float32\"):\n COp.__init__(self, [\"conv_desc.c\"], \"APPLY_SPECIFIC(conv_desc)\")\n\n if isinstance(border_mode, integer_types):\n border_mode = (border_mode,) * len(subsample)\n if isinstance(border_mode, tuple):\n assert len(border_mode) == len(subsample)\n border_mode = tuple(map(int, border_mode))\n if not ((isinstance(border_mode, tuple) and min(border_mode) >= 0) or\n border_mode in ('valid', 'full', 'half')):\n raise ValueError(\n 'invalid border_mode {}, which must be either '\n '\"valid\", \"full\", \"half\", an integer or a pair of'\n ' integers'.format(border_mode))\n self.border_mode = border_mode\n assert len(subsample) in (2, 3)\n self.subsample = subsample\n assert conv_mode in ('conv', 'cross')\n self.conv_mode = conv_mode\n\n assert precision in ['float16', 'float32', 'float64']\n self.precision = precision\n\n def make_node(self, kern_shape):\n if kern_shape.type.ndim != 1 or kern_shape.type.dtype != 'int64':\n raise TypeError('kern must be 1D shape tensor')\n\n return Apply(self, [kern_shape],\n [CDataType(\"cudnnConvolutionDescriptor_t\",\n freefunc=\"cudnnDestroyConvolutionDescriptor\")()])\n\n def get_op_params(self):\n pad0 = '0'\n pad1 = '0'\n pad2 = '0'\n if isinstance(self.border_mode, tuple):\n pad0 = str(self.border_mode[0])\n pad1 = str(self.border_mode[1])\n if len(self.border_mode) > 2:\n pad2 = str(self.border_mode[2])\n bmode = '1'\n elif self.border_mode == \"valid\":\n bmode = '1'\n elif self.border_mode == \"half\":\n bmode = '2'\n elif self.border_mode == \"full\":\n bmode = '0'\n else:\n raise ValueError(\"Invalid value for border_mode\")\n\n if self.conv_mode == 'conv':\n conv_flag = 'CUDNN_CONVOLUTION'\n else:\n conv_flag = 'CUDNN_CROSS_CORRELATION'\n\n sub0 = str(self.subsample[0])\n sub1 = str(self.subsample[1])\n if len(self.subsample) > 2:\n sub2 = str(self.subsample[2])\n else:\n sub2 = '0'\n\n if self.precision == 'float16':\n precision = 'CUDNN_DATA_HALF'\n elif self.precision == 'float32':\n precision = 'CUDNN_DATA_FLOAT'\n else:\n assert self.precision == 'float64'\n precision = 'CUDNN_DATA_DOUBLE'\n\n return [('NB_DIMS', str(len(self.subsample))),\n ('BORDER_MODE', bmode),\n ('PAD_0', pad0), ('PAD_1', pad1), ('PAD_2', pad2),\n ('CONV_MODE', conv_flag),\n ('SUB_0', sub0), ('SUB_1', sub1), ('SUB_2', sub2),\n ('PRECISION', precision)]\n\n def c_code_cache_version(self):\n return (super(GpuDnnConvDesc, self).c_code_cache_version(), version())\n\n# scalar constants\n_zero = constant(numpy.asarray(0.0, dtype='float64'))\n_one = constant(numpy.asarray(1.0, dtype='float64'))\n\n\ndef ensure_dt(val, default, name, dtype):\n if val is None:\n val = default.clone()\n if not isinstance(val, Variable):\n val = constant(val)\n if hasattr(val, 'ndim') and val.ndim == 0:\n val = as_scalar(val)\n if not isinstance(val.type, theano.scalar.Scalar):\n raise TypeError(\"%s: expected a scalar value\" % (name,))\n if not val.type.dtype == dtype:\n val = val.astype(dtype)\n return val\n\n\nclass GpuDnnConv(DnnBase):\n \"\"\"\n The forward convolution.\n\n Parameters\n ----------\n image\n kernel\n descr\n The convolution descriptor.\n algo : {'small', 'none', 'large', 'fft', 'fft_tiling', 'guess_once',\n 'guess_on_shape_change', 'time_once', 'time_on_shape_change'}\n Default is the value of :attr:`config.dnn.conv.algo_fwd`.\n\n \"\"\"\n\n __props__ = ('algo', 'inplace')\n\n def __init__(self, algo=None, inplace=False):\n DnnBase.__init__(self, [\"dnn_conv_base.c\", \"dnn_fwd.c\"],\n \"APPLY_SPECIFIC(conv_fwd)\")\n\n if algo is None:\n algo = config.dnn.conv.algo_fwd\n self.algo = algo\n\n self.inplace = inplace\n if self.inplace:\n self.destroy_map = {0: [2]}\n\n if version() < 3000:\n if self.algo == 'fft':\n raise RuntimeError(\"CuDNN FFT convolution requires CuDNN v3\")\n elif self.algo in ['guess_once', 'guess_on_shape_change']:\n raise RuntimeError(\"CuDNN selection of convolution \"\n \"implementation based on heuristics \"\n \"requires CuDNN v3\")\n elif self.algo in ['time_once', 'time_on_shape_change']:\n raise RuntimeError(\"CuDNN convolution timing requires CuDNN v3\")\n\n # The fft_tiling implementation is only available from CuDNN V4 onward\n if version() < 4000:\n if self.algo == 'fft_tiling':\n raise RuntimeError(\"CuDNN tiled-FFT convolution requires \"\n \"CuDNN v4 or more recent\")\n\n assert self.algo in ['none', 'small', 'large', 'fft', 'fft_tiling',\n 'guess_once', 'guess_on_shape_change',\n 'time_once', 'time_on_shape_change']\n\n def __setstate__(self, d):\n self.__dict__.update(d)\n if not hasattr(self, 'algo'):\n if hasattr(self, 'workmem'):\n self.algo = self.workmem\n else:\n self.algo = config.dnn.conv.algo_fwd\n if not hasattr(self, 'inplace'):\n self.inplace = False\n\n def get_op_params(self):\n defs = []\n if self.inplace:\n defs.append(('CONV_INPLACE', '1'))\n\n alg = 'CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM'\n if self.algo == 'none':\n alg = 'CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_GEMM'\n elif self.algo == 'small':\n alg = 'CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM'\n elif self.algo == 'large':\n alg = 'CUDNN_CONVOLUTION_FWD_ALGO_GEMM'\n elif self.algo == 'direct':\n alg = 'CUDNN_CONVOLUTION_FWD_ALGO_DIRECT'\n elif self.algo == 'fft':\n alg = 'CUDNN_CONVOLUTION_FWD_ALGO_FFT'\n elif self.algo == 'fft_tiling':\n # need v4\n alg = 'CUDNN_CONVOLUTION_FWD_ALGO_FFT_TILING'\n defs.append(('CONV_ALGO', alg))\n\n if self.algo in ['guess_once', 'guess_on_shape_change',\n 'time_once', 'time_on_shape_change']:\n defs.append(('CHOOSE_ALGO', ''))\n if self.algo in ['guess_once', 'time_once']:\n defs.append(('CHOOSE_ONCE', ''))\n if self.algo in ['time_once', 'time_on_shape_change']:\n defs.append(('CHOOSE_TIME', ''))\n\n return defs\n\n def make_node(self, img, kern, output, desc, alpha=None, beta=None):\n ctx_name = infer_context_name(img, kern, output)\n img = as_gpuarray_variable(img, ctx_name)\n kern = as_gpuarray_variable(kern, ctx_name)\n output = as_gpuarray_variable(output, ctx_name)\n if img.type.ndim not in (4, 5):\n raise TypeError('img must be 4D or 5D tensor')\n if kern.type.ndim not in (4, 5):\n raise TypeError('kern must be 4D or 5D tensor')\n if output.type.ndim not in (4, 5):\n raise TypeError('output must be a 4D or 5D tensor')\n\n if (img.type.ndim != kern.type.ndim or\n img.type.ndim != output.type.ndim):\n raise TypeError(\"The number of dimensions of \"\n \"img, kern and output must match\")\n\n if (img.type.ndim == 5 and\n self.algo in ['small', 'large', 'fft', 'fft_tiling']):\n raise ValueError(\"convolution algo %s can't be used for \"\n \"3d convolutions\", (self.algo,))\n\n if (not isinstance(desc.type, CDataType) or\n desc.type.ctype != 'cudnnConvolutionDescriptor_t'):\n raise TypeError('desc must be cudnnConvolutionDescriptor_t')\n\n alpha = ensure_dt(alpha, _one, 'alpha', img.dtype)\n beta = ensure_dt(beta, _zero, 'beta', img.dtype)\n\n return Apply(self, [img, kern, output, desc, alpha, beta],\n [output.type()])\n\n def grad(self, inp, grads):\n img, kerns, output, desc, alpha, beta = inp\n top, = grads\n\n top = gpu_contiguous(top)\n\n d_img = GpuDnnConvGradI()(kerns, top, empty_like(img), desc)\n d_kerns = GpuDnnConvGradW()(img, top, empty_like(kerns), desc)\n d_alpha = grad_not_implemented(self, 4, alpha)\n d_beta = grad_not_implemented(self, 5, beta)\n\n return [d_img * alpha, d_kerns * alpha, top * beta,\n DisconnectedType()(), d_alpha, d_beta]\n\n def connection_pattern(self, node):\n # not connected to desc\n return [[1], [1], [1], [0], [1], [1]]\n\n @staticmethod\n def get_out_shape(ishape, kshape, border_mode, subsample):\n \"\"\"\n This function computes the output shape for a convolution with\n the specified parameters. `ishape` and `kshape` can be symbolic\n or scalar.\n\n \"\"\"\n\n # if ishape and/or kshape are not tuples or list, but rather symbolic\n # vectors, turn them into lists of symbolic scalars.\n if not isinstance(ishape, (list, tuple)):\n ishape = [ishape[i] for i in range(len(subsample) + 2)]\n if not isinstance(kshape, (list, tuple)):\n kshape = [kshape[i] for i in range(len(subsample) + 2)]\n\n return get_conv_output_shape(\n ishape,\n kshape,\n border_mode,\n subsample)\n\n def infer_shape(self, node, shape):\n return [shape[2]]\n\n\nclass GpuDnnConvGradW(DnnBase):\n \"\"\"\n The convolution gradient with respect to the weights.\n\n Parameters\n ----------\n image\n kernel\n descr\n The convolution descriptor.\n\n \"\"\"\n\n __props__ = ('algo', 'inplace')\n\n def __init__(self, inplace=False, algo=None):\n DnnBase.__init__(self, [\"dnn_conv_base.c\", \"dnn_gw.c\"],\n \"APPLY_SPECIFIC(conv_gw)\")\n self.inplace = inplace\n if self.inplace:\n self.destroy_map = {0: [2]}\n if algo is None:\n algo = config.dnn.conv.algo_bwd_filter\n self.algo = algo\n\n assert self.algo in ['none', 'deterministic', 'fft', 'small',\n 'guess_once', 'guess_on_shape_change',\n 'time_once', 'time_on_shape_change']\n\n def __setstate__(self, d):\n self.__dict__.update(d)\n if not hasattr(self, 'inplace'):\n self.inplace = False\n if not hasattr(self, 'algo'):\n self.algo = config.dnn.conv.algo_bwd_filter\n\n def grad(self, inp, grads):\n img, top, output, desc, alpha, beta = inp\n kerns, = grads\n\n kerns = gpu_contiguous(kerns)\n\n d_img = GpuDnnConvGradI()(kerns, top, empty_like(img), desc)\n d_top = GpuDnnConv()(img, kerns, empty_like(top), desc)\n d_alpha = grad_not_implemented(self, 4, alpha)\n d_beta = grad_not_implemented(self, 5, beta)\n\n return (d_img * alpha, d_top * alpha, kerns * beta,\n DisconnectedType()(), d_alpha, d_beta)\n\n def connection_pattern(self, node):\n # not connected to desc\n return [[1], [1], [1], [0], [1], [1]]\n\n def get_op_params(self):\n defs = []\n if self.inplace:\n defs.append(('CONV_INPLACE', '1'))\n\n if version() < 3000:\n alg = '0'\n else:\n alg = 'CUDNN_CONVOLUTION_BWD_FILTER_ALGO_0'\n if self.algo == 'none':\n alg = 'CUDNN_CONVOLUTION_BWD_FILTER_ALGO_0'\n if self.algo == 'deterministic':\n alg = 'CUDNN_CONVOLUTION_BWD_FILTER_ALGO_1'\n if self.algo == 'fft':\n alg = 'CUDNN_CONVOLUTION_BWD_FILTER_ALGO_FFT'\n if self.algo == 'small':\n # non-deterministic, small workspace\n alg = 'CUDNN_CONVOLUTION_BWD_FILTER_ALGO_3'\n if self.algo in ['guess_once', 'guess_on_shape_change',\n 'time_once', 'time_on_shape_change']:\n defs.append(('CHOOSE_ALGO', ''))\n if self.algo in ['guess_once', 'time_once']:\n defs.append(('CHOOSE_ONCE', ''))\n if self.algo in ['time_once', 'time_on_shape_change']:\n defs.append(('CHOOSE_TIME', ''))\n\n defs.append(('CONV_ALGO', alg))\n\n return defs\n\n def make_node(self, img, topgrad, output, desc, alpha=None, beta=None):\n ctx_name = infer_context_name(img, topgrad, output)\n img = as_gpuarray_variable(img, ctx_name)\n topgrad = as_gpuarray_variable(topgrad, ctx_name)\n output = as_gpuarray_variable(output, ctx_name)\n if img.type.ndim not in (4, 5):\n raise TypeError('img must be 4D or 5D tensor')\n if topgrad.type.ndim not in (4, 5):\n raise TypeError('topgrad must be 4D or 5D tensor')\n if output.type.ndim not in (4, 5):\n raise TypeError('output must be 4D or 5D tensor')\n\n if (img.type.ndim != topgrad.type.ndim or\n img.type.ndim != output.type.ndim):\n raise TypeError(\"The number of dimensions of \"\n \"img, topgrad and output must match\")\n\n if (img.type.ndim == 5 and\n self.algo in ['fft', 'deterministic', 'small']):\n raise ValueError(\"convolution algo %s can't be used for \"\n \"3d convolutions\", (self.algo,))\n\n if (not isinstance(desc.type, CDataType) or\n desc.type.ctype != 'cudnnConvolutionDescriptor_t'):\n raise TypeError('desc must be cudnnConvolutionDescriptor_t')\n\n alpha = ensure_dt(alpha, _one, 'alpha', img.dtype)\n beta = ensure_dt(beta, _zero, 'beta', img.dtype)\n\n return Apply(self, [img, topgrad, output, desc, alpha, beta],\n [output.type()])\n\n def infer_shape(self, node, shape):\n return [shape[2]]\n\n\nclass GpuDnnConvGradI(DnnBase):\n \"\"\"\n The convolution gradient with respect to the inputs.\n\n Parameters\n ----------\n image\n kernel\n descr\n The convolution descriptor.\n\n \"\"\"\n\n __props__ = ('algo', 'inplace',)\n\n def __init__(self, inplace=False, algo=None):\n DnnBase.__init__(self, [\"dnn_conv_base.c\", \"dnn_gi.c\"],\n \"APPLY_SPECIFIC(conv_gi)\")\n self.inplace = inplace\n if self.inplace:\n self.destroy_map = {0: [2]}\n if algo is None:\n algo = config.dnn.conv.algo_bwd_data\n self.algo = algo\n\n # The small-workspace implementation is only available from CuDNN V4\n # onward.\n if version() < 4000 and self.algo == 'fft_tiling':\n raise RuntimeError(\"CuDNN's tiled-FFT convolution requires CuDNN \"\n \"v4 or more recent\")\n\n assert self.algo in ['none', 'deterministic', 'fft', 'fft_tiling',\n 'guess_once', 'guess_on_shape_change',\n 'time_once', 'time_on_shape_change']\n\n def __setstate__(self, d):\n self.__dict__.update(d)\n if not hasattr(self, 'algo'):\n self.algo = config.dnn.conv.algo_bwd_data\n if not hasattr(self, 'inplace'):\n self.inplace = False\n\n def grad(self, inp, grads):\n kerns, top, output, desc, alpha, beta = inp\n img, = grads\n\n img = gpu_contiguous(img)\n\n d_kerns = GpuDnnConvGradW()(img, top, empty_like(kerns), desc)\n d_top = GpuDnnConv()(img, kerns, empty_like(top), desc)\n d_alpha = grad_not_implemented(self, 4, alpha)\n d_beta = grad_not_implemented(self, 5, beta)\n\n return (d_kerns * alpha, d_top * alpha, img * beta,\n DisconnectedType()(), d_alpha, d_beta)\n\n def connection_pattern(self, node):\n # not connected to desc\n return [[1], [1], [1], [0], [1], [1]]\n\n def get_op_params(self):\n defs = []\n if self.inplace:\n defs.append(('CONV_INPLACE', '1'))\n\n if version() < 3000:\n alg = '0'\n else:\n alg = 'CUDNN_CONVOLUTION_BWD_DATA_ALGO_0'\n if self.algo == 'none':\n alg = 'CUDNN_CONVOLUTION_BWD_DATA_ALGO_0'\n if self.algo == 'deterministic':\n alg = 'CUDNN_CONVOLUTION_BWD_DATA_ALGO_1'\n if self.algo == 'fft':\n alg = 'CUDNN_CONVOLUTION_BWD_DATA_ALGO_FFT'\n if self.algo == 'fft_tiling':\n # big workspace but less than fft\n alg = 'CUDNN_CONVOLUTION_BWD_DATA_ALGO_FFT_TILING'\n\n if self.algo in ['guess_once', 'guess_on_shape_change',\n 'time_once', 'time_on_shape_change']:\n defs.append(('CHOOSE_ALGO', ''))\n if self.algo in ['guess_once', 'time_once']:\n defs.append(('CHOOSE_ONCE', ''))\n if self.algo in ['time_once', 'time_on_shape_change']:\n defs.append(('CHOOSE_TIME', ''))\n\n defs.append(('CONV_ALGO', alg))\n\n return defs\n\n def make_node(self, kern, topgrad, output, desc, alpha=None, beta=None):\n ctx_name = infer_context_name(kern, topgrad, output)\n kern = as_gpuarray_variable(kern, ctx_name)\n topgrad = as_gpuarray_variable(topgrad, ctx_name)\n output = as_gpuarray_variable(output, ctx_name)\n if kern.type.ndim not in (4, 5):\n raise TypeError('kern must be 4D or 5D tensor')\n if topgrad.type.ndim not in (4, 5):\n raise TypeError('topgrad must be 4D or 5D tensor')\n if output.type.ndim not in (4, 5):\n raise TypeError('output must be 4D or 5D tensor')\n\n if (kern.type.ndim != topgrad.type.ndim or\n kern.type.ndim != output.type.ndim):\n raise TypeError(\"The number of dimensions of \"\n \"kern, topgrad and output must match\")\n\n if (kern.type.ndim == 5 and\n self.algo in ['fft', 'deterministic', 'fft_tiling']):\n raise ValueError(\"convolution algo %s can't be used for \"\n \"3d convolutions\", (self.algo,))\n\n if (not isinstance(desc.type, CDataType) or\n desc.type.ctype != 'cudnnConvolutionDescriptor_t'):\n raise TypeError('desc must be cudnnConvolutionDescriptor_t')\n\n alpha = ensure_dt(alpha, _one, 'alpha', kern.dtype)\n beta = ensure_dt(beta, _zero, 'beta', kern.dtype)\n\n return Apply(self, [kern, topgrad, output, desc, alpha, beta],\n [output.type()])\n\n def infer_shape(self, node, shape):\n return [shape[2]]\n\n\ndef dnn_conv(img, kerns, border_mode='valid', subsample=(1, 1),\n conv_mode='conv', direction_hint=None, workmem=None,\n algo=None, precision=None):\n \"\"\"\n GPU convolution using cuDNN from NVIDIA.\n\n The memory layout to use is 'bc01', that is 'batch', 'channel',\n 'first dim', 'second dim' in that order.\n\n Parameters\n ----------\n img\n Images to do the convolution over.\n kerns\n Convolution filters.\n border_mode\n One of 'valid', 'full', 'half'; additionally, the padding size\n could be directly specified by an integer or a pair of integers.\n subsample\n Perform subsampling of the output (default: (1, 1)).\n conv_mode\n Perform convolution (kernels flipped) or cross-correlation.\n One of 'conv', 'cross' (default: 'conv').\n direction_hint\n Used by graph optimizers to change algorithm choice.\n By default, GpuDnnConv will be used to carry out the convolution.\n If border_mode is 'valid', subsample is (1, 1) and direction_hint is\n 'bprop weights', it will use GpuDnnConvGradW.\n If border_mode is 'full', subsample is (1, 1) and direction_hint is\n *not* 'forward!', it will use GpuDnnConvGradI.\n This parameter is used internally by graph optimizers and may be\n removed at any time without a deprecation period. You have been warned.\n algo : {'none', 'small', 'large', 'fft', 'guess_once', 'guess_on_shape_change', 'time_once', 'time_on_shape_change'}\n Convolution implementation to use. Some of its values may\n require certain versions of CuDNN to be installed. Default is\n the value of :attr:`config.dnn.conv.algo_fwd`.\n precision : {'as_input', 'float16', 'float32', 'float64'}\n Description of the dtype in which the computation of the convolution\n should be done. Possible values are 'as_input', 'float16', 'float32'\n and 'float64'. Default is the value of\n :attr:`config.dnn.conv.precision`.\n\n .. warning:: The cuDNN library only works with GPUs that have a compute\n capability of 3.0 or higer. This means that older GPUs will not\n work with this Op.\n\n \"\"\"\n\n # Establish dtype in which to perform the computation of the convolution\n if precision is None:\n precision = theano.config.dnn.conv.precision\n if precision == 'as_input':\n precision = theano.scalar.upcast(img.dtype, kerns.dtype)\n\n if workmem is not None:\n if algo is not None:\n raise ValueError(\"You can't use both algo and workmem\")\n warnings.warn(\"workmem is deprecated, use algo instead\", stacklevel=2)\n algo = workmem\n fgraph = getattr(img, 'fgraph', None) or getattr(kerns, 'fgraph', None)\n ctx_name = infer_context_name(img, kerns)\n if (border_mode == 'valid' and subsample == (1, 1) and\n direction_hint == 'bprop weights'):\n # Special case: We are asked to use GpuDnnConvGradW. We need to set\n # up a suitable 'fake' convolution to compute the gradient for.\n img = gpu_contiguous(img.dimshuffle(1, 0, 2, 3))\n if conv_mode == 'conv':\n # We need to flip manually. These 'kerns' are not the kernels\n # that would be flipped by conv_mode='conv' in GpuDnnConvGradW.\n kerns = kerns[:, :, ::-1, ::-1]\n kerns = gpu_contiguous(kerns.dimshuffle(1, 0, 2, 3))\n shape2 = shape_i(img, 2, fgraph) - shape_i(kerns, 2, fgraph) + 1\n shape3 = shape_i(img, 3, fgraph) - shape_i(kerns, 3, fgraph) + 1\n out = GpuAllocEmpty(img.dtype, ctx_name)(\n shape_i(kerns, 1, fgraph),\n shape_i(img, 1, fgraph), shape2, shape3)\n desc = GpuDnnConvDesc(border_mode='valid', subsample=(1, 1),\n conv_mode='cross', precision=precision)(out.shape)\n conv = GpuDnnConvGradW()(img, kerns, out, desc)\n return as_gpuarray_variable(conv.dimshuffle(1, 0, 2, 3), ctx_name)\n\n elif (border_mode == 'full' and subsample == (1, 1) and\n direction_hint != 'forward!'):\n # Special case: We can be faster by using GpuDnnConvGradI to compute\n # the full convolution as the backward pass of a valid convolution.\n # We just need to set up a suitable 'fake' valid convolution.\n img = gpu_contiguous(img) # cudnn v2 rc3 need contiguous data\n kerns = gpu_contiguous(kerns.dimshuffle(1, 0, 2, 3))\n conv_mode = 'cross' if conv_mode == 'conv' else 'conv'\n shape2 = shape_i(img, 2, fgraph) + shape_i(kerns, 2, fgraph) - 1\n shape3 = shape_i(img, 3, fgraph) + shape_i(kerns, 3, fgraph) - 1\n out = GpuAllocEmpty(img.dtype, ctx_name)(shape_i(img, 0, fgraph),\n shape_i(kerns, 1, fgraph),\n shape2, shape3)\n desc = GpuDnnConvDesc(border_mode='valid', subsample=(1, 1),\n conv_mode=conv_mode, precision=precision)(kerns.shape)\n return GpuDnnConvGradI()(kerns, img, out, desc)\n\n # Standard case: We use GpuDnnConv with suitable padding.\n # contig_version will return a gpu_contiguous copy\n # if the img contains negative strides\n img = gpu_contiguous(img)\n kerns = gpu_contiguous(kerns)\n desc = GpuDnnConvDesc(border_mode=border_mode, subsample=subsample,\n conv_mode=conv_mode, precision=precision)(kerns.shape)\n desc_op = desc.owner.op\n out_shp = GpuDnnConv.get_out_shape(img.shape, kerns.shape,\n desc_op.border_mode,\n desc_op.subsample)\n out = GpuAllocEmpty(img.dtype, ctx_name)(*out_shp)\n return GpuDnnConv(algo=algo)(img, kerns, out, desc)\n\n\ndef dnn_gradweight(img, topgrad, kerns_shp, border_mode='valid',\n subsample=(1, 1), conv_mode='conv'):\n ctx_name = infer_context_name(img, topgrad)\n img = as_gpuarray_variable(img, ctx_name)\n topgrad = as_gpuarray_variable(topgrad, ctx_name)\n img = gpu_contiguous(img)\n topgrad = gpu_contiguous(topgrad)\n kerns_shp = as_tensor_variable(kerns_shp)\n desc = GpuDnnConvDesc(border_mode=border_mode, subsample=subsample,\n conv_mode=conv_mode)(kerns_shp)\n out = GpuAllocEmpty(img.dtype, ctx_name)(*kerns_shp)\n return GpuDnnConvGradW()(img, topgrad, out, desc)\n\n\ndef dnn_gradinput(kerns, topgrad, img_shp, border_mode='valid',\n subsample=(1, 1), conv_mode='conv'):\n ctx_name = infer_context_name(kerns, topgrad)\n kerns = as_gpuarray_variable(kerns, ctx_name)\n topgrad = as_gpuarray_variable(topgrad, ctx_name)\n kerns = gpu_contiguous(kerns)\n topgrad = gpu_contiguous(topgrad)\n img_shp = as_tensor_variable(img_shp)\n desc = GpuDnnConvDesc(border_mode=border_mode, subsample=subsample,\n conv_mode=conv_mode)(kerns.shape)\n out = GpuAllocEmpty(kerns.dtype, ctx_name)(*img_shp)\n return GpuDnnConvGradI()(kerns, topgrad, out, desc)\n\n\nclass GpuDnnPoolDesc(Op):\n \"\"\"\n This Op builds a pooling descriptor for use in the other\n pooling operations.\n\n `ws`, `stride` and `pad` must have the same length.\n\n Parameters\n ----------\n ws : tuple\n Window size.\n stride : tuple\n (dx, dy) or (dx, dy, dz).\n mode : {'max', 'average_inc_pad', 'average_exc_pad'}\n The old deprecated name 'average' corresponds to 'average_inc_pad'.\n pad : tuple\n (padX, padY) or (padX, padY, padZ)\n\n \"\"\"\n\n __props__ = ('ws', 'stride', 'mode', 'pad')\n\n def c_headers(self):\n return ['cudnn.h', 'cudnn_helper.h']\n\n def c_header_dirs(self):\n return [os.path.dirname(__file__), config.dnn.include_path]\n\n def c_libraries(self):\n return ['cudnn']\n\n def c_lib_dirs(self):\n return [config.dnn.library_path]\n\n def do_constant_folding(self, node):\n return False\n\n def __init__(self, ws=(1, 1), stride=(1, 1), mode='max', pad=(0, 0)):\n if mode == 'average':\n mode = 'average_inc_pad'\n assert mode in ('max', 'average_inc_pad', 'average_exc_pad')\n self.mode = mode\n\n assert len(ws) == len(stride) and len(stride) == len(pad)\n assert len(ws) in (2, 3)\n self.ws = ws\n self.stride = stride\n self.pad = pad\n\n if self.get_ndim() == 3 and version() < 3000:\n raise RuntimeError(\"CuDNN 3d pooling requires v3\")\n if mode == 'average_exc_pad' and max(pad) > 0 and version() < 4004:\n raise RuntimeError(\n \"CuDNN pooling mode 'average_exc_pad' requires at least v4\")\n\n def get_ndim(self):\n return len(self.ws)\n\n def __setstate__(self, d):\n self.__dict__.update(d)\n if not hasattr(self, 'pad'):\n self.pad = (0, 0)\n\n def make_node(self):\n return Apply(self, [],\n [CDataType(\"cudnnPoolingDescriptor_t\",\n freefunc=\"cudnnDestroyPoolingDescriptor\")()])\n\n def c_code(self, node, name, inputs, outputs, sub):\n desc, = outputs\n\n if self.mode == 'max':\n mode_flag = 'CUDNN_POOLING_MAX'\n elif self.mode == \"average_inc_pad\":\n mode_flag = 'CUDNN_POOLING_AVERAGE_COUNT_INCLUDE_PADDING'\n elif self.mode == \"average_exc_pad\":\n mode_flag = 'CUDNN_POOLING_AVERAGE_COUNT_EXCLUDE_PADDING'\n else:\n raise NotImplementedError(\"Unsupported pooling model.\")\n\n return \"\"\"\n{\n cudnnStatus_t err;\n\n if ((err = cudnnCreatePoolingDescriptor(&%(desc)s)) != CUDNN_STATUS_SUCCESS) {\n PyErr_Format(PyExc_MemoryError, \"could not allocate pooling \"\n \"descriptor: %%s\", cudnnGetErrorString(err));\n %(fail)s\n }\n\n static const int win[%(nd)d] = {%(win)s};\n static const int pad[%(nd)d] = {%(pad)s};\n static const int str[%(nd)d] = {%(str)s};\n err = cudnnSetPoolingNdDescriptor(\n %(desc)s, %(mode_flag)s, %(nd)d,\n win, pad, str);\n if (err != CUDNN_STATUS_SUCCESS) {\n PyErr_Format(PyExc_RuntimeError, \"could not set op descriptor: %%s\",\n cudnnGetErrorString(err));\n %(fail)s\n }\n}\n\"\"\" % dict(name=name, desc=desc, mode_flag=mode_flag, fail=sub['fail'],\n nd=self.get_ndim(), win=', '.join(map(str, self.ws)),\n pad=', '.join(map(str, self.pad)),\n str=', '.join(map(str, self.stride)))\n\n def c_code_cache_version(self):\n return (3, version())\n\n\nclass GpuDnnPool(DnnBase):\n \"\"\"\n Pooling.\n\n Parameters\n ----------\n img\n The image 4d tensor.\n desc\n The pooling descriptor.\n\n \"\"\"\n\n __props__ = ()\n\n def __init__(self):\n DnnBase.__init__(self, [\"dnn_pool.c\"], \"APPLY_SPECIFIC(dnn_pool)\")\n\n def make_node(self, img, desc):\n img = as_gpuarray_variable(img, infer_context_name(img))\n\n if desc.owner is not None:\n e_ndim = desc.owner.op.get_ndim() + 2\n\n if img.type.ndim != e_ndim:\n raise TypeError('img must be %dD tensor' % (e_ndim,))\n\n if (not isinstance(desc.type, CDataType) or\n desc.type.ctype != 'cudnnPoolingDescriptor_t'):\n raise TypeError('desc must be cudnnPoolingDescriptor_t')\n\n return Apply(self, [img, desc], [img.type()])\n\n def infer_shape(self, node, shape):\n desc = node.inputs[1].owner.op\n w = desc.ws\n s = desc.stride\n p = desc.pad\n res = [shape[0][0], shape[0][1],\n (shape[0][2] + 2 * p[0] - w[0]) // s[0] + 1,\n (shape[0][3] + 2 * p[1] - w[1]) // s[1] + 1\n ]\n if len(w) > 2:\n res.append((shape[0][4] + 2 * p[2] - w[2]) // s[2] + 1)\n return [res]\n\n def grad(self, inp, grads):\n img, desc = inp\n grad, = grads\n\n grad = gpu_contiguous(grad)\n\n out = self(img, desc)\n\n g_out = GpuDnnPoolGrad()(img, out, grad, desc)\n\n return g_out, theano.gradient.DisconnectedType()()\n\n def connection_pattern(self, node):\n # not connected to desc\n return [[1], [0]]\n\n\nclass GpuDnnPoolGrad(DnnBase):\n \"\"\"\n The pooling gradient.\n\n Parameters\n ----------\n inp\n The input of the pooling.\n out\n The output of the pooling in the forward.\n out_grad\n Same size as out, but is the corresponding gradient information.\n desc\n The pooling descriptor.\n\n \"\"\"\n\n __props__ = ()\n\n def __init__(self):\n DnnBase.__init__(self, [\"dnn_pool_grad.c\"],\n \"APPLY_SPECIFIC(dnn_pool_grad)\")\n\n def make_node(self, inp, out, out_grad, desc):\n ctx_name = infer_context_name(inp, out, out_grad)\n inp = as_gpuarray_variable(inp, ctx_name)\n out_grad = as_gpuarray_variable(out_grad, ctx_name)\n out = as_gpuarray_variable(out, ctx_name)\n\n if desc.owner is not None:\n nd = desc.owner.op.get_ndim() + 2\n\n if inp.type.ndim != nd:\n raise TypeError('inp must be %dD tensor' % (nd,))\n\n if out_grad.type.ndim != nd:\n raise TypeError('out_grad must be %dD tensor' % (nd,))\n\n if out.type.ndim != nd:\n raise TypeError('out must be %dD tensor' % (nd,))\n\n if (not isinstance(desc.type, CDataType) or\n desc.type.ctype != 'cudnnPoolingDescriptor_t'):\n raise TypeError('desc must be cudnnPoolingDescriptor_t')\n\n return Apply(self, [inp, out, out_grad, desc], [inp.type()])\n\n def infer_shape(self, node, shape):\n return [shape[0]]\n\n\ndef dnn_pool(img, ws, stride=(1, 1), mode='max', pad=(0, 0)):\n \"\"\"\n GPU pooling using cuDNN from NVIDIA.\n\n The memory layout to use is 'bc01', that is 'batch', 'channel',\n 'first dim', 'second dim' in that order.\n\n `ws`, `stride` and `pad` must have the same length.\n\n Parameters\n ----------\n img\n Images to do the pooling over.\n ws : tuple\n Subsampling window size.\n stride : tuple\n Subsampling stride (default: (1, 1)).\n mode : {'max', 'average_inc_pad', 'average_exc_pad'}\n pad : tuple\n (padX, padY) or (padX, padY, padZ)\n default: (0, 0)\n\n .. warning:: The cuDNN library only works with GPU that have a compute\n capability of 3.0 or higer. This means that older GPU will not\n work with this Op.\n\n Notes\n -----\n This Op implements the ignore_border=True of max_pool_2d.\n\n \"\"\"\n img = gpu_contiguous(img)\n desc = GpuDnnPoolDesc(ws=ws, stride=stride, mode=mode, pad=pad)()\n return GpuDnnPool()(img, desc)\n\n\nclass GpuDnnSoftmaxBase(DnnBase):\n \"\"\"\n Op for the cuDNN Softmax.\n\n Parameters\n ----------\n algo\n 'fast', 'accurate' or 'log' indicating whether, respectively,\n computations should be optimized for speed, for accuracy, or if CuDNN\n should rather compute the log-softmax instead.\n mode\n 'instance' or 'channel' indicating whether the softmax should be\n computed per image across 'c01' or per spatial location '01' per\n image across 'c'.\n\n \"\"\"\n\n __props__ = ('mode', 'algo')\n\n def __init__(self, algo, mode):\n DnnBase.__init__(self, [self.file], self.c_func)\n\n assert(algo in ('fast', 'accurate', 'log'))\n if algo == 'log' and version(raises=False) < 3000:\n raise RuntimeError(\"Need CuDNN v3 for log-softmax\")\n self.algo = algo\n\n assert(mode in ('instance', 'channel'))\n self.mode = mode\n\n def infer_shape(self, node, shape):\n if self.direction == 'forward':\n return [shape[0]]\n else:\n return [shape[1]]\n\n def get_op_params(self):\n if self.mode == 'instance':\n mode = \"CUDNN_SOFTMAX_MODE_INSTANCE\"\n else:\n mode = \"CUDNN_SOFTMAX_MODE_CHANNEL\"\n\n if self.algo == 'fast':\n algo = \"CUDNN_SOFTMAX_FAST\"\n elif self.algo == 'log':\n algo = \"CUDNN_SOFTMAX_LOG\"\n else:\n algo = \"CUDNN_SOFTMAX_ACCURATE\"\n\n return [(\"SOFTMAX_MODE\", mode), (\"SOFTMAX_ALGO\", algo)]\n\n\nclass GpuDnnSoftmax(GpuDnnSoftmaxBase):\n \"\"\"\n Op for the cuDNN Softmax.\n\n algo\n 'fast', 'accurate' or 'log' indicating whether, respectively,\n computations should be optimized for speed, for accuracy, or if CuDNN\n should rather compute the log-softmax instead.\n mode\n 'instance' or 'channel' indicating whether the softmax should be\n computed per image across 'c01' or per spatial location '01' per\n image across 'c'.\n\n \"\"\"\n direction = \"forward\"\n file = \"dnn_softmax.c\"\n c_func = \"APPLY_SPECIFIC(softmax)\"\n\n def make_node(self, x):\n x = as_gpuarray_variable(x, infer_context_name(x))\n assert x.ndim == 4\n return Apply(self, [x], [x.type()])\n\n def grad(self, inp, grads):\n x, = inp\n g_sm, = grads\n sm = self.make_node(x).outputs[0]\n return [GpuDnnSoftmaxGrad(\n self.algo,\n self.mode\n )(g_sm, sm)]\n\n\nclass GpuDnnSoftmaxGrad(GpuDnnSoftmaxBase):\n \"\"\"\n Op for the cuDNN SoftmaxGrad.\n\n Parameters\n ----------\n algo\n 'fast', 'accurate' or 'log' indicating whether, respectively,\n computations should be optimized for speed, for accuracy, or if CuDNN\n should rather compute the gradient of the log-softmax instead.\n mode\n 'instance' or 'channel' indicating whether the softmax should\n be computed per image across 'c01' or per spatial location '01' per\n image across 'c'.\n\n \"\"\"\n direction = 'backward'\n file = \"dnn_softmax_grad.c\"\n c_func = \"APPLY_SPECIFIC(softmax_grad)\"\n\n def make_node(self, dy, sm):\n ctx_name = infer_context_name(dy, sm)\n dy = as_gpuarray_variable(dy, ctx_name)\n sm = as_gpuarray_variable(sm, ctx_name)\n assert dy.ndim == 4\n assert sm.ndim == 4\n return Apply(self, [dy, sm], [sm.type()])\n\n\n@local_optimizer([AbstractConv2d, AbstractConv2d_gradWeights,\n AbstractConv2d_gradInputs])\ndef local_abstractconv_cudnn(node):\n if (not isinstance(node.op, (AbstractConv2d,\n AbstractConv2d_gradWeights,\n AbstractConv2d_gradInputs))):\n return None\n\n inp1 = node.inputs[0]\n inp2 = node.inputs[1]\n\n if not isinstance(inp1.type, GpuArrayType):\n return None\n\n if not dnn_available(inp1.type.context_name):\n raise_no_cudnn()\n\n if node.op.filter_flip:\n conv_mode = 'conv'\n else:\n conv_mode = 'cross'\n\n if isinstance(node.op, AbstractConv2d):\n rval = dnn_conv(inp1, inp2,\n border_mode=node.op.border_mode,\n subsample=node.op.subsample,\n direction_hint='forward!',\n conv_mode=conv_mode)\n if isinstance(node.op, AbstractConv2d_gradWeights):\n shape = (inp2.shape[1], inp1.shape[1],\n node.inputs[2][0], node.inputs[2][1])\n rval = dnn_gradweight(inp1, inp2, shape,\n border_mode=node.op.border_mode,\n subsample=node.op.subsample,\n conv_mode=conv_mode)\n if isinstance(node.op, AbstractConv2d_gradInputs):\n shape = (inp2.shape[0], inp1.shape[1],\n node.inputs[2][0], node.inputs[2][1])\n rval = dnn_gradinput(inp1, inp2, shape,\n border_mode=node.op.border_mode,\n subsample=node.op.subsample,\n conv_mode=conv_mode)\n return [rval]\n\nconv_groupopt.register('local_abstractconv_cudnn',\n local_abstractconv_cudnn, 20,\n 'fast_compile', 'fast_run',\n 'gpuarray', 'conv_dnn', 'cudnn')\n\n\n@inplace_allocempty(GpuDnnConv, 2)\ndef local_dnn_conv_inplace(node, inputs):\n return [GpuDnnConv(algo=node.op.algo, inplace=True)(*inputs)]\n\n\n@inplace_allocempty(GpuDnnConvGradW, 2)\ndef local_dnn_convgw_inplace(node, inputs):\n return [GpuDnnConvGradW(algo=node.op.algo, inplace=True)(*inputs)]\n\n\n@inplace_allocempty(GpuDnnConvGradI, 2)\ndef local_dnn_convgi_inplace(node, inputs):\n return [GpuDnnConvGradI(algo=node.op.algo, inplace=True)(*inputs)]\n\noptdb.register('local_dnna_conv_inplace',\n tensor.opt.in2out(local_dnn_conv_inplace,\n local_dnn_convgw_inplace,\n local_dnn_convgi_inplace,\n name=\"local_dnna_conv_inplace\"),\n 70.0, 'fast_run', 'inplace', 'gpuarray', 'cudnn')\n\n\n@register_opt('cudnn')\n@alpha_merge(GpuDnnConv, alpha_in=4, beta_in=5)\ndef local_dnn_conv_alpha_merge(node, *inputs):\n return [GpuDnnConv(algo=node.op.algo)(*inputs)]\n\n\n@register_opt('cudnn')\n@alpha_merge(GpuDnnConvGradW, alpha_in=4, beta_in=5)\ndef local_dnn_convw_alpha_merge(node, *inputs):\n return [GpuDnnConvGradW(algo=node.op.algo)(*inputs)]\n\n\n@register_opt('cudnn')\n@alpha_merge(GpuDnnConvGradI, alpha_in=4, beta_in=5)\ndef local_dnn_convi_alpha_merge(node, *inputs):\n return [GpuDnnConvGradI(algo=node.op.algo)(*inputs)]\n\n\n@register_opt('cudnn')\n@output_merge(GpuDnnConv, alpha_in=4, beta_in=5, out_in=2)\ndef local_dnn_conv_output_merge(node, *inputs):\n inputs = inputs[0:2] + (gpu_contiguous(inputs[2]),) + inputs[3:]\n return [GpuDnnConv(algo=node.op.algo)(*inputs)]\n\n\n@register_opt('cudnn')\n@output_merge(GpuDnnConvGradW, alpha_in=4, beta_in=5, out_in=2)\ndef local_dnn_convw_output_merge(node, *inputs):\n inputs = inputs[0:2] + (gpu_contiguous(inputs[2]),) + inputs[3:]\n return [GpuDnnConvGradW(algo=node.op.algo)(*inputs)]\n\n\n@register_opt('cudnn')\n@output_merge(GpuDnnConvGradI, alpha_in=4, beta_in=5, out_in=2)\ndef local_dnn_convi_output_merge(node, *inputs):\n inputs = inputs[0:2] + (gpu_contiguous(inputs[2]),) + inputs[3:]\n return [GpuDnnConvGradI(algo=node.op.algo)(*inputs)]\n\n\n@register_opt('cudnn')\n@op_lifter([Pool])\ndef local_pool_dnn_alternative(node, ctx_name):\n if not dnn_available(ctx_name):\n raise_no_cudnn()\n if not node.op.ignore_border:\n return\n img, = node.inputs\n img = as_gpuarray_variable(img, ctx_name)\n ds = node.op.ds\n stride = node.op.st\n pad = node.op.padding\n mode = node.op.mode\n return dnn_pool(gpu_contiguous(img), ds, stride=stride, pad=pad, mode=mode)\n\n\n@register_opt('cudnn')\n@op_lifter([MaxPoolGrad])\ndef local_pool_dnn_grad_stride(node, ctx_name):\n if not dnn_available(ctx_name):\n raise_no_cudnn()\n if not node.op.ignore_border:\n return\n inp, out, out_grad = node.inputs\n inp = as_gpuarray_variable(inp, ctx_name)\n out = as_gpuarray_variable(out, ctx_name)\n out_grad = as_gpuarray_variable(out_grad, ctx_name)\n ds = node.op.ds\n st = node.op.st\n pad = node.op.padding\n mode = node.op.mode\n\n desc = GpuDnnPoolDesc(ws=ds, stride=st, mode=mode, pad=pad)()\n return GpuDnnPoolGrad()(gpu_contiguous(inp),\n gpu_contiguous(out),\n gpu_contiguous(out_grad),\n desc)\n\n\n@register_opt('cudnn')\n@op_lifter([AveragePoolGrad])\ndef local_avg_pool_dnn_grad_stride(node, ctx_name):\n if not dnn_available(ctx_name):\n raise_no_cudnn()\n if not node.op.ignore_border:\n return\n inp, out_grad = node.inputs\n inp = as_gpuarray_variable(inp, ctx_name)\n out_grad = as_gpuarray_variable(out_grad, ctx_name)\n ds = node.op.ds\n st = node.op.st\n pad = node.op.padding\n mode = node.op.mode\n\n cg = gpu_contiguous(out_grad)\n\n desc = GpuDnnPoolDesc(ws=ds, stride=st, mode=mode, pad=pad)()\n # We reuse cg because CuDNN does not use the value of the `out`\n # argument but still checks its shape for average pooling. This\n # has been observed in v2 and v3 as far as I know.\n return GpuDnnPoolGrad()(gpu_contiguous(inp), cg, cg, desc)\n\n\n@register_opt('cudnn')\n@local_optimizer([GpuSoftmax])\ndef local_softmax_dnn(node):\n if isinstance(node.op, GpuSoftmax):\n if not dnn_available(node.outputs[0].type.context_name):\n raise_no_cudnn()\n ins = node.inputs[0].dimshuffle(0, 1, 'x', 'x')\n ins = gpu_contiguous(ins)\n out = GpuDnnSoftmax('accurate', 'channel')(ins)\n out = as_gpuarray_variable(out.dimshuffle(0, 1), out.type.context_name)\n return [out]\n\n\n@register_opt('cudnn')\n@local_optimizer([GpuElemwise])\ndef local_log_softmax_dnn(node):\n # This looks for GpuDnnSoftmax so we know that we have cudnn.\n if (isinstance(node.op, GpuElemwise) and\n isinstance(node.op.scalar_op, Log) and\n node.inputs[0].owner and\n isinstance(node.inputs[0].owner.op, GpuDnnSoftmax) and\n len(node.inputs[0].clients) == 1):\n if version(raises=False) < 3000:\n # No log-softmax before cudnn v3\n raise_no_cudnn(\"Need CuDNN v3 for LogSoftmax\")\n softmax_node = node.inputs[0].owner\n new_softmax = GpuDnnSoftmax('log', softmax_node.op.mode)\n return [new_softmax(softmax_node.inputs[0])]\n\n\n@register_opt('cudnn')\n@op_lifter([LogSoftmax])\ndef local_logsoftmax_to_dnn(node, ctx_name):\n # Transform the input in the format expected by GpuDnnSoftmax\n inp = node.inputs[0]\n if inp.ndim != 2:\n return\n if not dnn_available(ctx_name) or version(raises=False) < 3000:\n # No log-softmax before cudnn v3\n raise_no_cudnn(\"Need CuDNN v3 for LogSoftmax\")\n\n inp = inp.dimshuffle(0, 1, 'x', 'x')\n inp.tag.context_name = ctx_name\n\n # Apply GpuDnnSoftmax and return the result\n out = GpuDnnSoftmax('log', 'channel')(gpu_contiguous(inp))\n return [out.dimshuffle(0, 1)]\n\n\nclass NoCuDNNRaise(Optimizer):\n def apply(self, fgraph):\n \"\"\"\n Raise a error if cudnn can't be used.\n\n \"\"\"\n for c in list_contexts():\n if not dnn_available(c):\n # Make an assert error as we want Theano to fail, not\n # just skip this optimization.\n raise AssertionError(\n \"cuDNN optimization was enabled, but Theano was not able \"\n \"to use it for context \" + c + \". We got this error: \\n\" +\n dnn_available.msg)\n\ngpu_seqopt.register(\"NoCuDNNRaise\", NoCuDNNRaise(), 0, 'cudnn')\n\n\n@register_opt('cudnn')\n@op_lifter([SoftmaxGrad])\ndef local_softmax_dnn_grad(node, ctx_name):\n if not dnn_available(ctx_name):\n raise_no_cudnn(\"CuDNN needed for SoftmaxGrad\")\n ins = []\n for n in node.inputs:\n n = as_gpuarray_variable(n, ctx_name)\n if n.ndim != 2:\n return\n ins.append(n.dimshuffle(0, 1, 'x', 'x'))\n\n out = GpuDnnSoftmaxGrad('accurate', 'channel')(\n gpu_contiguous(ins[0]), gpu_contiguous(ins[1]))\n return [out.dimshuffle(0, 1)]\n", "meta": {"hexsha": "297921770b703b21f42d0ffc0129998b0e8f7138", "size": 54335, "ext": "py", "lang": "Python", "max_stars_repo_path": "theano/sandbox/gpuarray/dnn.py", "max_stars_repo_name": "koningrobot/Theano", "max_stars_repo_head_hexsha": "2fe88f363944cee9f189ab03c735a49795359005", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "theano/sandbox/gpuarray/dnn.py", "max_issues_repo_name": "koningrobot/Theano", "max_issues_repo_head_hexsha": "2fe88f363944cee9f189ab03c735a49795359005", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "theano/sandbox/gpuarray/dnn.py", "max_forks_repo_name": "koningrobot/Theano", "max_forks_repo_head_hexsha": "2fe88f363944cee9f189ab03c735a49795359005", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6524234694, "max_line_length": 120, "alphanum_fraction": 0.6016011779, "include": true, "reason": "import numpy,import theano,from theano", "num_tokens": 13921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.22541662103868043, "lm_q1q2_score": 0.11886590891808635}} {"text": "import ROOT as root\nimport numpy as np\nimport time\nimport uncertainties.unumpy as unp\nfrom uncertainties import ufloat\nfrom uncertainties.unumpy import nominal_values as noms\nfrom uncertainties.unumpy import std_devs as stds\nfrom uncertainties import correlated_values\nfrom array import array\nimport os\n\n\n ########################## Data of .C file, insert data underneath ######################################\n#!!!!!!!!!!!!!!!! ATTENTION !!!!!!!!!!!!!!!!!!!! At 13 mm I had to use the not zoomed version of .C, becuase the other do not include any data !!!!!!!!!!!!!!!!!!!!!!!!\n\n\nqMap_Ag_C0_V0 = root.TProfile2D(\"qMap_Ag_C0_V0\",\"qMap_Ag_C0 (V0)\",52,0,52,80,0,80,0,0);\nqMap_Ag_C0_V0.SetBinEntries(2344,19);\nqMap_Ag_C0_V0.SetBinEntries(2345,14183);\nqMap_Ag_C0_V0.SetBinEntries(2346,14333);\nqMap_Ag_C0_V0.SetBinEntries(2347,2);\nqMap_Ag_C0_V0.SetBinEntries(2398,16046);\nqMap_Ag_C0_V0.SetBinEntries(2399,17020);\nqMap_Ag_C0_V0.SetBinEntries(2400,14729);\nqMap_Ag_C0_V0.SetBinEntries(2401,14369);\nqMap_Ag_C0_V0.SetBinEntries(2451,14419);\nqMap_Ag_C0_V0.SetBinEntries(2452,32449);\nqMap_Ag_C0_V0.SetBinEntries(2453,32476);\nqMap_Ag_C0_V0.SetBinEntries(2454,25302);\nqMap_Ag_C0_V0.SetBinEntries(2455,14472);\nqMap_Ag_C0_V0.SetBinEntries(2505,14523);\nqMap_Ag_C0_V0.SetBinEntries(2506,44794);\nqMap_Ag_C0_V0.SetBinEntries(2507,51170);\nqMap_Ag_C0_V0.SetBinEntries(2508,33516);\nqMap_Ag_C0_V0.SetBinEntries(2509,20073);\nqMap_Ag_C0_V0.SetBinEntries(2559,14075);\nqMap_Ag_C0_V0.SetBinEntries(2560,48868);\nqMap_Ag_C0_V0.SetBinEntries(2561,58641);\nqMap_Ag_C0_V0.SetBinEntries(2562,42812);\nqMap_Ag_C0_V0.SetBinEntries(2563,17004);\nqMap_Ag_C0_V0.SetBinEntries(2613,14522);\nqMap_Ag_C0_V0.SetBinEntries(2614,51382);\nqMap_Ag_C0_V0.SetBinEntries(2615,50565);\nqMap_Ag_C0_V0.SetBinEntries(2616,44027);\nqMap_Ag_C0_V0.SetBinEntries(2617,21044);\nqMap_Ag_C0_V0.SetBinEntries(2618,26);\nqMap_Ag_C0_V0.SetBinEntries(2668,39093);\nqMap_Ag_C0_V0.SetBinEntries(2669,39409);\nqMap_Ag_C0_V0.SetBinEntries(2670,30846);\nqMap_Ag_C0_V0.SetBinEntries(2671,18157);\nqMap_Ag_C0_V0.SetBinEntries(2723,17396);\nqMap_Ag_C0_V0.SetBinEntries(2724,14476);\nqMap_Ag_C0_V0.SetBinContent(2344,1727);\nqMap_Ag_C0_V0.SetBinContent(2345,1541144);\nqMap_Ag_C0_V0.SetBinContent(2346,1448396);\nqMap_Ag_C0_V0.SetBinContent(2347,188);\nqMap_Ag_C0_V0.SetBinContent(2398,1930663);\nqMap_Ag_C0_V0.SetBinContent(2399,2260151);\nqMap_Ag_C0_V0.SetBinContent(2400,1813706);\nqMap_Ag_C0_V0.SetBinContent(2401,1458013);\nqMap_Ag_C0_V0.SetBinContent(2451,1170875);\nqMap_Ag_C0_V0.SetBinContent(2452,3727473);\nqMap_Ag_C0_V0.SetBinContent(2453,4640774);\nqMap_Ag_C0_V0.SetBinContent(2454,3218252);\nqMap_Ag_C0_V0.SetBinContent(2455,1685736);\nqMap_Ag_C0_V0.SetBinContent(2505,1776388);\nqMap_Ag_C0_V0.SetBinContent(2506,5142724);\nqMap_Ag_C0_V0.SetBinContent(2507,6040486);\nqMap_Ag_C0_V0.SetBinContent(2508,4818365);\nqMap_Ag_C0_V0.SetBinContent(2509,2239111);\nqMap_Ag_C0_V0.SetBinContent(2559,1975378);\nqMap_Ag_C0_V0.SetBinContent(2560,5531553);\nqMap_Ag_C0_V0.SetBinContent(2561,8887634);\nqMap_Ag_C0_V0.SetBinContent(2562,1.672008e+07);\nqMap_Ag_C0_V0.SetBinContent(2563,2151277);\nqMap_Ag_C0_V0.SetBinContent(2613,1603932);\nqMap_Ag_C0_V0.SetBinContent(2614,5852932);\nqMap_Ag_C0_V0.SetBinContent(2615,5665718);\nqMap_Ag_C0_V0.SetBinContent(2616,5689668);\nqMap_Ag_C0_V0.SetBinContent(2617,2508568);\nqMap_Ag_C0_V0.SetBinContent(2618,2136);\nqMap_Ag_C0_V0.SetBinContent(2668,4186165);\nqMap_Ag_C0_V0.SetBinContent(2669,4672891);\nqMap_Ag_C0_V0.SetBinContent(2670,3811861);\nqMap_Ag_C0_V0.SetBinContent(2671,2255823);\nqMap_Ag_C0_V0.SetBinContent(2723,2049516);\nqMap_Ag_C0_V0.SetBinContent(2724,1700067);\nqMap_Ag_C0_V0.SetBinError(2344,402.8734);\nqMap_Ag_C0_V0.SetBinError(2345,12979.8);\nqMap_Ag_C0_V0.SetBinError(2346,12166.45);\nqMap_Ag_C0_V0.SetBinError(2347,134.4024);\nqMap_Ag_C0_V0.SetBinError(2398,93836.64);\nqMap_Ag_C0_V0.SetBinError(2399,161228.9);\nqMap_Ag_C0_V0.SetBinError(2400,114305.9);\nqMap_Ag_C0_V0.SetBinError(2401,12252.54);\nqMap_Ag_C0_V0.SetBinError(2451,9901.228);\nqMap_Ag_C0_V0.SetBinError(2452,147939.1);\nqMap_Ag_C0_V0.SetBinError(2453,293709.8);\nqMap_Ag_C0_V0.SetBinError(2454,218026.8);\nqMap_Ag_C0_V0.SetBinError(2455,14092.93);\nqMap_Ag_C0_V0.SetBinError(2505,14969.22);\nqMap_Ag_C0_V0.SetBinError(2506,26160.92);\nqMap_Ag_C0_V0.SetBinError(2507,198427.4);\nqMap_Ag_C0_V0.SetBinError(2508,246180.4);\nqMap_Ag_C0_V0.SetBinError(2509,16509.44);\nqMap_Ag_C0_V0.SetBinError(2559,16717.33);\nqMap_Ag_C0_V0.SetBinError(2560,27341.63);\nqMap_Ag_C0_V0.SetBinError(2561,366223.7);\nqMap_Ag_C0_V0.SetBinError(2562,886649);\nqMap_Ag_C0_V0.SetBinError(2563,16870.58);\nqMap_Ag_C0_V0.SetBinError(2613,13409.44);\nqMap_Ag_C0_V0.SetBinError(2614,29248.24);\nqMap_Ag_C0_V0.SetBinError(2615,96545.96);\nqMap_Ag_C0_V0.SetBinError(2616,208872.5);\nqMap_Ag_C0_V0.SetBinError(2617,17967.6);\nqMap_Ag_C0_V0.SetBinError(2618,423.1099);\nqMap_Ag_C0_V0.SetBinError(2668,69887.67);\nqMap_Ag_C0_V0.SetBinError(2669,148421.3);\nqMap_Ag_C0_V0.SetBinError(2670,161830.9);\nqMap_Ag_C0_V0.SetBinError(2671,17107.6);\nqMap_Ag_C0_V0.SetBinError(2723,16283.99);\nqMap_Ag_C0_V0.SetBinError(2724,14283.94);\nqMap_Ag_C0_V0.SetMinimum(0);\nqMap_Ag_C0_V0.SetEntries(896238);\nqMap_Ag_C0_V0.SetStats(0);\nqMap_Ag_C0_V0.SetContour(20);\nqMap_Ag_C0_V0.SetContourLevel(0,0);\nqMap_Ag_C0_V0.SetContourLevel(1,19.52733);\nqMap_Ag_C0_V0.SetContourLevel(2,39.05465);\nqMap_Ag_C0_V0.SetContourLevel(3,58.58198);\nqMap_Ag_C0_V0.SetContourLevel(4,78.10931);\nqMap_Ag_C0_V0.SetContourLevel(5,97.63663);\nqMap_Ag_C0_V0.SetContourLevel(6,117.164);\nqMap_Ag_C0_V0.SetContourLevel(7,136.6913);\nqMap_Ag_C0_V0.SetContourLevel(8,156.2186);\nqMap_Ag_C0_V0.SetContourLevel(9,175.7459);\nqMap_Ag_C0_V0.SetContourLevel(10,195.2733);\nqMap_Ag_C0_V0.SetContourLevel(11,214.8006);\nqMap_Ag_C0_V0.SetContourLevel(12,234.3279);\nqMap_Ag_C0_V0.SetContourLevel(13,253.8552);\nqMap_Ag_C0_V0.SetContourLevel(14,273.3826);\nqMap_Ag_C0_V0.SetContourLevel(15,292.9099);\nqMap_Ag_C0_V0.SetContourLevel(16,312.4372);\nqMap_Ag_C0_V0.SetContourLevel(17,331.9645);\nqMap_Ag_C0_V0.SetContourLevel(18,351.4919);\nqMap_Ag_C0_V0.SetContourLevel(19,371.0192);\n\nci = root.TColor.GetColor(\"#000099\");\nqMap_Ag_C0_V0.SetLineColor(ci);\nqMap_Ag_C0_V0.GetXaxis().SetTitle(\"col\");\nqMap_Ag_C0_V0.GetXaxis().SetRange(1,52);\nqMap_Ag_C0_V0.GetXaxis().SetNdivisions(508);\nqMap_Ag_C0_V0.GetXaxis().SetLabelFont(42);\nqMap_Ag_C0_V0.GetXaxis().SetLabelSize(0.05);\nqMap_Ag_C0_V0.GetXaxis().SetTitleSize(0.05);\nqMap_Ag_C0_V0.GetXaxis().SetTitleOffset(1.1);\nqMap_Ag_C0_V0.GetXaxis().SetTitleFont(42);\nqMap_Ag_C0_V0.GetYaxis().SetTitle(\"row\");\nqMap_Ag_C0_V0.GetYaxis().SetRange(1,80);\nqMap_Ag_C0_V0.GetYaxis().SetLabelFont(42);\nqMap_Ag_C0_V0.GetYaxis().SetLabelSize(0.05);\nqMap_Ag_C0_V0.GetYaxis().SetTitleSize(0.05);\nqMap_Ag_C0_V0.GetYaxis().SetTitleOffset(1.1);\nqMap_Ag_C0_V0.GetYaxis().SetTitleFont(42);\nqMap_Ag_C0_V0.GetZaxis().SetLabelFont(42);\nqMap_Ag_C0_V0.GetZaxis().SetLabelSize(0.035);\nqMap_Ag_C0_V0.GetZaxis().SetTitleSize(0.035);\nqMap_Ag_C0_V0.GetZaxis().SetTitleFont(42);\n\nroot.gStyle.SetOptTitle(0)\n##################################################### Insert Data above line #############################\n\n\n\n\n############################### Get name of folder #################################\n\nname_of_folder = os.path.basename( os.getcwd() )\n\n\n############################### Save Data in list #######################################\n\nmean_value_col_list = []\nmean_error_col_list = []\nx_value = []\ny_value = []\n\n\n##############################################################################################################################\n\n################################### Getting the mean hit value of all columns near the laserspot #############################\n\n###############################################################################################################################\n\n\n################################## Set sum area ###############################\n\nxmin = 18\nxmax = 27\n\nymin = 40\nymax = 52\n\n#################################### calculating mean of each coloum ################################\n\nfor i in range(xmin,xmax): # going thru all col\n content = []\n error = []\n\n x_value.append(i)\n y_value.append(0)\n\n for j in range(ymin,ymax): # going thru all rows\n content.append( qMap_Ag_C0_V0.GetBinContent(i,j))\n error.append( qMap_Ag_C0_V0.GetBinError(i,j)) # Is this the real error\n\n content_bin = unp.uarray( content, error)\n mean_content_col = content_bin.mean() # mean value of each bin in the col\n\n # Saving values in lists\n mean_value_col_list.append( noms(mean_content_col))\n mean_error_col_list.append( stds(mean_content_col))\n\n\n########################### Create errorbar plot #####################################\n\nerrorbar_plot_col = root.TGraphErrors( len(x_value), array( 'f', x_value), array( 'f', mean_value_col_list), array( 'f', y_value), array( 'f', mean_error_col_list) )\n\n############################## Set axis label of errobar plot ##################################\n\nerrorbar_plot_col.GetXaxis().SetTitle(\"Col\")\nerrorbar_plot_col.GetYaxis().SetTitle(\"Mean Hit / Vcal\")\n\n####################### create Canvas ##########################################\n\nc1 = root.TCanvas(\"c1\", \"c1\", 1980, 1080)\nerrorbar_plot_col.Fit('gaus')\nerrorbar_plot_col.Draw(\"ALP\")\n\nname_params = [ \"amplitude/[MeanVcal]\", \"mean/[Col]\", \"sigma/[Col]\"]\n\n############################### Create legend ####################################\ngaus_fit_col = errorbar_plot_col.GetFunction('gaus')\nlegend = root.TLegend(0.75,0.75,0.98,0.98)\nlegend.AddEntry(errorbar_plot_col,\"Coloumn mean hit value\",\"lep\")\nlegend.AddEntry( gaus_fit_col,\"Gaussian Fit\",\"l\")\nlegend.Draw()\n\n############################### Save parameter and plot ###########################################\n\nwith open( f'../fit_params/{name_of_folder}_fit_parameters_col_xaxis.txt', 'w') as file:\n for i in range(0,3):\n file.write( name_params[i] + ' ' + str( gaus_fit_col.GetParameter(i) ) + ' ' + str(gaus_fit_col.GetParError(i)) + '\\n')\n\nwith open( f'../sigma_col_xaxis.txt', 'a') as file:\n file.write( name_params[i] + '_' + name_of_folder + ' ' + str( gaus_fit_col.GetParameter(2) ) + ' ' + str(gaus_fit_col.GetParError(2)) + '\\n')\n\n\nc1.SaveAs(f'../plots/{name_of_folder}_erorbar_plot_col.pdf')\n\n\n\n##############################################################################################################################\n\n################################### Getting the mean hit value of all rows near the laserspot #############################\n\n###############################################################################################################################\n\n\n############################Reset lists###########################################\nmean_value_col_list = []\nmean_error_col_list = []\nx_value = []\ny_value = []\n\n\n#################################### calculating mean of each row #####################################\n\nfor i in range(ymin,ymax): # going thru all rows\n content = []\n error = []\n\n x_value.append(i)\n y_value.append(0)\n\n for j in range(xmin,xmax): # going thru all col\n content.append( qMap_Ag_C0_V0.GetBinContent(j,i))\n error.append( qMap_Ag_C0_V0.GetBinError(j,i)) # Is this the real error\n\n content_bin = unp.uarray( content, error)\n mean_content_col = content_bin.mean() # mean value of each bin in the col\n\n # Saving values in lists\n mean_value_col_list.append( noms(mean_content_col))\n mean_error_col_list.append( stds(mean_content_col))\n\n\n############################# Create new errorbar plot ####################################\nerrorbar_plot_rows = root.TGraphErrors( len(x_value), array( 'f', x_value), array( 'f', mean_value_col_list), array( 'f', y_value), array( 'f', mean_error_col_list) )\n\n############################### create Canvas ########################################\nc2 = root.TCanvas(\"c2\", \"c2\", 1980, 1080);\n\n############################## Set axis label of errobar plot ##################################\n\nerrorbar_plot_rows.GetXaxis().SetTitle(\"Row\")\nerrorbar_plot_rows.GetYaxis().SetTitle(\"Mean Hit / Vcal\")\n\n\n############################### Plot fucntion and fit #############################################\nerrorbar_plot_rows.Fit('gaus')\nerrorbar_plot_rows.Draw(\"ALP\")\n\n##################################### create legend ################################################\ngaus_fit_row = errorbar_plot_rows.GetFunction('gaus')\nlegend = root.TLegend(0.75,0.75,0.98,0.98)\nlegend.AddEntry(errorbar_plot_rows,\"Mean Mean Vcal of each row\",\"lep\")\nlegend.AddEntry( gaus_fit_row,\"Gaussian Fit\",\"l\")\nlegend.Draw()\n\n########################################### saveplot and fit params ########################################\nwith open( f'../fit_params/{name_of_folder}_fit_parameters_row_yaxis.txt', 'w') as file:\n for i in range(0,3):\n file.write( name_params[i] + ' ' + str( gaus_fit_row.GetParameter(i) ) + ' ' + str(gaus_fit_row.GetParError(i)) + '\\n')\n\nwith open( f'../sigma_row_yaxis.txt', 'a') as file:\n file.write( name_params[i] +'_' + name_of_folder + ' ' + str( gaus_fit_row.GetParameter(2) ) + ' ' + str(gaus_fit_row.GetParError(2)) + '\\n')\n\n\nc2.SaveAs(f'../plots/{name_of_folder}_erorbar_plot_row.pdf')\n", "meta": {"hexsha": "0fa0dc2cfbc7f71968f0978a0b6f8c5b7cbc4195", "size": 13166, "ext": "py", "lang": "Python", "max_stars_repo_path": "laser_width/first_position/13_mm/pyroot_analyse.py", "max_stars_repo_name": "beckstev/purdue_laser_box", "max_stars_repo_head_hexsha": "aa4fbf2f3cf6a43fea0a8939d2b22005ffae9bc0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "laser_width/first_position/13_mm/pyroot_analyse.py", "max_issues_repo_name": "beckstev/purdue_laser_box", "max_issues_repo_head_hexsha": "aa4fbf2f3cf6a43fea0a8939d2b22005ffae9bc0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "laser_width/first_position/13_mm/pyroot_analyse.py", "max_forks_repo_name": "beckstev/purdue_laser_box", "max_forks_repo_head_hexsha": "aa4fbf2f3cf6a43fea0a8939d2b22005ffae9bc0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7764350453, "max_line_length": 167, "alphanum_fraction": 0.6617803433, "include": true, "reason": "import numpy", "num_tokens": 4286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.21733751090819795, "lm_q1q2_score": 0.118826709070884}} {"text": "from typing import List, Dict, Any, Tuple\nfrom pathlib import Path\nimport re\nimport numpy as np\nimport pandas as pd\nfrom xml.etree.ElementTree import Element # noqa: S405\nimport defusedxml.ElementTree as ET\nfrom resistics.time import ChanMetadata\nfrom resistics.calibrate import SensorCalibrationReader, CalibrationData\nfrom resistics.spectra import SpectraMetadata\n\n\nclass SensorCalibration_RSP_RSPX_Base(SensorCalibrationReader):\n \"\"\"Base class for RSP and RSPX calibration data readers\"\"\"\n\n file_str: str = \"Metronix_Coil-----TYPE-$sensor_$chopper-ID-$serial$extension\"\n \"\"\"The file string to search for. Various parameters will be substituted\"\"\"\n\n def _get_path(self, dir_path: Path, metadata: SpectraMetadata, chan: str) -> Path:\n \"\"\"\n Get the path to the calibration file\n\n Parameters\n ----------\n dir_path : Path\n The directory path to look for calibration files\n metadata : SpectraMetadata\n SpectraMetadata with data information\n chan : str\n The channel to calibrate\n\n Returns\n -------\n Path\n The path to the calibration file\n \"\"\"\n chan_metadata = metadata.chans_metadata[chan]\n chopper_str = \"LF\" if chan_metadata.chopper else \"HF\"\n sensor_str = re.sub(\"[^0-9]\", \"\", chan_metadata.sensor)\n sensor_str = f\"{int(sensor_str):03d}\"\n serial_str = f\"{int(chan_metadata.serial):06d}\"\n file_name = self.file_str.replace(\"$sensor\", sensor_str)\n file_name = file_name.replace(\"$serial\", serial_str)\n file_name = file_name.replace(\"$chopper\", chopper_str)\n file_name = file_name.replace(\"$extension\", self.extension)\n return dir_path / file_name\n\n def _get_chopper(self, file_path: Path) -> bool:\n \"\"\"Get whether the calibration is chopper on or off\"\"\"\n if \"LF\" in file_path.stem or \"BB\" in file_path.stem:\n return True\n return False\n\n\nclass SensorCalibrationRSP(SensorCalibration_RSP_RSPX_Base):\n \"\"\"\n Reader for RSP calibration files\n\n RSP data is in units:\n\n - F [Hz]\n - Magnitude [mv/nT]\n - Phase [deg]\n\n Data is returned with units:\n\n - F [Hz]\n - Magnitude [mV/nT]\n - Phase [radians]\n\n The static gain for RSP files is applied to the magnitude as it is read in\n \"\"\"\n\n extension: str = \".RSP\"\n\n def read_calibration_data(\n self, file_path: Path, chan_metadata: ChanMetadata\n ) -> CalibrationData:\n \"\"\"\n Read data from a RSP calibration file\n\n Parameters\n ----------\n file_path : Path\n The file path of the calibration file\n chan_metadata : ChanMetadata\n The channel metadata for the channel to be calibrated\n\n Returns\n -------\n CalibrationData\n The calibration data\n \"\"\"\n with file_path.open(\"r\") as f:\n lines = f.readlines()\n lines = [x.strip() for x in lines]\n data_dict = self._read_metadata(lines)\n data_dict[\"chopper\"] = self._get_chopper(file_path)\n df = self._read_data(lines)\n df[\"magnitude\"] = df[\"magnitude\"] * data_dict[\"static_gain\"]\n df[\"phase\"] = df[\"phase\"] * (np.pi / 180)\n data_dict[\"frequency\"] = df.index.values.tolist()\n data_dict[\"magnitude\"] = df[\"magnitude\"].values.tolist()\n data_dict[\"phase\"] = df[\"phase\"].values.tolist()\n data_dict[\"file_path\"] = file_path\n return CalibrationData(**data_dict)\n\n def _read_metadata(self, lines: List[str]) -> Dict[str, Any]:\n \"\"\"Read the calibration file metadata\"\"\"\n serial, sensor = self._get_sensor_details(lines)\n static_gain = self._get_static_gain(lines)\n return {\n \"serial\": serial,\n \"sensor\": sensor,\n \"static_gain\": static_gain,\n \"magnitude_unit\": \"mV/nT\",\n \"phase_unit\": \"radians\",\n }\n\n def _get_sensor_details(self, lines: List[str]) -> Tuple[int, str]:\n \"\"\"Get sensor details from the file\"\"\"\n serial: int = 1\n sensor: str = \"\"\n for line in lines:\n if \"induction coil no\" in line:\n split1 = line.split(\":\")[1]\n serial = int(split1.split(\"-\")[0].strip())\n if \"SensorType\" in line:\n sensor = line.split()[1]\n return serial, sensor\n\n def _get_static_gain(self, lines: List[str]) -> float:\n static_gain: float = 1.0\n for line in lines:\n if \"StaticGain\" in line:\n static_gain = float(line.split()[1])\n return static_gain\n return static_gain\n\n def _read_data(self, lines: List[str]) -> pd.DataFrame:\n \"\"\"Read data from calibration file\"\"\"\n read_from = self._get_read_from(lines)\n data_lines = self._get_data_lines(lines, read_from)\n data = np.array([x.split() for x in data_lines], dtype=np.float32)\n df = pd.DataFrame(data=data, columns=[\"frequency\", \"magnitude\", \"phase\"])\n return df.set_index(\"frequency\").sort_index()\n\n def _get_read_from(self, lines: List[str]) -> int:\n \"\"\"Get the line number to read from\"\"\"\n for idx, line in enumerate(lines):\n if \"FREQUENCY\" in line:\n return idx + 2\n raise ValueError(\"Unable to determine location of data in file\")\n\n def _get_data_lines(self, lines: List[str], idx: int) -> List[str]:\n \"\"\"Get the data lines out of the file\"\"\"\n data_lines: List[str] = []\n while idx < len(lines) and lines[idx] != \"\":\n data_lines.append(lines[idx])\n idx += 1\n return data_lines\n\n\nclass SensorCalibrationRSPX(SensorCalibration_RSP_RSPX_Base):\n \"\"\"\n Read data from RSPX calibration file\n\n RSPX data is in units:\n\n - F [Hz]\n - Magnitude [mv/nT]\n - Phase [deg]\n\n Data is returned with units:\n\n - F [Hz]\n - Magnitude [mV/nT]\n - Phase [radians]\n\n Static gain is applied to the magnitude\n \"\"\"\n\n extension: str = \".RSPX\"\n\n def read_calibration_data(\n self, file_path: Path, chan_metadata: ChanMetadata\n ) -> CalibrationData:\n \"\"\"\n Read RSPX file\n\n Parameters\n ----------\n file_path : Path\n The file path of the calibration file\n chan_metadata : ChanMetadata\n The channel metadata for the channel to be calibrated\n\n Returns\n -------\n CalibrationData\n The calibration data\n \"\"\"\n root = ET.parse(file_path).getroot()\n data_dict = self._read_metadata(root)\n data_dict[\"chopper\"] = self._get_chopper(file_path)\n df = self._read_data(root)\n df[\"magnitude\"] = df[\"magnitude\"] * data_dict[\"static_gain\"]\n df[\"phase\"] = df[\"phase\"] * (np.pi / 180)\n data_dict[\"frequency\"] = df.index.values.tolist()\n data_dict[\"magnitude\"] = df[\"magnitude\"].values.tolist()\n data_dict[\"phase\"] = df[\"phase\"].values.tolist()\n data_dict[\"file_path\"] = file_path\n return CalibrationData(**data_dict)\n\n def _read_metadata(self, root: Element) -> Dict[str, Any]:\n \"\"\"Read the calibration file metadata\"\"\"\n serial, sensor = self._get_sensor_details(root)\n static_gain = self._get_static_gain(root)\n return {\n \"serial\": serial,\n \"sensor\": sensor,\n \"static_gain\": static_gain,\n \"magnitude_unit\": \"mV/nT\",\n \"phase_unit\": \"radians\",\n }\n\n def _get_sensor_details(self, root: Element) -> Tuple[int, str]:\n \"\"\"Get sensor details\"\"\"\n serial: int = 1\n if root.find(\"SensorId\") is not None:\n serial = int(root.find(\"SensorId\").text)\n sensor: str = \"\"\n if root.find(\"SensorSpecification\") is not None:\n sensor = root.find(\"SensorSpecification\").text\n return serial, sensor\n\n def _get_static_gain(self, root) -> float:\n \"\"\"Get the static gain\"\"\"\n static_gain: float = 1.0\n if root.find(\"StaticGain\") is not None:\n static_gain = float(root.find(\"StaticGain\").text)\n return static_gain\n\n def _read_data(self, root: Element) -> pd.DataFrame:\n \"\"\"Get data in a DataFrame\"\"\"\n data = []\n for resp in root.findall(\"ResponseData\"):\n data.append(\n [\n np.float32(resp.get(\"Frequency\")),\n np.float32(resp.get(\"Magnitude\")),\n np.float32(resp.get(\"Phase\")),\n ]\n )\n df = pd.DataFrame(data=data, columns=[\"frequency\", \"magnitude\", \"phase\"])\n return df.set_index(\"frequency\").sort_index()\n", "meta": {"hexsha": "2d0d7ffabb2c53ce436a83acbf3d239b8a179f1e", "size": 8697, "ext": "py", "lang": "Python", "max_stars_repo_path": "resistics_readers/spam/calibration.py", "max_stars_repo_name": "resistics/resistics-readers", "max_stars_repo_head_hexsha": "f36c10b396bb769b91884c5b41f9ac94e0b8deac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-06-22T09:29:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T07:20:41.000Z", "max_issues_repo_path": "resistics_readers/spam/calibration.py", "max_issues_repo_name": "resistics/resistics-readers", "max_issues_repo_head_hexsha": "f36c10b396bb769b91884c5b41f9ac94e0b8deac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "resistics_readers/spam/calibration.py", "max_forks_repo_name": "resistics/resistics-readers", "max_forks_repo_head_hexsha": "f36c10b396bb769b91884c5b41f9ac94e0b8deac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8404669261, "max_line_length": 86, "alphanum_fraction": 0.5929630907, "include": true, "reason": "import numpy", "num_tokens": 1994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.22815650216092534, "lm_q1q2_score": 0.1185321676146095}} {"text": "import numpy as np\nimport pdb\nfrom scipy.interpolate import interp1d\nfrom scipy.stats import pearsonr\nfrom scipy.stats import norm\nimport scipy.signal as signal\nfrom matplotlib import gridspec\nimport matplotlib\nmatplotlib.use('Qt4Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib.widgets import RadioButtons, Button, CheckButtons\nimport sys\nfrom types import *\n\nclass Estimateline:\n '''Class to manually estimate where lines are located'''\n def __init__(self,pspec,ax5,uline):\n print 'If redshift calibration appears correct, hit \"Accept and Close\". '\\\n 'Otherwise, \"right click\" approx. where the '+uline+' line is in the plotted spectrum. '\\\n 'The program will re-correlate based on this guess.'\n self.ax5 = ax5\n self.cid3 = pspec.figure.canvas.mpl_connect('button_press_event',self.onclick)\n\n def on_key_press(self,event):\n if event.key == 'shift':\n self.shift_is_held = True\n\n def on_key_release(self, event):\n if event.key == 'shift':\n self.shift_is_held = False\n\n def onclick(self,event):\n if event.inaxes == self.ax5:\n if event.button == 3:\n print 'xdata=%f, ydata%f'%(event.xdata, event.ydata)\n self.lam = event.xdata\n plt.close()\n '''\n if event.button == 1:\n #if self.shift_is_held:\n # print 'xdata=%f, ydata%f'%(event.xdata, event.ydata)\n # self.lam = event.xdata\n # plt.close()\n #else:\n plt.close()\n '''\n else: return\n\nclass z_est:\n def __init__(self,lower_w=3900.0,upper_w=5500.0,lower_z=0.01,upper_z=0.35,z_res=3.0e-5,skip_initial_priors=False):\n '''\n Initialize redshift estimate parameters\n '''\n\n #preconditions\n assert lower_w and upper_w, \"wavelength bounds must have values\"\n assert lower_z and upper_z, \"redshift bounds must have values\"\n assert (type(lower_w) == IntType or type(lower_w) == FloatType) and (type(upper_w) == IntType or \\\n type(upper_w) == FloatType), \"wavelength bounds must be integers or floats\"\n assert (type(lower_z) == IntType or type(lower_z) == FloatType) and (type(upper_z) == IntType or \\\n type(upper_z) == FloatType), \"wavelength bounds must be integers or floats\"\n assert lower_w < upper_w, \"lower_w must be < upper_w\"\n assert lower_z < upper_z, \"lower_z must be < upper_z\"\n\n #set class attributes\n self.lower_w = lower_w\n self.upper_w = upper_w\n self.lower_z = lower_z\n self.upper_z = upper_z\n self.z_res = z_res\n \n #create redshift array and initialize correlation value array\n self.ztest = np.arange(self.lower_z,self.upper_z,self.z_res)\n self.corr_val_i = np.zeros(self.ztest.size)\n \n #set redshift prior flag\n if skip_initial_priors:\n self.est_pre_z = '3'\n self.uline_n = 'HK'\n self.uline = 3950.0\n self.z_prior_width = 0.06\n else:\n self.est_pre_z = raw_input('(1) Use a known prior [Examples: median of known redshifts. Galaxy photoz measurements] \\n'\\\n '(2) View spectrum and specify a redshift prior \\n'\\\n '(3) No prior\\n')\n\n #catch and correct false entry\n _est_enter = False\n self.uline_n = raw_input('What is the name of a spectral line you wish to use to identify redshift priors? '\\\n '[Default: HK]: ')\n if not self.uline_n:\n self.uline_n = 'HK'\n self.uline = raw_input('Please list the approx. rest wavelength (in angstroms) of that line you seek to identify in your spectra '\\\n '[Default: HK lines are at about 3950]: ')\n if self.uline:\n self.uline = np.float(self.uline)\n else:\n self.uline = 3950.0\n while not _est_enter:\n if self.est_pre_z == '1':\n self.z_prior_width = 0.06\n print 'redshift prior width has been set to',self.z_prior_width\n _est_enter = True\n elif self.est_pre_z == '2':\n self.z_prior_width = 0.06\n print 'redshift prior width has been set to',self.z_prior_width\n _est_enter = True\n elif self.est_pre_z == '3':\n self.z_prior_width = 0.06\n _est_enter = True\n else:\n self.est_pre_z = raw_input('Incorrect entry: Please enter either (1), (2), or (3).')\n\n #remind user to set the correct values in next step\n if self.est_pre_z == '1':\n print 'Make sure to set the gal_prior argument to the value of the known redshift prior: '\\\n '[Example: z_est.redshift_estimate(gal_prior=0.1)]'\n\n #postconditions\n assert self.est_pre_z, \"Must define redshift prior flag\"\n assert self.est_pre_z == '1' or self.est_pre_z == '2' or self.est_pre_z == '3', \\\n \"Incorrect string value for prior\"\n\n\n def redshift_estimate(self,early_type_wave,early_type_flux,wave,Flux_science,plotlines=None,template_id='Galaxy',gal_prior=None):\n '''\n estimate redshift for object\n '''\n #manage redshift prior\n self.gal_prior = gal_prior\n self.template_number = template_id\n self.plotlines = plotlines\n\n #continuum subtract\n Flux_sc = Flux_science - signal.medfilt(Flux_science,171)\n early_type_flux_sc = early_type_flux - signal.medfilt(early_type_flux,171)\n\n #handle single redshift prior flag\n if self.est_pre_z == '1':\n if self.gal_prior:\n self.pre_z_est = self.gal_prior\n else:\n nospec = raw_input('You said you are either using a spectroscopic or photometric redshift prior. '\\\n 'You need to specify a prior value! Either enter a number in now or type (q) to exit')\n if nospec == 'q':\n sys.exit()\n elif not nospec:\n sys.exit()\n else:\n self.gal_prior = np.float(nospec)\n self.pre_z_est = self.gal_prior\n\n #handle user prior flag\n if self.est_pre_z == '2':\n print 'Take a look at the plotted galaxy spectrum and note, approximately, at what wavelength do you see the '+self.uline_n+' line. '\\\n 'Then close the plot and enter that wavelength in angstroms.'\n plt.plot(wave,Flux_science)\n plt.xlim(self.lower_w,self.upper_w)\n plt.show()\n line_init = raw_input(self.uline_n+' approx. wavelength (A): ')\n self.pre_z_est = np.float(line_init)/self.uline - 1\n\n #handle no prior flag\n if self.est_pre_z == '3':\n self.pre_z_est = None\n\n redshift_est,cor,ztest,corr_val = self._cross_cor(self.pre_z_est,self.z_prior_width,early_type_wave,early_type_flux_sc,wave,Flux_sc)\n\n self.qualityval = 1\n self.first_pass = True\n self.skip_spec_flag = False\n self._GUI_display(redshift_est,ztest,corr_val,wave,Flux_science)\n #self.line_est = Estimateline(self.pspec,ax)\n #plt.show()\n try:\n self.pre_lam_est = self.line_est.lam\n self.pre_z_est = self.pre_lam_est/3950.0 - 1.0\n self.first_pass = False\n redshift_est,cor,ztest,corr_val = self._cross_cor(self.pre_z_est,self.z_prior_width,early_type_wave,early_type_flux_sc,wave,Flux_sc)\n print 'redshift est:',redshift_est\n self._GUI_display(redshift_est,ztest,corr_val,wave,Flux_science)\n redshift_est = self.spectra2.finalz\n except AttributeError:\n pass\n print 'zpy redshift estimate',redshift_est\n return redshift_est,cor,ztest,corr_val,self.qualityval\n\n def _cross_cor(self,z_est,unc,early_type_wave,early_type_flux,wave,Flux_sc):\n '''\n This function cross-correlates a continuum subtracted template spectrum with a continuum subtracted observed spectrum.\n It then returns an estimate of the redshift, the correlation value at that redshift, the array of redshifts tested,\n and the unnormalized correlation value.\n '''\n \n #loop over each possible redshift to compute correlation values\n for i in range(self.ztest.size):\n z = self.ztest[i]\n #redshift the template wavelengths\n wshift = early_type_wave*(1+z)\n #identify the wavelength diff between the lower wave limit and the redshifted template spectrum\n wavediff = np.min(wshift - self.lower_w)\n\n #if the limit is above the minimum wavelength of the redshifted template spectrum...\n if wavediff < 0:\n wave_range = wave[np.where((waveself.lower_w))]\n Flux_range = Flux_sc[np.where((waveself.lower_w))]\n #if the limit is below the minimum wavelength of the redshifted template spectrum...\n else:\n wave_range = wave[np.where((waveself.lower_w+wavediff))]\n Flux_range = Flux_sc[np.where((waveself.lower_w+wavediff))]\n \n #interpolate the redshifted template spectrum and estimate the flux at the observed spectrum wavelengths\n inter = interp1d(wshift,early_type_flux)\n et_flux_range = inter(wave_range)\n\n #calculate the pearson r correlation value between the observed and template flux\n self.corr_val_i[i] = pearsonr(et_flux_range,Flux_range)[0]\n\n #normalize the correlation values as a function of redshift\n corr_val = (self.corr_val_i[np.isfinite(self.corr_val_i)]+1)/np.trapz((self.corr_val_i[np.isfinite(self.corr_val_i)]+1),self.ztest[np.isfinite(self.corr_val_i)])\n self.ztest = self.ztest[np.isfinite(self.corr_val_i)]\n \n #multiply in prior to likelihood if specified\n self.corr_prior = np.zeros(self.ztest.size)\n if z_est:\n rv = norm(z_est,unc)\n corr_val = corr_val * rv.pdf(self.ztest)\n self.corr_prior = rv.pdf(self.ztest)\n \n #make redshift estimate\n redshift_est = (self.ztest[np.where((self.ztest>self.lower_z)&(self.ztestself.lower_z)&(self.ztestself.lower_z)&(self.ztestself.lower_z)&(self.ztestself.lower_z)&(self.ztestself.lower_z)&(self.ztest self.MIN_INTENSITY_VALUE:\r\n ic = sp.correlate(frame_mod_prev, frame_s[0:self.win_s])\r\n intercorr = ic[self.win_s-2:self.win_s-1+2*self.length_weight] * self.weight\r\n I = intercorr.argmax()\r\n k_pos = I-(self.length_weight+1)\r\n else:\r\n k_pos = 0\r\n # Not clean, indices overflow buffer_mod size.\r\n # It works because overflowed values are taken into account.\r\n self.buffer_mod[self.shift_mod+k_pos+self.win_length:self.shift_mod+k_pos+self.frame_length] = \\\r\n frame_s[self.win_length:self.frame_length]\r\n self.buffer_mod[self.shift_mod+k_pos:self.shift_mod+k_pos+self.win_length] = \\\r\n + self.buffer_mod[self.shift_mod+k_pos:self.shift_mod+k_pos+self.win_length]*self.win_D \\\r\n + frame_s[0:self.win_length]*self.win_G\r\n\r\n # shift modified buffer\r\n self.buffer_mod = self.buffershift(self.buffer_mod,self.zeros_frame_mod)\r\n# frame_residue = lpcanalysis(self.buffer_mod[:self.shift_mod])\r\n # resample\r\n frame_output = sp.resample(self.buffer_mod[:self.shift_mod], new_frame.size)\r\n return frame_output\r\n\r\n def lpcanalysis(self, frame):\r\n raise NotImplementedError('Not yet implemented');\r\n# frame_preemphasis = sp.lfilter([1, -self.alpha], 1, frame.reshape([frame.size]))\r\n# frame_preemphasis_windowed = frame_preemphasis[self.n_lpc:] \\\r\n# *self.w_hamming\r\n# R = sp.correlate(frame_preemphasis_windowed, frame_preemphasis_windowed) # coefficients de corrélation\r\n# Ri = R[window_length-1:window_length+self.n_lpc]\r\n#\r\n# lpc_durbin = self.durbin(Ri) # calcul des ai\r\n# ai = lpc_durbin['a']\r\n# ai = ai.reshape([ai.size])\r\n# self._lpc_coeff[:, n] = ai\r\n# frame_filt = sp.lfilter(ai, 1.0, frame_preemphasis) # filtrage du signal\r\n# frame_residue = frame_filt[self.n_lpc:]\r\n\r\n\r\n def buffershift(self, buffer_loc, frame):\r\n buffer_loc[:-frame.size] = buffer_loc[frame.size:]\r\n buffer_loc[-frame.size:] = frame.reshape([frame.size, 1])\r\n return buffer_loc\r\n\r\n def str2numpy(self, frame):\r\n return np.fromstring(frame,self.frame_format)\r\n\r\n def numpy2str(self, frame):\r\n frame = frame.astype(self.frame_format)\r\n return frame.tostring()\r\n\r\n\r\n def durbin(self,frame_corr):\r\n \"\"\"Perform linear predictive coding with Levinson-Durbin recursion.\r\n\r\n Args:\r\n frame_corr (numpy array): First samples of auto-correlation frame.\r\n\r\n Returns:\r\n {\r\n 'a': a, the filter coefficient of an auto-regressive model\r\n 'k': k, the reflexion coefficient\r\n 'En': En, the prediction error\r\n }\r\n \"\"\"\r\n R0 = frame_corr[0]\r\n frame_corr = np.reshape(frame_corr/R0, [frame_corr.size, 1])\r\n p = frame_corr.size - 1\r\n k = np.zeros([p, 1])\r\n a = 1\r\n for n in range(0, p):\r\n a = np.append(a, 0.)\r\n a = a.reshape([a.size, 1])\r\n r = frame_corr[0:n+2]\r\n En = np.sum(r*a)\r\n Bn = np.sum(np.flipud(r)*a)\r\n ki = -Bn/En\r\n a = a + np.flipud(a)*ki\r\n k[n] = ki\r\n En = R0*np.sum(frame_corr*a)\r\n return {\r\n 'a': a,\r\n 'k': k,\r\n 'En': En,\r\n }\r\n\r\n\r\n def lsf2poly(lsf):\r\n \"\"\"Convert line spectral frequencies to prediction filter coefficients\r\n returns a vector a containing the prediction filter coefficients from a vector lsf of line spectral frequencies.\r\n\r\n \"\"\"\r\n # Reference: A.M. Kondoz, \"Digital Speech: Coding for Low Bit Rate Communications\r\n # Systems\" John Wiley & Sons 1994 ,Chapter 4\r\n\r\n # Line spectral frequencies must be real.\r\n\r\n lsf = np.array(lsf)\r\n\r\n if max(lsf) > np.pi or min(lsf) < 0:\r\n raise ValueError('Line spectral frequencies must be between 0 and pi.')\r\n\r\n p = len(lsf) # model order\r\n\r\n # Form zeros using the LSFs and unit amplitudes\r\n z = np.exp(1.j * lsf)\r\n\r\n # Separate the zeros to those belonging to P and Q\r\n rQ = z[0::2]\r\n rP = z[1::2]\r\n\r\n # Include the conjugates as well\r\n rQ = np.concatenate((rQ, rQ.conjugate()))\r\n rP = np.concatenate((rP, rP.conjugate()))\r\n\r\n # Form the polynomials P and Q, note that these should be real\r\n Q = np.poly(rQ);\r\n P = np.poly(rP);\r\n\r\n # Form the sum and difference filters by including known roots at z = 1 and\r\n # z = -1\r\n\r\n if p%2:\r\n # Odd order: z = +1 and z = -1 are roots of the difference filter, P1(z)\r\n P1 = sp.convolve(P, [1, 0, -1])\r\n Q1 = Q\r\n else:\r\n # Even order: z = -1 is a root of the sum filter, Q1(z) and z = 1 is a\r\n # root of the difference filter, P1(z)\r\n P1 = sp.convolve(P, [1, -1])\r\n Q1 = sp.convolve(Q, [1, 1])\r\n\r\n # Prediction polynomial is formed by averaging P1 and Q1\r\n\r\n a = .5 * (P1+Q1)\r\n return a[0:-1:1] # do not return last element\r\n\r\n\r\n def poly2lsf(a):\r\n \"\"\"Prediction polynomial to line spectral frequencies.\r\n\r\n converts the prediction polynomial specified by A,\r\n into the corresponding line spectral frequencies, LSF.\r\n normalizes the prediction polynomial by A(1).\r\n\r\n \"\"\"\r\n\r\n #Line spectral frequencies are not defined for complex polynomials.\r\n\r\n # Normalize the polynomial\r\n\r\n a = np.array(a)\r\n if a[0] != 1:\r\n a/=a[0]\r\n\r\n if max(np.abs(np.roots(a))) >= 1.0:\r\n raise ValueError('The polynomial must have all roots inside of the unit circle.');\r\n\r\n\r\n # Form the sum and difference filters\r\n\r\n p = len(a)-1 # The leading one in the polynomial is not used\r\n a1 = np.concatenate((a, np.array([0])))\r\n a2 = a1[-1::-1]\r\n P1 = a1 - a2 # Difference filter\r\n Q1 = a1 + a2 # Sum Filter\r\n\r\n # If order is even, remove the known root at z = 1 for P1 and z = -1 for Q1\r\n # If odd, remove both the roots from P1\r\n\r\n if p%2: # Odd order\r\n P, r = sp.deconvolve(P1,[1, 0 ,-1])\r\n Q = Q1\r\n else: # Even order\r\n P, r = sp.deconvolve(P1, [1, -1])\r\n Q, r = sp.deconvolve(Q1, [1, 1])\r\n\r\n rP = np.roots(P)\r\n rQ = np.roots(Q)\r\n\r\n aP = np.angle(rP[1::2])\r\n aQ = np.angle(rQ[1::2])\r\n\r\n lsf = sorted(np.concatenate((-aP,-aQ)))\r\n\r\n return lsf\r\n\r\n\r\n\r\n @property\r\n def mid_buffer_size(self):\r\n return self._mid_buffer_size\r\n\r\n @property\r\n def buffer(self):\r\n return self._buffer\r\n\r\n @property\r\n def pitch_rate(self):\r\n print(\"pitch_rate = {}\".format(self._pitch_rate))\r\n return self._pitch_rate\r\n\r\n @pitch_rate.setter\r\n def pitch_rate(self, new_pitch_rate):\r\n self._pitch_rate = new_pitch_rate\r\n self.initialize(self._pitch_rate, self.frame_format)\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "22bfc046acc86045ce90345030dcc670f894b3a9", "size": 11059, "ext": "py", "lang": "Python", "max_stars_repo_path": "ppsrt/ProsodicModificationRealTime.py", "max_stars_repo_name": "pprablanc/Python-pitch-shifting-RT", "max_stars_repo_head_hexsha": "ac9d478e7f67fbc5adb6890377d05b22c8f3c51d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-11-30T21:36:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T05:21:37.000Z", "max_issues_repo_path": "ppsrt/ProsodicModificationRealTime.py", "max_issues_repo_name": "pprablanc/ppsrt", "max_issues_repo_head_hexsha": "ac9d478e7f67fbc5adb6890377d05b22c8f3c51d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ppsrt/ProsodicModificationRealTime.py", "max_forks_repo_name": "pprablanc/ppsrt", "max_forks_repo_head_hexsha": "ac9d478e7f67fbc5adb6890377d05b22c8f3c51d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7440273038, "max_line_length": 128, "alphanum_fraction": 0.5679537029, "include": true, "reason": "import numpy,import scipy", "num_tokens": 2729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.19682620364309852, "lm_q1q2_score": 0.11813279622396629}} {"text": "\nfrom __future__ import (absolute_import, division,\n print_function, unicode_literals)\nimport numpy as np\nfrom scipy import stats\nfrom .profiles import GaussProfile\nfrom .profiles import UserProfile\nfrom .profiles import DataProfile\nfrom ..utils.utils import make_quant, shift_t\n\nclass Pulsar(object):\n \"\"\"class for pulsars\n\n The minimal data to instantiate a pulsar is the period, Smean, and\n pulse profile. The Profile is supplied via a :class:`PulseProfile`-like\n object.\n\n Parameters\n ----------\n\n period : float\n Pulse period (sec)\n\n Smean : float\n Mean pulse flux density (Jy)\n\n profile : :class:`PulseProfile`\n Pulse profile or 2-D pulse portrait\n\n name : str\n Name of pulsar\n \"\"\"\n #TODO Other data could be supplied via a `.par` file.\n def __init__(self, period, Smean, profiles=None, name=None):\n self._period = make_quant(period, 's')\n self._Smean = make_quant(Smean, 'Jy')\n\n self._name = name\n\n # Assign profile class; default to GaussProfile if nothing is specified\n if profiles is None:\n self._Profiles = GaussProfile()\n else:\n self._Profiles = profiles\n\n def __repr__(self):\n namestr = \"\" if self.name is None else self.name+\", \"\n return \"Pulsar(\"+namestr+\"{})\".format(self.period.to('ms'))\n\n @property\n def Profiles(self):\n return self._Profiles\n\n @property\n def name(self):\n return self._name\n\n @property\n def period(self):\n return self._period\n\n @property\n def Smean(self):\n return self._Smean\n\n def make_pulses(self, signal, tobs):\n \"\"\"generate pulses from Profiles, :class:`PulsePortrait` object\n\n Required Args:\n signal (:class:`Signal`-like): signal object to store pulses\n tobs (float): observation time (sec)\n \"\"\"\n signal._tobs = make_quant(tobs, 's')\n\n # init base profile at correct sample rate\n Nph = int((signal.samprate * self.period).decompose())\n\n # If there isn't enough frequencies in the profiles\n # And if it is a :class:`Profile` instance, reshape.\n self.Profiles.init_profiles(Nph, signal.Nchan)\n\n # if (signal.Nchan != self.Profiles.profiles.shape[0]\n # and hasattr(self.Profiles, 'set_Nchan')):\n # self.Profiles.set_Nchan(signal.Nchan)\n\n\n # select pulse generation method\n if signal.sigtype in [\"RFSignal\", \"BasebandSignal\"]:\n self._make_amp_pulses(signal)\n elif signal.sigtype is \"FilterBankSignal\":\n self._make_pow_pulses(signal)\n else:\n msg = \"no pulse method for signal: {}\".format(signal.sigtype)\n raise NotImplementedError(msg)\n\n # compute Smax (needed for radiometer noise level)\n #pr = self.Profiles()\n pr = self.Profiles._max_profile\n nbins = len(pr) # Think this assumes a single profile for now...\n signal._Smax = self.Smean * nbins / np.sum(pr)\n\n def _make_amp_pulses(self, signal):\n \"\"\"generate amplitude pulses\n\n This method should be used for radio frequency and basebanded\n pulses.\n\n Parameters\n ----------\n\n signal : :class:`Signal`-like\n Signal object to store pulses.\n \"\"\"\n # generate several pulses in time\n distr = stats.norm()\n\n Nsamp = int((signal.tobs * signal.samprate).decompose())\n signal.init_data(Nsamp)\n\n # TODO break into blocks\n # TODO phase from .par file\n # calc profile at phases\n phs = (np.arange(Nsamp) /\n (signal.samprate * self.period).decompose().value)\n phs %= 1 # clip integer part\n\n # convert intensity profile to amplitude!\n full_prof = np.sqrt(self.Profiles.calc_profiles(phs))\n\n signal._data = full_prof * distr.rvs(size=signal.data.shape)\n\n def _make_pow_pulses(self, signal):\n \"\"\"generate a power pulse\n\n This method should be used for filter bank pulses\n\n Parameters\n ----------\n\n signal : :class:`Signal`-like\n Signal object to store pulses.\n \"\"\"\n if signal.fold:\n # Determine how many subints to make\n if signal.sublen is None:\n signal._sublen = signal.tobs\n signal._nsub = 1\n else:\n # This should be an integer, if not, will round\n signal._nsub = int(np.round(signal.tobs / signal.sublen))\n\n # determine the number of data samples necessary\n signal._nsamp = int((signal.nsub*(self.period*signal.samprate)).decompose())\n # Need to make an initial empty data array\n signal.init_data(signal.nsamp)\n\n # Tile the profiles to number of desired subints\n sngl_prof = np.tile(self.Profiles(), signal.nsub)\n\n # changed to number of subints\n signal._Nfold = (signal.sublen / self.period).decompose()\n distr = stats.chi2(df=signal.Nfold)\n signal._set_draw_norm(df=signal.Nfold)\n\n #Why is there a second call to init_data?\n signal.init_data(sngl_prof.shape[1])\n signal._data = (sngl_prof * distr.rvs(size=signal.data.shape)\n * signal._draw_norm)\n else:\n # fold is false and will make single pulses\n signal._sublen = self.period\n # This should be an integer, if not, will round; may not be exact\n signal._nsub = int(np.round((signal.tobs / signal.sublen).decompose()))\n\n # generate several pulses in time\n distr = stats.chi2(df=1)\n signal._set_draw_norm(df=1)\n\n signal._nsamp = int((signal.tobs * signal.samprate).decompose())\n signal.init_data(signal.nsamp)\n\n # TODO break into blocks\n # TODO phase from .par file\n # calc profiles at phases\n phs = (np.arange(signal.nsamp) /\n (signal.samprate * self.period).decompose().value)\n phs %= 1 # clip integer part\n full_prof = self.Profiles.calc_profiles(phs,signal.Nchan)\n\n signal._data = (full_prof * distr.rvs(size=signal.data.shape)\n * signal._draw_norm)\n\n def null(self, signal, null_frac, length=None, frequency=None):\n \"\"\"\n Function to simulate pulsar pulse nulling. Given some nulling fraction,\n will replace simulated pulses with noise until nulling fraction is met.\n This function should only be run after running any ism or other delays\n have been added, e.g. disperison, FD, profile evolution, etc., but\n should be run before adding the radiometer noise ('telescope.observe()`),\n if nulling is desired.\n\n Parameters\n ----------\n\n signal [class] : signal class containing the simulated pulses\n null_frac [float] : desired pulsar nulling fraction, given as a\n decimal; range of 0.0 to 1.0.\n length [float] : desired length of each null in seconds. If not given,\n will randomly null pulses. Default is None.\n frequency [float] : frequency of pulse nulling, e.g. how often the pulsar\n nulls per hour. E.g. if frequency is 2, then the\n pulsar will null twice per hour for some length\n of time. If not given, will randomly null pulses.\n Default is None.\n \"\"\"\n # Determine how many pulses need to be nulled out\n null_pulses = int(np.round(signal.nsub * null_frac)) # needs to be int, may not be exact\n # Get the number of bins per pulse\n Nph = int((signal.samprate * self.period).decompose())\n # determine the off pulse window\n opw = self.Profiles._calcOffpulseWindow(Nphase = Nph)\n # define the random noise distribution\n if signal.fold:\n distr = stats.chi2(df=signal.Nfold)\n else:\n distr = stats.chi2(df=1)\n # have a test ditribution to determine null bins if Nfold is 1\n if not signal.fold or signal.Nfold < 100:\n check_distr = stats.chi2(df=100)\n else:\n check_distr = stats.chi2(df=signal.Nfold)\n # Figure out how off-center the pulses are\n shift_val = Nph//2 - np.where(signal.data[0,:Nph]==np.max(signal.data[0,:Nph]))[0]\n # Now null randomly if no length or frequency is given\n if length==None and frequency==None:\n # randomly draw pulse numbers to null\n rand_pulses = np.random.choice(signal.nsub, null_pulses, replace=False)\n # replace each pulse number with random noise\n if signal.delay == None:\n for p in rand_pulses:\n # convert to bins\n null_bins = np.arange(Nph*p, Nph*(p+1)) + shift_val\n # make sure we don't go beyond the data array length\n null_bins = null_bins[null_bins1))[1]\n noise = (distr.rvs(size=noise_shape) * signal._draw_norm)\n signal._data[np.where(null_array>1)] = noise*off_pulse_mean\n\n else:\n raise NotImplementedError(\"Length and Frequency not been implimented yet\")\n", "meta": {"hexsha": "4dabfe40b96233d7f1c92d383a53bdc415fdfea6", "size": 11296, "ext": "py", "lang": "Python", "max_stars_repo_path": "psrsigsim/pulsar/pulsar.py", "max_stars_repo_name": "paulthebaker/PsrSigSim", "max_stars_repo_head_hexsha": "e74e09f37d343e0ab91a24c6f5f3b87bdcb71d41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "psrsigsim/pulsar/pulsar.py", "max_issues_repo_name": "paulthebaker/PsrSigSim", "max_issues_repo_head_hexsha": "e74e09f37d343e0ab91a24c6f5f3b87bdcb71d41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "psrsigsim/pulsar/pulsar.py", "max_forks_repo_name": "paulthebaker/PsrSigSim", "max_forks_repo_head_hexsha": "e74e09f37d343e0ab91a24c6f5f3b87bdcb71d41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1992882562, "max_line_length": 108, "alphanum_fraction": 0.5805594901, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.22541661063147309, "lm_q1q2_score": 0.11798764099276914}} {"text": "\"\"\"\nresp_optimizer.py\nImplementation of open-source vrsion of RESP method\n\n\"\"\"\nimport os, sys\nimport numpy as np\nfrom shutil import copyfile\nfrom respyte.readinp_esp import *\nfrom respyte.readmol import * # read molecules and assign (what?)\nfrom respyte.molecule import * # copied from forcebalance package and modified\nfrom respyte.gen_grid_pts import * # take either rdkit ol or oechem mol to generate grid points around molecules (modified CIB's code)\nfrom respyte.engine import *\n\ndef main():\n # cwd = current working directory in which input folder exists\n cwd = os.getcwd()\n # check if the current working idr contains input folder\n print('\\n')\n print('---------------------------------------------------------')\n print(' 1. Reading input files and folders. ')\n print('---------------------------------------------------------')\n if os.path.isdir(\"%s/input\" % cwd):\n print(' Found the input folder. Now read input/input.yml')\n else:\n print(' Failed to find input folder. Should have input(folder) containing input.yml and molecules(folder)')\n # read input.yml and generate gridOption.\n inp = Input('%s/input/input.yml' % (cwd))\n gridOptions = inp.gridOptions\n\n # Visit all subfolder molecule/ moli/confj and generate grid.dat\n for idx, i in enumerate(inp.nmols):\n molN = 'mol%d' % (idx+1)\n wkd = '%s/input/molecules/%s' % (cwd, molN)\n for j in range(i):\n confN = 'conf%d' % (j+1)\n path = wkd + '/%s' % (confN)\n # gen molecule object from pdb file\n pdbfile = path + '/%s_%s.pdb' % (molN, confN)\n mol2file = path + '/%s_%s.mol2' % (molN, confN)\n xyzfile = path + '/%s_%s.xyz' % (molN, confN)\n if os.path.isfile(pdbfile):\n coordfile = pdbfile\n #mol = Molecule(pdbfile)\n elif os.path.isfile(mol2file):\n coordfile = mol2file\n #mol = Molecule(mol2file)\n elif os.path.isfile(xyzfile):\n print(\" Warning: Are you using xyz files? xyz format is not recommendable.\")\n print(\" But no worries! It will convert your xyz files to pdb with single residue named 'MOL'.\")\n xyztopdb(xyzfile)\n coordfile = pdbfile\n else:\n raise RuntimeError(\" Coordinate file does not exist! \")\n # Assign radii\n radii = inp.settings['radii']\n if inp.cheminformatics == 'openeye':\n mol = ReadOEMolFromFile(coordfile)\n mol = assignRadii(mol, 'OEMol', radii)\n moltype = 'OEMol'\n elif inp.cheminformatics == 'rdkit':\n mol = ReadRdMolFromFile(coordfile)\n mol = assignRadii(mol, 'RDMol', radii)\n moltype = 'RDMol'\n else:\n mol = ReadMolFromFile(coordfile)\n mol = assignRadii(mol, 'FBMol', radii)\n moltype = 'FBMol'\n # Generate points\n print('\\n')\n print('---------------------------------------------------------')\n print(' 2. Generating grid points around each molecules. ')\n print('---------------------------------------------------------')\n\n if moltype is 'FBMol':\n raise NotImplementedError('Grid gen using fbmol not implemented yet! Sorry!')\n if gridOptions['gridType'] == 'MSK' or gridOptions['gridType']=='extendedMsk':\n # generate Mers-Singh-Kollman Connolly surfaces at 1.4, 1.6, 1.8 and 2.0 * vdW radii\n allPts = GenerateMSKShellPts(mol, gridOptions, moltype)\n else:\n # Generate a face-centered cubic grid shell around the molecule using gridOptions\n allPts = [GenerateGridPointSetAroundOEMol(mol, gridOptions, moltype)]\n print('Total points:', np.sum([len(i) for i in allPts]))\n\n # Write grid.dat\n print('\\n')\n print('---------------------------------------------------------')\n print(' Psi calculations are done. Will create espf files. ')\n print('---------------------------------------------------------')\n tmppath = '%s/tmp' % path\n if inp.settings['forcegen'] == 'N' and os.path.isfile('%s/grid.dat' % path):\n if os.path.isdir(tmppath):\n print('Rename pre-existing tmp dir into tmp.0 and re-make tmp dir.')\n os.rename(tmppath, '%s/tmp.0' % path)\n os.mkdir(tmppath)\n copyfile('%s/grid.dat' % path, '%s/grid.dat' % tmppath)\n else:\n os.mkdir(tmppath)\n # copy grid.dat into tmp dir\n copyfile('%s/grid.dat' % path, '%s/grid.dat' % tmppath)\n print(' Pre-existing grid.dat has been copied into tmp for Psi4 calculation.')\n else:\n if os.path.isdir(tmppath):\n print(' Rename pre-existing tmp dir into tmp.0 and re-make tmp dir.')\n os.rename(tmppath, '%s/tmp.0' % path)\n os.mkdir(tmppath)\n ofs = open('%s/grid.dat' % tmppath,'w')\n\n for pts in allPts: #changed (for msk-based scheme, allPts is a list of lists)\n for pt in pts:\n ofs.write( '{0:10.6f} {1:10.6f} {2:10.6f}\\n'.format(pt[0], pt[1], pt[2]) )\n ofs.close()\n print(' grid.dat is successfully generated in %s.' % tmppath)\n # Run engine to run Psi4 calculation inside tmp directory.\n engine = EnginePsi4()\n if 'method' in inp.settings:\n mthd = inp.settings['method']\n else:\n mthd = 'hf'\n if 'basis' in inp.settings:\n bss = inp.settings['basis']\n else:\n bss = '6-31g*'\n\n chg = inp.charges[idx]\n\n ### Need to add 'solvation' setting!\n if 'pcm' in inp.settings:\n if inp.settings['pcm'] is 'N':\n solv = None\n elif inp.settings['pcm'] is 'Y':\n solv = inp.settings['solvent']\n else:\n solv = None\n\n engine.write_input(coordfile, method = mthd, basis = bss, charge = chg, solvent=solv, job_path = tmppath)\n engine.espcal(job_path= tmppath)\n griddat = tmppath + '/grid.dat'\n espdat = tmppath + '/grid_esp.dat'\n efdat = tmppath + '/grid_field.dat'\n espfoutput = tmppath + '/%s_%s.espf' % (molN, confN)\n engine.genespf(griddat, espdat, efdat, espfoutput)\n # copy espf file generated in moli/confj/tmp to moli/confj/\n copyfile(espfoutput, path + '/%s_%s.espf' % (molN, confN))\n copyfile(griddat, path + '/grid.dat')\n print('\\n')\n print('---------------------------------------------------------')\n print(' Done! Hope it helps, Will see you again:) ')\n print('---------------------------------------------------------')\n\nif __name__ == \"__main__\":\n main()\n", "meta": {"hexsha": "c546396fe25705b9fc40d5364b9e3c4995d5b09a", "size": 7222, "ext": "py", "lang": "Python", "max_stars_repo_path": "respyte/esp_generator.py", "max_stars_repo_name": "hyejang/respyte", "max_stars_repo_head_hexsha": "8d48d04754051ea18224f1c5fa8637b17da6d5b2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "respyte/esp_generator.py", "max_issues_repo_name": "hyejang/respyte", "max_issues_repo_head_hexsha": "8d48d04754051ea18224f1c5fa8637b17da6d5b2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-01-22T02:05:34.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-22T02:07:33.000Z", "max_forks_repo_path": "respyte/esp_generator.py", "max_forks_repo_name": "hyejang/respyte", "max_forks_repo_head_hexsha": "8d48d04754051ea18224f1c5fa8637b17da6d5b2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-22T00:51:26.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-22T00:51:26.000Z", "avg_line_length": 47.2026143791, "max_line_length": 134, "alphanum_fraction": 0.5012461922, "include": true, "reason": "import numpy", "num_tokens": 1688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.2337063622512696, "lm_q1q2_score": 0.11776607803031931}} {"text": "# encoding:utf-8\nimport sys\n\nsys.path.append(\"..\")\nimport numpy as np\nfrom collections import defaultdict\nfrom random import randint\nfrom random import shuffle,choice\nfrom math import log\nimport gensim.models.word2vec as w2v\nfrom prettyprinter import cpprint\n\nfrom mf import MF\nfrom reader.trust import TrustGetter\nfrom utility.matrix import SimMatrix\nfrom utility.similarity import cosine\nfrom utility import util\n\n\nclass CUNE(MF):\n \"\"\"\n docstring for CUNE\n\n Zhang et al. Collaborative User Network Embedding for Social Recommender Systems. SDM\n \"\"\"\n\n def __init__(self):\n super(CUNE, self).__init__()\n self.config.lambdaP = 0.01\n self.config.lambdaQ = 0.01\n self.config.alpha = 0.01\n self.config.isEarlyStopping = True\n self.tg = TrustGetter()\n self.config.walkCount = 30\n self.config.walkLength = 20\n self.config.walkDim = 20\n self.config.winSize = 5\n self.config.topK = 50\n\n def init_model(self, k):\n super(CUNE, self).init_model(k)\n self.user_sim = SimMatrix()\n self.generate_cu_net()\n self.deep_walk()\n self.compute_social_sim()\n\n def generate_cu_net(self):\n print('Building collaborative user network...')\n itemNet = {}\n for item in self.rg.trainSet_i:\n if len(self.rg.trainSet_i[item])>1:\n itemNet[item] = self.rg.trainSet_i[item]\n\n filteredRatings = defaultdict(list)\n for item in itemNet:\n for user in itemNet[item]:\n if itemNet[item][user] > 0:\n filteredRatings[user].append(item)\n\n self.CUNet = defaultdict(list)\n\n for user1 in filteredRatings:\n s1 = set(filteredRatings[user1])\n for user2 in filteredRatings:\n if user1 != user2:\n s2 = set(filteredRatings[user2])\n weight = len(s1.intersection(s2))\n if weight > 0:\n self.CUNet[user1]+=[user2] # * weight\n\n # cpprint(self.CUNet)\n pass\n def deep_walk(self):\n print('Generating random deep walks...')\n self.walks = []\n self.visited = defaultdict(dict)\n for user in self.CUNet:\n for t in range(self.config.walkCount):\n path = [str(user)]\n lastNode = user\n for i in range(1,self.config.walkLength):\n nextNode = choice(self.CUNet[lastNode])\n count=0\n while(nextNode in self.visited[lastNode]):\n nextNode = choice(self.CUNet[lastNode])\n #break infinite loop\n count+=1\n if count==self.config.walkLength: # 10\n break\n path.append(str(nextNode))\n self.visited[user][nextNode] = 1\n lastNode = nextNode\n self.walks.append(path)\n # shuffle(self.walks)\n # cpprint(self.walks)\n print('Generating user embedding...')\n self.model = w2v.Word2Vec(self.walks, size=self.config.walkDim, window=5, min_count=0, iter=3)\n print('User embedding generated.')\n pass\n\n def compute_social_sim(self):\n print('Constructing similarity matrix...')\n # self.W = np.zeros((self.rg.get_train_size()[0], self.config.walkDim))\n self.topKSim = defaultdict(dict)\n i = 0\n for user1 in self.CUNet:\n sims = {}\n for user2 in self.CUNet:\n if user1 != user2:\n wu1 = self.model[str(user1)]\n wu2 = self.model[str(user2)]\n sims[user2]=cosine(wu1,wu2) #若为空咋整\n self.topKSim[user1] = sorted(sims.items(), key=lambda d: d[1], reverse=True)[:self.config.topK]\n i += 1\n if i % 200 == 0:\n print('progress:', i, '/', len(self.CUNet))\n # print(self.topKSim)\n #构建被关注列表\n print('Constructing desimilarity matrix...')\n self.topKSimBy = defaultdict(dict)\n for user in self.topKSim:\n users=self.topKSim[user]\n for user2 in users:\n self.topKSimBy[user2[0]][user] = user2[1]\n print('Similarity matrix finished.')\n\n def train_model(self, k):\n super(CUNE, self).train_model(k)\n iteration = 0\n while iteration < self.config.maxIter:\n self.loss = 0\n for index, line in enumerate(self.rg.trainSet()):\n user, item, rating = line\n u = self.rg.user[user]\n i = self.rg.item[item]\n error = rating - self.predict(user, item)\n self.loss += 0.5 * error ** 2\n p, q = self.P[u], self.Q[i]\n\n social_term_p, social_term_loss = np.zeros((self.config.factor)), 0.0\n followees = self.topKSim[user] #self.tg.get_followees(user) #self.topKSim[user]\n # print(followees)\n for followee in followees:\n if self.rg.containsUser(followee[0]):\n # s = self.user_sim[user][followee]\n uf = self.P[self.rg.user[followee[0]]]\n social_term_p += followee[1]* (p - uf) \n social_term_loss += followee[1]* ((p - uf).dot(p - uf)) \n\n social_term_m = np.zeros((self.config.factor))\n followers = self.topKSimBy[user]\n followers = sorted(followers.items(), key=lambda d: d[1], reverse=True)[:self.config.topK]\n for follower in followers:\n if self.rg.containsUser(follower[0]):\n ug = self.P[self.rg.user[follower[0]]]\n social_term_m += follower[1]*(p - ug) \n\n\n # update latent vectors\n self.P[u] += self.config.lr * (\n error * q - self.config.alpha * (social_term_p + social_term_m) - self.config.lambdaP * p)\n self.Q[i] += self.config.lr * (error * p - self.config.lambdaQ * q)\n\n self.loss += 0.5 * self.config.alpha * social_term_loss\n\n self.loss += 0.5 * self.config.lambdaP * (self.P * self.P).sum() + 0.5 * self.config.lambdaQ * (\n self.Q * self.Q).sum()\n\n iteration += 1\n if self.isConverged(iteration):\n break\n\n\nif __name__ == '__main__':\n # srg = CUNE()\n # srg.train_model(0)\n # coldrmse = srg.predict_model_cold_users()\n # print('cold start user rmse is :' + str(coldrmse))\n # srg.show_rmse()\n\n rmses = []\n maes = []\n cunemf = CUNE()\n # cunemf.init_model(0)\n # cunemf.generate_cu_net()\n # cunemf.deep_walk()\n # print(bmf.rg.trainSet_u[1])\n cunemf.config.k_fold_num = 5\n for i in range(cunemf.config.k_fold_num):\n print('the %dth cross validation training' % i)\n cunemf.train_model(i)\n rmse, mae = cunemf.predict_model()\n rmses.append(rmse)\n maes.append(mae)\n rmse_avg = sum(rmses) / cunemf.config.k_fold_num\n mae_avg = sum(maes) / cunemf.config.k_fold_num\n print(\"the rmses are %s\" % rmses)\n print(\"the maes are %s\" % maes)\n print(\"the average of rmses is %s \" % rmse_avg)\n print(\"the average of maes is %s \" % mae_avg)\n", "meta": {"hexsha": "d901e1cf5b09946292eebcbb551ba6f1be1990c5", "size": 7375, "ext": "py", "lang": "Python", "max_stars_repo_path": "RSAlgorithms/model/social_cune.py", "max_stars_repo_name": "chenzheng128/SoRec", "max_stars_repo_head_hexsha": "deb045e3b9ce575671d08e15ec5a011b49e4d45f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-15T09:57:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-15T09:57:34.000Z", "max_issues_repo_path": "RSAlgorithms/model/social_cune.py", "max_issues_repo_name": "chenzheng128/SoRec", "max_issues_repo_head_hexsha": "deb045e3b9ce575671d08e15ec5a011b49e4d45f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RSAlgorithms/model/social_cune.py", "max_forks_repo_name": "chenzheng128/SoRec", "max_forks_repo_head_hexsha": "deb045e3b9ce575671d08e15ec5a011b49e4d45f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-12T07:32:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-12T07:32:47.000Z", "avg_line_length": 36.6915422886, "max_line_length": 114, "alphanum_fraction": 0.5465762712, "include": true, "reason": "import numpy", "num_tokens": 1808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.21469142413688416, "lm_q1q2_score": 0.11737999247954499}} {"text": "from __future__ import division, absolute_import, print_function\n\nfrom builtins import range\n\nimport numpy as np\nimport scipy.interpolate as interpolate\nimport scipy.integrate as integrate\nimport os\nimport sys\nfrom pkg_resources import resource_exists\nfrom pkg_resources import resource_filename\nfrom pkg_resources import resource_listdir\n\ntry:\n import fitsio\n fits_package = 'fitsio'\nexcept ImportError:\n try:\n import astropy.io.fits as pyfits\n fits_package = 'pyfits'\n except ImportError:\n try:\n import pyfits\n fits_package = 'pyfits'\n except ImportError:\n pass\n\nfrom .modtranGenerator import ModtranGenerator\n\nfrom .sharedNumpyMemManager import SharedNumpyMemManager as snmm\nfrom .fgcmLogger import FgcmLogger\n\nclass FgcmAtmosphereTable(object):\n \"\"\"\n Class to generate, store, and interpolate pre-computed atmospheres.\n\n parameters\n ----------\n atmConfig: dict\n Dictionary with FgcmAtmosphereTable config variables\n atmosphereTableFile: str, optional\n Name of the table file\n fgcmLog: FgcmLog, optional\n Logger\n \"\"\"\n\n def __init__(self, atmConfig, atmosphereTableFile=None, fgcmLog=None):\n\n if fgcmLog is None:\n self.fgcmLog = FgcmLogger('dummy.log', 'INFO', printLogger=True)\n else:\n self.fgcmLog = fgcmLog\n\n if atmosphereTableFile is not None:\n # We have an atmosphereTableFile, so read that\n self.atmosphereTableFile = atmosphereTableFile\n self.atmConfig = atmConfig\n else:\n # get modTran stuff ready since we're going to be generating\n # also check the config\n requiredKeys = ['elevation',\n 'pmbRange','pmbSteps',\n 'pwvRange','pwvSteps',\n 'o3Range','o3Steps',\n 'tauRange','tauSteps',\n 'alphaRange','alphaSteps',\n 'zenithRange','zenithSteps',\n 'pmbStd','pwvStd','o3Std',\n 'tauStd','alphaStd','airmassStd']\n\n for key in requiredKeys:\n if key not in atmConfig:\n raise ValueError(\"Required %s not in atmConfig\" % (key))\n if 'Range' in key:\n if len(atmConfig[key]) != 2:\n raise ValueError(\"%s must have 2 elements\" % (key))\n\n self.atmConfig = atmConfig\n\n self.elevation = self.atmConfig['elevation']\n\n self.modGen = ModtranGenerator(self.elevation)\n self.pmbElevation = self.modGen.pmbElevation\n\n self.pmbStd = self.atmConfig['pmbStd']\n self.pwvStd = self.atmConfig['pwvStd']\n self.lnPwvStd = np.log(self.pwvStd)\n self.o3Std = self.atmConfig['o3Std']\n self.tauStd = self.atmConfig['tauStd']\n self.lnTauStd = np.log(self.tauStd)\n self.alphaStd = self.atmConfig['alphaStd']\n self.secZenithStd = self.atmConfig['airmassStd']\n self.zenithStd = np.arccos(1./self.secZenithStd)*180./np.pi\n\n if ('lambdaRange' in self.atmConfig):\n self.lambdaRange = np.array(self.atmConfig['lambdaRange'])\n else:\n self.lambdaRange = np.array([3000.0,11000.0])\n\n if ('lambdaStep' in self.atmConfig):\n self.lambdaStep = self.atmConfig['lambdaStep']\n else:\n self.lambdaStep = 0.5\n\n if ('lambdaNorm' in self.atmConfig):\n self.lambdaNorm = self.atmConfig['lambdaNorm']\n else:\n self.lambdaNorm = 7750.0\n\n self.o2Interpolator = None\n self.o3Interpolator = None\n self.rayleighInterpolator = None\n self.lnPwvInterpolator = None\n\n\n @staticmethod\n def getAvailableTables():\n \"\"\"\n Get list of installed tables\n\n parameters\n ----------\n None\n\n returns\n -------\n List of installed table names\n \"\"\"\n\n try:\n files = resource_listdir(__name__,'data/tables/')\n except:\n raise IOError(\"Could not find associated data/tables path!\")\n\n # build a dictionary and put in the key details of each...\n\n availableTables = {}\n\n for f in files:\n availableTables[os.path.basename(f)] = FgcmAtmosphereTable.getInfoDict(f)\n\n return availableTables\n\n @staticmethod\n def getInfoDict(atmosphereTableFile):\n \"\"\"\n Get information dictionary on a table file\n\n parameters\n ----------\n atmosphereTableFile: str\n Name of the table file\n\n returns\n -------\n infoDict: dict\n Dictionary with key parameters describing the table\n \"\"\"\n\n if fits_package == 'fitsio':\n parStruct = fitsio.read(atmosphereTableFile, ext='PARS')\n elif fits_package == 'pyfits':\n parStruct = pyfits.getdata(atmosphereTableFile, ext=('PARS', 1))\n else:\n raise IOError(\"Reading atmosphere tables not supported without fitsio/astropy.io.fits/pyfits\")\n\n infoDict = {'elevation':parStruct['ELEVATION'][0],\n 'pmbRange':[parStruct['PMB'][0][0], parStruct['PMB'][0][-1]],\n 'pmbSteps':parStruct['PMB'][0].size,\n 'pwvRange':[np.exp(parStruct['LNPWV'][0][0]),\n np.exp(parStruct['LNPWV'][0][-1])],\n 'pwvSteps':parStruct['LNPWV'][0].size,\n 'o3Range':[parStruct['O3'][0][0], parStruct['O3'][0][-1]],\n 'o3Steps':parStruct['O3'][0].size,\n 'tauRange':[np.exp(parStruct['LNTAU'][0][0]), np.exp(parStruct['LNTAU'][0][-1])],\n 'tauSteps':parStruct['LNTAU'][0].size,\n 'alphaRange':[parStruct['ALPHA'][0][0], parStruct['ALPHA'][0][-1]],\n 'alphaSteps':parStruct['ALPHA'][0].size,\n 'zenithRange':[np.rad2deg(np.arccos(1./parStruct['SECZENITH'][0][0])),\n np.rad2deg(np.arccos(1./parStruct['SECZENITH'][0][-1]))],\n 'zenithSteps':parStruct['SECZENITH'][0].size,\n 'pmbStd':parStruct['PMBSTD'][0],\n 'pwvStd':parStruct['PWVSTD'][0],\n 'o3Std':parStruct['O3STD'][0],\n 'tauStd':parStruct['TAUSTD'][0],\n 'alphaStd':parStruct['ALPHASTD'][0],\n 'airmassStd':parStruct['AIRMASSSTD'][0]}\n\n return infoDict\n\n @classmethod\n def initWithTableName(cls, atmosphereTableName):\n \"\"\"\n Initialize FgcmAtmosphereTable with a table name\n\n parameters\n ----------\n atmosphereTableName: str\n Name of atmosphere table\n\n returns\n -------\n FgcmAtmosphereTable: FgcmAtmosphereTable object\n\n notes\n -----\n Raises IOError if atmosphereTableName couldn't be found\n \"\"\"\n\n # first, check if we have something in the path...\n if os.path.isfile(atmosphereTableName):\n atmosphereTableFile = os.path.abspath(atmosphereTableName)\n print(\"Found atmosphereTableName: %s\" % (atmosphereTableName))\n else:\n # allow for a name with or without .fits extension\n if resource_exists(__name__,'data/tables/%s' % (atmosphereTableName)):\n testFile = 'data/tables/%s' % (atmosphereTableName)\n elif resource_exists(__name__,'data/tables/%s.fits' % (atmosphereTableName)):\n testFile = 'data/tables/%s.fits' % (atmosphereTableName)\n else:\n raise IOError(\"Could not find atmosphereTableName (%s) in the path or in data/tables/\" % (atmosphereTableName))\n try:\n atmosphereTableFile = resource_filename(__name__,testFile)\n except:\n raise IOError(\"Error finding atmosphereTableName (%s)\" % (atmosphereTableName))\n\n # will set self.atmConfig\n print(\"Found atmosphere file: %s\" % (atmosphereTableFile))\n atmConfig = FgcmAtmosphereTable.getInfoDict(atmosphereTableFile)\n\n return cls(atmConfig, atmosphereTableFile=atmosphereTableFile)\n\n def loadTable(self):\n \"\"\"\n Load atmosphere table\n\n parameters\n ----------\n None\n\n returns\n -------\n None\n \"\"\"\n\n # note that at this point these are the only options\n if fits_package == 'fitsio':\n parStruct = fitsio.read(self.atmosphereTableFile, ext='PARS')\n else:\n parStruct = pyfits.getdata(self.atmosphereTableFile, ext=('PARS', 1))\n\n\n self.elevation = parStruct['ELEVATION'][0]\n self.pmbElevation = parStruct['PMBELEVATION'][0]\n self.pmbStd = parStruct['PMBSTD'][0]\n self.pwvStd = parStruct['PWVSTD'][0]\n self.o3Std = parStruct['O3STD'][0]\n self.tauStd = parStruct['TAUSTD'][0]\n self.alphaStd = parStruct['ALPHASTD'][0]\n self.secZenithStd = parStruct['AIRMASSSTD'][0]\n self.lambdaRange = parStruct['LAMBDARANGE'][0]\n self.lambdaStep = parStruct['LAMBDASTEP'][0]\n self.lambdaNorm = parStruct['LAMBDANORM'][0]\n\n self.atmLambda = parStruct['ATMLAMBDA'][0]\n self.atmStdTrans = parStruct['ATMSTDTRANS'][0]\n\n self.pmb = parStruct['PMB'][0]\n self.pmbDelta = parStruct['PMBDELTA'][0]\n self.lnPwv = parStruct['LNPWV'][0]\n self.lnPwvDelta = parStruct['LNPWVDELTA'][0]\n self.o3 = parStruct['O3'][0]\n self.o3Delta = parStruct['O3DELTA'][0]\n self.lnTau = parStruct['LNTAU'][0]\n self.lnTauDelta = parStruct['LNTAUDELTA'][0]\n self.alpha = parStruct['ALPHA'][0]\n self.alphaDelta = parStruct['ALPHADELTA'][0]\n self.secZenith = parStruct['SECZENITH'][0]\n self.secZenithDelta = parStruct['SECZENITHDELTA'][0]\n\n if fits_package == 'fitsio':\n self.pwvAtmTable = fitsio.read(self.atmosphereTableFile, ext='PWVATM')\n self.o3AtmTable = fitsio.read(self.atmosphereTableFile, ext='O3ATM')\n self.o2AtmTable = fitsio.read(self.atmosphereTableFile, ext='O2ATM')\n self.rayleighAtmTable = fitsio.read(self.atmosphereTableFile, ext='RAYATM')\n else:\n self.pwvAtmTable = pyfits.getdata(self.atmosphereTableFile, ext=('PWVATM', 1))\n self.o3AtmTable = pyfits.getdata(self.atmosphereTableFile, ext=('O3ATM', 1))\n self.o2AtmTable = pyfits.getdata(self.atmosphereTableFile, ext=('O2ATM', 1))\n self.rayleighAtmTable = pyfits.getdata(self.atmosphereTableFile, ext=('RAYATM', 1))\n\n def generateTable(self):\n \"\"\"\n Generate atmosphere table using MODTRAN\n\n parameters\n ----------\n None\n\n returns\n -------\n None\n \"\"\"\n self.atmStd = self.modGen(pmb=self.pmbStd,pwv=self.pwvStd,\n o3=self.o3Std,tau=self.tauStd,\n alpha=self.alphaStd,zenith=self.zenithStd,\n lambdaRange=self.lambdaRange/10.0,\n lambdaStep=self.lambdaStep)\n self.atmLambda = self.atmStd['LAMBDA']\n self.atmStdTrans = self.atmStd['COMBINED']\n\n # get all the steps\n self.pmb = np.linspace(self.atmConfig['pmbRange'][0],\n self.atmConfig['pmbRange'][1],\n num=self.atmConfig['pmbSteps'])\n self.pmbDelta = self.pmb[1] - self.pmb[0]\n pmbPlus = np.append(self.pmb, self.pmb[-1] + self.pmbDelta)\n\n self.lnPwv = np.linspace(np.log(self.atmConfig['pwvRange'][0]),\n np.log(self.atmConfig['pwvRange'][1]),\n num=self.atmConfig['pwvSteps'])\n self.lnPwvDelta = self.lnPwv[1] - self.lnPwv[0]\n lnPwvPlus = np.append(self.lnPwv, self.lnPwv[-1] + self.lnPwvDelta)\n pwvPlus = np.exp(lnPwvPlus)\n\n self.o3 = np.linspace(self.atmConfig['o3Range'][0],\n self.atmConfig['o3Range'][1],\n num=self.atmConfig['o3Steps'])\n self.o3Delta = self.o3[1] - self.o3[0]\n o3Plus = np.append(self.o3, self.o3[-1] + self.o3Delta)\n\n self.lnTau = np.linspace(np.log(self.atmConfig['tauRange'][0]),\n np.log(self.atmConfig['tauRange'][1]),\n num=self.atmConfig['tauSteps'])\n self.lnTauDelta = self.lnTau[1] - self.lnTau[0]\n self.tau = np.exp(self.lnTau)\n lnTauPlus = np.append(self.lnTau, self.lnTau[-1] + self.lnTauDelta)\n tauPlus = np.exp(lnTauPlus)\n\n self.alpha = np.linspace(self.atmConfig['alphaRange'][0],\n self.atmConfig['alphaRange'][1],\n num=self.atmConfig['alphaSteps'])\n self.alphaDelta = self.alpha[1] - self.alpha[0]\n alphaPlus = np.append(self.alpha, self.alpha[-1] + self.alphaDelta)\n\n self.secZenith = np.linspace(1./np.cos(self.atmConfig['zenithRange'][0]*np.pi/180.),\n 1./np.cos(self.atmConfig['zenithRange'][1]*np.pi/180.),\n num=self.atmConfig['zenithSteps'])\n self.secZenithDelta = self.secZenith[1]-self.secZenith[0]\n self.zenith = np.arccos(1./self.secZenith)*180./np.pi\n secZenithPlus = np.append(self.secZenith, self.secZenith[-1] + self.secZenithDelta)\n zenithPlus = np.arccos(1./secZenithPlus)*180./np.pi\n\n # run MODTRAN a bunch of times\n\n self.fgcmLog.info(\"Generating %d*%d=%d PWV atmospheres...\" % (pwvPlus.size,zenithPlus.size,pwvPlus.size*zenithPlus.size))\n self.pwvAtmTable = np.zeros((pwvPlus.size,zenithPlus.size,self.atmLambda.size))\n\n for i in range(pwvPlus.size):\n sys.stdout.write('%d' % (i))\n sys.stdout.flush()\n for j in range(zenithPlus.size):\n sys.stdout.write('.')\n sys.stdout.flush()\n atm=self.modGen(pwv=pwvPlus[i],zenith=zenithPlus[j],\n lambdaRange=self.lambdaRange/10.0,\n lambdaStep=self.lambdaStep)\n self.pwvAtmTable[i,j,:] = atm['H2O']\n\n self.fgcmLog.info(\"\\nGenerating %d*%d=%d O3 atmospheres...\" % (o3Plus.size,zenithPlus.size,o3Plus.size*zenithPlus.size))\n self.o3AtmTable = np.zeros((o3Plus.size, zenithPlus.size, self.atmLambda.size))\n\n for i in range(o3Plus.size):\n sys.stdout.write('%d' % (i))\n sys.stdout.flush()\n for j in range(zenithPlus.size):\n sys.stdout.write('.')\n sys.stdout.flush()\n atm=self.modGen(o3=o3Plus[i],zenith=zenithPlus[j],\n lambdaRange=self.lambdaRange/10.0,\n lambdaStep=self.lambdaStep)\n self.o3AtmTable[i,j,:] = atm['O3']\n\n self.fgcmLog.info(\"\\nGenerating %d O2/Rayleigh atmospheres...\" % (zenithPlus.size))\n\n self.o2AtmTable = np.zeros((zenithPlus.size, self.atmLambda.size))\n self.rayleighAtmTable = np.zeros((zenithPlus.size, self.atmLambda.size))\n\n for j in range(zenithPlus.size):\n sys.stdout.write('.')\n sys.stdout.flush()\n atm=self.modGen(zenith=zenithPlus[j],\n lambdaRange=self.lambdaRange/10.0,\n lambdaStep=self.lambdaStep)\n self.o2AtmTable[j,:] = atm['O2']\n self.rayleighAtmTable[j,:] = atm['RAYLEIGH']\n\n self.fgcmLog.info(\"\\nDone.\")\n\n def saveTable(self, fileName, clobber=False):\n \"\"\"\n Save atmosphere table to a file\n\n parameters\n ----------\n fileName: str\n File name to save file\n clobber: bool, default=False\n Clobber fileName if it exists\n \"\"\"\n # at the moment, only work with fitsio...\n\n import fitsio\n\n if os.path.isfile(fileName) and not clobber:\n raise IOError(\"File %s already exists and clobber is set to False\" % (fileName))\n\n fits = fitsio.FITS(fileName, 'rw')\n\n parStruct = np.zeros(1, dtype=[('ELEVATION','f4'),\n ('PMBELEVATION','f4'),\n ('PMBSTD','f4'),\n ('PWVSTD','f4'),\n ('O3STD','f4'),\n ('TAUSTD','f4'),\n ('ALPHASTD','f4'),\n ('AIRMASSSTD','f4'),\n ('LAMBDARANGE','f4',2),\n ('LAMBDASTEP','f4'),\n ('LAMBDANORM','f4'),\n ('ATMLAMBDA','f4',self.atmLambda.size),\n ('ATMSTDTRANS','f4',self.atmStdTrans.size),\n ('PMB','f4',self.pmb.size),\n ('PMBDELTA','f4'),\n ('LNPWV','f4',self.lnPwv.size),\n ('LNPWVDELTA','f4'),\n ('O3','f4',self.o3.size),\n ('O3DELTA','f4'),\n ('LNTAU','f4',self.lnTau.size),\n ('LNTAUDELTA','f4'),\n ('ALPHA','f4',self.alpha.size),\n ('ALPHADELTA','f4'),\n ('SECZENITH','f4',self.secZenith.size),\n ('SECZENITHDELTA','f4')])\n\n parStruct['ELEVATION'] = self.elevation\n parStruct['PMBELEVATION'] = self.pmbElevation\n parStruct['PMBSTD'] = self.pmbStd\n parStruct['PWVSTD'] = self.pwvStd\n parStruct['O3STD'] = self.o3Std\n parStruct['TAUSTD'] = self.tauStd\n parStruct['ALPHASTD'] = self.alphaStd\n parStruct['AIRMASSSTD'] = self.secZenithStd\n parStruct['LAMBDARANGE'][:] = self.lambdaRange\n parStruct['LAMBDASTEP'][:] = self.lambdaStep\n parStruct['LAMBDANORM'][:] = self.lambdaNorm\n\n parStruct['ATMLAMBDA'][:] = self.atmLambda\n parStruct['ATMSTDTRANS'][:] = self.atmStdTrans\n\n parStruct['PMB'][:] = self.pmb\n parStruct['PMBDELTA'] = self.pmbDelta\n parStruct['LNPWV'][:] = self.lnPwv\n parStruct['LNPWVDELTA'] = self.lnPwvDelta\n parStruct['O3'][:] = self.o3\n parStruct['O3DELTA'] = self.o3Delta\n parStruct['LNTAU'][:] = self.lnTau\n parStruct['LNTAUDELTA'] = self.lnTauDelta\n parStruct['ALPHA'][:] = self.alpha\n parStruct['ALPHADELTA'] = self.alphaDelta\n parStruct['SECZENITH'][:] = self.secZenith\n parStruct['SECZENITHDELTA'] = self.secZenithDelta\n\n fits.write_table(parStruct, extname='PARS')\n\n fits.write_image(self.pwvAtmTable, extname='PWVATM')\n fits.write_image(self.o3AtmTable, extname='O3ATM')\n fits.write_image(self.o2AtmTable, extname='O2ATM')\n fits.write_image(self.rayleighAtmTable, extname='RAYATM')\n\n fits.close()\n\n\n def interpolateAtmosphere(self, lam=None, pmb=None, pwv=None, o3=None, tau=None,\n alpha=None, zenith=None, ctranslamstd=None):\n \"\"\"\n Interpolate the atmosphere table to generate an atmosphere without\n requiring MODTRAN be installed.\n\n parameters\n ----------\n lam: float array, optional\n wavelengths. Default is self.atmLambda\n pmb: float, optional\n pressure in millibar. Default to pmbStd\n pwv: float, optional\n pwv in mm. Default to pwvStd\n o3: float, optional\n ozone in Dobson. Default to o3Std\n tau: float, optional\n Aerosol optical depth. Default to tauStd\n alpha: float, optional\n Aerosol slope. Default to alphaStd\n zenith: float, optional\n Zenith angle (degrees). Default to zenithStd\n ctranslamstd: [ctrans, lamstd], optional\n Transmission adjustment constant and lambdastd.\n Default to [0.0, lamnorm]\n\n returns\n -------\n atmInterpolated: float array\n Interpolated atmosphere at self.atmLambda wavelengths\n \"\"\"\n\n if lam is None:\n lam = self.atmLambda\n if pmb is None:\n pmb = self.pmbStd\n if pwv is None:\n pwv = self.pwvStd\n if o3 is None:\n o3 = self.o3Std\n if tau is None:\n tau = self.tauStd\n if alpha is None:\n alpha = self.alphaStd\n if zenith is None:\n zenith = self.zenithStd\n if ctranslamstd is None:\n ctranslamstd = [0.0, 7750.0]\n\n if self.o2Interpolator is None:\n secZenithPlus = np.append(self.secZenith, self.secZenith[-1] + self.secZenithDelta)\n self.o2Interpolator = interpolate.RegularGridInterpolator((secZenithPlus, self.atmLambda), self.o2AtmTable)\n\n if self.rayleighInterpolator is None:\n secZenithPlus = np.append(self.secZenith, self.secZenith[-1] + self.secZenithDelta)\n self.rayleighInterpolator = interpolate.RegularGridInterpolator((secZenithPlus, self.atmLambda), self.rayleighAtmTable)\n\n if self.lnPwvInterpolator is None:\n lnPwvPlus = np.append(self.lnPwv, self.lnPwv[-1] + self.lnPwvDelta)\n secZenithPlus = np.append(self.secZenith, self.secZenith[-1] + self.secZenithDelta)\n self.lnPwvInterpolator = interpolate.RegularGridInterpolator((lnPwvPlus, secZenithPlus, self.atmLambda), self.pwvAtmTable)\n\n if self.o3Interpolator is None:\n o3Plus = np.append(self.o3, self.o3[-1] + self.o3Delta)\n secZenithPlus = np.append(self.secZenith, self.secZenith[-1] + self.secZenithDelta)\n self.o3Interpolator = interpolate.RegularGridInterpolator((o3Plus, secZenithPlus, self.atmLambda), self.o3AtmTable)\n\n # And finally the pressure correction\n pmbMolecularScattering = np.exp(-(pmb - self.pmbElevation) / self.pmbElevation)\n pmbMolecularAbsorption = pmbMolecularScattering ** 0.6\n pmbFactor = pmbMolecularScattering * pmbMolecularAbsorption\n\n _secZenith = np.clip(1./np.cos(np.radians(zenith)), self.secZenith[0], self.secZenith[-1])\n _lnPwv = np.clip(np.log(pwv), self.lnPwv[0], self.lnPwv[-1])\n _o3 = np.clip(o3, self.o3[0], self.o3[-1])\n atmInterpolated = (pmbFactor *\n self.o2Interpolator((_secZenith, lam)) *\n self.rayleighInterpolator((_secZenith, lam)) *\n self.lnPwvInterpolator((_lnPwv, _secZenith, lam)) *\n self.o3Interpolator((_o3, _secZenith, lam)) *\n (1.0 + ctranslamstd[0] * (lam - ctranslamstd[1]) / ctranslamstd[1]) *\n np.exp(-1.0 * tau * _secZenith * (lam / self.lambdaNorm)**(-alpha)))\n\n return atmInterpolated\n", "meta": {"hexsha": "9c25db9ce18a788be77c6a140a1e1aa653c27a7f", "size": 23369, "ext": "py", "lang": "Python", "max_stars_repo_path": "fgcm/fgcmAtmosphereTable.py", "max_stars_repo_name": "HyperSuprime-Cam/fgcm", "max_stars_repo_head_hexsha": "b6fff6f774b4a59903680bcf995ed72c9de661ba", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fgcm/fgcmAtmosphereTable.py", "max_issues_repo_name": "HyperSuprime-Cam/fgcm", "max_issues_repo_head_hexsha": "b6fff6f774b4a59903680bcf995ed72c9de661ba", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fgcm/fgcmAtmosphereTable.py", "max_forks_repo_name": "HyperSuprime-Cam/fgcm", "max_forks_repo_head_hexsha": "b6fff6f774b4a59903680bcf995ed72c9de661ba", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1426056338, "max_line_length": 134, "alphanum_fraction": 0.5535538534, "include": true, "reason": "import numpy,import scipy,import astropy", "num_tokens": 5889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.21206880435710534, "lm_q1q2_score": 0.11676664567927408}} {"text": "\"\"\"Beam models and chromaticity corrections.\"\"\"\nfrom __future__ import annotations\n\nfrom pathlib import Path\nimport logging\nimport hashlib\nfrom methodtools import lru_cache\nimport astropy.coordinates as apc\nimport astropy.time as apt\nimport h5py\nimport numpy as np\nimport scipy.interpolate as spi\nfrom tqdm import tqdm\nimport attr\n\nfrom . import coordinates as coords\nfrom .loss import ground_loss\nfrom . import sky_models\n\nfrom edges_io.h5 import HDF5Object\n\nfrom ..config import config\nfrom .. import const\nfrom edges_cal import (\n FrequencyRange,\n modelling as mdl,\n)\nfrom .data import BEAM_PATH\nfrom . import types as tp\n\nlogger = logging.getLogger(__name__)\n\n# Reference UTC observation time. At this time, the LST is 0.1666 (00:10 Hrs LST) at the\n# EDGES location. NOTE: this is used by default, but can be changed by the user anywhere\n# it is used.\nREFERENCE_TIME = apt.Time(\"2014-01-01T09:39:42\", location=const.edges_location)\n\n\n@attr.s\nclass Beam:\n beam = attr.ib()\n frequency = attr.ib()\n elevation = attr.ib()\n azimuth = attr.ib()\n simulator = attr.ib(default=None, converter=str)\n instrument = attr.ib(default=None, converter=str)\n raw_file = attr.ib(default=None, converter=str)\n\n @classmethod\n def from_hfss(\n cls,\n path: [str, Path],\n frequency: float,\n linear: bool = True,\n theta_min: float = 0,\n theta_max: float = 180,\n theta_resolution: float = 1,\n phi_min: float = 0,\n phi_max: float = 359,\n phi_resolution: float = 1,\n ) -> Beam:\n \"\"\"\n Create a Beam object from a HFSS file.\n\n Parameters\n ----------\n path\n Path to the file. Use :meth:`resolve_file` to get the absolute path\n from a a relative path (starting with ':').\n linear\n Whether the beam values are in linear units (or decibels)\n theta_min, theta_max\n Min/Max of the zenith angle (degrees)\n theta_resolution\n Resolution of the zenith angle.\n phi_min, phi_max\n Min/Max of the azimuth angles (degrees)\n phi_resolution\n The resolution of the azimuth angle.\n\n Returns\n -------\n beam\n The beam object.\n \"\"\"\n d = np.genfromtxt(path, skip_header=1, delimiter=\",\")\n theta = np.arange(theta_min, theta_max + theta_resolution, theta_resolution)\n phi = np.arange(phi_min, phi_max + phi_resolution, phi_resolution)\n\n beam_map = np.zeros((len(theta), len(phi)))\n for i in range(len(theta)):\n mask = d[:, 1] == theta[i]\n\n this_phi = d[mask, 0]\n this_power = d[mask, 2]\n\n this_phi[this_phi < 0] += 360\n this_phi, unique_inds = np.unique(this_phi, axis=0, return_index=True)\n this_power = this_power[unique_inds]\n\n this_power = this_power[np.argsort(this_phi)]\n\n if not linear:\n this_power = 10 ** (this_power / 10)\n\n this_power[np.isnan(this_power)] = 0\n beam_map[i, :] = this_power\n\n return Beam(\n frequency=np.array([frequency]),\n elevation=theta,\n azimuth=phi,\n beam=beam_map,\n simulator=\"hfss\",\n raw_file=path,\n )\n\n @classmethod\n def from_wipld(cls, path: tp.PathLike, az_antenna_axis: float = 0) -> Beam:\n \"\"\"Read a WIPL-D beam.\"\"\"\n with open(path) as fn:\n file_length = 0\n number_of_frequencies = 0\n\n flag_columns = False\n frequencies_list = []\n for line in fn:\n file_length += 1\n if line[2] == \">\":\n number_of_frequencies += 1\n frequencies_list.append(float(line[19:32]))\n elif not flag_columns:\n line_splitted = line.split()\n number_of_columns = len(line_splitted)\n flag_columns = True\n\n rows_per_frequency = (\n file_length - number_of_frequencies\n ) / number_of_frequencies\n\n output = np.zeros(\n (\n int(number_of_frequencies),\n int(rows_per_frequency),\n int(number_of_columns),\n )\n )\n\n frequencies = np.array(frequencies_list)\n\n with open(path) as fn:\n i = -1\n for line in fn:\n\n if line[2] == \">\":\n i += 1\n j = -1\n else:\n j += 1\n line_splitted = line.split()\n line_array = np.array(line_splitted, dtype=float)\n output[i, j, :] = line_array\n\n # Re-arrange data\n phi_u = np.unique(output[0, :, 0])\n theta_u = np.unique(output[0, :, 1])\n beam = np.zeros((len(frequencies), len(theta_u), len(phi_u)))\n\n for i in range(len(frequencies)):\n out_2D = output[i, :, :]\n\n phi = out_2D[:, 0]\n theta = (\n 90 - out_2D[:, 1]\n ) # theta is zero at the zenith, and goes to 180 deg\n gain = out_2D[:, 6]\n\n theta_u = np.unique(theta)\n it = np.argsort(theta_u)\n theta_a = theta_u[it]\n\n for j in range(len(theta_a)):\n phi_j = phi[theta == theta_a[j]]\n gain_j = gain[theta == theta_a[j]]\n\n ip = np.argsort(phi_j)\n gp = gain_j[ip]\n\n beam[i, j, :] = gp\n\n # Flip beam from theta to elevation\n beam_maps = beam[:, ::-1, :]\n\n # Change coordinates from theta/phi, to AZ/EL\n el = np.arange(0, 91)\n az = np.arange(0, 360)\n\n # Shifting beam relative to true AZ (referenced at due North)\n beam_maps_shifted = cls.shift_beam_maps(az_antenna_axis, beam_maps)\n\n return Beam(\n frequency=frequencies,\n azimuth=az,\n elevation=el,\n beam=beam_maps_shifted,\n simulator=\"wipl-d\",\n raw_file=path,\n )\n\n @classmethod\n def from_ideal(cls, delta_f=2, f_low=40, f_high=200, delta_az=1, delta_el=1):\n \"\"\"Create an ideal beam that is completely unity.\"\"\"\n freq = np.arange(f_low, f_high, delta_f)\n az = np.arange(0, 360, delta_az)\n el = np.arange(0, 90 + 0.1 * delta_el, delta_el)\n return Beam(\n frequency=freq,\n azimuth=az,\n elevation=el,\n beam=np.ones((len(freq), len(el), len(az))),\n simulator=\"ideal\",\n )\n\n @classmethod\n def from_feko(cls, path: [str, Path], az_antenna_axis: float = 0) -> Beam:\n \"\"\"\n Read a FEKO beam file.\n\n Parameters\n ----------\n filename\n The path to the file.\n az_antenna_axis\n The azimuth of the primary antenna axis, in degrees.\n\n Returns\n -------\n beam_maps\n A ``(Nfreq, Nel, Naz)`` array giving values of the beam. Note that elevation\n and azimuth are always in 1-degree increments.\n freq\n The frequencies at which the beam is defined.\n \"\"\"\n filename = Path(path)\n\n data = np.genfromtxt(str(filename))\n frequency = []\n with open(filename) as fl:\n for line in fl.readlines():\n if line.startswith(\"#FREQUENCY\"):\n line = line.split(\" \")\n indx = line.index(\"MHz\")\n frequency.append(float(line[indx - 1]))\n freq = FrequencyRange(np.array(frequency))\n\n # Loading data and convert to linear representation\n beam_maps = np.zeros((len(frequency), 91, 360))\n for i in range(len(frequency)):\n beam_maps[i] = (10 ** (data[(i * 360) : ((i + 1) * 360), 2::] / 10)).T\n\n # Shifting beam relative to true AZ (referenced at due North)\n # Due to angle of orientation of excited antenna panels relative to due North\n beam_maps = cls.shift_beam_maps(az_antenna_axis, beam_maps)\n\n return Beam(\n frequency=freq.freq,\n beam=beam_maps,\n azimuth=np.arange(0, 360),\n elevation=np.arange(0, 91),\n simulator=\"feko\",\n raw_file=path,\n )\n\n @classmethod\n def from_cst(\n cls,\n file_name_prefix: tp.PathLike,\n f_low: int = 40,\n f_high: int = 100,\n freq_p: int = 61,\n theta_p: float = 181,\n phi_p: float = 361,\n az_antenna_axis: float = 0,\n ) -> Beam:\n \"\"\"\n Read a CST beam file.\n\n Parameters\n ----------\n filename\n The path to the file.\n az_antenna_axis\n The azimuth of the primary antenna axis, in degrees.\n f_low, f_high\n lower and higher frequency bounds\n freq_p\n Number of frequency points in the simulation file.\n theta_p\n Number of zenith angle points in the simulation file.\n phi_p\n Number of azimuth points in the simulation file.\n\n Returns\n -------\n beam\n The beam object.\n \"\"\"\n phi_t = np.zeros((freq_p, theta_p * phi_p))\n frequency = np.linspace(f_low, f_high, freq_p)\n beam_square = np.zeros((freq_p, theta_p, phi_p))\n res = (f_high - f_low) / (freq_p - 1)\n\n for i in range(freq_p):\n n = int(i * res + f_low)\n fc_file = open(\n file_name_prefix + \"farfield (f=\" + str(n) + \") [1].txt\", \"rb\"\n ) #\n for x, line in enumerate(fc_file):\n if x > 1:\n check = 0\n for o in range(len(line)):\n\n if line[o] != \"\":\n check = check + 1\n if check == 3:\n phi_t[i][x - 2] = float(line.split()[2])\n\n fc_file.close()\n for i in range(freq_p):\n for x in range(phi_p):\n beam_square[i, :, x] = phi_t[i, x * theta_p : (x + 1) * theta_p]\n beam_square[i, :, 0 : int(phi_p / 2)] = beam_square[\n i, :, int(phi_p / 2) : phi_p - 1\n ]\n\n freq = FrequencyRange(np.array(frequency))\n beam_square[:, 91:, :] = 0\n beam_maps = np.flip(beam_square[:, :91, :360], axis=1)\n # Shifting beam relative to true AZ (referenced at due North)\n # Due to angle of orientation of excited antenna panels relative to due North\n beam_maps = cls.shift_beam_maps(az_antenna_axis, beam_maps)\n\n return Beam(\n frequency=freq.freq,\n beam=beam_maps,\n azimuth=np.arange(0, 360),\n elevation=np.arange(0, 91),\n simulator=\"cst\",\n raw_file=file_name_prefix,\n )\n\n @classmethod\n def from_feko_raw(\n cls,\n file_name_prefix: tp.PathLike,\n ext: str = \"txt\",\n f_low: int = 40,\n f_high: int = 100,\n freq_p: int = 61,\n theta_p: float = 181,\n phi_p: float = 361,\n az_antenna_axis: float = 0,\n ) -> Beam:\n \"\"\"\n Read a FEKO beam file.\n\n Parameters\n ----------\n filename\n The path to the file.\n az_antenna_axis\n The azimuth of the primary antenna axis, in degrees.\n f_low, f_high\n lower and higher frequency bounds\n freq_p\n Number of frequency points in the simulation file.\n theta_p\n Number of zenith angle points in the simulation file.\n phi_p\n Number of azimuth points in the simulation file.\n\n Returns\n -------\n beam\n The beam object.\n \"\"\"\n beam_square = np.zeros((freq_p, theta_p, phi_p))\n frequency = np.linspace(f_low, f_high, freq_p)\n f1 = open(str(file_name_prefix) + \"_0-90.\" + ext)\n f2 = open(str(file_name_prefix) + \"_91-180.\" + ext)\n f3 = open(str(file_name_prefix) + \"_181-270.\" + ext)\n f4 = open(str(file_name_prefix) + \"_271-360.\" + ext)\n\n z = (\n theta_p * 91 + 10\n ) # ---> change this to no.of theta * no.of phi + No.of header lines\n\n for index, line in enumerate(f1):\n if index % z == 0:\n co = 0\n if index % z >= 10:\n x = list(map(float, line.split()))\n beam_square[int(index / z), co % theta_p, int(co / theta_p)] = 10 ** (\n x[8] / 10\n )\n co += 1\n\n z = theta_p * 90 + 10 #\n\n for index, line in enumerate(f2):\n if index % z == 0:\n co = 0\n if index % z >= 10:\n x = list(map(float, line.split()))\n beam_square[\n int(index / z), co % theta_p, int(co / theta_p) + 91\n ] = 10 ** (x[8] / 10)\n co += 1\n\n for index, line in enumerate(f3):\n if index % z == 0:\n co = 0\n if index % z >= 10:\n x = list(map(float, line.split()))\n beam_square[\n int(index / z), co % theta_p, int(co / theta_p) + 181\n ] = 10 ** (x[8] / 10)\n co += 1\n\n for index, line in enumerate(f4):\n if index % z == 0:\n co = 0\n if index % z >= 10:\n x = list(map(float, line.split()))\n beam_square[\n int(index / z), co % theta_p, int(co / theta_p) + 271\n ] = 10 ** (x[8] / 10)\n co += 1\n\n freq = FrequencyRange(np.array(frequency))\n beam_square[:, 90:, :] = 0\n beam_maps = np.flip(beam_square[:, :91, :360], axis=1)\n # Shifting beam relative to true AZ (referenced at due North)\n # Due to angle of orientation of excited antenna panels relative to due North\n beam_maps = cls.shift_beam_maps(az_antenna_axis, beam_maps)\n\n return Beam(\n frequency=freq.freq,\n beam=beam_maps,\n azimuth=np.arange(0, 360),\n elevation=np.arange(0, 91),\n simulator=\"feko\",\n raw_file=file_name_prefix,\n )\n\n @classmethod\n def get_beam_path(cls, band: str, kind: str | None = None) -> Path:\n \"\"\"Get a standard path to a beam file.\"\"\"\n pth = BEAM_PATH / band / \"default.txt\" if not kind else kind + \".txt\"\n if not pth.exists():\n raise FileNotFoundError(f\"No beam exists for band={band}.\")\n return pth\n\n def at_freq(\n self,\n freq: np.ndarray,\n model: mdl.Model = mdl.Polynomial(\n n_terms=13, transform=mdl.ScaleTransform(scale=75.0)\n ),\n ) -> Beam:\n \"\"\"\n Interpolate the beam to a new set of frequencies.\n\n Parameters\n ----------\n freq\n Frequencies to interpolate to.\n\n Returns\n -------\n beam\n The Beam object at the new frequencies.\n \"\"\"\n if len(self.frequency) < 3:\n raise ValueError(\n \"Can't freq-interpolate beam that has fewer than three frequencies.\"\n )\n\n # Frequency interpolation\n interp_beam = np.zeros((len(freq), len(self.elevation), len(self.azimuth)))\n cached_model = model.at(x=self.frequency)\n for i, bm in enumerate(self.beam.T):\n for j, b in enumerate(bm):\n model_fit = cached_model.fit(ydata=b)\n interp_beam[:, j, i] = model_fit.evaluate(freq)\n\n return Beam(\n frequency=freq,\n azimuth=self.azimuth,\n elevation=self.elevation,\n beam=interp_beam,\n )\n\n def smoothed(\n self,\n model: mdl.Model = mdl.Polynomial(n_terms=12),\n ) -> Beam:\n \"\"\"\n Smoothes the beam within its same set of frequencies.\n\n ----------\n\n Returns\n -------\n beam\n The Beam object smoothed over its same frequencies.\n \"\"\"\n if len(self.frequency) < 3:\n raise ValueError(\n \"Can't freq-interpolate beam that has fewer than three frequencies.\"\n )\n\n # Frequency smoothing\n smooth_beam = np.zeros_like(self.beam)\n cached_model = model.at(x=self.frequency)\n for i, bm in enumerate(self.beam.T):\n for j, b in enumerate(bm):\n model_fit = cached_model.fit(ydata=b)\n smooth_beam[:, j, i] = model_fit.evaluate()\n return Beam(\n frequency=self.frequency,\n azimuth=self.azimuth,\n elevation=self.elevation,\n beam=smooth_beam,\n )\n\n @staticmethod\n def shift_beam_maps(az_antenna_axis: float, beam_maps: np.ndarray):\n \"\"\"Rotate beam maps around an axis.\n\n Parameters\n ----------\n az_antenna_axis\n The aximuth angle of the antenna axis.\n beam_maps\n Beam maps as a function of frequency, za and az.\n\n Returns\n -------\n beam maps\n Array of the same shape as the input, but rotated.\n \"\"\"\n if az_antenna_axis < 0:\n index = -az_antenna_axis\n bm1 = beam_maps[:, :, index::]\n bm2 = beam_maps[:, :, 0:index]\n return np.append(bm1, bm2, axis=2)\n elif az_antenna_axis > 0:\n index = az_antenna_axis\n bm1 = beam_maps[:, :, 0:(-index)]\n bm2 = beam_maps[:, :, (360 - index) : :]\n return np.append(bm2, bm1, axis=2)\n else:\n return beam_maps\n\n @classmethod\n def resolve_file(\n cls,\n path: tp.PathLike,\n band: str | None = None,\n configuration: str = \"default\",\n simulator: str = \"feko\",\n ) -> Path:\n \"\"\"Resolve a file path to a standard location.\"\"\"\n if str(path) == \":\":\n if band is None:\n raise ValueError(\"band must be given if path starts with a colon (:)\")\n\n # Get the default beam file.\n return BEAM_PATH / band / f\"{configuration}.txt\"\n elif str(path).startswith(\":\"):\n if band is None:\n raise ValueError(\"band must be given if path starts with a colon (:)\")\n\n # Use a beam file in the standard directory.\n return (\n Path(config[\"paths\"][\"beams\"]).expanduser()\n / f\"{band}/simulations/{simulator}/{str(path)[1:]}\"\n ).absolute()\n else:\n return Path(path).absolute()\n\n @classmethod\n def from_file(\n cls,\n band: str | None,\n simulator: str = \"feko\",\n beam_file: tp.PathLike = \":\",\n configuration: str = \"default\",\n rotation_from_north: float = 90,\n ) -> Beam:\n \"\"\"Read a beam from file.\"\"\"\n beam_file = cls.resolve_file(beam_file, band, configuration, simulator)\n\n if simulator == \"feko\":\n rotation_from_north -= 90\n out = cls.from_feko(beam_file, az_antenna_axis=rotation_from_north)\n elif simulator == \"wipl-d\": # Beams from WIPL-D\n out = cls.from_wipld(beam_file, rotation_from_north)\n elif simulator == \"hfss\":\n out = cls.from_hfss(beam_file)\n else:\n raise ValueError(f\"Unknown value for simulator: '{simulator}'\")\n\n out.instrument = band\n return out\n\n @lru_cache(maxsize=1000)\n def angular_interpolator(self, freq_indx: int):\n \"\"\"Return a callable function that interpolates the beam.\n\n The returned function has the signature ``interp(az, el)``, where ``az`` is\n azimuth in degrees, and ``el`` is elevation in degrees. They may be arrays,\n in which case they should be the same length.\n \"\"\"\n el = self.elevation * np.pi / 180 + np.pi / 2\n\n beam = self.beam[freq_indx]\n\n if el[-1] > 0.999 * np.pi:\n el = el[:-1]\n beam = beam[:-1]\n\n spl = spi.RectSphereBivariateSpline(\n el,\n self.azimuth * np.pi / 180,\n beam,\n pole_values=(None, beam[-1]),\n pole_exact=True,\n )\n return lambda az, el: spl(\n el * np.pi / 180 + np.pi / 2, az * np.pi / 180, grid=False\n )\n\n def between_freqs(self, low=0, high=np.inf) -> Beam:\n \"\"\"Return a new :class:`Beam` object restricted a given frequency range.\"\"\"\n mask = (self.frequency >= low) & (self.frequency <= high)\n return attr.evolve(self, frequency=self.frequency[mask], beam=self.beam[mask])\n\n def get_beam_solid_angle(self) -> float:\n \"\"\"Calculate the integrated beam solid angle.\"\"\"\n # Theta vector valid for the FEKO beams. In the beam, dimension 1 increases\n # from index 0 to 90 corresponding to elevation, which is 90-theta\n theta = self.elevation[::-1]\n\n sin_theta = np.sin(theta * (np.pi / 180))\n sin_theta_2D = np.tile(sin_theta, (360, 1)).T\n\n beam_integration = np.sum(self.beam * sin_theta_2D)\n return (1 / (4 * np.pi)) * ((np.pi / 180) ** 2) * beam_integration\n\n\nclass BeamFactor(HDF5Object):\n \"\"\"A non-interpolated beam factor.\"\"\"\n\n _structure = {\n \"frequency\": lambda x: (x.ndim == 1 and x.dtype == float),\n \"lst\": lambda x: (x.ndim == 1 and x.dtype == float),\n \"antenna_temp_above_horizon\": lambda x: (x.ndim == 2 and x.dtype == float),\n \"loss_fraction\": lambda x: (x.ndim == 2 and x.dtype == float),\n \"beam_factor\": lambda x: (x.ndim == 2 and x.dtype == float),\n \"meta\": {\n \"beam_file\": lambda x: isinstance(x, str),\n \"simulator\": lambda x: isinstance(x, str),\n \"f_low\": lambda x: isinstance(x, float),\n \"f_high\": lambda x: isinstance(x, float),\n \"normalize_beam\": lambda x: isinstance(x, (bool, np.bool_)),\n \"sky_model\": lambda x: isinstance(x, str),\n \"rotation_from_north\": lambda x: isinstance(x, float),\n \"index_model\": lambda x: isinstance(x, str),\n \"reference_frequency\": lambda x: isinstance(x, float),\n \"max_nside\": lambda x: isinstance(x, (int, np.int64)),\n },\n }\n\n @property\n def beam_factor(self):\n \"\"\"The beam chromaticity factor. Array is ``(n_lsts, n_freq)``.\"\"\"\n return self.load(\"beam_factor\")\n\n @property\n def frequency(self):\n \"\"\"The frequencies at which the beam factor is defined.\"\"\"\n return self.load(\"frequency\")\n\n @property\n def lsts(self):\n \"\"\"The LSTs at which the beam factor is defined.\"\"\"\n return self.load(\"lst\")\n\n\ndef sky_convolution_generator(\n lsts: np.ndarray,\n ground_loss_file: str,\n beam: Beam,\n sky_model: sky_models.SkyModel,\n index_model: sky_models.IndexModel,\n normalize_beam: bool,\n beam_smoothing: bool,\n smoothing_model: mdl.Model,\n location: apc.EarthLocation = const.edges_location,\n ref_time: apt.Time = REFERENCE_TIME,\n):\n \"\"\"\n Iterate through given LSTs and generate a beam*sky product at each freq and LST.\n\n This is a generator, so it will yield a single item at a time (to save on memory).\n\n Parameters\n ----------\n lsts\n The LSTs at which to evaluate the convolution.\n ground_loss_file\n A path to a file containing ground loss information.\n beam\n The beam to convolve.\n sky_model\n The sky model to convolve\n index_model\n The spectral index model of the sky model.\n normalize_beam\n Whether to ensure the beam is properly normalised.\n beam_interpolation\n Whether to smooth over freq axis\n\n Yields\n ------\n i\n The LST enumerator\n j\n The frequency enumerator\n mean_conv_temp\n The mean temperature after multiplying by the beam (above the horizon)\n conv_temp\n An array containing the temperature after multiuplying by the beam in each pixel\n above the horizon.\n sky\n An array containing the sky temperature in pixel above the horizon.\n beam\n An array containing the interpolatedbeam in pixels above the horizon\n time\n The local time at each LST.\n n_pixels\n The total number of pixels that are not masked.\n\n Examples\n --------\n Use this function as follows:\n\n >>> for i, j, mean_t, conv_t, sky, bm, time, npix in sky_convolution_generator():\n >>> print(conv_t)\n \"\"\"\n if beam_smoothing:\n beam = beam.smoothed(smoothing_model)\n sky_map = sky_model.at_freq(\n beam.frequency,\n index_model=index_model,\n )\n\n ground_gain = ground_loss(\n ground_loss_file, band=beam.instrument, freq=beam.frequency\n )\n galactic_coords = sky_model.get_sky_coords()\n\n # Get the local times corresponding to the given LSTs\n times = coords.lsts_to_times(lsts, ref_time, location)\n\n for i, time in tqdm(enumerate(times), unit=\"LST\"):\n # Transform Galactic coordinates of Sky Model to Local coordinates\n altaz = galactic_coords.transform_to(\n apc.AltAz(\n location=const.edges_location,\n obstime=time,\n )\n )\n az = np.asarray(altaz.az.deg)\n el = np.asarray(altaz.alt.deg)\n\n # Number of pixels over 4pi that are not 'nan'\n n_pix_tot = len(el)\n\n # Selecting coordinates above the horizon\n horizon_mask = el >= 0\n az_above_horizon = az[horizon_mask]\n el_above_horizon = el[horizon_mask]\n\n # Selecting sky data above the horizon\n sky_above_horizon = np.ones_like(sky_map) * np.nan\n sky_above_horizon[horizon_mask, :] = sky_map[horizon_mask, :]\n\n # Loop over frequency\n for j in tqdm(range(len(beam.frequency)), unit=\"Frequency\"):\n beam_above_horizon = np.ones(len(sky_map)) * np.nan\n beam_above_horizon[horizon_mask] = beam.angular_interpolator(j)(\n az_above_horizon, el_above_horizon\n )\n\n n_pix_ok = np.sum(~np.isnan(beam_above_horizon))\n\n # The nans are only above the horizon\n n_pix_tot_no_nan = n_pix_tot - (len(el_above_horizon) - n_pix_ok)\n\n if normalize_beam:\n solid_angle = np.nansum(beam_above_horizon) / n_pix_tot_no_nan\n beam_above_horizon *= ground_gain[j] / solid_angle\n\n antenna_temperature_above_horizon = (\n beam_above_horizon * sky_above_horizon[:, j]\n )\n\n yield (\n i,\n j,\n np.nansum(antenna_temperature_above_horizon) / n_pix_tot_no_nan,\n antenna_temperature_above_horizon,\n sky_above_horizon,\n beam_above_horizon,\n time,\n n_pix_tot_no_nan,\n )\n\n\ndef simulate_spectra(\n beam: Beam,\n ground_loss_file: [str, Path] = \":\",\n f_low: [None, float] = 0,\n f_high: [None, float] = np.inf,\n normalize_beam: bool = True,\n sky_model: sky_models.SkyModel = sky_models.Haslam408(),\n index_model: sky_models.IndexModel = sky_models.ConstantIndex(),\n lsts: np.ndarray = None,\n beam_smoothing: bool = True,\n smoothing_model: mdl.Model = mdl.Polynomial(n_terms=12),\n) -> tuple[np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"\n Simulate global spectra from sky and beam models.\n\n Parameters\n ----------\n band\n The band of the antenna (low, mid, high).\n beam\n A :class:`Beam` object.\n ground_loss_file\n A file pointing to a ground-loss model. By default, gets the default ground loss\n model for the given ``band``.\n f_low\n Minimum frequency to keep in the simulation (frequencies otherwise defined by\n the beam).\n f_high\n Maximum frequency to keep in the simulation (frequencies otherwise defined by\n the beam).\n normalize_beam\n Whether to normalize the beam to be maximum unity.\n sky_model\n A sky model to use.\n index_model\n An :class:`IndexModel` to use to generate different frequencies of the sky\n model.\n lsts\n The LSTs at which to simulate\n\n Returns\n -------\n antenna_temperature_above_horizon\n The antenna temperature for pixels above the horizon, shape (Nlst, Nfreq)\n freq\n The frequencies at which the simulation is defined.\n lst\n The LSTs at which the sim is defined.\n \"\"\"\n beam = beam.between_freqs(f_low, f_high)\n if lsts is None:\n lsts = np.arange(0, 24, 0.5)\n\n antenna_temperature_above_horizon = np.zeros((len(lsts), len(beam.frequency)))\n for i, j, temperature, _, _, _, _, _ in sky_convolution_generator(\n lsts,\n ground_loss_file,\n beam,\n sky_model,\n index_model,\n normalize_beam,\n beam_smoothing,\n smoothing_model,\n ):\n antenna_temperature_above_horizon[i, j] = temperature\n\n return antenna_temperature_above_horizon, beam.frequency, lsts\n\n\ndef antenna_beam_factor(\n beam: Beam,\n ground_loss_file: [str, Path] = \":\",\n f_low: float = 0,\n f_high: float = np.inf,\n normalize_beam: bool = True,\n sky_model: sky_models.SkyModel = sky_models.Haslam408(),\n index_model: sky_models.IndexModel = sky_models.GaussianIndex(),\n lsts: [None, np.ndarray] = None,\n save_dir: [None, str, Path] = None,\n save_fname: [None, str, Path, bool] = None,\n reference_frequency: [None, float] = None,\n beam_smoothing: bool = True,\n smoothing_model: mdl.Model = mdl.Polynomial(n_terms=12),\n):\n \"\"\"\n Calculate the antenna beam factor.\n\n Parameters\n ----------\n beam\n A :class:`Beam` object.\n ground_loss_file\n A file pointing to a ground-loss model. By default, gets the default ground loss\n model for the given ``band``.\n f_low\n Minimum frequency to keep in the simulation (frequencies otherwise defined by\n the beam).\n f_high\n Maximum frequency to keep in the simulation (frequencies otherwise defined by\n the beam).\n normalize_beam\n Whether to normalize the beam to be maximum unity.\n sky_model\n A sky model to use.\n index_model\n An :class:`IndexModel` to use to generate different frequencies of the sky\n model.\n twenty_min_per_lst\n How many periods of twenty minutes fit into each LST bin.\n save_dir\n The directory in which to save the output beam factor.\n save_fname\n The filename to save the output beam factor.\n reference_frequency\n The frequency to take as the \"reference\", i.e. where the chromaticity will\n be by construction unity.\n\n Returns\n -------\n beam_factor : :class`BeamFactor` instance\n \"\"\"\n if not save_dir:\n save_dir = Path(config[\"paths\"][\"beams\"]) / f\"{beam.instrument}/beam_factors/\"\n else:\n save_dir = Path(save_dir)\n\n if str(save_fname).startswith(\":\"):\n save_fname = Path(save_dir).absolute() / str(save_fname)[1:]\n\n beam = beam.between_freqs(f_low, f_high)\n\n if lsts is None:\n lsts = np.arange(0, 24, 0.5)\n\n # Get index of reference frequency\n if reference_frequency is None:\n reference_frequency = (f_high + f_low) / 2\n\n indx_ref_freq = np.argwhere(beam.frequency >= reference_frequency)[0][0]\n reference_frequency = beam.frequency[indx_ref_freq]\n\n antenna_temperature_above_horizon = np.zeros((len(lsts), len(beam.frequency)))\n convolution_ref = np.zeros((len(lsts), len(beam.frequency)))\n loss_fraction = np.zeros((len(lsts), len(beam.frequency)))\n\n for i, j, temperature, _, sky, bm, _, npix_no_nan in sky_convolution_generator(\n lsts,\n beam=beam,\n sky_model=sky_model,\n index_model=index_model,\n normalize_beam=normalize_beam,\n beam_smoothing=beam_smoothing,\n smoothing_model=smoothing_model,\n ground_loss_file=ground_loss_file,\n ):\n antenna_temperature_above_horizon[i, j] = temperature\n # Convolution between (beam at all frequencies) and (sky at reference frequency)\n convolution_ref[i, j] = np.nansum(bm * sky[:, indx_ref_freq])\n\n # Loss fraction\n loss_fraction[i, j] = 1 - np.nansum(bm) / npix_no_nan\n\n # Beam factor\n beam_factor = (convolution_ref.T / convolution_ref[:, indx_ref_freq]).T\n\n out = {\n \"frequency\": beam.frequency.astype(float),\n \"lst\": np.array(lsts).astype(float),\n \"antenna_temp_above_horizon\": antenna_temperature_above_horizon,\n \"loss_fraction\": loss_fraction,\n \"beam_factor\": beam_factor,\n \"meta\": {\n \"beam_file\": str(beam.raw_file),\n \"simulator\": beam.simulator,\n \"f_low\": float(f_low),\n \"f_high\": float(f_high),\n \"normalize_beam\": bool(normalize_beam),\n \"sky_model\": str(sky_model),\n \"index_model\": str(index_model),\n \"reference_frequency\": float(reference_frequency),\n \"rotation_from_north\": float(90),\n \"max_nside\": int(sky_model.max_res or 0),\n },\n }\n\n if save_fname is None:\n hsh = hashlib.md5(repr(out[\"meta\"]).encode()).hexdigest()\n save_fname = save_dir / (\n f\"{beam.simulator}_{sky_model.__class__.__name__}_\"\n f\"ref{reference_frequency:.2f}_{hsh}.h5\"\n )\n\n logger.info(f\"Writing out beam file to {save_fname}\")\n bf = BeamFactor.from_data(out, filename=save_fname)\n bf.write(clobber=True)\n\n return bf\n\n\nclass InterpolatedBeamFactor(HDF5Object):\n _structure = {\n \"beam_factor\": None,\n \"frequency\": None,\n \"lst\": None,\n }\n\n @classmethod\n def from_beam_factor(\n cls,\n beam_factor_file,\n band: str | None = None,\n lst_new: np.ndarray | None = None,\n f_new: np.ndarray | None = None,\n ):\n \"\"\"\n Interpolate beam factor to a new set of LSTs and frequencies.\n\n The LST interpolation is done using `griddata`, whilst the frequency\n interpolation is done using a polynomial fit.\n\n Parameters\n ----------\n beam_factor_file : path\n Path to a file containing beam factors produced by\n :func:`antenna_beam_factor`.\n If just a filename (no path), the `beams/band/beam_factors/` directory will\n be searched (dependent on the configured \"beams\" directory).\n band : str, optional\n If `beam_factor_file` is relative, the band is required to find the file.\n lst_new : array-like, optional\n The LSTs to interpolate to. By default, keep same LSTs as input.\n f_new : array-like, optional\n The frequencies to interpolate to. By default, keep same frequencies as\n input.\n \"\"\"\n beam_factor_file = Path(beam_factor_file).expanduser()\n if str(beam_factor_file).startswith(\":\"):\n beam_factor_file = (\n Path(config[\"paths\"][\"beams\"])\n / band\n / \"beam_factors\"\n / str(beam_factor_file)[1:]\n )\n\n if not beam_factor_file.exists():\n raise ValueError(f\"The beam factor file {beam_factor_file} does not exist!\")\n\n with h5py.File(beam_factor_file, \"r\") as fl:\n beam_factor = fl[\"beam_factor\"][...]\n freq = fl[\"frequency\"][...]\n lst = fl[\"lst\"][...]\n\n # Wrap beam factor and LST for 24-hr interpolation\n beam_factor = np.vstack((beam_factor[-1], beam_factor, beam_factor[0]))\n lst0 = np.append(lst[-1] - 24, lst)\n lst = np.append(lst0, lst[0] + 24)\n\n if lst_new is not None:\n beam_factor_lst = np.zeros((len(lst_new), len(freq)))\n for i, bf in enumerate(beam_factor.T):\n beam_factor_lst[:, i] = spi.interp1d(lst, bf, kind=\"cubic\")(lst_new)\n lst = lst_new\n else:\n beam_factor_lst = beam_factor\n\n if f_new is not None:\n # Interpolating beam factor to high frequency resolution\n beam_factor_freq = np.zeros((len(beam_factor_lst), len(f_new)))\n for i, bf in enumerate(beam_factor_lst):\n beam_factor_freq[i] = spi.interp1d(freq, bf, kind=\"cubic\")(f_new)\n\n freq = f_new\n else:\n beam_factor_freq = beam_factor_lst\n\n return cls.from_data(\n {\"beam_factor\": beam_factor_freq, \"frequency\": freq, \"lst\": lst}\n )\n\n def evaluate(self, lst):\n \"\"\"Fast nearest-neighbour evaluation of the beam factor for a given LST.\"\"\"\n beam_factor = np.zeros((len(lst), len(self[\"frequency\"])))\n\n for i, lst_ in enumerate(lst):\n index = np.argmin(np.abs(self[\"lst\"] - lst_))\n beam_factor[i] = self[\"beam_factor\"][index]\n\n return beam_factor\n", "meta": {"hexsha": "de8e44f2a8b3c838512b9feba86cd5523cf57613", "size": 36971, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/edges_analysis/analysis/beams.py", "max_stars_repo_name": "edges-collab/edges-analysis", "max_stars_repo_head_hexsha": "b5165c55b7ae4334f6ac0578ade76ad875612605", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/edges_analysis/analysis/beams.py", "max_issues_repo_name": "edges-collab/edges-analysis", "max_issues_repo_head_hexsha": "b5165c55b7ae4334f6ac0578ade76ad875612605", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 99, "max_issues_repo_issues_event_min_datetime": "2020-02-04T14:55:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T21:35:57.000Z", "max_forks_repo_path": "src/edges_analysis/analysis/beams.py", "max_forks_repo_name": "edges-collab/edges-analysis", "max_forks_repo_head_hexsha": "b5165c55b7ae4334f6ac0578ade76ad875612605", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9803746655, "max_line_length": 88, "alphanum_fraction": 0.563630954, "include": true, "reason": "import numpy,import scipy,import astropy", "num_tokens": 8711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725051, "lm_q2_score": 0.21469141911224193, "lm_q1q2_score": 0.11654808864823596}} {"text": "# -*- coding: utf-8 -*-\n\"\"\"\nAcademy Color Encoding System - Input Transform\n===============================================\n\nDefines the *Academy Color Encoding System* (ACES) *Input Transform* utilities:\n\n- :func:`colour.sd_to_aces_relative_exposure_values`\n\nSee Also\n--------\n`RGB Colourspaces Jupyter Notebook\n`_\n\nReferences\n----------\n- :cite:`Forsythe2018` : Forsythe, A. (2018). Private Discussion with\n Mansencal, T.\n- :cite:`TheAcademyofMotionPictureArtsandSciences2014q` : The Academy of\n Motion Picture Arts and Sciences, Science and Technology Council, & Academy\n Color Encoding System (ACES) Project Subcommittee. (2014). Technical\n Bulletin TB-2014-004 - Informative Notes on SMPTE ST 2065-1 - Academy Color\n Encoding Specification (ACES). Retrieved from\n https://github.com/ampas/aces-dev/tree/master/documents\n- :cite:`TheAcademyofMotionPictureArtsandSciences2014r` : The Academy of\n Motion Picture Arts and Sciences, Science and Technology Council, & Academy\n Color Encoding System (ACES) Project Subcommittee. (2014). Technical\n Bulletin TB-2014-012 - Academy Color Encoding System Version 1.0 Component\n Names. Retrieved from\n https://github.com/ampas/aces-dev/tree/master/documents\n- :cite:`TheAcademyofMotionPictureArtsandSciencese` : The Academy of Motion\n Picture Arts and Sciences, Science and Technology Council, & Academy Color\n Encoding System (ACES) Project Subcommittee. (n.d.). Academy Color Encoding\n System. Retrieved February 24, 2014, from\n http://www.oscars.org/science-technology/council/projects/aces.html\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport numpy as np\n\nfrom colour.colorimetry import ILLUMINANTS_SDS, sd_to_XYZ\nfrom colour.models import XYZ_to_xy\nfrom colour.models.rgb import (ACES_2065_1_COLOURSPACE, ACES_RICD, RGB_to_XYZ,\n XYZ_to_RGB, normalised_primary_matrix)\nfrom colour.utilities import from_range_1, tsplit\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013-2019 - Colour Developers'\n__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-developers@colour-science.org'\n__status__ = 'Production'\n\n__all__ = [\n 'FLARE_PERCENTAGE', 'S_FLARE_FACTOR', 'sd_to_aces_relative_exposure_values'\n]\n\nFLARE_PERCENTAGE = 0.00500\nS_FLARE_FACTOR = 0.18000 / (0.18000 + FLARE_PERCENTAGE)\n\n\ndef sd_to_aces_relative_exposure_values(\n sd,\n illuminant=ILLUMINANTS_SDS['D65'],\n apply_chromatic_adaptation=False,\n chromatic_adaptation_transform='CAT02'):\n \"\"\"\n Converts given spectral distribution to *ACES2065-1* colourspace relative\n exposure values.\n\n Parameters\n ----------\n sd : SpectralDistribution\n Spectral distribution.\n illuminant : SpectralDistribution, optional\n *Illuminant* spectral distribution.\n apply_chromatic_adaptation : bool, optional\n Whether to apply chromatic adaptation using given transform.\n chromatic_adaptation_transform : unicode, optional\n **{'CAT02', 'XYZ Scaling', 'Von Kries', 'Bradford', 'Sharp',\n 'Fairchild', 'CMCCAT97', 'CMCCAT2000', 'CAT02_BRILL_CAT', 'Bianco',\n 'Bianco PC'}**,\n *Chromatic adaptation* transform.\n\n Returns\n -------\n ndarray, (3,)\n *ACES2065-1* colourspace relative exposure values array.\n\n Notes\n -----\n\n +------------+-----------------------+---------------+\n | **Range** | **Scale - Reference** | **Scale - 1** |\n +============+=======================+===============+\n | ``XYZ`` | [0, 100] | [0, 1] |\n +------------+-----------------------+---------------+\n\n - The chromatic adaptation method implemented here is a bit unusual\n as it involves building a new colourspace based on *ACES2065-1*\n colourspace primaries but using the whitepoint of the illuminant that\n the spectral distribution was measured under.\n\n References\n ----------\n :cite:`Forsythe2018`,\n :cite:`TheAcademyofMotionPictureArtsandSciences2014q`,\n :cite:`TheAcademyofMotionPictureArtsandSciences2014r`,\n :cite:`TheAcademyofMotionPictureArtsandSciencese`\n\n Examples\n --------\n >>> from colour import COLOURCHECKERS_SDS\n >>> sd = COLOURCHECKERS_SDS['ColorChecker N Ohta']['dark skin']\n >>> sd_to_aces_relative_exposure_values(sd) # doctest: +ELLIPSIS\n array([ 0.1171785..., 0.0866347..., 0.0589707...])\n >>> sd_to_aces_relative_exposure_values(sd,\n ... apply_chromatic_adaptation=True) # doctest: +ELLIPSIS\n array([ 0.1180766..., 0.0869023..., 0.0589104...])\n \"\"\"\n\n shape = ACES_RICD.shape\n if sd.shape != ACES_RICD.shape:\n sd = sd.copy().align(shape)\n\n if illuminant.shape != ACES_RICD.shape:\n illuminant = illuminant.copy().align(shape)\n\n s_v = sd.values\n i_v = illuminant.values\n\n r_bar, g_bar, b_bar = tsplit(ACES_RICD.values)\n\n def k(x, y):\n \"\"\"\n Computes the :math:`K_r`, :math:`K_g` or :math:`K_b` scale factors.\n \"\"\"\n\n return 1 / np.sum(x * y)\n\n k_r = k(i_v, r_bar)\n k_g = k(i_v, g_bar)\n k_b = k(i_v, b_bar)\n\n E_r = k_r * np.sum(i_v * s_v * r_bar)\n E_g = k_g * np.sum(i_v * s_v * g_bar)\n E_b = k_b * np.sum(i_v * s_v * b_bar)\n\n E_rgb = np.array([E_r, E_g, E_b])\n\n # Accounting for flare.\n E_rgb += FLARE_PERCENTAGE\n E_rgb *= S_FLARE_FACTOR\n\n if apply_chromatic_adaptation:\n xy = XYZ_to_xy(sd_to_XYZ(illuminant) / 100)\n NPM = normalised_primary_matrix(ACES_2065_1_COLOURSPACE.primaries, xy)\n XYZ = RGB_to_XYZ(E_rgb, xy, ACES_2065_1_COLOURSPACE.whitepoint, NPM,\n chromatic_adaptation_transform)\n E_rgb = XYZ_to_RGB(XYZ, ACES_2065_1_COLOURSPACE.whitepoint,\n ACES_2065_1_COLOURSPACE.whitepoint,\n ACES_2065_1_COLOURSPACE.XYZ_to_RGB_matrix)\n\n return from_range_1(E_rgb)\n", "meta": {"hexsha": "b9efab312dbcf1c293fe65234729493c6052bacf", "size": 6098, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/models/rgb/aces_it.py", "max_stars_repo_name": "MaxSchambach/colour", "max_stars_repo_head_hexsha": "3f3685d616fda4be58cec20bc1e16194805d7e2d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "colour/models/rgb/aces_it.py", "max_issues_repo_name": "MaxSchambach/colour", "max_issues_repo_head_hexsha": "3f3685d616fda4be58cec20bc1e16194805d7e2d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colour/models/rgb/aces_it.py", "max_forks_repo_name": "MaxSchambach/colour", "max_forks_repo_head_hexsha": "3f3685d616fda4be58cec20bc1e16194805d7e2d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5149700599, "max_line_length": 79, "alphanum_fraction": 0.6608724172, "include": true, "reason": "import numpy", "num_tokens": 1663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.20181322466072713, "lm_q1q2_score": 0.1165462018747729}} {"text": "#!/usr/bin/env python3\n\"\"\"\nThis file contains classes for calculating the position of the indicator\nwith Numpy\n\"\"\"\nimport sys\nimport numpy as np\nfrom itertools import permutations\nfrom numba import jit\n\n\nclass Indicator:\n \"\"\"\n This is the implementation of the indicator as detailed in our 2019\n paper on EcCLC\n \"\"\"\n\n def __init__(self):\n # Dictionary (atom_type: rdh) These are used to calculate\n # rdh0 and pmax\n self.rxh = {'OT': 1.0, 'SOT': 1.0, 'CLA': 1.4, 'OC': 1.0}\n # self.num_rdh0 = 0\n self.rlist = 3.5\n # The coordinates of the donor\n self.x_d = np.zeros(3, dtype=float)\n # Number of acceptors within rlist of donor\n self.num_acceptors = 0\n # Number of protons bound to donor\n self.num_h = 0\n # Location of the indicator\n self.x_i = np.zeros(3, dtype=float)\n # Identity of the donor\n self.donor = 0\n # Describes a proton hop\n # elements are: [[int:ind of proton, which acceptor hop to, pmj], ...]\n self.hop = []\n # Location of the acceptors\n self.x_as = []\n # Print flag\n self.print_all = False\n # Output reaction coordinates?\n self.output_freq = 0\n # Where to print indicator reaction coordinate information?\n self.log_path = 'indicator.log'\n self.xyz_path = 'donor.xyz'\n # Where to print debug information?\n self.ofi = sys.stdout\n # Log file object\n self._lfi = None\n self._xyz = None\n self.max_xyz_atoms = 5\n # This step\n self.step = 0\n\n def initialize_outind(self, path):\n \"Open the outind file\"\n self.indfi = open(path, 'w')\n print(\"In indicator outfile, first atom is indicator 2nd mcec\")\n\n def set_output_freq(self, freq, prefix=''):\n \"\"\"\n Initialize variables for writing the xyz and the log file\n\n Parameters\n ----------\n freq: int\n output frequency\n prefix: str\n file prefix\n \"\"\"\n try:\n int(freq)\n except TypeError:\n sys.exit(\"Error: indicator output frequency must be an integer\")\n if freq > 0:\n self.output_freq = freq\n if prefix != '':\n self.log_path = prefix + '-' + self.log_path\n self.xyz_path = prefix + '-' + self.xyz_path\n self._lfi = open(self.log_path, 'w')\n self._lfi.write(\"# Step rho dr\\n\")\n self._xyz = open(self.xyz_path, 'w')\n\n def reset_hop(self):\n \"\"\"\n After proton hop, clear the list of hops\n \"\"\"\n self.hop = []\n\n def _write_log(self, p, dr, coords=None):\n \"\"\"\n Write the results of a step\n Write the rho and dr coordinates\n If a matrix of coordinates is present, write them to the xyz file\n\n Parameters\n ----------\n :param p:\n :param dr:\n :param coords:\n :return:\n \"\"\"\n self._lfi.write('{0:10d} {1:10.6f} {2:10.6f}\\n'.format(\n self.step, p, dr))\n\n if coords is None:\n return\n #if not coords.any():\n # return\n\n natoms = coords.shape[0]\n\n try:\n self._xyz.write('%d\\n' % self.max_xyz_atoms)\n except:\n sys.exit(\"Error writing number of atoms\")\n self._xyz.write('\\n')\n\n xyz_str = \"{3} {0:12.6} {1:12.6f} {2:12.6f}\\n\"\n els = [\"Ti\", \"V \", \"Cr\", \"Mn\", \"Fe\", \"Co\", \"Ni\", \"Cu\", \"Zn\", \"Ga\", \"Ge\"]\n try:\n for i in range(natoms):\n self._xyz.write(xyz_str.format(*coords[i], els[i]))\n for j in range(i + 1, self.max_xyz_atoms):\n self._xyz.write(xyz_str.format(0., 0., 0., els[j]))\n except IOError:\n print(\"Error writing coords\")\n raise\n return\n\n def add_rdh0(self, rdh, atom_type: str):\n \"\"\"\n Add a rho parameter and atom type to the dict of parameters\n\n Parameters\n ----------\n rdh: float\n equilibrium dh distance in angstrom\n atom_type: str\n atom type to associate with rdh value\n\n \"\"\"\n try:\n if rdh < 0:\n print(\"Error, rdh must be greater than 0.\")\n raise ValueError('add_rdh 1')\n except TypeError('add_rdh 2'):\n print(\"Error, excpected a number for rdh \")\n sys.exit()\n\n try:\n atom_upper = atom_type.upper()\n except TypeError('add_rdh3'):\n print(\"Error parsing atom type {0}\".format(atom_type))\n sys.exit()\n\n try:\n self.rxh[atom_type] = rdh\n except TypeError(\"add rdh 4\"):\n print(\"Error adding atom {0} and rdh parameter {1} to \"\n \"rdh\".format(atom_type, rdh))\n return\n\n def print_rdh0(self, ofi=None):\n \"\"\"\n Output data for double checking\n\n Parameters\n ----------\n ofi: file object with write permissions\n The output file object. If None, then this will print to stdout\n \"\"\"\n print(\"Atom_Type rDH\", file=ofi)\n for key, rdh in self.rxh:\n print(\"{0:8} {0:5.3f}\".format(key, rdh), file=ofi)\n return\n\n def calc_indicator(self, x_d, x_as, x_hms, type_d, type_as, ofi=None):\n \"\"\"\n This is the main subroutine for calculating the indicator\n\n Parameters\n ----------\n x_d: ndarray of float\n coordinates with shape [3]\n x_as: ndarray of float\n acceptor coordinates each with shape [j,3]\n x_hms: ndarray of float\n hydrogen coordinates each with shape [m,3]\n type_d: str\n donor type to link with rho parameters\n type_as: list of str\n acceptor types to link with rho parameters\n ofi: file object\n where to print stuff\n \"\"\"\n cstr = \"{0:0.5f} {1:0.5f} {2:0.5f}\\n\"\n icstr = \"{0:9d} {1:9.5f} {2:9.5f} {3:9.5f}\\n\"\n\n # Set donor coordinates\n try:\n self.x_d[:] = x_d[:]\n except RuntimeError(\"calc_indicator 1\"):\n print(\"Error setting donor coordinates\")\n sys.exit()\n\n # Set acceptor coordinates\n try:\n self.num_acceptors = x_as.shape[0]\n if self.num_acceptors == 0:\n print(\"Warning: NO ACCEPTOR\")\n print(\"Setting indicator location to donor coordinates\")\n self.x_i[:] = self.x_d[:]\n return 1\n self.x_as = np.zeros((self.num_acceptors, 3), dtype=float)\n self.x_as[:, :] = x_as[:, :]\n except RuntimeError(\"calc_indicator 2\"):\n print(\"Error setting acceptor coordinates\")\n sys.exit()\n\n # Set hydrogen coordinates\n self.num_h = x_hms.shape[0]\n if self.num_h <= 0:\n print(\"Error, no protons for indicator\")\n raise RuntimeError(\"calc_indicator 4\")\n try:\n self.x_hs = np.zeros((self.num_h, 3), dtype=float)\n self.x_hs = x_hms[:, :]\n except RuntimeError(\"Calc indicator 3\"):\n print(\"Error setting Hydrogen coordinates\")\n sys.exit()\n\n # Initialize the rho parameters\n try:\n rdh0 = self.rxh[type_d]\n except RuntimeError:\n print(\"Error hashing donor. Is donor in rdh0 list? is only one\"\n \" donor passed to subroutine?\")\n raise\n pmaxs = np.asarray([rdh0 / (rdh0 + self.rxh[a]) for a in type_as])\n pmj0 = rdh0 / self.rlist\n\n # Initialize the other arrays\n dims = (self.num_h, self.num_acceptors)\n pmjs = np.zeros(dims, dtype=float)\n xmjs = np.zeros(dims, dtype=float)\n gmjs = np.zeros(dims, dtype=float)\n self.hop = []\n\n #Begin the calculations\n largest_p = 0\n dr = 0\n for m in range(self.num_h):\n for j in range(self.num_acceptors):\n pmjs[m, j] = self.calc_pmj(self.x_d, self.x_as[j], self.x_hs[m])\n if pmjs[m, j] > pmaxs[j]:\n self.hop.append((m, j, pmjs[m, j]))\n if pmjs[m, j] > largest_p:\n largest_p = pmjs[m, j]\n dr = np.linalg.norm(self.x_d - self.x_hs[m]) - \\\n np.linalg.norm(self.x_as[j] - self.x_hs[m] )\n xmjs[m, j] = self.calc_xmj(pmjs[m, j], pmj0, pmaxs[j])\n gmjs[m, j] = self.calc_gmj(xmjs[m, j])\n\n gI = self.calc_gI(gmjs)\n self.x_i[:] = self.x_d[:]\n for j in range(self.num_acceptors):\n for m in range(self.num_h):\n self.x_i[:] += gmjs[m, j] * x_as[j]\n self.x_i *= 1. / gI\n\n if self.print_all:\n self.ofi.write(\"Detailed Stats\\n\")\n self.ofi.write(\"Donor Coords:\\n\")\n self.ofi.write(cstr.format(*self.x_d))\n self.ofi.write(\"Acceptor Coords:\\n\")\n for j in range(self.num_acceptors):\n self.ofi.write(icstr.format(j, *self.x_as[j]))\n self.ofi.write(\"Proton Coords\\n\")\n for m in range(self.num_h):\n self.ofi.write(icstr.format(m, *self.x_hs[m]))\n self.ofi.write(\"pmjs\\n\")\n print(pmjs, file=ofi)\n self.ofi.write(\"xmjs\\n\")\n print(xmjs, file=ofi)\n self.ofi.write(\"gmjs\\n\")\n print(gmjs, file=ofi)\n self.ofi.write(\"gI\\n\")\n print(gI, file=ofi)\n self.ofi.write(\"Hops:\\n\")\n print(self.hop, file=ofi)\n if self.output_freq:\n if self.step % self.output_freq == 0:\n self._write_log(largest_p, dr, coords=self.x_d.reshape(-1, 3))\n self.step += 1\n return 0\n\n @staticmethod\n @jit\n def calc_pmj(x_d, x_aj, x_hm):\n \"\"\"\n calculate the variable p_mj [ rho_mj ]\n this is the projection of the D-H vec onto the D-A vec\n\n Parameters\n ----------\n x_d: ndarray of float with shape(3)\n coordinates of donor (np.float array [3] )\n x_aj: ndarray of float with shape(3)\n coordinates of acceptor j (np.float array [3] )\n x_hm: ndarray of float with shape(3)\n coordinates of hydrogen m (np.float array [3] )\n\n Returns\n -------\n float\n \"\"\"\n r_dhm = x_hm - x_d\n r_daj = x_aj - x_d\n return np.dot(r_dhm, r_daj) / np.linalg.norm(r_daj)**2\n\n @staticmethod\n @jit(nopython=True)\n def calc_xmj(pmj, pmj0, pmax):\n \"\"\"\n calculate the variable x(p_mj) [ x(rho_mj) ]. This is the ratio\n that deals with how far we are away from equilibrium.\n\n Parameters\n ----------\n pmj: float\n projection scalar\n pmj0: float\n scaling parameter parameter\n pmax: float\n equilibrium bond constant ratio\n\n Returns\n -------\n x_pmj: float\n \"\"\"\n return 1 - (pmj - pmj0) / (pmax - pmj0)\n\n @staticmethod\n @jit(nopython=True)\n def calc_gmj(xmj):\n\n if 1 <= xmj:\n gmj = 0.\n elif xmj < 0:\n gmj = 1\n else:\n gmj = -6 * xmj**5 + 15 * xmj**4 - 10 * xmj**3 + 1\n return gmj\n\n @staticmethod\n @jit\n def calc_gI(gmjs):\n \"\"\"\n Calculate the normalization constant gI\n\n Parameters\n ----------\n :param gmjs: the splined projection vectors\n :type gmjs: np.ndarray\n :return: the normalization constant\n :rtype: np.float\n \"\"\"\n return 1 + np.sum(gmjs)\n\n\n# class Indicator2(Indicator):\n# \"\"\"\n# This implementation of the indicator is the one where the projection\n# vectors between donors in a group and other acceptors are calcualted.\n# The results from each donor are then added back to calculate the final\n# location for the indicator.\n#\n# X_I = 1./g_I * [ X_D_com + \\sum_k \\sum_j \\sum_m { rho_kmj * X_A_j } ] s\n#\n# \"\"\"\n# def __init__(self):\n# Indicator.__init__(self)\n#\n# def calc_indicator(self, x_d, x_as, x_hms, type_d, type_as, intrap, xk, ofi=None):\n# \"\"\"\n# This is the main subroutine for calculating the indicator\n# :param x_d: ndarray float coordinates with shape [3]\n# :param x_as: ndarray of acceptor coordinates each with shape [j,3]\n# :param x_hms: ndarray of hydrogen coordiantes each with shape [m,3]\n# :param type_d: string of donor types to link with rho parameters\n# :param type_as: list of strings of acceptor types to link with rho parameters\n# :param ofi: where to print stuff\n# :return:\n# \"\"\"\n# cstr = \"{0:0.5f} {1:0.5f} {2:0.5f}\\n\"\n# icstr = \"{0:9d} {1:9.5f} {2:9.5f} {3:9.5f}\\n\"\n#\n# # Set donor coordinates\n# try:\n# self.x_d[:] = x_d[:]\n# except RuntimeError(\"calc_indicator 1\"):\n# print(\"Error setting donor coordinates\")\n# sys.exit()\n#\n# # Set acceptor coordinates\n# try:\n# self.num_acceptors = x_as.shape[0]\n# if self.num_acceptors == 0:\n# print(\"WARNING: NO ACCEPTOR\")\n# return 1\n# self.x_as = np.zeros((self.num_acceptors, 3), dtype=float)\n# self.x_as[:, :] = x_as[:, :]\n# except RuntimeError(\"calc_indicator 2\"):\n# print(\"Error setting acceptor coordinates\")\n# sys.exit()\n#\n# # Set hydrogen coordinates\n# self.num_h = x_hms.shape[0]\n# if self.num_h <= 0:\n# print(\"Error, no protons for indicator\")\n# raise RuntimeError(\"calc_indicator 4\")\n# try:\n# self.x_hs = np.zeros((self.num_h, 3), dtype=float)\n# self.x_hs = x_hms[:, :]\n# except RuntimeError(\"Calc indicator 3\"):\n# print(\"Error setting Hydrogen coordinates\")\n# sys.exit()\n#\n# # Initialize the rho parameters\n# try:\n# rdh0 = self.rxh[type_d]\n# except RuntimeError:\n# \"Error hashing donor. Is donor in rdh0 list? is only one donor \" \\\n# \"passed to subroutine?\"\n# pmaxs = np.asarray([rdh0 / (rdh0 + self.rxh[a]) for a in type_as])\n# pmj0 = rdh0 / self.rlist\n#\n# # Initialize the other arrays\n# dims = (self.num_h, self.num_acceptors)\n# pmjs = np.zeros(dims, dtype=float)\n# xmjs = np.zeros(dims, dtype=float)\n# gmjs = np.zeros(dims, dtype=float)\n# self.hop = []\n#\n# #Begin the calculations\n# largest_p = 0\n# dr = 0\n# for m in range(self.num_h):\n# for j in range(self.num_acceptors):\n# pmjs[m,j] = self.calc_pmj(self.x_d, self.x_as[j], self.x_hs[m])\n# if pmjs[m, j] > pmaxs[j]:\n# self.hop.append((m, j, pmjs[m, j]))\n# if pmjs[m, j] > largest_p:\n# largest_p = pmjs[m, j]\n# dr = np.linalg.norm(self.x_d - self.x_hs[m]) - \\\n# np.linalg.norm(self.x_as[j] - self.x_hs[m] )\n# xmjs[m,j] = self.calc_xmj(pmjs[m,j], pmj0, pmaxs[j])\n# gmjs[m,j] = self.calc_gmj(xmjs[m,j])\n#\n# self.x_i[:] = self.x_d[:]\n#\n# found_intra_hop = False\n# intrag = 0\n# for pp in range(len(intrap)):\n# if intrap[pp] > 0.5:\n# if not found_intra_hop:\n# self.hop = []\n# found_intra_hop = True\n# self.hop.append((m, j, intrap[pp], k, True))\n# xmk = self.calc_xmj( pmj0, pmaxs[j])\n# gmk = self.calc_gmj(xmjs[m, j])\n# my_g = self.calc_gmj(my_p_don)\n# self.x_i += my_g * self.x_d[k]\n# sum_gs += my_g\n#\n# gI = self.calc_gI(gmjs)\n# for j in range(self.num_acceptors):\n# for m in range(self.num_h):\n# self.x_i[:] += gmjs[m,j] * x_as[j]\n# self.x_i *= 1. / gI\n#\n# if self.print_all:\n# self.ofi.write(\"Detailed Stats\\n\")\n# self.ofi.write(\"Donor Coords:\\n\")\n# for k in len(self.x_d):\n# self.ofi.write(cstr.format(*self.x_d[k]))\n# self.ofi.write(\"Acceptor Coords:\\n\")\n# for j in range(self.num_acceptors):\n# self.ofi.write(icstr.format(j, *self.x_as[j]))\n# self.ofi.write(\"Proton Coords\\n\")\n# for m in range(self.num_h):\n# self.ofi.write(icstr.format(m, *self.x_hs[m]))\n# self.ofi.write(\"pmjs\\n\")\n# print(pmjs, file=ofi)\n# self.ofi.write(\"xmjs\\n\")\n# print(xmjs, file=ofi)\n# self.ofi.write(\"gmjs\\n\")\n# print(gmjs, file=ofi)\n# self.ofi.write(\"gI\\n\")\n# print(gI, file=ofi)\n# self.ofi.write(\"Hops:\\n\")\n# print(self.hop, file=ofi)\n# if self.output_freq:\n# if self.step % self.output_freq == 0:\n# self._write_log(largest_p, dr, coords=self.x_d.reshape(-1, 3))\n# self.step += 1\n# return 0\n\nclass IndicatorNull(Indicator):\n \"\"\"\n Indicator class if there is no indicator\n \"\"\"\n\n def __init__(self):\n Indicator.__init__(self)\n\n\nclass Indicator4(Indicator):\n \"\"\"\n This implementation of the indicator is the one where the projection\n vectors between donors in a group and other acceptors are calcualted.\n The results from each donor are then added back to calculate the final\n location for the indicator.\n\n X_I = 1./g_I * [ X_D_com + \\sum_k \\sum_j \\sum_m { rho_kmj * X_A_j } ] s\n\n \"\"\"\n\n def __init__(self):\n Indicator.__init__(self)\n self.donor_com = []\n self.acceptor_com = []\n\n def calc_indicator(self, x_d, x_as, x_hms, type_d, type_as, d_com, as_com,\n ofi=None):\n \"\"\"\n\n Parameters\n ----------\n :param x_d: ndarray of donor coordinates with shape [k,3]\n :param x_as: ndarray of acc coordinates with shape [j,3]\n :param x_hms: ndarra of hyd coordinates with shape [m,3]\n :param type_d: list of strings with length k\n :param type_as: list of strings with length j\n :param d_com: list of length 1 with [3] array !TODO make this less wacky\n :param as_com: list of acceptor centers of mass\n :param ofi: where to print stuff\n :return:\n \"\"\"\n cstr = \"{0:0.5f} {1:0.5f} {2:0.5f}\\n\"\n icstr = \"{0:9d} {1:9.5f} {2:9.5f} {3:9.5f}\\n\"\n\n num_d = len(x_d)\n # Set donor coordinates\n try:\n self.x_d = x_d.copy()\n self.d_com = d_com.copy()[0]\n except RuntimeError(\"calc_indicator 1\"):\n print(\"Error setting donor coordinates\")\n sys.exit()\n\n # Set acceptor coordinates\n try:\n self.num_acceptors = x_as.shape[0]\n if self.num_acceptors == 0:\n print(\"Warning: NO ACCEPTOR\")\n print(\"Setting indicator location to donor com\")\n self.x_i[:] = self.d_com[:]\n return 1\n self.x_as = np.zeros((self.num_acceptors, 3), dtype=float)\n self.x_as[:, :] = x_as[:, :]\n except RuntimeError(\"calc_indicator 2\"):\n print(\"Error setting acceptor coordinates\")\n sys.exit()\n\n if self.print_all:\n self.ofi.write(\"*****STEP %d\\n\" % self.step)\n self.ofi.write(\"Donor Coords:\\n\")\n for k in range(len(x_d)):\n self.ofi.write(cstr.format(*self.x_d[k]))\n self.ofi.write(\"Acceptor Coords:\\n\")\n for j in range(self.num_acceptors):\n self.ofi.write(icstr.format(j, *self.x_as[j]))\n self.ofi.write(\"Proton Coords\\n\")\n self.ofi.write(\"Donor COM\\n\")\n print(d_com, file=ofi)\n print(\"Acceptor COMs\", file=ofi)\n print(as_com)\n\n gI = 0\n self.x_i = np.zeros(3)\n largest_p = 0\n dr = 0\n self.hop = []\n sum_gs = 0.0\n found_proton = False\n\n for k in range(num_d):\n\n # Set hydrogen coordinates\n self.num_h = np.shape(x_hms[k])[0]\n if self.num_h <= 0:\n continue\n found_proton = True\n try:\n self.x_hs = np.zeros((self.num_h, 3), dtype=float)\n self.x_hs = x_hms[k][:, :]\n except RuntimeError(\"Calc indicator 3\"):\n print(\"Error setting Hydrogen coordinates\")\n sys.exit()\n\n # Initialize the rho parameters\n try:\n rdh0 = self.rxh[type_d[k]]\n except RuntimeError:\n print(\"Error hashing donor. Is donor in rdh0 list? is only\"\n \" one donor passed to subroutine?\")\n raise\n pmaxs = np.asarray([rdh0 / (rdh0 + self.rxh[a]) for a in type_as])\n pmj0 = rdh0 / self.rlist\n\n # Initialize the other arrays\n dims = (self.num_h, self.num_acceptors)\n pmjs = np.zeros(dims, dtype=float)\n xmjs = np.zeros(dims, dtype=float)\n gmjs = np.zeros(dims, dtype=float)\n\n #Begin the calculations\n for m in range(self.num_h):\n for j in range(self.num_acceptors):\n pmjs[m, j] = self.calc_pmj(self.x_d[k], self.x_as[j],\n self.x_hs[m])\n if pmjs[m, j] > pmaxs[j]:\n self.hop.append((m, j, pmjs[m, j], k))\n if pmjs[m, j] > largest_p:\n largest_p = pmjs[m, j]\n dr = np.linalg.norm(self.x_d[k] - self.x_hs[m]) - \\\n np.linalg.norm(self.x_as[j] - self.x_hs[m] )\n xmjs[m, j] = self.calc_xmj(pmjs[m, j], pmj0, pmaxs[j])\n gmjs[m, j] = self.calc_gmj(xmjs[m, j])\n print(\"Correction: \", x_d[k] - d_com[0])\n # Add the weighted Acceptor cog coordinate\n self.x_i[:] += gmjs[m, j] * as_com[j]\n sum_gs += np.sum(gmjs[:])\n\n if self.print_all:\n print(\"For donor %d\" % k)\n print(\"Hydrogen coordinates:\")\n for m in range(self.num_h):\n self.ofi.write(icstr.format(m, *self.x_hs[m]))\n self.ofi.write(\"pmjs\\n\")\n print(pmjs, file=ofi)\n self.ofi.write(\"xmjs\\n\")\n print(xmjs, file=ofi)\n self.ofi.write(\"gmjs\\n\")\n print(gmjs, file=ofi)\n self.ofi.write(\"pmaxs\\n\")\n print(pmaxs, file=ofi)\n self.ofi.write(\"Hops:\\n\")\n print(self.hop, file=ofi)\n print(\"cumulative_sum_of_gI\", sum_gs, file=ofi)\n\n if not found_proton:\n print(\"Error, no protons for indicator\")\n raise RuntimeError(\"calc_indicator 4\")\n\n gI = self.calc_gI(sum_gs)\n\n self.calc_ind(d_com, gI)\n\n if self.print_all:\n self.ofi.write(\"gI\\n\")\n print(gI, file=ofi)\n print(\"Final location\", file=ofi)\n print(self.x_i)\n\n if self.output_freq:\n if self.step % self.output_freq == 0:\n self._write_log(largest_p, dr, d_com[0][np.newaxis, :])\n self.step += 1\n return 0\n\n def calc_ind(self, d_com, gI):\n self.x_i += d_com[0][:]\n self.x_i /= gI\n\n\nclass Indicator6(Indicator4):\n \"\"\"\n Modify indicator 4 by exponentiating the gmj terms\n\n g(pmj) -> exp[g(pmj)]\n gI -> e + sum{exp[g(pmj)]}\n \"\"\"\n\n def __init__(self):\n Indicator4.__init__(self)\n\n def calc_gmj(self, xmj):\n if 1 <= xmj:\n gmj = 0.\n elif xmj < 0:\n gmj = 1\n else:\n gmj = -6 * xmj**5 + 15 * xmj**4 - 10 * xmj**3 + 1\n return gmj * np.exp(gmj)\n\n def calc_ind(self, d_com, gI):\n self.x_i += d_com[0][:] * np.e\n self.x_i /= gI\n\n @staticmethod\n @jit(nopython=True)\n def calc_gI(gmjs):\n \"\"\"\n Calculate the normalization constant gI\n\n Parameters\n ----------\n :param gmjs: the splined projection vectors\n :type gmjs: np.ndarray\n :return: the normalization constant\n :rtype: np.float\n \"\"\"\n return np.e + np.sum(gmjs)\n\n\nclass Indicator7(Indicator4):\n \"\"\"\n This is indicator 4 with the intramolecular rho's added to the location\n \"\"\"\n\n def __init__(self):\n Indicator4.__init__(self)\n\n def calc_indicator(self,\n x_d,\n x_as,\n x_hms,\n type_d,\n type_as,\n d_com,\n as_com,\n ofi=None):\n cstr = \"{0:0.5f} {1:0.5f} {2:0.5f}\\n\"\n icstr = \"{0:9d} {1:9.5f} {2:9.5f} {3:9.5f}\\n\"\n\n num_d = len(x_d)\n self.num_d = num_d\n # Set donor coordinates\n try:\n self.x_d = x_d.copy()\n except RuntimeError(\"calc_indicator 1\"):\n print(\"Error setting donor coordinates\")\n sys.exit()\n\n # Set acceptor coordinates\n try:\n self.num_acceptors = x_as.shape[0]\n if self.num_acceptors == 0:\n print(\"WARNING: NO ACCEPTOR\")\n return 1\n self.x_as = np.zeros((self.num_acceptors, 3), dtype=float)\n self.x_as[:, :] = x_as[:, :]\n except RuntimeError(\"calc_indicator 2\"):\n print(\"Error setting acceptor coordinates\")\n sys.exit()\n\n if self.print_all:\n self.ofi.write(\"*****STEP %d\\n\" % self.step)\n self.ofi.write(\"Donor Coords:\\n\")\n for k in range(len(x_d)):\n self.ofi.write(cstr.format(*self.x_d[k]))\n self.ofi.write(\"Acceptor Coords:\\n\")\n for j in range(self.num_acceptors):\n self.ofi.write(icstr.format(j, *self.x_as[j]))\n self.ofi.write(\"Proton Coords\\n\")\n self.ofi.write(\"Donor COM\\n\")\n print(d_com, file=ofi)\n print(\"Acceptor COMs\", file=ofi)\n print(as_com)\n\n gI = 0\n self.x_i = np.zeros(3)\n largest_p = 0\n dr = 0\n self.hop = []\n sum_gs = 0.0\n intra_p = False\n p_don = 0\n\n # Calculate the intramolecular rhos\n for k in range(num_d):\n\n # Set hydrogen coordinates\n self.num_h = x_hms[k].shape[0]\n # if self.num_h <= 0:\n # print(\"Error, no protons for indicator\")\n # raise RuntimeError(\"calc_indicator 4\")\n try:\n self.x_hs = np.zeros((self.num_h, 3), dtype=float)\n self.x_hs = x_hms[k][:, :]\n except RuntimeError(\"Calc indicator 3\"):\n print(\"Error setting Hydrogen coordinates\")\n sys.exit()\n\n # Initialize the rho parameters\n try:\n rdh0 = self.rxh[type_d[k]]\n except RuntimeError:\n print(\n \"Error hashing donor. Is donor in rdh0 list? is only one donor \"\n \"passed to subroutine?\")\n raise\n pmaxs = np.asarray([rdh0 / (rdh0 + self.rxh[a]) for a in type_as])\n pmj0 = rdh0 / self.rlist\n\n # Initialize the other arrays\n dims = (self.num_h, self.num_acceptors)\n pmjs = np.zeros(dims, dtype=float)\n xmjs = np.zeros(dims, dtype=float)\n gmjs = np.zeros(dims, dtype=float)\n\n #Begin the calculations\n for m in range(self.num_h):\n for j in range(self.num_acceptors):\n pmjs[m, j] = self.calc_pmj(self.x_d[k], self.x_as[j],\n self.x_hs[m])\n if pmjs[m, j] > pmaxs[j] and not intra_p:\n self.hop.append((m, j, pmjs[m, j], k, False))\n if pmjs[m, j] > largest_p:\n largest_p = pmjs[m, j]\n dr = np.linalg.norm(self.x_d[k] - self.x_hs[m]) - \\\n np.linalg.norm(self.x_as[j] - self.x_hs[m] )\n xmjs[m, j] = self.calc_xmj(pmjs[m, j], pmj0, pmaxs[j])\n gmjs[m, j] = self.calc_gmj(xmjs[m, j])\n # self.x_i[:] += gmjs[m, j] * (2*x_as[j] - as_com[j] + d_com[0] - x_d[k])\n # self.x_i[:] += gmjs[m, j] * (x_as[j])\n self.x_i[:] += gmjs[m, j] * (as_com[j])\n sum_gs += np.sum(gmjs[:])\n\n if self.print_all:\n print(\"For donor %d\" % k)\n for m in range(self.num_h):\n self.ofi.write(icstr.format(m, *self.x_hs[m]))\n self.ofi.write(\"pmjs\\n\")\n print(pmjs, file=ofi)\n self.ofi.write(\"xmjs\\n\")\n print(xmjs, file=ofi)\n self.ofi.write(\"gmjs\\n\")\n print(gmjs, file=ofi)\n self.ofi.write(\"pmaxs\\n\")\n print(pmaxs, file=ofi)\n self.ofi.write(\"Hops:\\n\")\n print(self.hop, file=ofi)\n print(\"cumulative_sum_of_gI\", sum_gs, file=ofi)\n\n found_intra_hop = False\n for k in range(num_d):\n self.num_h = x_hms[k].shape[0]\n try:\n self.x_hs = np.zeros((self.num_h, 3), dtype=float)\n self.x_hs = x_hms[k][:, :]\n except RuntimeError(\"Calc indicator 9\"):\n print(\"Error setting Hydrogen coordinates\")\n sys.exit()\n for j in range(self.num_d):\n if j == k:\n continue\n for m in range(self.num_h):\n rah = np.linalg.norm(self.x_hs[m] - self.x_d[j])\n my_p_don = rah / (\n rah + np.linalg.norm(self.x_hs[m] - self.x_d[k]))\n if my_p_don < 0.5:\n if not found_intra_hop:\n self.hop = []\n found_intra_hop = True\n self.hop.append((m, j, my_p_don, k, True))\n my_g = self.calc_gmj(my_p_don)\n self.x_i += my_g * self.x_d[k]\n sum_gs += my_g\n\n gI = self.calc_gI(sum_gs)\n\n self.calc_ind(d_com, gI)\n\n if self.print_all:\n self.ofi.write(\"gI\\n\")\n print(gI, file=ofi)\n print(\"Final location\", file=ofi)\n print(self.x_i)\n\n if self.output_freq:\n if self.step % self.output_freq == 0:\n self._write_log(largest_p, dr)\n self.step += 1\n\n return 0\n\n\nclass Indicator9(Indicator4):\n \"\"\"\n Indicator 4 with weighting of the donor coordinate by the following formula\n\n X_k_w = [r_km - rDH^0] / [\\sum_k (\\sum_m_k r_km - rDH^0)]\n\n It worked slightly better in some cases than 4 but was\n very sensitive to vibrations of molecular bonds at equilbirium\n \"\"\"\n\n def __init__(self):\n Indicator4.__init__(self)\n\n def calc_indicator(self,\n x_d,\n x_as,\n x_hms,\n type_d,\n type_as,\n d_com,\n as_com,\n ofi=None):\n cstr = \"{0:0.5f} {1:0.5f} {2:0.5f}\\n\"\n icstr = \"{0:9d} {1:9.5f} {2:9.5f} {3:9.5f}\\n\"\n\n num_d = len(x_d)\n # Set donor coordinates\n try:\n self.x_d = x_d.copy()\n self.d_com = d_com.copy()[0]\n except RuntimeError(\"calc_indicator 1\"):\n print(\"Error setting donor coordinates\")\n sys.exit()\n\n # Set acceptor coordinates\n try:\n self.num_acceptors = x_as.shape[0]\n if self.num_acceptors == 0:\n print(\"WARNING: NO ACCEPTOR\")\n return 1\n self.x_as = np.zeros((self.num_acceptors, 3), dtype=float)\n self.x_as[:, :] = x_as[:, :]\n except RuntimeError(\"calc_indicator 2\"):\n print(\"Error setting acceptor coordinates\")\n sys.exit()\n\n if self.print_all:\n self.ofi.write(\"*****STEP %d\\n\" % self.step)\n self.ofi.write(\"Donor Coords:\\n\")\n for k in range(len(x_d)):\n self.ofi.write(cstr.format(*self.x_d[k]))\n self.ofi.write(\"Acceptor Coords:\\n\")\n for j in range(self.num_acceptors):\n self.ofi.write(icstr.format(j, *self.x_as[j]))\n self.ofi.write(\"Proton Coords\\n\")\n self.ofi.write(\"Donor COM\\n\")\n print(d_com, file=ofi)\n print(\"Acceptor COMs\", file=ofi)\n print(as_com)\n\n gI = 0\n self.x_i = np.zeros(3)\n largest_p = 0\n dr = 0\n self.hop = []\n sum_gs = 0.0\n found_proton = False\n\n # Calculate the new weighting\n my_dcom = d_com\n if num_d > 1:\n my_dcom = self.calc_d_weights(type_d, x_hms)\n\n for k in range(num_d):\n\n # Set hydrogen coordinates\n self.num_h = x_hms[k].shape[0]\n if self.num_h <= 0:\n continue\n found_proton = True\n try:\n self.x_hs = np.zeros((self.num_h, 3), dtype=float)\n self.x_hs = x_hms[k][:, :]\n except RuntimeError(\"Calc indicator 3\"):\n print(\"Error setting Hydrogen coordinates\")\n sys.exit()\n\n # Initialize the rho parameters\n try:\n rdh0 = self.rxh[type_d[k]]\n except RuntimeError:\n \"Error hashing donor. Is donor in rdh0 list? is only one donor \" \\\n \"passed to subroutine?\"\n pmaxs = np.asarray([rdh0 / (rdh0 + self.rxh[a]) for a in type_as])\n pmj0 = rdh0 / self.rlist\n\n # Initialize the other arrays\n dims = (self.num_h, self.num_acceptors)\n pmjs = np.zeros(dims, dtype=float)\n xmjs = np.zeros(dims, dtype=float)\n gmjs = np.zeros(dims, dtype=float)\n\n #Begin the calculations\n for m in range(self.num_h):\n for j in range(self.num_acceptors):\n pmjs[m, j] = self.calc_pmj(self.x_d[k], self.x_as[j],\n self.x_hs[m])\n if pmjs[m, j] > pmaxs[j]:\n self.hop.append((m, j, pmjs[m, j], k))\n if pmjs[m, j] > largest_p:\n largest_p = pmjs[m, j]\n dr = np.linalg.norm(self.x_d[k] - self.x_hs[m]) - \\\n np.linalg.norm(self.x_as[j] - self.x_hs[m] )\n xmjs[m, j] = self.calc_xmj(pmjs[m, j], pmj0, pmaxs[j])\n gmjs[m, j] = self.calc_gmj(xmjs[m, j])\n # self.x_i[:] += gmjs[m, j] * (2*x_as[j] - as_com[j] + d_com[0] - x_d[k])\n # self.x_i[:] += gmjs[m, j] * (x_as[j])\n self.x_i[:] += gmjs[m, j] * (as_com[j])\n sum_gs += np.sum(gmjs[:])\n\n if self.print_all:\n print(\"For donor %d\" % k)\n for m in range(self.num_h):\n self.ofi.write(icstr.format(m, *self.x_hs[m]))\n self.ofi.write(\"pmjs\\n\")\n print(pmjs, file=ofi)\n self.ofi.write(\"xmjs\\n\")\n print(xmjs, file=ofi)\n self.ofi.write(\"gmjs\\n\")\n print(gmjs, file=ofi)\n self.ofi.write(\"pmaxs\\n\")\n print(pmaxs, file=ofi)\n self.ofi.write(\"Hops:\\n\")\n print(self.hop, file=ofi)\n print(\"cumulative_sum_of_gI\", sum_gs, file=ofi)\n\n if not found_proton:\n print(\"Error, no protons for indicator\")\n raise RuntimeError(\"calc_indicator 4\")\n\n gI = self.calc_gI(sum_gs)\n\n self.calc_ind(my_dcom, gI)\n\n if self.print_all:\n self.ofi.write(\"gI\\n\")\n print(gI, file=ofi)\n print(\"Final location\", file=ofi)\n print(self.x_i)\n\n if self.output_freq:\n if self.step % self.output_freq == 0:\n self._write_log(largest_p, dr, my_dcom[0][np.newaxis, :])\n self.step += 1\n return 0\n\n def calc_d_weights(self, type_d, x_hms):\n num_d = self.x_d.shape[0]\n w = np.zeros(num_d)\n sum_r = 0\n d_com = np.zeros(3)\n for k in range(num_d):\n rdh0 = self.rxh[type_d[k]]\n for m in range(x_hms[k].shape[0]):\n rdh = np.linalg.norm(self.x_d[k] - x_hms[k][m, :3])\n rdh -= rdh0\n rdh *= rdh\n w[k] += rdh\n sum_r += rdh\n if sum_r > 1e-5:\n w /= sum_r\n else:\n w[:] = 0\n has_h = 0\n for k in range(num_d):\n if x_hms[k].shape[0] > 0:\n has_h += 1\n w[k] = 1\n if has_h > 0:\n w[:] /= has_h\n else:\n w[:] = 1 / num_d\n for k in range(num_d):\n d_com += w[k] * self.x_d[k]\n return [d_com]\n\n\nclass Indicator11(Indicator):\n \"\"\"\n This is equivalent to 4 and was only added because I didn't realize\n that it was the same at the time...\n\n Do not use it.\n \"\"\"\n\n # TODO: Finish this documentation\n def __init__(self):\n Indicator.__init__(self)\n self.donor_com = []\n self.acceptor_com = []\n\n def calc_indicator(self,\n x_d,\n x_as,\n x_hms,\n type_d,\n type_as,\n d_com,\n as_com,\n ofi=None):\n cstr = \"{0:0.5f} {1:0.5f} {2:0.5f}\\n\"\n icstr = \"{0:9d} {1:9.5f} {2:9.5f} {3:9.5f}\\n\"\n\n num_d = len(x_d)\n # Set donor coordinates\n try:\n self.x_d = x_d.copy()\n self.d_com = d_com.copy()[0]\n except RuntimeError(\"calc_indicator 11\"):\n print(\"Error setting donor coordinates\")\n sys.exit()\n\n # Set acceptor coordinates\n try:\n self.num_acceptors = x_as.shape[0]\n if self.num_acceptors == 0:\n print(\"Warning: NO ACCEPTOR\")\n print(\"Setting indicator location to donor com\")\n self.x_i[:] = self.x_d[:]\n return 1\n self.x_as = np.zeros((self.num_acceptors, 3), dtype=float)\n self.x_as[:, :] = x_as[:, :]\n except RuntimeError(\"calc_indicator 2\"):\n print(\"Error setting acceptor coordinates\")\n sys.exit()\n\n if self.print_all:\n self.ofi.write(\"*****STEP %d\\n\" % self.step)\n self.ofi.write(\"Donor Coords:\\n\")\n for k in range(len(x_d)):\n self.ofi.write(cstr.format(*self.x_d[k]))\n self.ofi.write(\"Acceptor Coords:\\n\")\n for j in range(self.num_acceptors):\n self.ofi.write(icstr.format(j, *self.x_as[j]))\n self.ofi.write(\"Proton Coords\\n\")\n self.ofi.write(\"Donor COM\\n\")\n print(d_com, file=ofi)\n print(\"Acceptor COMs\", file=ofi)\n print(as_com)\n\n gI = 0\n self.x_i = np.zeros(3)\n largest_p = 0\n dr = 0\n self.hop = []\n sum_gs = 0.0\n found_proton = False\n\n for k in range(num_d):\n\n # Set hydrogen coordinates\n self.num_h = x_hms[k].shape[0]\n if self.num_h <= 0:\n continue\n found_proton = True\n try:\n self.x_hs = np.zeros((self.num_h, 3), dtype=float)\n self.x_hs = x_hms[k][:, :]\n except RuntimeError(\"Calc indicator 3\"):\n print(\"Error setting Hydrogen coordinates\")\n sys.exit()\n\n # Initialize the rho parameters\n try:\n rdh0 = self.rxh[type_d[k]]\n except RuntimeError:\n print(\n \"Error hashing donor. Is donor in rdh0 list? is only one donor \" \\\n \"passed to subroutine?\"\n )\n raise\n pmaxs = np.asarray([rdh0 / (rdh0 + self.rxh[a]) for a in type_as])\n pmj0 = rdh0 / self.rlist\n\n # Initialize the other arrays\n dims = (self.num_h, self.num_acceptors)\n pmjs = np.zeros(dims, dtype=float)\n xmjs = np.zeros(dims, dtype=float)\n gmjs = np.zeros(dims, dtype=float)\n\n #Begin the calculations\n for m in range(self.num_h):\n for j in range(self.num_acceptors):\n pmjs[m, j] = self.calc_pmj(self.x_d[k], self.x_as[j],\n self.x_hs[m])\n if pmjs[m, j] > pmaxs[j]:\n self.hop.append((m, j, pmjs[m, j], k))\n if pmjs[m, j] > largest_p:\n largest_p = pmjs[m, j]\n dr = np.linalg.norm(self.x_d[k] - self.x_hs[m]) - \\\n np.linalg.norm(self.x_as[j] - self.x_hs[m] )\n xmjs[m, j] = self.calc_xmj(pmjs[m, j], pmj0, pmaxs[j])\n gmjs[m, j] = self.calc_gmj(xmjs[m, j])\n # self.x_i[:] += gmjs[m, j] * (2*x_as[j] - as_com[j] + d_com[0] - x_d[k])\n # self.x_i[:] += gmjs[m, j] * (x_as[j])\n self.x_i[:] += gmjs[m, j] * (x_as[j] + self.x_d[k] -\n d_com[0].reshape(3))\n sum_gs += np.sum(gmjs[:])\n\n if self.print_all:\n print(\"For donor %d\" % k)\n for m in range(self.num_h):\n self.ofi.write(icstr.format(m, *self.x_hs[m]))\n self.ofi.write(\"pmjs\\n\")\n print(pmjs, file=ofi)\n self.ofi.write(\"xmjs\\n\")\n print(xmjs, file=ofi)\n self.ofi.write(\"gmjs\\n\")\n print(gmjs, file=ofi)\n self.ofi.write(\"pmaxs\\n\")\n print(pmaxs, file=ofi)\n self.ofi.write(\"Hops:\\n\")\n print(self.hop, file=ofi)\n print(\"cumulative_sum_of_gI\", sum_gs, file=ofi)\n\n if not found_proton:\n print(\"Error, no protons for indicator\")\n raise RuntimeError(\"calc_indicator 4\")\n\n gI = self.calc_gI(sum_gs)\n\n self.calc_ind(d_com, gI)\n\n if self.print_all:\n self.ofi.write(\"gI\\n\")\n print(gI, file=ofi)\n print(\"Final location\", file=ofi)\n print(self.x_i)\n\n if self.output_freq:\n if self.step % self.output_freq == 0:\n self._write_log(largest_p, dr, d_com[0][np.newaxis, :])\n self.step += 1\n return 0\n\n def calc_ind(self, d_com, gI):\n self.x_i += d_com[0][:]\n self.x_i /= gI\n\n\nclass VariablePower(Indicator4):\n \"\"\"\n This indicator exponentiates the g(x) variable using x_min, s, and t.\n It is chosen with Indicator 12 in the code.\n \"\"\"\n def __init__(self, s=4., t=6.):\n Indicator4.__init__(self)\n self.s = s\n self.t = t\n def set_output_freq(self, freq, prefix=''):\n \"\"\"\n Initialize variables for writing the xyz and the log file\n\n Parameters\n ----------\n freq: int\n output frequency\n prefix: str\n file prefix\n \"\"\"\n try:\n int(freq)\n except TypeError:\n sys.exit(\"Error: indicator output frequency must be an integer\")\n if freq > 0:\n self.output_freq = freq\n if prefix != '':\n self.log_path = prefix + '-' + self.log_path\n self.xyz_path = prefix + '-' + self.xyz_path\n self._lfi = open(self.log_path, 'w')\n self._lfi.write(\"# Step rho dr minx maxg\\n\")\n self._xyz = open(self.xyz_path, 'w')\n\n def calc_indicator(self, x_d, x_as, x_hms, type_d, type_as, ofi=None):\n \"\"\"\n This is the main subroutine for calculating the indicator\n\n Parameters\n ----------\n x_d: ndarray of float\n coordinates with shape [3]\n x_as: ndarray of float\n acceptor coordinates each with shape [j,3]\n x_hms: ndarray of float\n hydrogen coordinates each with shape [m,3]\n type_d: str\n donor type to link with rho parameters\n type_as: list of str\n acceptor types to link with rho parameters\n ofi: file object\n where to print stuff\n \"\"\"\n cstr = \"{0:0.5f} {1:0.5f} {2:0.5f}\\n\"\n icstr = \"{0:9d} {1:9.5f} {2:9.5f} {3:9.5f}\\n\"\n\n # Set donor coordinates\n try:\n self.x_d[:] = x_d[:]\n except RuntimeError(\"calc_indicator 1\"):\n print(\"Error setting donor coordinates\")\n sys.exit()\n\n # Set acceptor coordinates\n try:\n self.num_acceptors = x_as.shape[0]\n if self.num_acceptors == 0:\n print(\"Warning: NO ACCEPTOR\")\n print(\"Setting indicator location to donor coordinates\")\n self.x_i[:] = self.x_d[:]\n return 1\n self.x_as = np.zeros((self.num_acceptors, 3), dtype=float)\n self.x_as[:, :] = x_as[:, :]\n except RuntimeError(\"calc_indicator 2\"):\n print(\"Error setting acceptor coordinates\")\n sys.exit()\n\n # Set hydrogen coordinates\n self.num_h = x_hms.shape[0]\n if self.num_h <= 0:\n print(\"Error, no protons for indicator\")\n raise RuntimeError(\"calc_indicator 4\")\n try:\n self.x_hs = np.zeros((self.num_h, 3), dtype=float)\n self.x_hs = x_hms[:, :]\n except RuntimeError(\"Calc indicator 3\"):\n print(\"Error setting Hydrogen coordinates\")\n sys.exit()\n\n # Initialize the rho parameters\n try:\n rdh0 = self.rxh[type_d]\n except RuntimeError:\n print(\"Error hashing donor. Is donor in rdh0 list? is only one\"\n \" donor passed to subroutine?\")\n raise\n pmaxs = np.asarray([rdh0 / (rdh0 + self.rxh[a]) for a in type_as])\n pmj0 = rdh0 / self.rlist\n\n # Initialize the other arrays\n dims = (self.num_h, self.num_acceptors)\n pmjs = np.zeros(dims, dtype=float)\n xmjs = np.zeros(dims, dtype=float)\n gmjs = np.zeros(dims, dtype=float)\n xmjes= np.zeros(dims, dtype=float)\n self.hop = []\n\n #Begin the calculations\n largest_p = 0\n dr = 0\n for m in range(self.num_h):\n for j in range(self.num_acceptors):\n pmjs[m, j] = self.calc_pmj(self.x_d, self.x_as[j], self.x_hs[m])\n if pmjs[m, j] > pmaxs[j]:\n self.hop.append((m, j, pmjs[m, j]))\n if pmjs[m, j] > largest_p:\n largest_p = pmjs[m, j]\n dr = np.linalg.norm(self.x_d - self.x_hs[m]) - \\\n np.linalg.norm(self.x_as[j] - self.x_hs[m] )\n xmjs[m, j] = self.calc_xmj(pmjs[m, j], pmj0, pmaxs[j])\n #gmjs[m, j] = self.calc_gmj(xmjs[m, j])\n xmjes = self.calc_xmje(xmjs, xmjes, self.s, self.t)\n for m in range(self.num_h):\n for j in range(self.num_acceptors):\n gmjs[m, j] = self.calc_gmj(xmjs[m, j], xmjes[m, j])\n minx, maxg = self.calc_vars(xmjs, gmjs)\n gI = self.calc_gI(gmjs)\n self.x_i[:] = self.x_d[:]\n for j in range(self.num_acceptors):\n for m in range(self.num_h):\n self.x_i[:] += gmjs[m, j] * x_as[j]\n self.x_i *= 1. / gI\n\n if self.print_all:\n self.ofi.write(\"Detailed Stats\\n\")\n self.ofi.write(\"Donor Coords:\\n\")\n self.ofi.write(cstr.format(*self.x_d))\n self.ofi.write(\"Acceptor Coords:\\n\")\n for j in range(self.num_acceptors):\n self.ofi.write(icstr.format(j, *self.x_as[j]))\n self.ofi.write(\"Proton Coords\\n\")\n for m in range(self.num_h):\n self.ofi.write(icstr.format(m, *self.x_hs[m]))\n self.ofi.write(\"pmjs\\n\")\n print(pmjs, file=ofi)\n self.ofi.write(\"xmjs\\n\")\n print(xmjs, file=ofi)\n self.ofi.write(\"gmjs\\n\")\n print(gmjs, file=ofi)\n self.ofi.write(\"gI\\n\")\n print(gI, file=ofi)\n self.ofi.write(\"Hops:\\n\")\n print(self.hop, file=ofi)\n if self.output_freq:\n if self.step % self.output_freq == 0:\n self._write_log(largest_p, dr, minx, maxg, coords=self.x_d.reshape(-1, 3))\n self.step += 1\n return 0\n\n @staticmethod\n @jit(nopython=True)\n def calc_vars(amx, gmjs):\n \"\"\"provides minimum variables for analysis\"\"\"\n minx = 1\n maxg = 0\n for m in range(len(amx)):\n for j in range(len(amx[0])):\n if amx[m,j] >= 1:\n nothing = 0\n elif amx[m, j] < 0:\n minx = 0\n maxg = gmjs[m, j]\n elif amx[m, j] < minx and amx[m, j] >=0:\n minx = amx[m, j]\n maxg = gmjs[m, j]\n return minx, maxg\n\n def _write_log(self, p, dr, minx, maxg, coords=None):\n \"\"\"\n Write the results of a step\n Write the rho and dr coordinates\n If a matrix of coordinates is present, write them to the xyz file\n\n Parameters\n ----------\n :param p:\n :param dr:\n :param minx: float\n :param maxg: float\n :param coords:\n :return:\n \"\"\"\n self._lfi.write('{0:10d} {1:10.6f} {2:10.6f} {3:10.6f} {4:10.6f}\\n'.format(\n self.step, p, dr, minx, maxg))\n\n if coords is None:\n return\n #if not coords.any():\n # return\n\n natoms = coords.shape[0]\n\n try:\n self._xyz.write('%d\\n' % self.max_xyz_atoms)\n except:\n sys.exit(\"Error writing number of atoms\")\n self._xyz.write('\\n')\n\n xyz_str = \"{3} {0:12.6} {1:12.6f} {2:12.6f}\\n\"\n els = [\"Ti\", \"V \", \"Cr\", \"Mn\", \"Fe\", \"Co\", \"Ni\", \"Cu\", \"Zn\", \"Ga\", \"Ge\"]\n try:\n for i in range(natoms):\n self._xyz.write(xyz_str.format(*coords[i], els[i]))\n for j in range(i + 1, self.max_xyz_atoms):\n self._xyz.write(xyz_str.format(0., 0., 0., els[j]))\n except IOError:\n print(\"Error writing coords\")\n raise\n self._lfi.flush()\n return\n @staticmethod\n @jit(nopython=True)\n def calc_xmje(amx, xmjes, s, t):\n \"\"\"calculate the variable B for g(x). This is the exponent that deals\n with how much power must be added to smoothing function\n\n Parameters\n ----------\n amx: xmjs as ndrray\n xmjes: empty ndarray for exponents\n s: float for s parameter in exponent\n t: float for t parameter in exponent\n\n Returns\n -------\n xmjes: ndarray\n \"\"\"\n min =1\n for m in range(len(amx)):\n for j in range(len(amx[0])):\n if amx[m, j] >= 1:\n xmjes[m, j] = 1\n elif amx[m, j] < 0:\n xmjes[m, j] = 1\n min = 0\n elif amx[m, j] < min and amx[m, j] >=0:\n min = amx[m,j]\n for m in range(len(amx)):\n for j in range(len(amx[0])):\n if amx[m, j] >= 0 and amx[m, j] < 1:\n xmjes[m, j] = float(t + (amx[m, j] - min)*s)\n \"\"\"The power level goes from 1 to 10 for B\"\"\"\n return xmjes\n\n @staticmethod\n @jit(nopython=True)\n def calc_gmj(xmj, xmjes):\n\n if 1 <= xmj:\n gmj = 0\n elif xmj < 0:\n gmj = 1\n else:\n gmj = (-6 * xmj**5 + 15 * xmj**4 - 10 * xmj**3 + 1)**xmjes\n return gmj\n\nclass Softmax(Indicator4):\n def __init__(self, a=0.05, zmax=30):\n Indicator4.__init__(self)\n self.a = a\n self.zmax = zmax\n pass\n\n def calc_indicator(self, x_d, x_as, x_hms, type_d, type_as, ofi=None):\n \"\"\"\n This is the main subroutine for calculating the indicator\n\n Parameters\n ----------\n x_d: ndarray of float\n coordinates with shape [3]\n x_as: ndarray of float\n acceptor coordinates each with shape [j,3]\n x_hms: ndarray of float\n hydrogen coordinates each with shape [m,3]\n type_d: str\n donor type to link with rho parameters\n type_as: list of str\n acceptor types to link with rho parameters\n ofi: file object\n where to print stuff\n \"\"\"\n cstr = \"{0:0.5f} {1:0.5f} {2:0.5f}\\n\"\n icstr = \"{0:9d} {1:9.5f} {2:9.5f} {3:9.5f}\\n\"\n\n # Set donor coordinates\n try:\n self.x_d[:] = x_d[:]\n except RuntimeError(\"calc_indicator 1\"):\n print(\"Error setting donor coordinates\")\n sys.exit()\n\n # Set acceptor coordinates\n try:\n self.num_acceptors = x_as.shape[0]\n if self.num_acceptors == 0:\n print(\"Warning: NO ACCEPTOR\")\n print(\"Setting indicator location to donor coordinates\")\n self.x_i[:] = self.x_d[:]\n return 1\n self.x_as = np.zeros((self.num_acceptors, 3), dtype=float)\n self.x_as[:, :] = x_as[:, :]\n except RuntimeError(\"calc_indicator 2\"):\n print(\"Error setting acceptor coordinates\")\n sys.exit()\n\n # Set hydrogen coordinates\n self.num_h = x_hms.shape[0]\n if self.num_h <= 0:\n print(\"Error, no protons for indicator\")\n raise RuntimeError(\"calc_indicator 4\")\n try:\n self.x_hs = np.zeros((self.num_h, 3), dtype=float)\n self.x_hs = x_hms[:, :]\n except RuntimeError(\"Calc indicator 3\"):\n print(\"Error setting Hydrogen coordinates\")\n sys.exit()\n\n # Initialize the rho parameters\n try:\n rdh0 = self.rxh[type_d]\n except RuntimeError:\n print(\"Error hashing donor. Is donor in rdh0 list? is only one\"\n \" donor passed to subroutine?\")\n raise\n pmaxs = np.asarray([rdh0 / (rdh0 + self.rxh[a]) for a in type_as])\n pmj0 = rdh0 / self.rlist\n\n # Initialize the other arrays\n dims = (self.num_h, self.num_acceptors)\n pmjs = np.zeros(dims, dtype=float)\n xmjs = np.zeros(dims, dtype=float)\n gmjs = np.zeros(dims, dtype=float)\n zmjs = np.zeros(dims, dtype=float)\n exmjs = np.zeros(dims, dtype=float)\n sms = np.zeros(dims, dtype=float)\n self.hop = []\n\n #Begin the calculations\n largest_p = 0\n dr = 0\n for m in range(self.num_h):\n for j in range(self.num_acceptors):\n pmjs[m, j] = self.calc_pmj(self.x_d, self.x_as[j], self.x_hs[m])\n if pmjs[m, j] > pmaxs[j]:\n self.hop.append((m, j, pmjs[m, j]))\n if pmjs[m, j] > largest_p:\n largest_p = pmjs[m, j]\n dr = np.linalg.norm(self.x_d - self.x_hs[m]) - \\\n np.linalg.norm(self.x_as[j] - self.x_hs[m] )\n xmjs[m, j] = self.calc_xmj(pmjs[m, j], pmj0, pmaxs[j])\n gmjs[m, j] = self.calc_gmj(xmjs[m, j])\n zmjs = self.calc_zmj(gmjs, zmjs)\n sms = self.calc_sm(zmjs, xmjs, exmjs, sms, gmjs)\n sI = self.calc_sI(sms)\n gI = self.calc_gI(gmjs)\n self.x_i[:] = self.x_d[:]\n for j in range(self.num_acceptors):\n for m in range(self.num_h):\n self.x_i[:] += sms[m, j] * x_as[j]\n self.x_i *= 1. / sI\n\n if self.print_all:\n self.ofi.write(\"Detailed Stats\\n\")\n self.ofi.write(\"Donor Coords:\\n\")\n self.ofi.write(cstr.format(*self.x_d))\n self.ofi.write(\"Acceptor Coords:\\n\")\n for j in range(self.num_acceptors):\n self.ofi.write(icstr.format(j, *self.x_as[j]))\n self.ofi.write(\"Proton Coords\\n\")\n for m in range(self.num_h):\n self.ofi.write(icstr.format(m, *self.x_hs[m]))\n self.ofi.write(\"pmjs\\n\")\n print(pmjs, file=ofi)\n self.ofi.write(\"xmjs\\n\")\n print(xmjs, file=ofi)\n self.ofi.write(\"gmjs\\n\")\n print(gmjs, file=ofi)\n self.ofi.write(\"sms\\n\")\n print(sms, file=ofi)\n self.ofi.write(\"sI\\n\")\n print(sI, file=ofi)\n self.ofi.write(\"Hops:\\n\")\n print(self.hop, file=ofi)\n if self.output_freq:\n if self.step % self.output_freq == 0:\n self._write_log(largest_p, dr, coords=self.x_d.reshape(-1, 3))\n self.step += 1\n return 0\n\n @staticmethod\n @jit\n def calc_zmj(gmjs, zmjs):\n \"\"\"\n Calculate the softmax function zmj parameter\n\n Parameters\n ----------\n gmjs: array\n smoothing function parameters\n\n Returns\n ----------\n zmjs: array\n \"\"\"\n for m in range(len(gmjs)):\n for j in range(len(gmjs[0])):\n tempz=gmjs[m][j]/(1.0000000000001-gmjs[m][j])\n if tempz > 30:\n zmjs[m][j] = 30\n else:\n zmjs[m][j] = tempz\n return zmjs\n @staticmethod\n @jit\n def calc_sm(zmjs, xmjs, exmjs, sms, gmjs):\n \"\"\"\n Calculates the Softmax function sz\n\n Paremeters\n ----------\n zmjs: the calculated numerator vectors\n xmjs: the calcualted xrho values\n sms: empty array in dims of zmjs\n\n Returns\n ----------\n sms: array full of softmax parameters\n \"\"\"\n for m in range(len(zmjs)):\n for j in range(len(zmjs[0])):\n exmjs[m][j] = np.exp(0.05*zmjs[m][j])-1\n denom = np.sum(exmjs)\n for m in range(len(zmjs)):\n for j in range(len(zmjs[0])):\n sms[m][j] = ((np.exp(0.05*zmjs[m][j])-1)/(denom + 0.0000000000000001))*gmjs[m][j]\n return sms\n @staticmethod\n @jit\n def calc_sI(sms):\n \"\"\"\n Calculate the normalization constant sI\n\n Parameters\n ----------\n :param sms: the projection vectors\n :type sms: np.ndarray\n :return: the normalization constant\n :rtype: np.float\n \"\"\"\n return 1 + np.sum(sms)\n\nclass MCEC(Indicator4):\n \"\"\"\n Implementation of the mCEC.\n This implementation of mCEC has indicator 4 as base class for switching\n topology. Then the mCEC stuff sits right on top of it.\n \"\"\"\n\n def __init__(self, switching='chakrabarti'):\n Indicator4.__init__(self)\n if switching == 'chakrabarti':\n self.switch = chakrabarti_switching\n elif switching == 'fos':\n self.switch = self.fos\n print(\"Error, not implemented\")\n sys.exit()\n else:\n print(\"Improper value for switching function. Should be \"\n \"'chakrabarti' or 'fos'\")\n sys.exit()\n\n self.switch = np.vectorize(self.switch)\n self.m_acc_weight = {'OT': 2, 'SOT': 2, 'CLA': 0, 'OC': 0}\n self.rsw = 1.40\n self.dsw = 0.04\n self.x_mcec = np.asarray([0.00, 0.00, 0.00])\n self.correction_groups = []\n self.correction_weights = []\n\n def calc_mcec(self, rH, rXj, acc_types, correction_groups=None):\n \"\"\"\n Main loop for calculating the mCEC location.\n\n The result is stored in self.x_mcec.\n\n Parameters\n ----------\n rH: ndarray with shape(m,3)\n The positions of the hydrogens\n rXj: ndarray of float with shape (j,3)\n The locations of the acceptors\n acc_types: list of str with len (j)\n The atom type corresponding to an the Jth acceptor\n correction_groups: list of lr\n\n Returns\n -------\n\n \"\"\"\n if len(acc_types) != rXj.shape[0]:\n print(\"Error, number of acceptor types does not equal\"\n \"the number of acceptor coordinates\")\n if rH.size == 0:\n print(\"Error, no hydrogen coordinates found\")\n raise IndexError\n if rXj.size == 0:\n print(\"Error, no acceptor coordinates found\")\n raise IndexError\n self.get_weight_vector(acc_types)\n self.x_mcec[:] = calc_mcec_location(rH, rXj, self.acc_weights, self.rsw,\n self.dsw)\n # self.x_mcec[:] = self.calc_mcec_location(rH, rXj, self.acc_weights,\n # self.switch, self.rsw, self.dsw)\n print(\"MCEC before correction\", self.x_mcec)\n if correction_groups:\n self.x_mcec[:] += self.calc_mcec_correction(rH, correction_groups)\n print(\"Final mCEC\", self.x_mcec)\n\n def calc_mcec_correction(self, rH, rGroups, verbose=True):\n \"\"\"\n Calculate the correction term for the mCEC.\n\n Currently the max function is used instead of the nondifferentiable\n max function due to numerical issues.\n\n Parameters\n ----------\n rH: ndarray of float with shape(m,3)\n The positions of the hydrogens\n rGroups: list of ndarrays with shape(m,3)\n The position of the groups.\n Example:\n ([[1.1 1.1 1.1],\n [1.2 1.2 1.2]],\n [[2.1 2.1 2.1],\n [2.2 2.2 2.2],\n [2.3 2.3 2.3]])\n\n Returns\n -------\n ndarray of float with shape(3)\n\n \"\"\"\n num_groups = len(self.correction_groups)\n correction = np.asarray([0., 0., 0.])\n my_correction = np.asarray([0., 0., 0.])\n if num_groups != len(rGroups):\n print(\n \"Error, the number of groups found does not equal the number of groups parsed\"\n )\n raise LookupError\n for g in range(num_groups):\n my_correction[:] = 0.\n group_length = len(self.correction_groups[g])\n group_diff_max = np.empty(group_length)\n # Calculate the array of switching functions\n for x in range(group_length):\n dists = rH - rGroups[g][x]\n dists = np.linalg.norm(dists, axis=1)\n dists = chakrabarti_switching(dists, self.rsw, self.dsw)\n # The differentiable maximum function is disabled.\n # group_diff_max[x] = self.diff_max(dists)\n group_diff_max[x] = dists.max()\n print(group_diff_max)\n for l, k in permutations(range(group_length), 2):\n my_correction += group_diff_max[k] * (rGroups[g][l] -\n rGroups[g][k])\n my_correction *= self.correction_weights[g]\n correction += my_correction\n if verbose:\n print('Correciton amount', correction)\n return correction\n\n def get_weight_vector(self, types):\n \"\"\"\n Return an array of weights for each exceptor in list 'types'\n\n Parameters\n ----------\n types: list of str\n list of atom types to lookup weights for\n\n Returns\n -------\n ndarray of floats\n\n Exceptions\n ----------\n LookupError: Could not find the type in the acceptor type dictionary\n \"\"\"\n num_acc = len(types)\n self.acc_weights = np.zeros(num_acc, dtype=float)\n\n for i in range(num_acc):\n try:\n self.acc_weights[i] = self.m_acc_weight[types[i]]\n except LookupError:\n print(\"Error looking up acceptor %d, type not found\" % i)\n raise\n\n @staticmethod\n @jit(nopython=True)\n def diff_max(results, power=15):\n \"\"\"\n Differentiable maximum function. Given a list of floats,\n calculate the differentiable maximum function\n\n Parameters\n ----------\n results: ndarray of floats\n array of floats to exponentiate and sum\n\n Returns\n -------\n float\n \"\"\"\n a = results**power\n b = a * results\n if (a[:] == np.nan).any():\n a[a == np.nan] == 0.0\n if (b[:] == np.nan).any():\n b[b == np.nan] == 0.0\n return b.sum() / a.sum()\n\n # @staticmethod\n # def calc_mcec_location(rH, rXj, w, switch, rsw, dsw):\n # \"\"\"\n # Returns the mcec location from equation 6 of\n # J. Phys. Chem. A, Vol. 110, 2006\n #\n # This is the mCEC location without the correction term\n #\n # :param rH: np.ndarray of floats with size (n,3) where n is\n # number of hydrogens. hydrogen locations\n # :param rXj: np.ndarray of floats with size (J,3) where J is\n # number of acceptors. acceptor locations\n # :param w: np.ndarray of integers with size J representing\n # the minimum protonatied state of the acceptor\n # :param switch: vectorized switching function that takes a scalar\n # distance. Must accept numpy arrays.\n # :return: zeta: The mcec without the correction term\n # \"\"\"\n #\n # # hydrogen and weighted acceptors\n # zeta = np.sum(rH, axis=0)\n # zeta -= np.dot(w, rXj)\n #\n # num_m = rH.shape[0]\n # num_j = rXj.shape[0]\n # slow = False # Is 2 seconds slower for 25 second job...\n # #_Slow way to calculate zeta\n # if slow:\n # for m in range(num_m):\n # for j in range(num_j):\n # displacement = rH[m] - rXj[j]\n # distance = np.linalg.norm(displacement)\n # factor = switch(distance, rsw, dsw)\n # zeta -= factor * displacement\n # else:\n # # pairwise distances and switching functions\n # rHXj = np.zeros((rXj.shape[0], rH.shape[0], 3))\n # rHXj[:] = rH[:]\n # rHXj = np.transpose(rHXj, (1, 0, 2)) - rXj\n # zeta -= np.tensordot(rHXj, switch(np.linalg.norm(rHXj, axis=2), rsw, dsw), [(0,1),(0,1)])\n # return zeta\n\n # @staticmethod\n # def chakrabarti_switching(d, rsw, dsw):\n # \"\"\"\n # Chakrabarti switching function from\n # Konig et all\n # J. Phys. Chem. A. Vol 110, No.2\n # :param d: real distance\n # :param rsw: real midpoint of switching function\n # :param dsw: real slope of switching function\n # :return:\n # \"\"\"\n # return (1+np.exp((d-rsw)/dsw))**-1\n\n @staticmethod\n @jit(nopython=True)\n def fos(x):\n \"\"\"\n Our fifth order spline\n\n Parameters\n ----------\n :param x:\n :return:\n \"\"\"\n return -6 * x**5 + 15 * x**4 - 10 * x**3 + 1\n\nclass EPI(Indicator4):\n def __init__(self, c=0.0, ro=1.3, a=0.129):\n Indicator4.__init__(self)\n self.a = a # NOte in the equation, they say that a is a parameter but\n # in the equation it says d. Here we set d to a\n self.d = self.a\n self.ro = ro\n self.c = c\n self.correction_groups = None\n # Yes this is the EPi but we can just use this as the\n # holder for the variable to reuse as much code as possible\n self.x_mcec = np.zeros(3)\n def calc_mcec(self, rH, rXj, acc_types, correction_groups=None):\n \"\"\"\n Main loop for calculating the EPI location.\n\n The result is stored in self.x_mcec.\n\n Parameters\n ----------\n rH: ndarray with shape(m,3)\n The positions of the hydrogens\n rXj: ndarray of float with shape (j,3)\n The locations of the acceptors\n acc_types: list of str with len (j)\n The atom type corresponding to an the Jth acceptor\n correction_groups: list of lr\n\n Returns\n -------\n\n \"\"\"\n if rH.size == 0:\n print(\"Error, no hydrogen coordinates found\")\n raise IndexError\n if rXj.size == 0:\n print(\"Error, no acceptor coordinates found\")\n raise IndexError\n self.x_mcec[:] = calc_epi_location(rH, rXj, self.c, self.ro, self.d)\n print(\"Final EPI\", self.x_mcec)\n\n@jit\ndef calc_epi_location(rH, rXj, c, r0, d):\n \"\"\"\n Here we use i for oxygens and a for hydrogen indices like in the\n paper\n Parameters\n ----------\n rH\n rXj\n c\n r0\n ao\n\n Returns\n -------\n\n \"\"\"\n num_hyd = rH.shape[0]\n num_acc = rXj.shape[0]\n epi = np.zeros(3)\n sum_W = 0\n for i in range(num_acc):\n # Distance between ith oxygen and all of the hydrogens\n ria = np.linalg.norm(rXj[i] - rH, axis=1)\n n_i = calc_virtual_site(rH, ria, num_hyd, r0, d)\n z_i = c*n_i + (1-c)*rXj[i]\n W_i = calc_Wi(ria, num_hyd)\n sum_W += W_i\n epi += W_i * z_i\n epi /= sum_W\n return epi\n\n@jit(nopython=True)\ndef calc_Wi(ria, num_hyd):\n psi_i = 0\n for a in range(num_hyd):\n psi_i += epi_spline_S(ria[a])\n return epi_spline_W(psi_i)\n\n@jit(nopython=True)\ndef calc_virtual_site(rH, ria, num_hyd, r0, d):\n \"\"\"\n Calculate the virtual site (eta_i) from equation 15 by summation\n of gaussians phi_ia multiplied by the coordinates of its hydrogen a\n Parameters\n ----------\n rH: ndarray\n mx3 array of hydrogen coordinates\n ria: ndarray\n m array of distances from an oxygen to the a'th hydrogen\n num_hyd: int\n this is m, the number of hydrogens\n r0: float\n the r0 parameter for the gaussian function\n d: float\n the d parameter for the gaussian function\n\n Returns\n -------\n virt_site: ndarray\n vector of floats, size 3\n\n \"\"\"\n virt_site = np.zeros(3)\n sum_phi = 0.0\n for a in range(num_hyd):\n phi_ia = epi_gauss(ria[a], r0, d)\n virt_site += phi_ia * rH[a]\n sum_phi += phi_ia\n virt_site /= sum_phi\n return virt_site\n\n@jit(nopython=True)\ndef epi_gauss(x, r0, d):\n \"\"\"\n The EPI Gaussian function (equation 16)\n Parameters\n ----------\n x: float\n ro: float\n d: float\n\n Returns\n -------\n float\n \"\"\"\n return np.exp(-(x - r0)**2 / d**2)\n\n@jit(nopython=True)\ndef epi_spline_S(x):\n\n a = 12.0\n b = 13.2\n d = b - a\n p = (2*a + b) / 3\n q = (a + 2*b) / 3\n\n if x < a:\n return 1\n elif x >= a and x < p:\n return -9*(x - a)**3 / (2 * d**3) + 1\n elif x >= p and x < q:\n return 9 * (x - p)**3 / (d**3) -\\\n 9 * (x - p)**2 / (2 * d**2) -\\\n 3*(x-p)/(2*d) + 5/6.\n elif x >= q and x < b:\n return -9*(x - b)**3 / (2 * d**3)\n return 0\n\n@jit(nopython=True)\ndef epi_spline_W(x):\n \"\"\"\n Calculate the EPI spline function (equation 31) for the\n equation 19 in the EPI paper.\n This outputs a float between 1 and 0 for numbers within the range\n of a=2 and b=3, respectively.\n\n The a, b, c, and d parameters are hardcoded.\n\n CHECK IF 9(d-p)**2 should be 9(x-p)**2\n Parameters\n ----------\n x: float\n\n Returns\n -------\n float\n \"\"\"\n a = 2\n b = 3\n d = b - a\n p = (2 * a + b) / 3\n q = (a + 2 * b) / 3\n\n if x < a:\n return 0.\n elif x >= a and x < p:\n return 9 * (x - a) ** 3 / (2 * d ** 3)\n elif x >= p and x < q:\n return -9 * (x - p) ** 3 / d ** 3 + \\\n 9 * (x - p) ** 2 / (2 * d ** 2) + \\\n 3 * (x - p) / (2 * d) + 1 / 6.\n elif x >= q and x < b:\n return 9 * (x - b) ** 3 / 2 * d ** 3 + 1\n return 1.\n\n\n@jit(nopython=True, parallel=True)\ndef chakrabarti_switching(d, rsw, dsw):\n \"\"\"\n Chakrabarti switching function from\n Konig et all\n J. Phys. Chem. A. Vol 110, No.2\n\n Parameters\n ----------\n d: real\n distance\n rsw: real\n midpoint of switching function\n dsw: real\n slope of switching function\n\n Returns\n -------\n float\n \"\"\"\n return (1 + np.exp((d - rsw) / dsw))**-1\n\n\n@jit\ndef calc_mcec_location(rH, rXj, w, rsw, dsw, verbose=False):\n \"\"\"\n Returns the mcec location from equation 6 of\n J. Phys. Chem. A, Vol. 110, 2006\n\n This is the mCEC location without the correction term\n\n Parameters\n ----------\n rH: np.ndarray of floats with size (n,3) where n is\n number of hydrogens.\n hydrogen locations\n rXj: np.ndarray of floats w ith size (J,3) where J is\n number of acceptors.\n acceptor locations\n w: np.ndarray of int with size J\n The reference protonation state of each acceptor\n\n Returns\n -------\n zeta: The mcec without the correction term\n \"\"\"\n\n # hydrogen and weighted acceptors\n zeta = np.sum(rH, axis=0)\n if verbose:\n print('sum_hydrogen', zeta)\n zeta -= np.dot(w, rXj)\n print('after subtracting acc', zeta)\n num_m = rH.shape[0]\n num_j = rXj.shape[0]\n slow = False # Is 2 seconds slower for 25 second job...\n #_Slow way to calculate zeta\n if slow:\n for m in range(num_m):\n for j in range(num_j):\n displacement = rH[m] - rXj[j]\n distance = np.linalg.norm(displacement)\n factor = chakrabarti_switching(distance, rsw, dsw)\n zeta -= factor * displacement\n else:\n # pairwise distances and switching functions\n rHXj = np.zeros((rXj.shape[0], rH.shape[0], 3))\n rHXj[:] = rH[:]\n rHXj = np.transpose(rHXj, (1, 0, 2)) - rXj\n zeta -= np.tensordot(\n rHXj, chakrabarti_switching(np.linalg.norm(rHXj, axis=2), rsw, dsw),\n [(0, 1), (0, 1)])\n return zeta\n", "meta": {"hexsha": "cb8ae598b5b93b5658ec8349577e329b3629cab8", "size": 74580, "ext": "py", "lang": "Python", "max_stars_repo_path": "adaptive_md_tools/indicator.py", "max_stars_repo_name": "adamduster/adaptive_md_tools", "max_stars_repo_head_hexsha": "9753d69747f84dcb453a08ba8d837d969f8e067b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "adaptive_md_tools/indicator.py", "max_issues_repo_name": "adamduster/adaptive_md_tools", "max_issues_repo_head_hexsha": "9753d69747f84dcb453a08ba8d837d969f8e067b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "adaptive_md_tools/indicator.py", "max_forks_repo_name": "adamduster/adaptive_md_tools", "max_forks_repo_head_hexsha": "9753d69747f84dcb453a08ba8d837d969f8e067b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6704288939, "max_line_length": 103, "alphanum_fraction": 0.5008045052, "include": true, "reason": "import numpy,from numba", "num_tokens": 19585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.2227001388253089, "lm_q1q2_score": 0.11569747052143908}} {"text": "### copyright by Mingchen Chen\n### Updated on 7Dec/2019\n### New features: add tertiary_frustration.dat file in AWSEM format; Should be able to get rid of contact.map file;\n### Add pymol visulaization part;\n### Remove unnecessary sections for clarifications;\n\nimport random\nimport scipy.io\nimport numpy as np\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import cm as cm\nfrom scipy.stats import norm\nimport matplotlib.mlab as mlab\nimport os\nfrom numpy import array\nimport sys\nimport warnings\nfrom math import *\nwarnings.filterwarnings(\"ignore\")\n\n\ndef vector(p1, p2):\n return [p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2]]\n\ndef vabs(a):\n return sqrt(pow(a[0],2)+pow(a[1],2)+pow(a[2],2))\n\ndef vector_center(p1,p2):\n return [0.5*p2[0]+0.5*p1[0], 0.5*p2[1]+0.5*p1[1], 0.5*p2[2]+0.5*p1[2]]\n\n\n### get pairwise interactions from native structures\ndef calc_residue_dist_new(residue_one, residue_two) :\n \"\"\"Returns the C-alpha distance between two residues\"\"\"\n dist = 999999;\n for atom1 in residue_one:\n for atom2 in residue_two:\n diff_vector = atom1.coord - atom2.coord;\n temp = np.sqrt(np.sum(diff_vector * diff_vector))\n if temp < dist:\n dist = temp;\n return temp\n\ndef calc_dist_matrix(ca_atoms) :\n \"\"\"Returns a matrix of C-alpha distances between two chains\"\"\"\n reslen = len(ca_atoms);\n answer = [];\n answer_new = np.zeros((reslen, reslen), np.float)\n\n import Bio.PDB\n import numpy\n from numpy import array\n from Bio.PDB.PDBParser import PDBParser\n se_map = [\"ALA\", \"ARG\", \"ASN\", \"ASP\", \"CYS\", \"GLN\", \"GLU\", \"GLY\", \"HIS\", \"ILE\", \"LEU\", \"LYS\", \"MET\", \"PHE\", \"PRO\", \"SER\", \"THR\", \"TRP\", \"TYR\", \"VAL\", \"MSE\"]\n atom_map = ['CB', 'CB','CB','CB','CB','CB','CB','CA','CB','CB','CB','CB','CB','CB','CB','CB','CB','CB','CB','CB', 'CB'];\n p = PDBParser(PERMISSIVE=1)\n pdbcode = '3gso';\n s = p.get_structure(pdbcode, pdbcode+'.pdb')\n #chains = s[0].get_list()\n chains = s[0].get_list()\n for chain1 in chains:\n for res1 in chain1:\n for chain2 in chains:\n for res2 in chain2:\n if res1.has_id('CB')==1 and res2.has_id('CB')==1 and (res1.get_resname() in se_map) and (res2.get_resname() in se_map):\n answer.append(vabs(vector(res1['CB'].get_coord(), res2['CB'].get_coord())));\n if res1.has_id('CB')==1 and res2.has_id('CB')==0 and res2.has_id('CA')==1 and (res1.get_resname() in se_map) and (res2.get_resname() in se_map):\n answer.append(vabs(vector(res1['CB'].get_coord(), res2['CA'].get_coord())));\n if res1.has_id('CB')==0 and res1.has_id('CA')==1 and res2.has_id('CB')==1 and (res1.get_resname() in se_map) and (res2.get_resname() in se_map):\n answer.append(vabs(vector(res1['CA'].get_coord(), res2['CB'].get_coord())));\n if res1.has_id('CB')==0 and res1.has_id('CA')==1 and res2.has_id('CB')==0 and res2.has_id('CA')==1 and (res1.get_resname() in se_map) and (res2.get_resname() in se_map):\n answer.append(vabs(vector(res1['CA'].get_coord(), res2['CA'].get_coord())));\n if (res1.get_resname() not in se_map) or (res2.get_resname() not in se_map):\n result_temp = calc_residue_dist_new(res1, res2);\n answer.append(result_temp)\n answer_new = array(answer).reshape(reslen, reslen);\n return answer_new\n\ndef get_index(pdbcode):\n import Bio.PDB\n import numpy\n from Bio.PDB.PDBParser import PDBParser\n se_map = [\"ALA\", \"ARG\", \"ASN\", \"ASP\", \"CYS\", \"GLN\", \"GLU\", \"GLY\", \"HIS\", \"ILE\", \"LEU\", \"LYS\", \"MET\", \"PHE\", \"PRO\", \"SER\", \"THR\", \"TRP\", \"TYR\", \"VAL\", \"MSE\"]\n se_map_b = [\"A\", \"R\", \"N\", \"D\", \"C\", \"Q\", \"E\", \"G\", \"H\", \"I\", \"L\", \"K\", \"M\", \"F\", \"P\", \"S\", \"T\", \"W\", \"Y\", \"V\", \"M\"]\n p = PDBParser(PERMISSIVE=1)\n s = p.get_structure(pdbcode, pdbcode+'.pdb')\n chains = s[0].get_list()\n ca_atoms = [];\n cid_list = [];\n atom_list = [];\n res_list_name = [];\n ichain = 0;\n\n #residue_one[atom_map[se_map.index(residue_one.get_resname())]];\n for chain in chains:\n for res in chain:\n cid_list.append(chain.id+str(res.get_id()[1]));\n print res.get_id()[1]\n if (res.get_resname() in se_map) and (res.get_resname() == 'GLY' or res.has_id('CB')==0 ) and res.has_id('CA')==1:\n ca_atoms.append(res['CA'].get_coord())\n atom_list.append('CA');\n res_list_name.append(se_map_b[se_map.index(res.get_resname())])\n if (res.get_resname() in se_map) and res.has_id('CB'):\n ca_atoms.append(res['CB'].get_coord())\n atom_list.append('CA');\n res_list_name.append(se_map_b[se_map.index(res.get_resname())])\n if (res.get_resname() in se_map) and res.has_id('CB')==0 and res.has_id('CA')==0:\n ca_atoms.append(res['O'].get_coord())\n atom_list.append('O');\n res_list_name.append(se_map_b[se_map.index(res.get_resname())])\n dist_matrix = calc_dist_matrix(ca_atoms);\n return dist_matrix, cid_list, atom_list,res_list_name, ca_atoms\n\n\n\ndef read_log(fname, cid_list, scheme):\n fin = open(fname, 'r');\n reslen = len(cid_list);\n mat = np.zeros((reslen,reslen));\n ene_res = np.zeros((reslen, ));\n\n for line in fin:\n strs = line.split()\n if strs[1]!='Res1' and strs[1]!='nonzero' and float(strs[4])<= 5.000:# and float(strs[16]) <:\n #print strs[1][3:], strs[2]\n ### typically, all the residues without detected vander-Walls repulsion will not be counted.\n ind1 = cid_list.index(strs[1][2:]);\n ind2 = cid_list.index(strs[2][2:]);\n if scheme == \"Function1\": ### leave out the rep term only\n ene = float(strs[-1])- 1.0*(float(strs[4]))- float(strs[10]) - float(strs[15]);\n ene_res[ind1] += 0.5*ene;\n ene_res[ind2] += 0.5*ene;\n for i in range(reslen):\n for j in range(reslen):\n mat[i][j]=ene_res[i] + ene_res[j];\n mat[j][i]=ene_res[i] + ene_res[j];\n return mat\n\ndef read_nat_log(fname, cid_list, scheme):\n fin = open(fname, 'r');\n reslen = len(cid_list);\n mat = 999*np.ones((reslen,reslen));\n ene_res = np.zeros((reslen, ));\n for line in fin:\n strs = line.split()\n if strs[1]!='Res1' and strs[1]!='nonzero' and float(strs[4])<= 5.000:\n #print strs[1][3:], strs[2]\n ### typically, all the residues without detected vander-Walls repulsion will not be counted.\n ind1 = cid_list.index(strs[1][2:]);\n ind2 = cid_list.index(strs[2][2:]);\n if scheme == \"Function1\": ### leave out the rep term only\n ene = float(strs[-1])- 1.0*(float(strs[4]))- float(strs[10]) - float(strs[15]);\n ene_res[ind1] += 0.5*ene;\n ene_res[ind2] += 0.5*ene;\n for i in range(reslen):\n for j in range(reslen):\n mat[i][j]=ene_res[i] + ene_res[j];\n mat[j][i]=ene_res[i] + ene_res[j];\n return mat\n\ndef decoy_stat(cid_list, contact_map, decoy_num, sep, scheme):\n reslen = len(cid_list)\n mat_all = np.zeros((reslen,reslen,decoy_num));\n ### count the number of zero matrices;\n bad_seq = 0;\n good_seq = 0;\n for i in range(decoy_num):\n temp = read_log(str(i+1)+'.log',cid_list, scheme);\n if temp.sum()==0:\n bad_seq = bad_seq + 1;\n else:\n good_seq = good_seq + 1;\n mat_all[:,:,good_seq - 1] = temp;\n print \"The number of Bad Sequences is: \" + str(bad_seq);\n print \"The number of Good Sequences is: \" + str(good_seq);\n\n pro_mat = [];\n res_mean = [0 for i in range(reslen)];\n res_std = [0 for i in range(reslen)];\n ### test the number of decoys for protein-only\n for i in range(reslen):\n for j in range(i, reslen):\n if (abs(i-j)>sep or cid_list[i][0]!=cid_list[j][0]) and contact_map[i,j] <=10.0: #and stat_std[i,j]<=5.0 and stat_mean[i,j] !=0:\n for k in range(good_seq):\n if mat_all[i,j,k] != 0.0:#and mat_all[i,j,k] <= 5.0:\n pro_mat.append(mat_all[i,j,k])\n pro_mean = np.mean(pro_mat);\n pro_std = np.std(pro_mat)\n\n for i in range(reslen):\n res_mean[i] = pro_mean;\n res_std[i] = pro_std;\n\n return pro_mean, pro_std,res_mean, res_std\n\ndef frust_map(mat_nat, stat_mean, stat_std, contact_map, minvalue, maxvalue, sep, enable, cid_list, atom_list,res_mean, res_std,ca_atoms, res_list_name):\n reslen = len(cid_list)\n frust = np.zeros((reslen,reslen));\n frust_d = np.zeros((reslen, reslen));\n fter = open('tertiary_frustration.tcl','w');\n fdat = open('tertiary_frustration.dat','w');\n fpml = open('tertiary_frustration.pml','w');\n tcl_index = 0;\n for i in range(reslen):\n for j in range(i, reslen):\n if (abs(i-j)>sep or cid_list[i][0]!=cid_list[j][0]) and contact_map[i,j] <=10.0 and mat_nat[i,j]!=999:\n frust[i,j] = (mat_nat[i,j] - res_mean[i])/(res_std[i])\n frust[j,i] = (mat_nat[i,j] - res_mean[i])/(res_std[i])\n fdat.write(str(i) + ' '+ str(j) + ' '+ cid_list[i][0] + ' '+ cid_list[j][0] + ' '+ str(ca_atoms[i][0]) + ' '+ str(ca_atoms[i][1]) + ' '+ str(ca_atoms[i][2]) + ' '+ str(ca_atoms[j][0]) + ' '+ str(ca_atoms[j][1]) + ' '+ str(ca_atoms[j][2]) + ' '+ str(contact_map[i,j]) + ' ' + res_list_name[i] + ' ' + res_list_name[j] + ' '+ str(mat_nat[i,j]) + ' '+ str(res_mean[i]) + ' '+ str(res_std[i]) + '\\n')\n fdat.close()\n\n ### write pml script header files\n fpml.write(\"hide all\\n\")\n fpml.write(\"unset dynamic_measures\\n\")\n fpml.write(\"show cartoon, all\\n\")\n fpml.write(\"color grey, all\\n\")\n fpml.write(\"run draw_links.py\\n\")\n\n for i in range(reslen):\n for j in range(i, reslen):\n ### residue-residue interactions\n if (abs(i-j)>sep or cid_list[i][0]!=cid_list[j][0]) and contact_map[i,j] <=10.0 and mat_nat[i,j]!=999:\n i_resid = cid_list[i][1:];\n j_resid = cid_list[j][1:];\n i_chainid = cid_list[i][0];\n j_chainid = cid_list[j][0];\n atom_i = atom_list[i];\n atom_j = atom_list[j]\n if frust[i,j] <= minvalue:\n frust_d[i,j] = -1; frust_d[j,i] = -1;\n fter.write(\"set sel\" + str(i+1) + \" [atomselect top \\\"resid \" + i_resid + \" and chain \" + i_chainid + \" and name \" + atom_i + \"\\\"]\\n\");\n fter.write(\"set sel\" + str(j+1) + \" [atomselect top \\\"resid \" + j_resid + \" and chain \" + j_chainid + \" and name \" + atom_j + \"\\\"]\\n\");\n fter.write(\"lassign [atomselect\" + str(tcl_index) + \" get {x y z}] pos1\\n\");\n tcl_index = tcl_index + 1;\n fter.write(\"lassign [atomselect\" + str(tcl_index) + \" get {x y z}] pos2\\n\");\n tcl_index = tcl_index + 1;\n fter.write(\"draw color green\\n\");\n fter.write(\"draw line $pos1 $pos2 style solid width 2\\n\")\n fpml.write(\"draw_links resi \" + i_resid + \" and name \" + atom_i + \" and Chain \" + i_chainid + \", resi \" + j_resid + \" and name \" + atom_j + \" and Chain \" + j_chainid + \", color=green, color2=green, radius=0.05, object_name=\" + i_resid+\":\"+j_resid + \"_green\\n\" );\n\n if frust[i,j] >= maxvalue:\n frust_d[i,j] = 1; frust_d[j,i] = 1;\n fter.write(\"set sel\" + str(i+1) + \" [atomselect top \\\"resid \" + i_resid + \" and chain \" + i_chainid + \" and name \" + atom_i + \"\\\"]\\n\");\n fter.write(\"set sel\" + str(j+1) + \" [atomselect top \\\"resid \" + j_resid + \" and chain \" + j_chainid + \" and name \" + atom_j + \"\\\"]\\n\");\n fter.write(\"lassign [atomselect\" + str(tcl_index) + \" get {x y z}] pos1\\n\");\n tcl_index = tcl_index + 1;\n fter.write(\"lassign [atomselect\" + str(tcl_index) + \" get {x y z}] pos2\\n\");\n tcl_index = tcl_index + 1;\n fter.write(\"draw color red\\n\");\n fter.write(\"draw line $pos1 $pos2 style solid width 2\\n\")\n fpml.write(\"draw_links resi \" + i_resid + \" and name \" + atom_i + \" and Chain \" + i_chainid + \", resi \" + j_resid + \" and name \" + atom_j + \" and Chain \" + j_chainid + \", color=red, color2=red, radius=0.05, object_name=\" + i_resid+\":\"+j_resid + \"_red\\n\" );\n\n if enable !=0 and frust[i,j] > minvalue and frust[i,j] <= 0:\n fter.write(\"set sel\" + str(i+1) + \" [atomselect top \\\"resid \" + i_resid + \" and chain \" + i_chainid + \" and name \" + atom_i + \"\\\"]\\n\");\n fter.write(\"set sel\" + str(j+1) + \" [atomselect top \\\"resid \" + j_resid + \" and chain \" + j_chainid + \" and name \" + atom_j + \"\\\"]\\n\");\n fter.write(\"lassign [atomselect\" + str(tcl_index) + \" get {x y z}] pos1\\n\");\n tcl_index = tcl_index + 1;\n fter.write(\"lassign [atomselect\" + str(tcl_index) + \" get {x y z}] pos2\\n\");\n tcl_index = tcl_index + 1;\n fter.write(\"draw color yellow\\n\");\n fter.write(\"draw line $pos1 $pos2 style dashed width 2\\n\")\n if enable !=0 and frust[i,j] > 0 and frust[i,j] <= maxvalue:\n fter.write(\"set sel\" + str(i+1) + \" [atomselect top \\\"resid \" + i_resid + \" and chain \" + i_chainid + \" and name \" + atom_i + \"\\\"]\\n\");\n fter.write(\"set sel\" + str(j+1) + \" [atomselect top \\\"resid \" + j_resid + \" and chain \" + j_chainid + \" and name \" + atom_j + \"\\\"]\\n\");\n fter.write(\"lassign [atomselect\" + str(tcl_index) + \" get {x y z}] pos1\\n\");\n tcl_index = tcl_index + 1;\n fter.write(\"lassign [atomselect\" + str(tcl_index) + \" get {x y z}] pos2\\n\");\n tcl_index = tcl_index + 1;\n fter.write(\"draw color magenta\\n\");\n fter.write(\"draw line $pos1 $pos2 style dashed width 2\\n\")\n\n fter.write(\"mol modselect 0 top \\\"all\\\"\\n\");\n fter.write(\"mol modstyle 0 top newcartoon\\n\")\n fter.write(\"mol modcolor 0 top colorid 15\\n\")\n fter.write('color Display Background white\\n')\n fter.close()\n\n fpml.write(\"zoom all\\n\");\n fpml.write(\"hide labels\\n\");\n fpml.close()\n\n #np.savetxt('contact.map', frust, delimiter='\\t')\n return frust, frust_d\n\n\nreslen = int(sys.argv[1]);\nminvalue = float(sys.argv[2]);\nmaxvalue = float(sys.argv[3]);\ndecoy_num = int(sys.argv[4]);\nsep = int(sys.argv[5]);\nenable = int(sys.argv[6]); ### enable the display of neutral frustration\nscheme = sys.argv[7]; #\"Packing Frustratometer\" or \"Function Frustratometer\"\n\nprint \"suggest input for Frunction1 frustratometer: python Frust_Post_public.py 92 -2.5 0.5 200 9 0 Function1\"\nprint \"the cutoff of minimal frustration is: \" + str(minvalue);\nprint \"the cutoff of high frustration is: \" + str(maxvalue);\nprint \"the number of decoys used is: \" + str(decoy_num);\nprint \"the sequence separation used is: \" + str(sep);\nif enable == 1:\n print \"the neutral frustration is also displayed \"\nif enable == 0:\n print \"the neutral frustration will not be displayed \"\nprint \"the scheme of \" + str(scheme) + \" frustratometer is used\";\n\ncontact_map, cid_list, atom_list,res_list_name, ca_atoms = get_index('3gso');\n#print cid_list\n#print atom_list\nmat_nat = read_nat_log('./native.log', cid_list, scheme);\nstat_mean, stat_std, res_mean, res_std = decoy_stat(cid_list, contact_map, decoy_num, sep, scheme)\nfrust, frust_d = frust_map(mat_nat, stat_mean, stat_std, contact_map, minvalue, maxvalue, sep, enable, cid_list, atom_list, res_mean, res_std,ca_atoms, res_list_name)\n", "meta": {"hexsha": "31e2a6329e61bc72d06e796675fbef2bd86158d9", "size": 15917, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/example_input/Frust_Post_public.py", "max_stars_repo_name": "Mingchenchen/AtomicFrustratometer_Results", "max_stars_repo_head_hexsha": "9691418b12cac362a531e4eb6195c2e98cb56583", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/example_input/Frust_Post_public.py", "max_issues_repo_name": "Mingchenchen/AtomicFrustratometer_Results", "max_issues_repo_head_hexsha": "9691418b12cac362a531e4eb6195c2e98cb56583", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/example_input/Frust_Post_public.py", "max_forks_repo_name": "Mingchenchen/AtomicFrustratometer_Results", "max_forks_repo_head_hexsha": "9691418b12cac362a531e4eb6195c2e98cb56583", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-11T20:14:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T20:14:39.000Z", "avg_line_length": 50.8530351438, "max_line_length": 413, "alphanum_fraction": 0.567255136, "include": true, "reason": "import numpy,from numpy,import scipy,from scipy", "num_tokens": 4731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.19193278875832634, "lm_q1q2_score": 0.1144750770704723}} {"text": "#!/usr/bin/env python\n\n# Ideas to test:\n# record first one million accessible states and compute occupancy from these\n# Load previous fort.38 as start point to speed up equilibration\n# Include biggest interacting nodes in cluster even if they are smaller than the cut-off\n\n\"\"\"\nGlobal Optimization by Local Equilibrium Sampling\n\"\"\"\nimport sys\nimport os.path\nimport random\nimport numpy as np\nimport math\nimport itertools\nimport time\n\nROOMT = 298.15\nPH2KCAL = 1.364\nKCAL2KT = 1.688\nCLUSTER_PWCUTOFF = 0.5 # include into a cluster if conf-conf pw is bigger than this value\nCLUSTER_EXTENDED_LEVEL = 3 # extend nodes at this level of neighbor search\nEQ_MAXCYCLES = 100 # maximum cycles to equilibrate the clusters\nEQ_CONVERGE = 0.02 # occupancy convergence (max deviation of free confs) criterion\n\nresidue_report = \"nodes.info\"\nneighbor_report = \"neighbor.info\"\ncluster_report = \"cluster.info\"\nconverge_progress = \"converge.progress\"\nenergy_progress = \"energy.progress\"\nmc_progress = \"mc.log\"\n\nfloat_values = [\"(EPSILON_PROT)\", \"(TITR_PH0)\", \"(TITR_PHD)\", \"(TITR_EH0)\", \"(TITR_EHD)\", \"EXTRA\", \"SCALING\",\n \"(MONTE_T)\"]\nint_values = [\"(TITR_STEPS)\", \"(NSTATE_MAX)\", \"(MONTE_FLIPS)\", \"(MONTE_TRACE)\", \"(MONTE_NITER)\"]\n\n\nclass Env:\n def __init__(self):\n # Hard define values\n self.fn_runprm = \"run.prm\"\n self.fn_conflist3 = \"head3.lst\"\n self.energy_table = \"energies\"\n self.var = {}\n\n # load parameters\n self.load_runprm()\n self.read_extra()\n return\n\n def load_runprm(self):\n lines = open(self.fn_runprm).readlines()\n # Sample line: \"t step 1: pre-run, pdb-> mcce pdb (DO_PREMCCE)\"\n for line in lines:\n line = line.strip()\n line = line.split(\"#\")[0] # This cuts off everything after #\n left_p = line.rfind(\"(\")\n right_p = line.rfind(\")\")\n\n if left_p > 0 and right_p > left_p + 1:\n key = line[left_p:right_p + 1]\n fields = line[:left_p].split()\n if len(fields) >= 1:\n value = fields[0]\n self.set(key, value)\n return\n\n def set(self, key, value):\n # Known non-string value are converted, otherwise string presumed\n if key in float_values:\n self.var[key] = float(value)\n elif key in int_values:\n self.var[key] = int(value)\n else:\n self.var[key] = value\n return\n\n def load_tpl(self, fname):\n \"\"\"Load a tpl file.\"\"\"\n lines = open(fname).readlines()\n for line in lines:\n line = line.split(\"#\")[0]\n fields = line.split(\":\")\n if len(fields) != 2:\n continue\n\n key_string = fields[0].strip()\n keys = key_string.split(\",\")\n keys = [x.strip().strip(\"\\\"\") for x in keys]\n keys = [x for x in keys if x]\n keys_str = \",\".join(keys)\n\n value_str = fields[1].strip()\n if keys[0] in float_values:\n self.var[keys_str] = float(value_str)\n elif keys[0] in int_values:\n self.var[keys_str] = int(value_str)\n else:\n self.var[keys_str] = value_str\n return\n\n def read_extra(self):\n \"\"\"Read extra.tpl.\"\"\"\n self.load_tpl(self.var[\"(EXTRA)\"])\n default_values_keys = [\"SCALING,VDW0\",\n \"SCALING,VDW1\",\n \"SCALING,VDW\",\n \"SCALING,TORS\",\n \"SCALING,ELE\",\n \"SCALING,DSOLV\"]\n for element in default_values_keys:\n if element not in self.var:\n self.var[element] = 1.0\n\n return\n\n def printme(self):\n for key in self.var.keys():\n print(\"%-25s:%s\" % (key, str(self.var[key])))\n return\n\n\nclass Head3lst:\n \"\"\" Conformer structure \"\"\"\n\n def __init__(self, fields):\n # from head3.lst\n self.iConf = int(fields[0])\n self.confname = fields[1]\n self.flag = fields[2].lower()\n self.occ = float(fields[3])\n self.crg = float(fields[4])\n self.em0 = float(fields[5])\n self.pk0 = float(fields[6])\n self.ne = int(fields[7])\n self.nh = int(fields[8])\n self.vdw0 = float(fields[9]) * env.var[\"SCALING,VDW0\"]\n self.vdw1 = float(fields[10]) * env.var[\"SCALING,VDW1\"]\n self.tors = float(fields[11]) * env.var[\"SCALING,TORS\"]\n self.epol = float(fields[12]) * env.var[\"SCALING,ELE\"]\n self.dsolv = float(fields[13]) * env.var[\"SCALING,DSOLV\"]\n self.extra = float(fields[14])\n self.history = fields[15]\n return\n\n def printme(self):\n print(\"%05d %s %c %4.2f %6.3f %5d %5.2f %2d %2d %7.3f %7.3f %7.3f %7.3f %7.3f %7.3f %s\" % (self.iConf,\n self.confname,\n self.flag,\n self.occ,\n self.crg,\n self.em0,\n self.pk0,\n self.ne,\n self.nh,\n self.vdw0,\n self.vdw1,\n self.tors,\n self.epol,\n self.dsolv,\n self.extra,\n self.history))\n\n\nclass Residue:\n def __init__(self, resid):\n self.resid = resid\n self.neighbors = []\n self.conformers = []\n self.fixed_conformers = []\n self.free_conformers = []\n return\n\n def verify_flags(self):\n socc = 0.0\n n_freeconf = len(self.conformers)\n for conf in self.conformers:\n if not conf.on:\n socc += conf.occ\n n_freeconf -= 1\n elif abs(conf.occ) > 0.001: # free residue has non-0 occ\n print(\" %s %c %4.2f -> %s f 0.00 (free conformer initial occ = 0)\" % (\n head3lst[conf.i].confname,\n conf.flag,\n conf.occ, head3lst[conf.i].confname))\n conf.occ = 0.0\n if abs(socc - 1.0) < 0.001: # total occ of fixed conformers are 1.0, all fixed\n for conf in self.conformers:\n if conf.on:\n print(\" %s %c %4.2f -> %s t 0.00 (fixed conformers already have occ 1.0)\" % (\n head3lst[conf.i].confname,\n conf.flag, conf.occ, head3lst[conf.i].confname))\n conf.occ = 0.0\n conf.on = False\n conf.flag = \"t\"\n self.fixed_conformers.append(conf)\n elif abs(socc) < 0.001: # total occ is 0\n if n_freeconf == 1: # The only free conformer will be rest to t 1.0\n for conf in self.conformers:\n if conf.on:\n print(\" %s %c %4.2f -> %s t 1.00 (single free conformer of the residue)\" % (\n head3lst[conf.i].confname,\n conf.flag,\n conf.occ,\n head3lst[conf.i].confname))\n conf.on = False\n conf.occ = 1.0\n conf.flag = \"t\"\n self.fixed_conformers.append(conf)\n else:\n self.fixed_conformers.append(conf) # The rest are fixed at 0\n else:\n for conf in self.conformers:\n if not conf.on:\n self.fixed_conformers.append(conf)\n else:\n self.free_conformers.append(conf)\n else: # total occ is neither 0 or 1\n print(\" Error: Total %s occupancy is %.2f, 0.00 or 1.00 expected.\" % (self.resid, socc))\n for conf in self.conformers:\n conf.printme()\n print(\" Exiting ...\")\n sys.exit()\n return\n\n\nclass Conformer:\n def __init__(self, ic):\n self.i = ic # make a link to the head3lst\n self.flag = \"\"\n self.on = True # True means to be sampled, False means fixed at occ\n self.occ = 0.0 # final occ calculated from a sampling cycle\n self.occ_old = 0.0\n self.counter = 0\n self.mc_occ = 0.0 # Monte Carlo occ, used for entropy calculation\n self.E_self = head3lst[ic].vdw0 + head3lst[ic].vdw1 + head3lst[ic].epol + head3lst[ic].tors + head3lst[\n ic].dsolv + head3lst[ic].extra\n self.E_pheh = 0.0 # ph and eh effect\n self.E_mfe = 0.0 # when in an active cluster, this is the pairwise from outside conformers.\n self.entropy = 0.0 # entropy correction, used by metropolis criterion but not by system energy.\n self.E_total = 0.0\n self.type = \"\"\n self.load(ic)\n return\n\n def load(self, ic):\n self.flag = head3lst[ic].flag\n if head3lst[ic].flag.upper() == \"T\":\n self.on = False\n self.occ = head3lst[ic].occ\n else:\n self.on = True\n self.occ = 0.0\n self.type = (head3lst[ic].ne, head3lst[ic].nh, head3lst[ic].confname[3])\n return\n\n def printme(self):\n if self.on:\n flag = \"f\"\n else:\n flag = \"t\"\n line = \"%05d %s %c %4.2f %6.3f %5d %5.2f %2d %2d %7.3f %7.3f %7.3f %7.3f %7.3f %7.3f %s\" % (\n head3lst[self.i].iConf,\n head3lst[self.i].confname,\n flag,\n self.occ,\n head3lst[self.i].crg,\n head3lst[self.i].em0,\n head3lst[self.i].pk0,\n head3lst[self.i].ne,\n head3lst[self.i].nh,\n head3lst[self.i].vdw0,\n head3lst[self.i].vdw1,\n head3lst[self.i].tors,\n head3lst[self.i].epol,\n head3lst[self.i].dsolv,\n head3lst[self.i].extra,\n head3lst[self.i].history)\n return line\n\n\nclass Node:\n \"\"\"\n Node is a simplified structure for free residues and contains only free conformers. It is the core for MC sampling.\n \"\"\"\n\n def __init__(self, res):\n self.resid = res.resid\n self.free_conformers = res.free_conformers\n self.neighbors = []\n return\n\n def find_neighbors(self):\n for n in nodes:\n if self.resid != n.resid:\n maxpw = self.find_maxpw(self, n)\n if maxpw > CLUSTER_PWCUTOFF:\n self.neighbors.append(n)\n\n @staticmethod\n def find_maxpw(n1, n2):\n max_val = -0.1\n for conf1 in n1.free_conformers:\n ic = conf1.i\n for conf2 in n2.free_conformers:\n jc = conf2.i\n pw = abs(pairwise[ic][jc])\n if max_val < pw:\n max_val = pw\n return max_val\n\n\nclass Cluster:\n def __init__(self, nd):\n self.nodes = [nd]\n self.open_ends = False\n # Traverse to get nodes at predefined level\n queue = []\n current_node = nd\n current_level = 0\n while current_node:\n if current_level < CLUSTER_EXTENDED_LEVEL: # only lower level needs to be extended\n for x in current_node.neighbors:\n if x not in self.nodes:\n queue.append((x, current_level + 1))\n self.nodes.append(x)\n else: # at the highest level\n # print(\"%s:%s = %d\" % (nd.resid, current_node.resid, current_level))\n for x in current_node.neighbors:\n if x not in self.nodes:\n self.open_ends = True # some extended nodes are outside the level\n break\n if self.open_ends:\n break\n if queue:\n current_node, current_level = queue.pop(0)\n else:\n self.open_ends = False # all nodes exaused\n break\n self.accessible_states = []\n self.E_ambient = 0.0\n self.E_cluster = 0.0\n self.E_global = 0.0\n self.net_charge = 0.0\n self.dipole_direction = (0.0, 0.0, 0.0)\n self.dipole_magnitude = 0.0\n # Now get outside residues\n self.outside_residues = []\n cluster_resid = [x.resid for x in self.nodes]\n for res in residues:\n if res.resid not in cluster_resid:\n self.outside_residues.append(res)\n return\n\n def mc_run(self):\n T = env.var[\"(MONTE_T)\"]\n b = -KCAL2KT / (T / ROOMT)\n n_free = len(self.nodes)\n nflips = env.var[\"(MONTE_FLIPS)\"]\n\n state = [random.choice(x.free_conformers).i for x in self.nodes]\n # clear counters and compute total self energy\n for node in self.nodes:\n for conf in node.free_conformers:\n conf.counter = 0\n conf.E_total = conf.E_self + conf.E_pheh + conf.E_mfe + conf.entropy\n H_average = 0.0\n\n E_minimum = E_state = get_stateE(state)\n H_state = get_stateH(state)\n\n\n # trace cycles\n n_confs = sum([len(nd.free_conformers) for nd in self.nodes])\n N = env.var[\"(MONTE_NITER)\"] * n_confs\n # print(\"%d, %d, %d\" % (n_confs, env.var[\"(MONTE_NITER)\"], N))\n if env.var[\"(MONTE_TRACE)\"] > 0:\n cycles = int((N - 1) / env.var[\"(MONTE_TRACE)\"]) + 1 # minimum 1\n n_total = cycles * env.var[\"(MONTE_TRACE)\"]\n n_cycle = env.var[\"(MONTE_TRACE)\"]\n else:\n cycles = 1\n n_total = n_cycle = N\n\n\n for i in range(cycles):\n fp_mc_progress.write(\" Step %6d [%s], E_minimum = %.2f, E_running = %.2f, H_running = %.2f\\n\" % (i *\n n_cycle,\n \",\".\n join([\n str(\n x)\n for\n x in\n state]),\n E_minimum,\n E_state,\n H_state))\n fp_mc_progress.flush()\n\n iters = n_cycle\n while iters:\n old_satet = [x for x in state]\n\n # 1st flip\n inode = random.randrange(n_free)\n while True:\n new_conf = random.choice(self.nodes[inode].free_conformers).i\n if new_conf != state[inode]:\n break\n old_conf = state[inode]\n state[inode] = new_conf\n dE = conformers[new_conf].E_total - conformers[old_conf].E_total\n for j in range(n_free):\n dE += pairwise[new_conf][state[j]] - pairwise[old_conf][state[j]]\n dH_correction = - (conformers[new_conf].entropy - conformers[old_conf].entropy) # take off entropy\n\n # multi flip\n if random.choice([True, False]):\n other_nodes = [x for x in range(n_free) if x != inode]\n # print inode, other_nodes\n if other_nodes:\n for k in range(nflips):\n iflip = random.choice(other_nodes) # which node to flip\n old_conf = state[iflip]\n new_conf = random.choice(self.nodes[iflip].free_conformers).i\n #print [x.i for x in self.nodes[iflip].free_conformers], old_conf, new_conf\n state[iflip] = new_conf\n\n dE += conformers[new_conf].E_total - conformers[old_conf].E_total\n dH_correction += - (conformers[new_conf].entropy - conformers[old_conf].entropy)\n for j in range(n_free):\n dE += pairwise[new_conf][state[j]] - pairwise[old_conf][state[j]]\n\n dH = dE + dH_correction # dH equals dE plus the correction on entropy\n\n if dE < 0.0:\n flip = True\n elif random.random() < math.exp(b * dE):\n flip = True\n else:\n flip = False\n\n if flip: # update energy and enthalpy\n E_state += dE\n H_state += dH\n if E_minimum > E_state:\n E_minimum = E_state\n else: # go back to old state\n state = [x for x in old_satet]\n\n for ic in state:\n conformers[ic].counter += 1\n\n H_average += H_state\n iters -= 1\n\n fp_mc_progress.write(\" Exit cluster state: [%s]\\n\" % \",\".join([\"%d\" % x for x in state]))\n fp_mc_progress.write(\" Exit %d, E_minimum = %10.2f, E_running = %.2f, H_running = %.2f\\n\" % (n_total,\n E_minimum,\n E_state, H_state))\n fp_mc_progress.write(\" The average running enthalpy is %8.3f\\n\" % (H_average / n_total))\n fp_mc_progress.flush()\n\n for nd in self.nodes:\n for conf in nd.free_conformers:\n conf.mc_occ = float(conf.counter)/n_total\n\n self.E_cluster = H_average / n_total\n self.E_global = self.E_ambient + self.E_cluster\n\n return\n\n def analytical_run(self):\n T = env.var[\"(MONTE_T)\"]\n b = -KCAL2KT / (T / ROOMT)\n n_free = len(self.nodes)\n\n free_conformers = [[conf.i for conf in x.free_conformers] for x in self.nodes]\n analytical_states = list(itertools.product(*free_conformers))\n analytical_energies = np.zeros(len(analytical_states))\n analytical_enthalpy = np.zeros(len(analytical_states))\n\n # clear counters and compute total self energy\n for node in self.nodes:\n for conf in node.free_conformers:\n conf.counter = 0\n conf.E_total = conf.E_self + conf.E_pheh + conf.E_mfe + conf.entropy\n\n old_state = state = list(analytical_states[0])\n analytical_energies[0] = E_minimum = E_state = get_stateE(state)\n H_state = get_stateH(state)\n\n #print E_minimum, E_state\n for i in range(1, len(analytical_states)):\n new_state = analytical_states[i]\n dE = 0.0\n dH_correction = 0.0\n for ires in range(len(new_state)):\n if old_state[ires] != new_state[ires]:\n old_conf = old_state[ires]\n new_conf = new_state[ires]\n dE += conformers[new_conf].E_total - conformers[old_conf].E_total\n dH_correction += - (conformers[new_conf].entropy - conformers[old_conf].entropy)\n for j in range(n_free):\n dE += pairwise[new_conf][state[j]] - pairwise[old_conf][state[j]]\n old_state[ires] = new_state[ires]\n E_state += dE\n H_state += dE + dH_correction\n analytical_energies[i] = E_state\n analytical_enthalpy[i] = H_state\n if E_minimum > E_state:\n E_minimum = E_state\n\n #if not (i % 10000):\n # E_scratch = get_stateE(new_state)\n # print(\"Drift test: From dE: %.3f, From scratch: %.3f\" % (E_state, E_scratch))\n\n\n tared_Es = analytical_energies - E_minimum\n #print analytical_states, analytical_energies\n occ_states = np.fromiter([math.exp(b*x) for x in tared_Es], float)\n total_occ = np.sum(occ_states)\n occ_norm = occ_states / total_occ\n #print occ_norm\n for nd in self.nodes:\n for conf in nd.free_conformers:\n conf.mc_occ = 0.0\n\n for istate in range(len(analytical_states)):\n for ic in analytical_states[istate]:\n conformers[ic].mc_occ += occ_norm[istate]\n\n self.E_cluster = np.sum(analytical_enthalpy * occ_norm)\n self.E_global = self.E_cluster + self.E_ambient\n\n return\n\n def update_entropy(self):\n for nd in self.nodes:\n typeids = {}\n for conf in nd.free_conformers:\n if conf.type in typeids:\n typeids[conf.type].append(conf)\n else:\n typeids[conf.type] = [conf]\n\n for typeid in typeids:\n TS = 0.0\n sum_occ = 0.0\n confs = typeids[typeid]\n\n for conf in confs:\n sum_occ += conf.occ\n\n if sum_occ < 0.0001:\n for conf in confs:\n conf.entropy = 0.0\n else:\n for conf in confs:\n p = conf.occ / sum_occ\n if p > 1.0E-6:\n TS -= p * math.log(p) / 1.688\n for conf in confs:\n conf.entropy = TS\n\n return\n\n\ndef load_head3lst():\n conformers = []\n fname = env.fn_conflist3\n lines = open(fname).readlines()\n lines.pop(0)\n for line in lines:\n fields = line.split()\n if len(fields) >= 16:\n conf = Head3lst(fields)\n conformers.append(conf)\n\n confnames = [x.confname for x in conformers]\n for name in confnames:\n if len(name) != 14:\n print(\"%s is not a conformer name.\")\n sys.exit()\n occurrence = confnames.count(name)\n if occurrence > 1:\n print(\"Conformer %s occurred %d times\" % (name, occurrence))\n sys.exit()\n return conformers\n\n\ndef load_pairwise():\n folder = env.energy_table\n n_conf = len(head3lst)\n\n confnames = [x.confname for x in head3lst]\n scale_ele = env.var[\"SCALING,ELE\"]\n scale_vdw = env.var[\"SCALING,VDW\"]\n pw = np.zeros(shape=(n_conf, n_conf))\n for ic in range(n_conf):\n conf = head3lst[ic]\n oppfile = \"%s/%s.opp\" % (folder, conf.confname)\n if os.path.isfile(oppfile):\n lines = open(oppfile)\n for line in lines:\n fields = line.split()\n if len(fields) < 6:\n continue\n confname = fields[1]\n jc = confnames.index(confname)\n if jc < 0:\n print(\" Warning: %s in file %s is not a conformer\" % (confname, oppfile))\n continue\n ele = float(fields[2])\n vdw = float(fields[3])\n pw[ic][jc] = ele * scale_ele + vdw * scale_vdw\n\n # average the opposite sides\n for ic in range(n_conf - 1):\n ires_id = confnames[ic][:3] + confnames[ic][5:11]\n for jc in range(ic + 1, n_conf):\n # if abs(pw[ic][jc] - pw[jc][ic]) > 0.000001:\n # print(\"%s %.3f <-> %s %.3f\" % (confnames[ic], pw[ic][jc], confnames[jc], pw[jc][ic]))\n averaged_pw = (pw[ic][jc] + pw[jc][ic]) * 0.5\n pw[ic][jc] = pw[jc][ic] = averaged_pw\n\n # pw in the same residue set to 0\n jres_id = confnames[jc][:3] + confnames[jc][5:11]\n if ires_id == jres_id:\n pw[ic][jc] = pw[jc][ic] = 0.0\n\n return pw\n\n\ndef group_residues():\n residue_ids = []\n confnames = [x.confname for x in head3lst]\n for confname in confnames:\n resid = confname[:3] + confname[5:11]\n if resid not in residue_ids:\n residue_ids.append(resid)\n\n residues = [Residue(x) for x in residue_ids]\n for ic in range(len(confnames)):\n confname = confnames[ic]\n resid = confname[:3] + confname[5:11]\n index = residue_ids.index(resid)\n residues[index].conformers.append(conformers[ic])\n\n print(\" Verifying conformers ...\")\n for res in residues:\n res.verify_flags()\n return residues\n\n\ndef report_residues():\n lines = []\n lines.append(\"iConf CONFORMER FL occ Residue Node Free conformer\\n\")\n for res in residues:\n if len(res.free_conformers) > 0:\n iline = 0\n for conf in res.free_conformers:\n line = \"%05d %s f %4.2f |\" % (head3lst[conf.i].iConf, head3lst[conf.i].confname, conf.occ)\n if iline == 0:\n line += \" ----- %s ----- %s ----- | %s\" % (res.resid, res.resid, head3lst[conf.i].confname)\n else:\n line += \" %s | %s\" % (\" \" * 37, head3lst[conf.i].confname)\n lines.append(\"%s\\n\" % line)\n iline += 1\n for conf in res.fixed_conformers:\n line = \"%05d %s t %4.2f |\" % (head3lst[conf.i].iConf, head3lst[conf.i].confname, conf.occ)\n if iline == 0:\n line += \" ----- %s ----- %s ----- | %s\" % (res.resid, res.resid, head3lst[conf.i].confname)\n lines.append(\"%s\\n\" % line)\n iline += 1\n else:\n iline = 0\n for conf in res.fixed_conformers:\n line = \"%05d %s t %4.2f |\" % (head3lst[conf.i].iConf, head3lst[conf.i].confname, conf.occ)\n if iline == 0:\n line += \" ----- %s\" % (res.resid)\n lines.append(\"%s\\n\" % line)\n iline += 1\n\n lines.append(\"%s\\n\" % (\".\" * 84))\n\n open(residue_report, \"w\").writelines(lines)\n return\n\n\ndef report_neighbors():\n lines = []\n for nd in nodes:\n lines.append(\"%3d %s: %s\\n\" % (len(nd.neighbors), nd.resid, \",\".join([x.resid for x in nd.neighbors])))\n\n lines.append(\"\\n\")\n open(neighbor_report, \"w\").writelines(lines)\n return\n\n\ndef define_nodes():\n nodes = []\n for res in residues:\n if len(res.free_conformers) > 1:\n nodes.append(Node(res))\n return nodes\n\n\ndef define_clusters():\n cls = []\n for nd in nodes:\n cls.append(Cluster(nd))\n\n # Filter clusters: merge closed clusters\n filtered_clusters = []\n while cls:\n # print(\"%s\" % \",\".join([x.nodes[0].resid for x in filtered_clusters]))\n cluster = cls.pop(0)\n filtered_clusters.append(cluster)\n if not cluster.open_ends: # closed cluster\n # Remove any other clusters that are member of this cluster\n member_nodes = [x.resid for x in cluster.nodes[1:]]\n cls = [x for x in cls if x.nodes[0].resid not in member_nodes]\n filtered_clusters = [x for x in filtered_clusters if x.nodes[0].resid not in member_nodes]\n\n return filtered_clusters\n\n\ndef report_clusters():\n lines = []\n for cluster in clusters:\n if cluster.open_ends:\n t = \"+\"\n else:\n t = \"\"\n lines.append(\"%3d %s: %s %s\\n\" % (len(cluster.nodes), cluster.nodes[0].resid, \",\".join([x.resid for x in\n cluster.nodes]), t))\n\n lines.append(\"\\n\")\n open(cluster_report, \"w\").writelines(lines)\n return\n\n\ndef update_conf_energy(ph, eh):\n for ic in range(len(conformers)):\n monte_temp = env.var[\"(MONTE_T)\"]\n E_ph = monte_temp / ROOMT * head3lst[ic].nh * (ph - head3lst[ic].pk0) * PH2KCAL\n E_eh = monte_temp / ROOMT * head3lst[ic].ne * (eh - head3lst[ic].em0) * PH2KCAL / 58.0\n conformers[ic].E_pheh = E_ph + E_eh\n return\n\n\ndef get_stateE(state):\n E = 0.0\n for ic in state:\n E += conformers[ic].E_self + conformers[ic].E_pheh + conformers[ic].E_mfe + conformers[ic].entropy\n for i in range(len(state) - 1):\n ic = state[i]\n for j in range(i + 1, len(state)):\n jc = state[j]\n E += pairwise[ic][jc]\n return E\n\n\ndef get_stateH(state):\n H = 0.0\n for ic in state:\n H += conformers[ic].E_self + conformers[ic].E_pheh + conformers[ic].E_mfe\n for i in range(len(state) - 1):\n ic = state[i]\n for j in range(i + 1, len(state)):\n jc = state[j]\n H += pairwise[ic][jc]\n return H\n\n\ndef cluster_MC(cluster):\n # initialize in-cluster conformer self energy, mfe and entropy\n for nd in cluster.nodes:\n for conf in nd.free_conformers:\n conf.E_mfe = 0.0\n for res in cluster.outside_residues:\n for conf2 in res.conformers:\n conf.E_mfe += pairwise[conf.i][conf2.i] * conf2.occ\n # print(\"%s: %6.2f\" % (head3lst[conf.i].confname, conf.E_mfe))\n\n # compute ambient energy\n # self\n E_self = 0.0\n for res in cluster.outside_residues:\n for conf in res.conformers:\n E_self += (conf.E_self + conf.E_pheh) * conf.occ\n\n # pw\n E_pw = 0.0\n n_res = len(cluster.outside_residues)\n for ires in range(n_res - 1):\n for jres in range(ires + 1, n_res):\n for conf1 in cluster.outside_residues[ires].conformers:\n for conf2 in cluster.outside_residues[jres].conformers:\n E_pw += pairwise[conf1.i][conf2.i] * conf1.occ * conf2.occ\n\n cluster.E_ambient = E_self + E_pw\n\n # Test analytical\n nstate = 1\n for nd in cluster.nodes:\n nstate *= len(nd.free_conformers)\n\n if nstate > env.var[\"(NSTATE_MAX)\"]:\n # Monte Carlo sampling\n if cluster.open_ends:\n t = \"+\"\n else:\n t = \" \"\n msg = \"Cluster: %s %s\\n\" % (\", \".join([x.resid for x in cluster.nodes]), t)\n fp_mc_progress.write(msg)\n msg = \"n = %d, > %d Monte Carlo sampling\\n\" % (nstate, env.var[\"(NSTATE_MAX)\"])\n fp_mc_progress.write(msg)\n\n # entropy run\n if env.var[\"(MONTE_TSX)\"].upper() == \"T\":\n fp_mc_progress.write(\"Doing entropy correction.\\n\")\n #cluster.mc_run()\n cluster.update_entropy()\n\n # occ run\n fp_mc_progress.write(\"Occ run:\\n\")\n cluster.mc_run()\n\n else:\n # Analytical solution\n if cluster.open_ends:\n t = \"+\"\n else:\n t = \" \"\n msg = \"Cluster: %s %s\\n\" % (\", \".join([x.resid for x in cluster.nodes]), t)\n fp_mc_progress.write(msg)\n msg = \"n = %d, <= %d Analytical solution\\n\" % (nstate, env.var[\"(NSTATE_MAX)\"])\n fp_mc_progress.write(msg)\n\n # entropy run\n if env.var[\"(MONTE_TSX)\"].upper() == \"T\":\n #cluster.analytical_run()\n cluster.update_entropy()\n\n # occ run\n cluster.analytical_run()\n\n\n\n # Push occ to occ_old and compute new occ.\n if cluster.open_ends: # only set occ of the first node for open cluster so that other nodes keep their occ\n for conf in cluster.nodes[0].free_conformers:\n conf.occ_old = conf.occ\n conf.occ = conf.mc_occ\n else: # set occ of closed nodes\n for nd in cluster.nodes:\n for conf in nd.free_conformers:\n conf.occ_old = conf.occ\n conf.occ = conf.mc_occ\n\n return\n\n\ndef equilibrate_clusters():\n exit_eq = False\n\n # clear entropy, do it outside the cycles.\n for conf in conformers:\n conf.entropy = 0.0\n\n for icycle in range(EQ_MAXCYCLES):\n # print icycle\n q = [x for x in range(len(clusters))]\n random.shuffle(q)\n for icluster in q:\n cluster_MC(clusters[icluster])\n\n # write entropy\n line = \"Entropy from cycle %d: Occ Entropy\\n\" % icycle\n fp_mc_progress.write(line)\n for conf in conformers:\n line = \"%s %.3f %.2f\\n\" % (head3lst[conf.i].confname, conf.occ, conf.entropy)\n fp_mc_progress.write(line)\n\n # compute occ convergence\n line = \"\\nOccupancy convergence in cycle %d: Confname previousOcc CurrentOcc Delta\\n\" % icycle\n fp_mc_progress.write(line)\n for conf in conformers:\n line = \"%s %.3f %.3f %.3f\\n\" % (head3lst[conf.i].confname, conf.occ_old, conf.occ, abs(conf.occ -\n conf.occ_old))\n fp_mc_progress.write(line)\n\n deltas = [abs(conf.occ - conf.occ_old) for conf in conformers]\n convergence = max(deltas)\n line = \"\\nOccupancy convergence (max diff) in cycle %d: %s %.3f\\n\\n\" % (icycle, head3lst[deltas.index(max(\n deltas))].confname, convergence)\n fp_mc_progress.write(line)\n\n # compute energy convergence\n cluster_Hs = [(cluster.E_ambient, cluster.E_cluster, cluster.E_global) for cluster in clusters]\n line = \"\\nCluster energy: Ambient+inCluster=Global\\n\"\n fp_mc_progress.write(line)\n for h in cluster_Hs:\n line = \"%8.3f+%8.3f=%8.3f\\n\" % h\n fp_mc_progress.write(line)\n fp_mc_progress.write(\"\\n\")\n\n cluster_Hs = np.array([cluster.E_global for cluster in clusters])\n H_mean = float(cluster_Hs.mean())\n H_stdev = float(cluster_Hs.std())\n\n line = \"\\nCluster energy mean and standard deviation in cycle %d: %.3f %.3f\\n\" % (icycle, H_mean, H_stdev)\n fp_mc_progress.write(line)\n\n # break if converged early\n if convergence < EQ_CONVERGE:\n line = \"\\nReached occupancy convergence: %.3f < %.3f\\n\\n\" % (convergence, EQ_CONVERGE)\n fp_mc_progress.write(line)\n break\n\n return\n\ntimerA = time.time()\n\nenv = Env()\nhead3lst = load_head3lst()\nconformers = [Conformer(ic) for ic in range(len(head3lst))]\npairwise = load_pairwise()\nresidues = group_residues()\nnodes = define_nodes()\nfor node in nodes:\n node.find_neighbors()\nclusters = define_clusters()\n\nif __name__ == \"__main__\":\n report_residues()\n report_neighbors()\n report_clusters()\n\n ph_start = env.var[\"(TITR_PH0)\"]\n ph_step = env.var[\"(TITR_PHD)\"]\n eh_start = env.var[\"(TITR_EH0)\"]\n eh_step = env.var[\"(TITR_EHD)\"]\n titration_type = env.var[\"(TITR_TYPE)\"]\n titration_steps = env.var[\"(TITR_STEPS)\"]\n\n for conf in conformers:\n conf.occ_old = conf.occ\n\n fp_mc_progress = open(mc_progress, \"w\")\n occ_at_points = []\n entropy_at_points = []\n points = []\n for ititr in range(titration_steps):\n if titration_type == \"ph\":\n ph = ph_start + ph_step * ititr\n eh = eh_start\n points.append(ph)\n else:\n ph = ph_start\n eh = eh_start + eh_step * ititr\n points.append(eh)\n print (\"\\n Titration at pH = %.1f and Eh = %.f\" % (ph, eh))\n line = \"Sampling at pH = %.1f and Eh = %.f\\n\" % (ph, eh)\n fp_mc_progress.write(line)\n\n update_conf_energy(ph, eh)\n equilibrate_clusters()\n\n occ_at_points.append([conf.occ for conf in conformers])\n entropy_at_points.append([conf.entropy for conf in conformers])\n\n fp_mc_progress.close()\n\n # print fort.38\n lines_occ = []\n lines_entropy = []\n if titration_type == \"ph\":\n points_str = \" \".join([\"%5.3f\" % x for x in points])\n else:\n points_str = \" \".join([\"%5.f\" % x for x in points])\n lines_occ.append(\" %s %s\\n\" % (titration_type, points_str))\n lines_entropy.append(\" %s %s\\n\" % (titration_type, points_str))\n\n for ic in range(len(conformers)):\n occ_str = \" \".join([\"%5.3f\" % occ_at_points[ip][ic] for ip in range(titration_steps)])\n line = \"%s %s\\n\" % (head3lst[conformers[ic].i].confname, occ_str)\n lines_occ.append(line)\n occ_str = \" \".join([\"%5.3f\" % entropy_at_points[ip][ic] for ip in range(titration_steps)])\n line = \"%s %s\\n\" % (head3lst[conformers[ic].i].confname, occ_str)\n lines_entropy.append(line)\n\n open(\"fort.38\", \"w\").writelines(lines_occ)\n open(\"entropy.out\", \"w\").writelines(lines_entropy)\n\n timerB = time.time()\n print(\"Total time on MC: %1d seconds.\\n\" % (timerB - timerA))\n", "meta": {"hexsha": "f4850cb4772e95bb34910b671bb1b0f7cddefdc8", "size": 37947, "ext": "py", "lang": "Python", "max_stars_repo_path": "bin/gobles.py", "max_stars_repo_name": "newbooks/pymcce", "max_stars_repo_head_hexsha": "7ded9f8fba0cb5758672b982d1a9e59e4fe32ceb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bin/gobles.py", "max_issues_repo_name": "newbooks/pymcce", "max_issues_repo_head_hexsha": "7ded9f8fba0cb5758672b982d1a9e59e4fe32ceb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-12-20T03:39:12.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-23T17:46:31.000Z", "max_forks_repo_path": "bin/gobles.py", "max_forks_repo_name": "newbooks/pymcce", "max_forks_repo_head_hexsha": "7ded9f8fba0cb5758672b982d1a9e59e4fe32ceb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.871257485, "max_line_length": 123, "alphanum_fraction": 0.493609508, "include": true, "reason": "import numpy", "num_tokens": 9282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.22541662103868038, "lm_q1q2_score": 0.11446923456917121}} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# \n# \n# # Earth Analytics Education - EA Python Course Spring 2021\n\n# ## Important - Assignment Guidelines\n# \n# 1. Before you submit your assignment to GitHub, make sure to run the entire notebook with a fresh kernel. To do this first, **restart the kernel** (in the menubar, select Kernel$\\rightarrow$Restart & Run All)\n# 2. Always replace the `raise NotImplementedError()` code with your code that addresses the activity challenge. If you don't replace that code, your notebook will not run.\n# \n# ```\n# # YOUR CODE HERE\n# raise NotImplementedError()\n# ```\n# \n# 3. Any open ended questions will have a \"YOUR ANSWER HERE\" within a markdown cell. Replace that text with your answer also formatted using Markdown.\n# 4. **DO NOT RENAME THIS NOTEBOOK File!** If the file name changes, the autograder will not grade your assignment properly.\n# 6. When you create a figure, comment out `plt.show()` to ensure the autograder can grade your plots. For figure cells, DO NOT DELETE the code that says `DO NOT REMOVE LINE BELOW`.\n# \n# ```\n# ### DO NOT REMOVE LINE BELOW ###\n# student_plot1_ax = nb.convert_axes(plt)\n# ```\n# \n# * Only include the package imports, code, and outputs that are required to run your homework assignment.\n# * Be sure that your code can be run on any operating system. This means that:\n# 1. the data should be downloaded in the notebook to ensure it's reproducible\n# 2. all paths should be created dynamically using the `os.path.join`\n# \n# ## Follow to PEP 8 Syntax Guidelines & Documentation\n# \n# * Run the `autopep8` tool on all cells prior to submitting (HINT: hit shift + the tool to run it on all cells at once!\n# * Use clear and expressive names for variables. \n# * Organize your code to support readability.\n# * Check for code line length\n# * Use comments and white space sparingly where it is needed\n# * Make sure all python imports are at the top of your notebook and follow PEP 8 order conventions\n# * Spell check your Notebook before submitting it.\n# \n# For all of the plots below, be sure to do the following:\n# \n# * Make sure each plot has a clear TITLE and, where appropriate, label the x and y axes. Be sure to include UNITS in your labels.\n# \n\n# ### Add Your Name Below \n# **Your Name:** Adam Mansur\n\n# \n\n# ---\n\n# # Week 04 and 05 Homework - Automate NDVI Workflow\n# \n# For this assignment, you will write code to generate a plot of the mean normalized difference vegetation index (NDVI) for two different sites in the United States across one year of data:\n# \n# * San Joaquin Experimental Range (SJER) in Southern California, United States\n# * Harvard Forest (HARV) in the Northeastern United States\n# \n# The data that you will use for this week is available from **earthpy** using the following download: \n# \n# `et.data.get_data('ndvi-automation')`\n# \n# ## Assignment Goals\n# \n# Your goal in this assignment is to create the most efficient and concise workflow that you can that allows for:\n# \n# 1. The code to scale if you added new sites or more time periods to the analysis.\n# 2. Someone else to understand your workflow.\n# 3. The LEAST and most efficient (i.e. runs fast, minimize repetition) amount of code that completes the task.\n# \n# ### HINTS\n# \n# * Remove values outside of the landsat valid range of values as specified in the metadata, as needed.\n# * Keep any output files SEPARATE FROM input files. Outputs should be created in an outputs directory that is created in the code (if needed) and/or tested for.\n# * Use the functions that we demonstrated during class to make your workflow more efficient.\n# * BONUS - if you chose - you can export your data as a csv file. You will get bonus points for doing this.\n# \n# \n# ## Assignment Requirements\n# \n# Your submission to the GitHub repository should include:\n# * This Jupyter Notebook file (.ipynb) with:\n# * The code to create a plot of mean NDVI across a year for 2 NEON Field Sites:\n# * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object\n# * The **data should be cleaned to remove the influence of clouds**. See the [earthdatascience website for an example of what your plot might look like with and without removal of clouds](https://www.earthdatascience.org/courses/earth-analytics-python/create-efficient-data-workflows/).\n# * BONUS: Create one output `.csv` file that has 3 columns - NDVI, Date and Site Name - with values for SJER and HARV.\n# \n# Your notebook should:\n# * Have *at least* 2 well documented and well named functions with docstrings.\n# * Include a Markdown cell at the top of the notebook that outlines the overall workflow using pseudocode (i.e. plain language, not code)\n# * Include additional Markdown cells throughout the notebook to describe: \n# * the data that you used - and where it is from\n# * how data are being processing\n# * how the code is optimized to run fast and be more concise\n\n# # Replace this cell with your pseudocode for this workflow\n# \n# If you happen to be a diagram person a diagram is ok too\n# \n# \n\n# # Pseudocode\n# \n# *The cell above is locked*\n# \n# + Identify and iterate through 2017 Landstat tilesets for HARV and\n# SJER sites. For each site:\n# + Read the site boundary vector file\n# + For each scene:\n# + Read and label red, NIR, and QA bands\n# + Remove extreme values\n# + Crop bands to site boundary\n# + Remove clouds and cloud shadows\n# + Calculate NDVI and mean NDVI\n# + Parse acquisition date from Landsat file names\n# + Create dataframe with site name, date, and mean NDVI\n# + Concatenate individual dataframes into a single dataframe\n# + Plot NDVI over time for both sites \n# \n# \n# # Approach\n# \n# The functions for reading, cropping, and masking Landsat data were combined\n# into an xarray accessor class called LandsatAccessor. The accessor structure is\n# the recommended way to extend xarray objects. I chose this approach because:\n# \n# 1. I've found it difficult to keep track of what's going on when cleaning and\n# plotting data using xarray. Many of the procedures require remembering to use\n# functions I don't really understand (like plotting_extent) or process bands\n# using list indices that could vary depending on exactly how the data was read.\n# This makes it hard to re-use code or remember how to make various plots. The\n# accessor shifts some of the confusing bits (like deriving and applying the\n# cloud QA mask) behind the scenes.\n# 2. The functions I came up with are more readable/reproducible if the Landsat\n# data is read in a specific way (for example, with the band attribute set to\n# match the original band number instead of the read order). That is a good\n# case for bundling methods in a class.\n# \n# Some other things I like about this approach include that it:\n# \n# + Allows access to individual bands by name (red, green, blue, nir)\n# + Clarifies calculations like NDVI by explicitly naming the bands involved\n# + Compiles Landsat-related logic inside a single class (plus a helper function\n# used to read the Landsat images) that are available from any xarray object\n# \n# Drawbacks to this approach include:\n# \n# + The ad hoc attributes required to use the accessor methods are not always\n# carried over by array operations, so the accessor is somewhat brittle. This\n# is a limitation of xarray, which prioritizes letting calcualtions run over\n# preserving metadata.\n# + The accessor currently only works on Landsat data. Currently Landsat-specific\n# logic is used for mapping bands to colors, reading metadata, and masking\n# using the QA layer. The first thing could be generalized, but not the other\n# two seem to depend heavily on the exact satellite producing the data.\n# + Length of code is excessive for the current assignment\n# \n# The code isn't optimized besides really basic stuff like using built-in array\n# functions. The loop used to look for all HARV and SJER data should scale.\n\n# In[1]:\n\n\n# Autograding imports - do not modify this cell\nimport matplotcheck.autograde as ag\nimport matplotcheck.notebook as nb\nimport matplotcheck.timeseries as ts\nfrom datetime import datetime\n\n\n# In[2]:\n\n\n# Import needed packages in PEP 8 order\n# and no unused imports listed (10 points total)\nfrom glob import glob\nimport os\nimport re\n\nimport earthpy as et\nimport earthpy.mask as em\nimport earthpy.plot as ep\nimport geopandas as gpd\nimport matplotlib.dates as mdates \nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport rioxarray as rxr\nimport xarray as xr\n\n\n\n\n# Increase default font size on all plots\nsns.set(font_scale=1.5)\n\n# Download NDVI automation dataset\net.data.get_data(\"ndvi-automation\")\n\n# Set working directory\nos.chdir(os.path.join(et.io.HOME, \"earth-analytics\", \"data\"))\n\n\n# In[3]:\n\n\n# DO NOT MODIFY THIS CELL\n# Tests that the working directory is set to earth-analytics/data\n\npath = os.path.normpath(os.getcwd())\nstudent_wd_parts = path.split(os.sep)\n\nif student_wd_parts[-2:] == ['earth-analytics', 'data']:\n print(\"\\u2705 Great - it looks like your working directory is set correctly to ~/earth-analytics/data\")\nelse:\n print(\"\\u274C Oops, the autograder will not run unless your working directory is set to earth-analytics/data\")\n\n\n# # Figure 1: Plot 1 - Mean NDVI For Each Site Across the Year (50 points)\n# \n# Create a plot of the mean normalized difference vegetation index (NDVI) for the two different sites in the United States across the year: \n# \n# * NDVI on the x axis and formatted dates on the y for both NEON sites on one figure/axis object.\n# * Each site should be identified with a different color in the plot and legend.\n# * The final plot **data should be cleaned to remove the influence of clouds**.\n# * Be sure to include appropriate title and axes labels.\n# \n# Add additional cells as needed for processing data (e.g. defining functions, etc), but be sure to:\n# * follow the instructions in the code cells that have been provided to ensure that you are able to use the sanity check tests that are provided. \n# * include only the plot code in the cell identified for the final plot code below\n\n# ## Task 1: \n# \n# In the cell below, create a single dataframe containing MEAN NDVI, the site name, \n# and the date of the data for the HARV site \n# scene `HARV/landsat-crop/LC080130302017031701T1-SC20181023151837`. The column names for the final\n# DataFrame should be`mean_ndvi`, and `site`, and the data should be **indexed on the date**. \n# \n# Use the functions that we reviewed in class (or create your own versions of them) to implement your code\n# \n# ### In the Cell below Place All Functions Needed to Run this Notebook (20 points)\n\n# In[4]:\n\n\n### DO NOT REMOVE THIS LINE OR EDIT / MOVE THIS CELL ###\nstart_time = datetime.now()\n\n\n# In[5]:\n\n\n# In this cell place all of the functions needed to run your notebook\n# You will be graded here on function application, docstrings, efficiency so ensure\n# All functions are placed here!\n\n\n@xr.register_dataarray_accessor(\"landsat\")\nclass LandsatAccessor:\n \"\"\"Extends data array to parse and run common calculations on Landsat data\n \n Attributes\n ----------\n red : xarray DataArray\n red band\n green : xarray DataArray\n green band\n blue : xarray DataArray\n blue band\n nir : xarray DataArray\n near-infrared band\n qa : xarray DataArray\n pixel qa band\n metadata : dict\n Landsat metadata parsed from filename\n \"\"\"\n \n def __init__(self, xarr):\n self._obj = xarr\n self._metadata = None\n self._names = {\n 2: \"blue\",\n 3: \"green\",\n 4: \"red\",\n 5: \"nir\",\n }\n \n \n @property\n def blue(self):\n return self._obj.sel(band=2)\n \n \n @property\n def green(self):\n return self._obj.sel(band=3)\n \n \n @property\n def red(self):\n return self._obj.sel(band=4)\n \n \n @property\n def nir(self):\n return self._obj.sel(band=5)\n \n \n @property\n def qa(self):\n return self._obj.sel(band=\"qa\")\n \n \n @property\n def metadata(self):\n \"\"\"Returns Landsat metadata, deriving it from a filename if needed\n \n Metadata parsing is deferred so that non-Landsat arrays don't get\n tripped up by the parse function when they are created.\n \"\"\"\n if self._metadata is None:\n self._metadata = self._parse_product_id()\n return self._metadata\n \n \n def clean_all_bands(self, **kwargs):\n \"\"\"Cleans all bands in the array\n \n Arguments\n ---------\n kwargs:\n any keyword argument accepted by clean_band()\n \n Returns\n -------\n xarray DataArray\n Array with out-of-range data set to nan \n \"\"\"\n # Clean each band and build a new DataArray\n out_xr = []\n for arr in self._obj:\n if arr.band != \"qa\":\n out_xr.append(self.clean_band(arr, **kwargs))\n out_xr.append(self.qa.copy())\n\n return xr.concat(out_xr, dim=\"band\")\n \n \n def mask_qa_pixels(self, flags):\n \"\"\"Masks array based on Landsat QA pixel flags\n \n Arguments\n ---------\n flags : list-like\n list of pixel QA flags to mask\n \n Returns\n -------\n xarray DataArray\n Array with specified features set to nan\n \"\"\"\n \n # Format key for earthy.mask lookup from satellite number\n key = \"L{}\".format(self.metadata[\"satellite\"].lstrip(\"0\"))\n \n # Read pixel values for specified flags\n mask = []\n for flag in flags:\n mask.extend(em.pixel_flags[\"pixel_qa\"][key][flag])\n \n # Mask each data band separately and build a new DataArray\n out_xr = []\n for arr in self._obj:\n if arr.band != \"qa\":\n out_xr.append(arr.where(~self.qa.isin(mask)))\n \n # Ad hoc attributes are lost here, so set them manually.\n out_xr[-1][\"band\"] = arr.band\n out_xr[-1][\"path\"] = arr.path\n \n out_xr.append(self.qa.copy())\n\n return xr.concat(out_xr, dim=\"band\")\n\n \n def mask_clouds(self):\n \"\"\"Masks clouds in an array (Landsat 8 only)\n \n Returns\n -------\n xarray DataArray\n Array with cloud features set to nan\n \"\"\"\n return self.mask_qa_pixels(\n [\"Cloud\", \"Cloud Shadow\", \"High Cloud Confidence\"]\n )\n \n \n def ndvi(self):\n \"\"\"Calculates NDVI using the named NIR and red bands\n \n Returns\n -------\n xarray DataArray\n Array containing NDVI values\n \"\"\"\n return (self.nir - self.red) / (self.nir + self.red)\n \n \n def plot_bands(self, **kwargs):\n \"\"\"Plots all bands in the array\n \n Arguments\n ---------\n kwargs:\n any keyword argument accepted by ep.plot_bands(). The title\n arguments is provided if not given.\n \n Returns\n -------\n None\n \"\"\"\n # Set default titles for each band\n bands = [a.band.values[()] for a in self._obj]\n kwargs.setdefault(\"title\", [self._names.get(b, b) for b in bands])\n \n ep.plot_bands(self._obj, **kwargs)\n\n \n @staticmethod\n def clean_band(band, valid_range=None):\n \"\"\"Cleans a single Landsat band\n\n Parameters\n -----------\n band : str or array\n Either an array or the path to the array to be opened\n valid_range : tuple (optional)\n A tuple of min and max range of values for the data. Default = None\n\n\n Returns\n -----------\n xarray DataArray\n Array with out-of-range values set to nan\n \"\"\"\n # Read band from file if passed as a string\n if isinstance(band, str):\n band = rxr.open_rasterio(band_path, masked=True).squeeze()\n\n # Remove pixels outside valid range if provided\n if valid_range:\n mask = ((band < min(valid_range)) | (band > max(valid_range)))\n band = band.where(~xr.where(mask, True, False))\n\n return band\n \n \n def _parse_product_id(self):\n \"\"\"Parses acquisition and processing info from Landsat filename\n \n Returns\n -------\n dict\n Dictionary containing the parsed metadata\n \"\"\"\n prod_id = os.path.basename(self._obj[0].path.values[()])\n sat, corr, wrs, acq, proc, coll_num, coll_cat = prod_id.split(\"_\")[:7]\n \n return {\n \"sensor\": sat[1],\n \"satellite\": sat[3:],\n \"wrs_path\": wrs[:3],\n \"wrs_row\": wrs[3:],\n \"acq_date\": datetime.strptime(acq, \"%Y%m%d\"),\n \"proc_date\": datetime.strptime(proc, \"%Y%m%d\"),\n \"coll_num\": coll_num,\n \"coll_cat\": coll_cat \n } \n\n \n \n \ndef open_landsat(path, min_band=1, max_band=7):\n \"\"\"Combines Landsat TIFFs in a directory into an xarray\n \n Also adds two ad hoc attributes, band and path. Some methods, like\n arr.where(), seem to lose track of these attributes in some cases.\n\n Arguments\n ---------\n path : str\n path to directory containing a set of Landsat TIFFs\n min_band: int\n minimum band to retrieve\n max_band: int\n maximum band to retrieve\n\n Returns\n -------\n xarray DataArray\n Array merging all matching TIFFs into one object\n\n Raises\n ------\n IOError\n If wrong number of bands found\n \"\"\"\n\n # Read TIFFs along path matching selected bands, then add the QA band\n paths = []\n for fp in glob(os.path.join(path, f\"*band[{min_band}-{max_band}]*.tif\")):\n paths.append(fp)\n paths.sort()\n paths.extend(glob(os.path.join(path, f\"*pixel_qa*.tif\")))\n \n # Raise an error if any of the expected bands are missing\n expected = (max_band - min_band + 2)\n if len(paths) != expected:\n raise IOError(f\"Wrong number of TIFFs found on {os.path.abspath(path)}\"\n f\" (found {len(paths)}, expected={expected})\")\n\n # Combine ordered list of TIFFs into an xarray\n out_xr =[]\n for fp in paths:\n out_xr.append(rxr.open_rasterio(fp, masked=True).squeeze())\n\n # Add min_band so that the band id matches original Landsat band\n out_xr[-1][\"band\"] = len(out_xr) + min_band - 1\n out_xr[-1][\"path\"] = os.path.realpath(fp)\n\n # Rename the last band to \"qa\"\n out_xr[-1][\"band\"] = \"qa\"\n\n return xr.concat(out_xr, dim=\"band\")\n\n\n\ndef mean_ndvi_from_landsat(path, site_name, site_boundary=None):\n \"\"\"Calculates mean NDVI for a set of Landsat images\n \n Arguments\n ---------\n path: str\n path to directory containing a set of Landsat images\n site_name : str\n name of the site imaged by Landsat\n site_boundary : str or geopandas.GeoDatafFrame\n boundary of the site as either a path to a shapefile or GeoDataFrame\n\n Returns\n -------\n pandas DataFrame\n Date-indexed dataframe with the mean NDVI from the Landsat data\n \"\"\"\n arr = open_landsat(path, min_band=4, max_band=5)\n \n # Clip site to boundary\n if site_boundary is not None:\n \n # Read boundary from file if string given\n if isinstance(site_boundary, str):\n site_boundary = gpd.read_file(site_boundary)\n \n # Align CRS if not the same\n if arr.rio.crs != site_boundary.crs:\n site_boundary = site_boundary.to_crs(arr.rio.crs)\n \n arr = arr.rio.clip(site_boundary.geometry)\n \n # Remove extreme values from all bands\n arr = arr.landsat.clean_all_bands(valid_range=(0, 10000))\n \n # Mask clouds\n arr = arr.landsat.mask_clouds()\n \n # Return a data-indexed dataframe with the mean NDVI for the dataset\n return pd.DataFrame({\n \"site\": site_name,\n \"mean_ndvi\": float(arr.landsat.ndvi().mean())\n },\n index=[arr.landsat.metadata[\"acq_date\"]]\n )\n \n \n \n\n\n# ### Data sources\n# \n# Data for the following calculation of NDVI was collected by the Landsat 8 \n# satellite in March 2017 at the HARV field site as part of the NEON program.\n\n# In[6]:\n\n\n# Create dataframe of mean NDVI in this cell using the functions created above\n# Important: to use the ungraded tests below as a sanity check,\n# name your columns: mean_ndvi and site\n# Call the dataframe at the end of the cell so the tests run on it!\n# Be sure that the date column is an index of type date\n# HINT: the time series lessons may help you remember how to do this!\n\n# Define path to HARV folder\nharv_path = os.path.join(\"ndvi-automation\", \"sites\", \"HARV\")\n\n# Define path to HARV site boundary\nharv_bound_path = os.path.join(harv_path, \"vector\", \"HARV-crop.shp\")\n\n# Define path to specific dataset\nharv_20170317_path = os.path.join(\n harv_path, \"landsat-crop\", \"LC080130302017031701T1-SC20181023151837\"\n)\n\n# Calculate mean NDVI\nharv_20170317_mean_ndvi = mean_ndvi_from_landsat(\n harv_20170317_path, \"HARV\", harv_bound_path\n)\nharv_20170317_mean_ndvi\n\n\n# In[7]:\n\n\n# This cell is testing your data output above\n\nstudent_ndvi_ts_single_site = _\n\nsingle_scene_points = 0\n\n# Ensure the data is stored in a dataframe.\nif isinstance(student_ndvi_ts_single_site, pd.DataFrame):\n print('\\u2705 Your data is stored in a DataFrame!')\n single_scene_points += 1\nelse:\n print('\\u274C It appears your data is not stored in a DataFrame. ',\n 'To see what type of object your data is stored in, check its type with type(object)')\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_ts_single_site.index, pd.core.indexes.datetimes.DatetimeIndex):\n print('\\u2705 You have the index set to the date column!')\n single_scene_points += 2\nelse:\n print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_ts_single_site.index[0], pd._libs.tslibs.timestamps.Timestamp):\n print('\\u2705 The data in your date column is datetime!')\n single_scene_points += 2\nelse:\n print('\\u274C The data in your date column is not datetime.')\n\n# Ensure the site name is correct\nif student_ndvi_ts_single_site.site.values[0] == 'HARV':\n print('\\u2705 You have the correct site name!')\n single_scene_points += 5\nelse:\n print('\\u274C You do not have the correct site name.')\n\nif np.allclose(0.281131628228094, student_ndvi_ts_single_site.mean_ndvi.values[0]):\n print('\\u2705 You have the correct mean NDVI value!')\n single_scene_points += 5\nelse:\n print('\\u274C You do not have the correct mean ndvi value.')\n\nprint(\"\\n \\u27A1 You received {} out of 15 points for creating a dataframe.\".format(\n single_scene_points))\nsingle_scene_points\n\n\n# ## Task 2:\n# \n# In the cell below, process all of the landsat scenes. Create a DataFrame that contains the following \n# information for each scene\n# \n# \n# | | index | site | mean_ndvi | \n# |---|---|---|---|\n# | Date | | | |\n# | 2017-01-07 | 0 | SJER | .4 | \n# \n# Be sure to call your dataframe at the end of the cell to ensure autograding works.\n# HINT: FOR THIS STEP, leave any rows containing missing values (`NAN`).\n\n# ### Data sources\n# \n# Data for the following calculation of NDVI was collected by the Landsat 8\n# satellite in 2017 for the HARV and SJER field sites as part of the NEON program.\n\n# In[8]:\n\n\n# Create dataframe of NDVI including the cleaning data to deal with clouds\n\n# Important: to use the ungraded tests below as a sanity check,\n# name your columns: mean_ndvi and site\n# Don't forget to set date as the index and make the values of type datetime\n\n# Define path to SJER folder (the path to HARV is defined above)\nsjer_path = os.path.join(\"ndvi-automation\", \"sites\", \"SJER\")\n\n# Read boundaries for each site\nboundaries = {\n \"HARV\": gpd.read_file(os.path.join(harv_path, \"vector\", \"HARV-crop.shp\")),\n \"SJER\": gpd.read_file(os.path.join(sjer_path, \"vector\", \"SJER-crop.shp\"))\n}\n\n# Calculate NDVI for each scene\nndvi_by_scene = []\nfor root, dirs, files in os.walk(os.path.join(\"ndvi-automation\", \"sites\")):\n if os.path.basename(root).startswith(\"LC08\"):\n # Grab site name from root and process scene\n site_name = re.search(r\"\\b[A-Z]{4}\\b\", root).group()\n ndvi_by_scene.append(\n mean_ndvi_from_landsat(root, site_name, boundaries[site_name])\n )\n \nmean_ndvi_all = pd.concat(ndvi_by_scene).sort_index()\nmean_ndvi_all\n\n\n# In[9]:\n\n\n# Last sanity check before creating your plot (10 points)\n\n# Ensure that you call your dataframe at the bottom of the cell above\n# and that it has columns called: mean_ndvi and site\n\n# Ensure the data is stored in a dataframe.\nstudent_ndvi_df = _\n\ndf_points = 0\n\nif isinstance(student_ndvi_df, pd.DataFrame):\n print('\\u2705 Your data is stored in a DataFrame!')\n df_points +=2\nelse:\n print('\\u274C It appears your data is not stored in a DataFrame. ',\n 'To see what type of object your data is stored in, check its type with type(object)')\n\n# Check that dataframe contains the appropriate number of NAN values\nif student_ndvi_df.mean_ndvi.isna().sum() == 15:\n print('\\u2705 Correct number of masked data values!')\n df_points +=2\nelse:\n print('\\u274C The amount of null data in your dataframe is incorrect.')\n\n\n# Ensure that the date column is the index\nif isinstance(student_ndvi_df.index, pd.core.indexes.datetimes.DatetimeIndex):\n print('\\u2705 You have the index set to the date column!')\n df_points +=3\nelse:\n print('\\u274C You do not have the index set to the date column.')\n\n# Ensure that the date column is datetime\nif isinstance(student_ndvi_df.index[0], pd._libs.tslibs.timestamps.Timestamp):\n print('\\u2705 The data in your date column is datetime!')\n df_points +=3\nelse:\n print('\\u274C The data in your date column is not datetime.')\n\n# Output for timer, # DO NOT MODIFY\nend_time = datetime.now()\ntotal_time = end_time - start_time\nprint(\n \"Your total run time for processing the data was {0}.\".format(total_time))\n\nprint(\"\\n \\u27A1 You received {} out of 10 points for creating a dataframe.\".format(\n df_points))\n\ndf_points\n\n\n# In[10]:\n\n\n# Add only the plot code to this cell\n\n# This is the final figure of mean NDVI\n# for both sites across the year\n# with data cleaned to deal with clouds\n\n# Remove null NDVIs so lines connect all points\nmean_ndvi_sub = mean_ndvi_all.dropna(how=\"any\", axis=0)\n\nfig, ax = plt.subplots(1, 1, figsize=(12, 6))\nax.set(\n title=\"Mean NDVI at two NEON sites in 2017\",\n xlabel=\"Date\",\n ylabel=\"Mean NDVI\",\n ylim=(0, 1)\n)\n\n# Plot scenes for each site as a line\nfor site, rows in mean_ndvi_sub.groupby(\"site\"):\n ax.plot(rows.index, rows.mean_ndvi, marker=\"o\", label=site)\n\n# Use short month names to label the x axis\nax.xaxis.set_major_formatter(mdates.DateFormatter('%b\\n%Y')) \n\nax.legend()\n\nfig.text(0.5, -0.1, f\"Source: NEON (Landsat 8)\", fontsize=14, ha=\"center\")\n\n### DO NOT REMOVE LINES BELOW ###\nfinal_masked_solution = nb.convert_axes(plt, which_axes=\"current\")\n\n\n# In[11]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# In[12]:\n\n\n# Ignore this cell for the autograding tests\n\n\n# # Question 1 (10 points)\n# \n# Imagine that you are planning NEON’s upcoming flight season to capture remote sensing data in these locations and want to ensure that you fly the area when the vegetation is the most green.\n# \n# When would you recommend the flights take place for each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# Healthy, green vegetation will show a moderate to high NDVI. The highest NDVI (and\n# therefore greenest vegeation) occurred at the SJER site between March and mid-April\n# and at the HARV site between mid-May and late September, so those would be the best\n# windows for scheduling flights.\n\n# # Question 2 (10 points)\n# \n# How could you modify your workflow to look at vegetation changes over time in each site? \n# \n# Answer the question in 2-3 sentences in the Markdown cell below.\n\n# One approach would be to compare results from periods of high and low NDVI. For SJER,\n# that would mean scheduling a flight for sometime between July and December in addition\n# to the high NDVI flight above. For HARV, the low NDVI flight would be scheduled for\n# March to April (and possibily earlier since data from January and February are not\n# available but NDVI at this site is trending down in December).\n\n# # Do not edit this cell! (10 points)\n# \n# The notebook includes:\n# * additional Markdown cells throughout the notebook to describe: \n# * the data that you used - and where it is from\n# * how data are being processing\n# * how the code is optimized to run fast and be more concise\n\n# # Do not edit this cell! (20 points)\n# \n# The notebook will also be checked for overall clean code requirements as specified at the **top** of this notebook. Some of these requirements include (review the top cells for more specifics): \n# \n# * Notebook begins at cell [1] and runs on any machine in its entirety.\n# * PEP 8 format is applied throughout (including lengths of comment and code lines).\n# * No additional code or imports in the notebook that is not needed for the workflow.\n# * Notebook is fully reproducible. This means:\n# * reproducible paths using the os module.\n# * data downloaded using code in the notebook.\n# * all imports at top of notebook.\n\n# ## BONUS - Export a .CSV File to Share (10 points possible)\n# \n# This is optional - if you export a **.csv** file with the columns specified above: Site, Date and NDVI Value you can get an additional 10 points.\n# \n# * FULL CREDIT: File exists in csv format and contains the columns specified.\n# We will check your github repo for this file!\n# \n\n# In[13]:\n\n\n# Export CSV with mean NDVI to outputs folder\nmean_ndvi_all.to_csv(os.path.join(\"ndvi-automation\", \"outputs\", \"mean_ndvi.csv\"),\n header=[\"Site\", \"NDVI Value\"],\n index_label=\"Date\")\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "31674374f4d5018a9b38c07f43d29d9c17e30ffe", "size": 30387, "ext": "py", "lang": "Python", "max_stars_repo_path": "mansur_adam_ndvi.py", "max_stars_repo_name": "adamancer/ea-2021-ndvi-automation-review", "max_stars_repo_head_hexsha": "5b55275f079655c0ec55beff47371ae213dee996", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mansur_adam_ndvi.py", "max_issues_repo_name": "adamancer/ea-2021-ndvi-automation-review", "max_issues_repo_head_hexsha": "5b55275f079655c0ec55beff47371ae213dee996", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mansur_adam_ndvi.py", "max_forks_repo_name": "adamancer/ea-2021-ndvi-automation-review", "max_forks_repo_head_hexsha": "5b55275f079655c0ec55beff47371ae213dee996", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0279955207, "max_line_length": 291, "alphanum_fraction": 0.6757494981, "include": true, "reason": "import numpy", "num_tokens": 7465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606815201671963, "lm_q2_score": 0.28776782186926264, "lm_q1q2_score": 0.11397566941763541}} {"text": "from __future__ import division, absolute_import, print_function\nfrom past.builtins import xrange\n\nimport numpy as np\nimport scipy.interpolate as interpolate\nimport scipy.integrate as integrate\nimport os\nimport sys\nfrom pkg_resources import resource_filename\n\n\nfrom .modtranGenerator import ModtranGenerator\nfrom .fgcmAtmosphereTable import FgcmAtmosphereTable\n\n\nfrom .sharedNumpyMemManager import SharedNumpyMemManager as snmm\nfrom .fgcmLogger import FgcmLogger\n\n\nclass FgcmLUTMaker(object):\n \"\"\"\n Class to make a look-up table.\n\n parameters\n ----------\n lutConfig: dict\n Dictionary with LUT config variables\n makeSeds: bool, default=False\n Make a SED-table in the look-up table (experimental)\n \"\"\"\n\n def __init__(self,lutConfig,makeSeds=False):\n self._checkLUTConfig(lutConfig)\n\n self.magConstant = 2.5/np.log(10)\n self._setThroughput = False\n self.makeSeds = makeSeds\n\n try:\n self.stellarTemplateFile = resource_filename(__name__,'data/templates/stellar_templates_master.fits')\n except:\n raise IOError(\"Could not find stellar template file\")\n\n if (not os.path.isfile(self.stellarTemplateFile)):\n raise IOError(\"Could not find stellar template file\")\n\n if 'logger' in lutConfig:\n self.fgcmLog = lutConfig['logger']\n else:\n self.fgcmLog = FgcmLogger('dummy.log', 'INFO', printLogger=True)\n\n def _checkLUTConfig(self,lutConfig):\n \"\"\"\n Internal method to check the lutConfig dictionary\n\n parameters\n ----------\n lutConfig: dict\n \"\"\"\n\n self.runModtran = False\n\n requiredKeys = ['filterNames', 'stdFilterNames', 'nCCD']\n\n\n # first: check if there is a tableName here!\n if 'atmosphereTableName' in lutConfig:\n # Can we find this table?\n\n # load parameters from it and stuff into config dict\n self.atmosphereTable = FgcmAtmosphereTable.initWithTableName(lutConfig['atmosphereTableName'])\n\n # look for consistency between configs?\n # Note that we're assuming if somebody asked for a table they wanted\n # what was in the table\n for key in self.atmosphereTable.atmConfig:\n if key in lutConfig:\n if 'Range' in key:\n if (not np.isclose(lutConfig[key][0], self.atmosphereTable.atmConfig[key][0]) or\n not np.isclose(lutConfig[key][1], self.atmosphereTable.atmConfig[key][1])):\n print(\"Warning: input config %s is %.5f-%.5f but precomputed table is %.5f-%.5f\" %\n (key, lutConfig[key][0], lutConfig[key][1],\n self.atmosphereTable.atmConfig[key][0],\n self.atmosphereTable.atmConfig[key][1]))\n else:\n if not np.isclose(lutConfig[key], self.atmosphereTable.atmConfig[key]):\n print(\"Warning: input config %s is %.5f but precomputed table is %.5f\" %\n (key, lutConfig[key], self.atmosphereTable.atmConfig[key]))\n\n else:\n # regular config with parameters\n self.runModtran = True\n self.atmosphereTable = FgcmAtmosphereTable(lutConfig)\n\n for key in requiredKeys:\n if (key not in lutConfig):\n raise ValueError(\"required %s not in lutConfig\" % (key))\n if ('Range' in key):\n if (len(lutConfig[key]) != 2):\n raise ValueError(\"%s must have 2 elements\" % (key))\n\n self.lutConfig = lutConfig\n\n self.filterNames = self.lutConfig['filterNames']\n self.stdFilterNames = self.lutConfig['stdFilterNames']\n\n if len(self.filterNames) != len(self.stdFilterNames):\n raise ValueError(\"Length of filterNames must be same as stdFilterNames\")\n\n for stdFilterName in self.stdFilterNames:\n if stdFilterName not in self.filterNames:\n raise ValueError(\"stdFilterName %s not in list of filterNames\" % (stdFilterName))\n\n self.nCCD = self.lutConfig['nCCD']\n self.nCCDStep = self.nCCD+1\n\n # and record the standard values out of the config\n # (these will also come out of the save file)\n\n self.pmbStd = self.atmosphereTable.atmConfig['pmbStd']\n self.pwvStd = self.atmosphereTable.atmConfig['pwvStd']\n self.o3Std = self.atmosphereTable.atmConfig['o3Std']\n self.tauStd = self.atmosphereTable.atmConfig['tauStd']\n self.lnTauStd = np.log(self.tauStd)\n self.alphaStd = self.atmosphereTable.atmConfig['alphaStd']\n self.secZenithStd = self.atmosphereTable.atmConfig['airmassStd']\n self.zenithStd = np.arccos(1./self.secZenithStd)*180./np.pi\n\n if ('lambdaRange' in self.atmosphereTable.atmConfig):\n self.lambdaRange = np.array(self.atmosphereTable.atmConfig['lambdaRange'])\n else:\n self.lambdaRange = np.array([3000.0,11000.0])\n\n if ('lambdaStep' in self.atmosphereTable.atmConfig):\n self.lambdaStep = self.atmosphereTable.atmConfig['lambdaStep']\n else:\n self.lambdaStep = 0.5\n\n if ('lambdaNorm' in self.atmosphereTable.atmConfig):\n self.lambdaNorm = self.atmosphereTable.atmConfig['lambdaNorm']\n else:\n self.lambdaNorm = 7750.0\n\n def setThroughputs(self, throughputDict):\n \"\"\"\n Set the throughputs per CCD\n\n parameters\n ----------\n throughputDict: dict\n Dict with throughput information\n\n The throughput dict should have one entry for each filterName.\n Each of these elements should be a dictionary with the following keys:\n 'LAMBDA': numpy float array with wavelength values\n ccd_index: numpy float array with throughput values for the ccd_index\n There should be one entry for each CCD.\n \"\"\"\n\n self.inThroughputs=[]\n for filterName in self.filterNames:\n try:\n lam = throughputDict[filterName]['LAMBDA']\n except:\n raise ValueError(\"Wavelength LAMBDA not found for filter %s in throughputDict!\" % (filterName))\n\n tput = np.zeros(lam.size, dtype=[('LAMBDA','f4'),\n ('THROUGHPUT_AVG','f4'),\n ('THROUGHPUT_CCD','f4',self.nCCD)])\n tput['LAMBDA'][:] = lam\n for ccdIndex in xrange(self.nCCD):\n try:\n tput['THROUGHPUT_CCD'][:,ccdIndex] = throughputDict[filterName][ccdIndex]\n except:\n raise ValueError(\"CCD Index %d not found for filter %s in throughputDict!\" % (ccdIndex,filterName))\n\n # check if the average is there, if not compute it\n if ('AVG' in throughputDict[filterName]):\n tput['THROUGHPUT_AVG'][:] = throughputDict[filterName]['AVG']\n else:\n self.fgcmLog.info(\"Average throughput not found in throughputDict for filter %s. Computing now...\" % (filterName))\n for i in xrange(lam.size):\n use,=np.where(tput['THROUGHPUT_CCD'][i,:] > 0.0)\n if (use.size > 0):\n tput['THROUGHPUT_AVG'][i] = np.mean(tput['THROUGHPUT_CCD'][i,use])\n\n self.inThroughputs.append(tput)\n\n self._setThroughput = True\n\n def makeLUT(self):\n \"\"\"\n Make the look-up table. This can either be saved with saveLUT or accessed via\n attributes.\n\n parameters\n ----------\n None\n\n output attributes\n -----------------\n pmb: float array\n Pressure (millibars)\n pmbFactor: float array\n Pressure factor\n pmbElevation: float\n Standard PMB at elevation\n pwv: float array\n Water vapor array\n o3: float array\n Ozone array\n tau: float array\n Aerosol optical index array\n lambdaNorm: float\n Aerosol normalization wavelength\n alpha: float array\n Aerosol slope array\n zenith: float array\n Zenith angle array\n nccd: int\n Number of CCDs in table\n pmbStd: float\n Standard PMB\n pwvStd: float\n Standard PWV\n o3Std: float\n Standard O3\n tauStd: float\n Standard tau\n alphaStd: float\n Standard alpha\n zenithStd: float\n Standard zenith angle (deg)\n lambdaRange: numpy float array\n Wavelength range (A)\n lambdaStep: float\n Wavelength step (A)\n lambdaStd: numpy float array\n Standard wavelength for each filterName (A) at each standard band\n lambdaStdRaw: numpy float array\n Standard wavelength for each filterName (A)\n I0Std: numpy float array\n Standard value for I0 for each filterName\n I1Std: numpy float array\n Standard value for I1 for each filterName\n I10Std: numpy float array\n Standard value for I10 for each filterName\n lambdaB: numpy float array\n Standard wavelength for each filterName (A) assuming no atmosphere\n atmLambda: numpy float array\n Standard atmosphere wavelength array (A)\n atmStdTrans: numpy float array\n Standard atmosphere transmission array\n lut: Look-up table recarray\n lut['I0']: I0 LUT (multi-dimensional)\n lut['I1']: I1 LUT (multi-dimensional)\n lutDeriv: Derivative recarray\n lutDeriv['D_PMB']: I0 PMB derivative\n lutDeriv['D_PWV']: I0 PWV derivative\n lutDeriv['D_O3']: I0 O3 derivative\n lutDeriv['D_LNTAU']: I0 log(tau) derivative\n lutDeriv['D_ALPHA']: I0 alpha derivative\n lutDeriv['D_SECZENITH']: I0 sec(zenith) derivative\n lutDeriv['D_PMB_I1']: I1 PMB derivative\n lutDeriv['D_PWV_I1']: I1 PWV derivative\n lutDeriv['D_O3_I1']: I1 O3 derivative\n lutDeriv['D_LNTAU_I1']: I1 log(tau) derivative\n lutDeriv['D_ALPHA_I1']: I1 alpha derivative\n lutDeriv['D_SECZENITH_I1']: I0 sec(zenith) derivative\n \"\"\"\n\n if not self._setThroughput:\n raise ValueError(\"Must set the throughput before running makeLUT\")\n\n if self.runModtran:\n # need to build the table\n self.atmosphereTable.generateTable()\n else:\n # load from data\n self.atmosphereTable.loadTable()\n\n # and grab from the table\n self.atmLambda = self.atmosphereTable.atmLambda\n self.atmStdTrans = self.atmosphereTable.atmStdTrans\n\n self.pmbElevation = self.atmosphereTable.pmbElevation\n\n self.pmb = self.atmosphereTable.pmb\n self.pmbDelta = self.atmosphereTable.pmbDelta\n pmbPlus = np.append(self.pmb, self.pmb[-1] + self.pmbDelta)\n\n self.pwv = self.atmosphereTable.pwv\n self.pwvDelta = self.atmosphereTable.pwvDelta\n pwvPlus = np.append(self.pwv, self.pwv[-1] + self.pwvDelta)\n\n self.o3 = self.atmosphereTable.o3\n self.o3Delta = self.atmosphereTable.o3Delta\n o3Plus = np.append(self.o3, self.o3[-1] + self.o3Delta)\n\n self.lnTau = self.atmosphereTable.lnTau\n self.lnTauDelta = self.atmosphereTable.lnTauDelta\n self.tau = np.exp(self.lnTau)\n lnTauPlus = np.append(self.lnTau, self.lnTau[-1] + self.lnTauDelta)\n tauPlus = np.exp(lnTauPlus)\n\n self.alpha = self.atmosphereTable.alpha\n self.alphaDelta = self.atmosphereTable.alphaDelta\n alphaPlus = np.append(self.alpha, self.alpha[-1] + self.alphaDelta)\n\n self.secZenith = self.atmosphereTable.secZenith\n self.secZenithDelta = self.atmosphereTable.secZenithDelta\n self.zenith = np.arccos(1./self.secZenith)*180./np.pi\n secZenithPlus = np.append(self.secZenith, self.secZenith[-1] + self.secZenithDelta)\n zenithPlus = np.arccos(1./secZenithPlus)*180./np.pi\n\n # and compute the proper airmass...\n self.airmass = self.secZenith - 0.0018167*(self.secZenith-1.0) - 0.002875*(self.secZenith-1.0)**2.0 - 0.0008083*(self.secZenith-1.0)**3.0\n airmassPlus = secZenithPlus - 0.0018167*(secZenithPlus-1.0) - 0.002875*(secZenithPlus-1.0)**2.0 - 0.0008083*(secZenithPlus-1.0)**3.0\n\n pwvAtmTable = self.atmosphereTable.pwvAtmTable\n o3AtmTable = self.atmosphereTable.o3AtmTable\n o2AtmTable = self.atmosphereTable.o2AtmTable\n rayleighAtmTable = self.atmosphereTable.rayleighAtmTable\n\n # get the filters over the same lambda ranges...\n self.fgcmLog.info(\"\\nInterpolating filters...\")\n self.throughputs = []\n for i in xrange(len(self.filterNames)):\n inLam = self.inThroughputs[i]['LAMBDA']\n\n tput = np.zeros(self.atmLambda.size, dtype=[('LAMBDA','f4'),\n ('THROUGHPUT_AVG','f4'),\n ('THROUGHPUT_CCD','f4',self.nCCD)])\n tput['LAMBDA'][:] = self.atmLambda\n\n for ccdIndex in xrange(self.nCCD):\n ifunc = interpolate.interp1d(inLam, self.inThroughputs[i]['THROUGHPUT_CCD'][:,ccdIndex])\n tput['THROUGHPUT_CCD'][:,ccdIndex] = np.clip(ifunc(self.atmLambda),\n 0.0,\n 1e100)\n ifunc = interpolate.interp1d(inLam, self.inThroughputs[i]['THROUGHPUT_AVG'])\n tput['THROUGHPUT_AVG'][:] = np.clip(ifunc(self.atmLambda), 0.0, 1e100)\n\n self.throughputs.append(tput)\n\n # and now we can get the standard atmosphere and lambda_b\n self.fgcmLog.info(\"Computing lambdaB\")\n self.lambdaB = np.zeros(len(self.filterNames))\n for i in xrange(len(self.filterNames)):\n num = integrate.simps(self.atmLambda * self.throughputs[i]['THROUGHPUT_AVG'] / self.atmLambda, self.atmLambda)\n denom = integrate.simps(self.throughputs[i]['THROUGHPUT_AVG'] / self.atmLambda, self.atmLambda)\n self.lambdaB[i] = num / denom\n self.fgcmLog.info(\"Filter: %s, lambdaB = %.3f\" % (self.filterNames[i], self.lambdaB[i]))\n\n self.fgcmLog.info(\"Computing lambdaStdFilter\")\n self.lambdaStdFilter = np.zeros(len(self.filterNames))\n for i in xrange(len(self.filterNames)):\n num = integrate.simps(self.atmLambda * self.throughputs[i]['THROUGHPUT_AVG'] * self.atmStdTrans / self.atmLambda, self.atmLambda)\n denom = integrate.simps(self.throughputs[i]['THROUGHPUT_AVG'] * self.atmStdTrans / self.atmLambda, self.atmLambda)\n self.lambdaStdFilter[i] = num / denom\n self.fgcmLog.info(\"Filter: %s, lambdaStdFilter = %.3f\" % (self.filterNames[i],self.lambdaStdFilter[i]))\n\n # now compute lambdaStd based on the desired standards...\n self.fgcmLog.info(\"Calculating lambdaStd\")\n self.lambdaStd = np.zeros(len(self.filterNames))\n\n for i, filterName in enumerate(self.filterNames):\n ind = self.filterNames.index(self.stdFilterNames[i])\n #ind, = np.where(self.filterNames == self.stdFilterNames[i])\n #self.lambdaStd[i] = self.lambdaStdFilter[ind[0]]\n self.lambdaStd[i] = self.lambdaStdFilter[ind]\n self.fgcmLog.info(\"Filter: %s (from %s) lambdaStd = %.3f\" %\n (filterName, self.stdFilterNames[i], self.lambdaStd[i]))\n\n self.fgcmLog.info(\"Computing I0Std/I1Std\")\n self.I0Std = np.zeros(len(self.filterNames))\n self.I1Std = np.zeros(len(self.filterNames))\n\n for i in xrange(len(self.filterNames)):\n self.I0Std[i] = integrate.simps(self.throughputs[i]['THROUGHPUT_AVG'] * self.atmStdTrans / self.atmLambda, self.atmLambda)\n self.I1Std[i] = integrate.simps(self.throughputs[i]['THROUGHPUT_AVG'] * self.atmStdTrans * (self.atmLambda - self.lambdaStd[i]) / self.atmLambda, self.atmLambda)\n\n self.I10Std = self.I1Std / self.I0Std\n\n #################################\n ## Make the I0/I1 LUT\n #################################\n\n self.fgcmLog.info(\"Building look-up table...\")\n lutPlus = np.zeros((len(self.filterNames),\n pwvPlus.size,\n o3Plus.size,\n tauPlus.size,\n alphaPlus.size,\n zenithPlus.size,\n self.nCCDStep),\n dtype=[('I0','f4'),\n ('I1','f4')])\n\n # pre-compute pmb factors\n pmbMolecularScattering = np.exp(-(pmbPlus - self.pmbElevation)/self.pmbElevation)\n pmbMolecularAbsorption = pmbMolecularScattering ** 0.6\n pmbFactorPlus = pmbMolecularScattering * pmbMolecularAbsorption\n self.pmbFactor = pmbFactorPlus[:-1]\n\n # this set of nexted for loops could probably be vectorized in some way\n for i in xrange(len(self.filterNames)):\n self.fgcmLog.info(\"Working on filter %s\" % (self.filterNames[i]))\n for j in xrange(pwvPlus.size):\n self.fgcmLog.info(\" and on pwv #%d\" % (j))\n for k in xrange(o3Plus.size):\n self.fgcmLog.info(\" and on o3 #%d\" % (k))\n for m in xrange(tauPlus.size):\n for n in xrange(alphaPlus.size):\n for o in xrange(zenithPlus.size):\n aerosolTauLambda = np.exp(-1.0*tauPlus[m]*airmassPlus[o]*(self.atmLambda/self.lambdaNorm)**(-alphaPlus[n]))\n for p in xrange(self.nCCDStep):\n if (p == self.nCCD):\n Sb = self.throughputs[i]['THROUGHPUT_AVG'] * o2AtmTable[o,:] * rayleighAtmTable[o,:] * pwvAtmTable[j,o,:] * o3AtmTable[k,o,:] * aerosolTauLambda\n else:\n Sb = self.throughputs[i]['THROUGHPUT_CCD'][:,p] * o2AtmTable[o,:] * rayleighAtmTable[o,:] * pwvAtmTable[j,o,:] * o3AtmTable[k,o,:] * aerosolTauLambda\n\n lutPlus['I0'][i,j,k,m,n,o,p] = integrate.simps(Sb / self.atmLambda, self.atmLambda)\n lutPlus['I1'][i,j,k,m,n,o,p] = integrate.simps(Sb * (self.atmLambda - self.lambdaStd[i]) / self.atmLambda, self.atmLambda)\n\n # and create the LUT (not plus)\n self.lut = np.zeros((len(self.filterNames),\n self.pwv.size,\n self.o3.size,\n self.tau.size,\n self.alpha.size,\n self.zenith.size,\n self.nCCDStep),\n dtype=lutPlus.dtype)\n\n temp = np.delete(lutPlus['I0'], self.pwv.size, axis=1)\n temp = np.delete(temp, self.o3.size, axis=2)\n temp = np.delete(temp, self.tau.size, axis=3)\n temp = np.delete(temp, self.alpha.size, axis=4)\n temp = np.delete(temp, self.zenith.size, axis=5)\n\n self.lut['I0'] = temp\n\n temp = np.delete(lutPlus['I1'], self.pwv.size, axis=1)\n temp = np.delete(temp, self.o3.size, axis=2)\n temp = np.delete(temp, self.tau.size, axis=3)\n temp = np.delete(temp, self.alpha.size, axis=4)\n temp = np.delete(temp, self.zenith.size, axis=5)\n\n self.lut['I1'] = temp\n\n #################################\n ## Make the I0/I1 derivative LUTs\n #################################\n\n # This is *not* done plus-size\n\n self.lutDeriv = np.zeros((len(self.filterNames),\n self.pwv.size,\n self.o3.size,\n self.tau.size,\n self.alpha.size,\n self.zenith.size,\n self.nCCDStep),\n dtype=[('D_PMB','f4'),\n ('D_PWV','f4'),\n ('D_O3','f4'),\n ('D_LNTAU','f4'),\n ('D_ALPHA','f4'),\n ('D_SECZENITH','f4'),\n ('D_PMB_I1','f4'),\n ('D_PWV_I1','f4'),\n ('D_O3_I1','f4'),\n ('D_LNTAU_I1','f4'),\n ('D_ALPHA_I1','f4'),\n ('D_SECZENITH_I1','f4')])\n\n self.fgcmLog.info(\"Computing derivatives...\")\n\n ## FIXME: figure out PMB derivative?\n\n for i in xrange(len(self.filterNames)):\n self.fgcmLog.info(\"Working on filter %s\" % (self.filterNames[i]))\n for j in xrange(self.pwv.size):\n for k in xrange(self.o3.size):\n for m in xrange(self.tau.size):\n for n in xrange(self.alpha.size):\n for o in xrange(self.zenith.size):\n for p in xrange(self.nCCDStep):\n self.lutDeriv['D_PWV'][i,j,k,m,n,o,p] = (\n ((lutPlus['I0'][i,j+1,k,m,n,o,p] -\n lutPlus['I0'][i,j,k,m,n,o,p]) /\n self.pwvDelta)\n )\n self.lutDeriv['D_PWV_I1'][i,j,k,m,n,o,p] = (\n ((lutPlus['I1'][i,j+1,k,m,n,o,p] -\n lutPlus['I1'][i,j,k,m,n,o,p]) /\n self.pwvDelta)\n )\n self.lutDeriv['D_O3'][i,j,k,m,n,o,p] = (\n ((lutPlus['I0'][i,j,k+1,m,n,o,p] -\n lutPlus['I0'][i,j,k,m,n,o,p]) /\n self.o3Delta)\n )\n self.lutDeriv['D_O3_I1'][i,j,k,m,n,o,p] = (\n ((lutPlus['I1'][i,j,k+1,m,n,o,p] -\n lutPlus['I1'][i,j,k,m,n,o,p]) /\n self.o3Delta)\n )\n self.lutDeriv['D_LNTAU'][i,j,k,m,n,o,p] = (\n ((lutPlus['I0'][i,j,k,m+1,n,o,p] -\n lutPlus['I0'][i,j,k,m,n,o,p]) /\n self.lnTauDelta)\n )\n self.lutDeriv['D_LNTAU_I1'][i,j,k,m,n,o,p] = (\n ((lutPlus['I1'][i,j,k,m+1,n,o,p] -\n lutPlus['I1'][i,j,k,m,n,o,p]) /\n self.lnTauDelta)\n )\n self.lutDeriv['D_ALPHA'][i,j,k,m,n,o,p] = (\n ((lutPlus['I0'][i,j,k,m,n+1,o,p] -\n lutPlus['I0'][i,j,k,m,n,o,p]) /\n self.alphaDelta)\n )\n self.lutDeriv['D_ALPHA_I1'][i,j,k,m,n,o,p] = (\n ((lutPlus['I1'][i,j,k,m,n+1,o,p] -\n lutPlus['I1'][i,j,k,m,n,o,p]) /\n self.alphaDelta)\n )\n self.lutDeriv['D_SECZENITH'][i,j,k,m,n,o,p] = (\n ((lutPlus['I0'][i,j,k,m,n,o+1,p] -\n lutPlus['I0'][i,j,k,m,n,o,p]) /\n self.secZenithDelta)\n )\n self.lutDeriv['D_SECZENITH_I1'][i,j,k,m,n,o,p] = (\n ((lutPlus['I1'][i,j,k,m,n,o+1,p] -\n lutPlus['I1'][i,j,k,m,n,o,p]) /\n self.secZenithDelta)\n )\n\n\n if (self.makeSeds):\n # and the SED LUT\n self.fgcmLog.info(\"Building SED LUT\")\n\n # arbitrary. Configure? Fit? Seems stable...\n delta = 600.0\n\n # blah on fits here...\n import fitsio\n\n # how many extensions?\n fits=fitsio.FITS(self.stellarTemplateFile)\n fits.update_hdu_list()\n extNames = []\n for hdu in fits.hdu_list:\n extName = hdu.get_extname()\n if ('TEMPLATE_' in extName):\n extNames.append(extName)\n\n # set up SED look-up table\n nTemplates = len(extNames)\n\n self.sedLUT = np.zeros(nTemplates, dtype=[('TEMPLATE','i4'),\n ('SYNTHMAG','f4',len(self.filterNames)),\n ('FPRIME','f4',len(self.filterNames))])\n\n # now do it...looping is no problem since there aren't that many.\n\n for i in xrange(nTemplates):\n data = fits[extNames[i]].read()\n\n templateLambda = data['LAMBDA']\n templateFLambda = data['FLUX']\n templateFnu = templateFLambda * templateLambda * templateLambda\n\n parts=extNames[i].split('_')\n self.sedLUT['TEMPLATE'][i] = int(parts[1])\n\n # interpolate to atmLambda\n intFunc = interpolate.interp1d(templateLambda, templateFnu)\n fnu = np.zeros(self.atmLambda.size)\n good,=np.where((self.atmLambda >= templateLambda[0]) &\n (self.atmLambda <= templateLambda[-1]))\n fnu[good] = intFunc(self.atmLambda[good])\n\n # out of range, let it hit the limit\n lo,=np.where(self.atmLambda < templateLambda[0])\n if (lo.size > 0):\n fnu[lo] = intFunc(self.atmLambda[good[0]])\n hi,=np.where(self.atmLambda > templateLambda[-1])\n if (hi.size > 0):\n fnu[hi] = intFunc(self.atmLambda[good[-1]])\n\n # compute synthetic mags\n for j in xrange(len(self.filterNames)):\n num = integrate.simps(fnu * self.throughputs[j]['THROUGHPUT_AVG'][:] * self.atmStdTrans / self.atmLambda, self.atmLambda)\n denom = integrate.simps(self.throughputs[j]['THROUGHPUT_AVG'][:] * self.atmStdTrans / self.atmLambda, self.atmLambda)\n\n self.sedLUT['SYNTHMAG'][i,j] = -2.5*np.log10(num/denom)\n\n # and compute fprimes\n for j in xrange(len(self.filterNames)):\n use,=np.where((templateLambda >= (self.lambdaStd[j]-delta)) &\n (templateLambda <= (self.lambdaStd[j]+delta)))\n\n fit = np.polyfit(templateLambda[use] - self.lambdaStd[j],\n templateFnu[use],\n 1)\n\n self.sedLUT['FPRIME'][i,j] = fit[0] / fit[1]\n\n fits.close()\n\n def saveLUT(self,lutFile,clobber=False):\n \"\"\"\n \"\"\"\n\n import fitsio\n\n if (os.path.isfile(lutFile) and not clobber):\n self.fgcmLog.info(\"lutFile %s already exists, and clobber is False.\" % (lutFile))\n return\n\n self.fgcmLog.info(\"Saving LUT to %s\" % (lutFile))\n\n # first, save the LUT itself\n fitsio.write(lutFile,self.lut.flatten(),extname='LUT',clobber=True)\n\n # and now save the indices\n maxFilterLen = len(max(self.filterNames, key=len))\n\n indexVals = np.zeros(1,dtype=[('FILTERNAMES', 'a%d' % (maxFilterLen), len(self.filterNames)),\n ('STDFILTERNAMES', 'a%d' % (maxFilterLen), len(self.stdFilterNames)),\n ('PMB','f8',self.pmb.size),\n ('PMBFACTOR','f8',self.pmb.size),\n ('PMBELEVATION','f8'),\n ('PWV','f8',self.pwv.size),\n ('O3','f8',self.o3.size),\n ('TAU','f8',self.tau.size),\n ('LAMBDANORM','f8'),\n ('ALPHA','f8',self.alpha.size),\n ('ZENITH','f8',self.zenith.size),\n ('NCCD','i4')])\n indexVals['FILTERNAMES'] = self.filterNames\n indexVals['STDFILTERNAMES'] = self.stdFilterNames\n indexVals['PMB'] = self.pmb\n indexVals['PMBFACTOR'] = self.pmbFactor\n indexVals['PMBELEVATION'] = self.pmbElevation\n indexVals['PWV'] = self.pwv\n indexVals['O3'] = self.o3\n indexVals['TAU'] = self.tau\n indexVals['LAMBDANORM'] = self.lambdaNorm\n indexVals['ALPHA'] = self.alpha\n indexVals['ZENITH'] = self.zenith\n indexVals['NCCD'] = self.nCCD\n\n fitsio.write(lutFile,indexVals,extname='INDEX')\n\n # and the standard values\n stdVals = np.zeros(1,dtype=[('PMBSTD','f8'),\n ('PWVSTD','f8'),\n ('O3STD','f8'),\n ('TAUSTD','f8'),\n ('ALPHASTD','f8'),\n ('ZENITHSTD','f8'),\n ('LAMBDARANGE','f8',2),\n ('LAMBDASTEP','f8'),\n ('LAMBDASTD','f8',len(self.filterNames)),\n ('LAMBDASTDFILTER','f8',len(self.filterNames)),\n ('LAMBDANORM','f8'),\n ('I0STD','f8',len(self.filterNames)),\n ('I1STD','f8',len(self.filterNames)),\n ('I10STD','f8',len(self.filterNames)),\n ('LAMBDAB','f8',len(self.filterNames)),\n ('ATMLAMBDA','f8',self.atmLambda.size),\n ('ATMSTDTRANS','f8',self.atmStdTrans.size)])\n stdVals['PMBSTD'] = self.pmbStd\n stdVals['PWVSTD'] = self.pwvStd\n stdVals['O3STD'] = self.o3Std\n stdVals['TAUSTD'] = self.tauStd\n stdVals['ALPHASTD'] = self.alphaStd\n stdVals['ZENITHSTD'] = self.zenithStd\n stdVals['LAMBDARANGE'] = self.lambdaRange\n stdVals['LAMBDASTEP'] = self.lambdaStep\n stdVals['LAMBDASTD'][:] = self.lambdaStd\n stdVals['LAMBDASTDFILTER'][:] = self.lambdaStdFilter\n stdVals['LAMBDANORM'][:] = self.lambdaNorm\n stdVals['I0STD'][:] = self.I0Std\n stdVals['I1STD'][:] = self.I1Std\n stdVals['I10STD'][:] = self.I10Std\n stdVals['LAMBDAB'][:] = self.lambdaB\n stdVals['ATMLAMBDA'][:] = self.atmLambda\n stdVals['ATMSTDTRANS'][:] = self.atmStdTrans\n\n fitsio.write(lutFile,stdVals,extname='STD')\n\n # and the derivatives\n self.fgcmLog.info(\"Writing Derivative LUT\")\n fitsio.write(lutFile,self.lutDeriv.flatten(),extname='DERIV')\n\n # and the SED LUT\n if (self.makeSeds):\n self.fgcmLog.info(\"Writing SED LUT\")\n fitsio.write(lutFile,self.sedLUT,extname='SED')\n\n\nclass FgcmLUT(object):\n \"\"\"\n Class to hold the main throughput look-up table and apply it. If loading from\n a fits table, initialize with initFromFits(lutFile).\n\n parameters\n ----------\n indexVals: numpy recarray\n With LUT index values\n lutFlat: numpy recarray\n Flattened I0/I1 arrays\n lutDerivFlat: numpy recarray\n Flattened I0/I1 derivative arrays\n stdVals: numpy recarray\n Standard atmosphere and associated values\n sedLUT: bool, default=False\n Use SED look-up table instead of colors (experimental).\n filterToBand: dict, optional\n Dictionary to map filterNames to bands if not unique\n \"\"\"\n\n def __init__(self, indexVals, lutFlat, lutDerivFlat, stdVals, sedLUT=None, filterToBand=None):\n\n #self.filterNames = indexVals['FILTERNAMES'][0]\n #self.stdFilterNames = indexVals['STDFILTERNAMES'][0]\n self.filterNames = [n.decode('utf-8') for n in indexVals['FILTERNAMES'][0]]\n self.stdFilterNames = [n.decode('utf-8') for n in indexVals['STDFILTERNAMES'][0]]\n self.pmb = indexVals['PMB'][0]\n self.pmbFactor = indexVals['PMBFACTOR'][0]\n self.pmbDelta = self.pmb[1] - self.pmb[0]\n self.pmbElevation = indexVals['PMBELEVATION'][0]\n self.lambdaNorm = indexVals['LAMBDANORM'][0]\n\n self.pwv = indexVals['PWV'][0]\n self.pwvDelta = self.pwv[1] - self.pwv[0]\n self.o3 = indexVals['O3'][0]\n self.o3Delta = self.o3[1] - self.o3[0]\n self.tau = indexVals['TAU'][0]\n self.lnTau = np.log(self.tau)\n self.lnTauDelta = self.lnTau[1] - self.lnTau[0]\n self.alpha = indexVals['ALPHA'][0]\n self.alphaDelta = self.alpha[1] - self.alpha[0]\n self.zenith = indexVals['ZENITH'][0]\n self.secZenith = 1./np.cos(self.zenith*np.pi/180.)\n self.secZenithDelta = self.secZenith[1] - self.secZenith[0]\n self.nCCD = indexVals['NCCD'][0]\n self.nCCDStep = self.nCCD+1\n\n # make shared memory arrays for LUTs\n sizeTuple = (len(self.filterNames),self.pwv.size,self.o3.size,\n self.tau.size,self.alpha.size,self.zenith.size,self.nCCDStep)\n\n self.lutI0Handle = snmm.createArray(sizeTuple,dtype='f4')\n snmm.getArray(self.lutI0Handle)[:,:,:,:,:,:,:] = lutFlat['I0'].reshape(sizeTuple)\n\n self.lutI1Handle = snmm.createArray(sizeTuple,dtype='f4')\n snmm.getArray(self.lutI1Handle)[:,:,:,:,:,:,:] = lutFlat['I1'].reshape(sizeTuple)\n\n # and read in the derivatives\n\n # create shared memory\n self.lutDPWVHandle = snmm.createArray(sizeTuple,dtype='f4')\n self.lutDO3Handle = snmm.createArray(sizeTuple,dtype='f4')\n self.lutDLnTauHandle = snmm.createArray(sizeTuple,dtype='f4')\n self.lutDAlphaHandle = snmm.createArray(sizeTuple,dtype='f4')\n self.lutDSecZenithHandle = snmm.createArray(sizeTuple,dtype='f4')\n\n self.lutDPWVI1Handle = snmm.createArray(sizeTuple,dtype='f4')\n self.lutDO3I1Handle = snmm.createArray(sizeTuple,dtype='f4')\n self.lutDLnTauI1Handle = snmm.createArray(sizeTuple,dtype='f4')\n self.lutDAlphaI1Handle = snmm.createArray(sizeTuple,dtype='f4')\n self.lutDSecZenithI1Handle = snmm.createArray(sizeTuple,dtype='f4')\n\n snmm.getArray(self.lutDPWVHandle)[:,:,:,:,:,:,:] = lutDerivFlat['D_PWV'].reshape(sizeTuple)\n snmm.getArray(self.lutDO3Handle)[:,:,:,:,:,:,:] = lutDerivFlat['D_O3'].reshape(sizeTuple)\n snmm.getArray(self.lutDLnTauHandle)[:,:,:,:,:,:,:] = lutDerivFlat['D_LNTAU'].reshape(sizeTuple)\n snmm.getArray(self.lutDAlphaHandle)[:,:,:,:,:,:,:] = lutDerivFlat['D_ALPHA'].reshape(sizeTuple)\n snmm.getArray(self.lutDSecZenithHandle)[:,:,:,:,:,:,:] = lutDerivFlat['D_SECZENITH'].reshape(sizeTuple)\n\n self.hasI1Derivatives = False\n try:\n snmm.getArray(self.lutDPWVI1Handle)[:,:,:,:,:,:,:] = lutDerivFlat['D_PWV_I1'].reshape(sizeTuple)\n snmm.getArray(self.lutDO3I1Handle)[:,:,:,:,:,:,:] = lutDerivFlat['D_O3_I1'].reshape(sizeTuple)\n snmm.getArray(self.lutDLnTauI1Handle)[:,:,:,:,:,:,:] = lutDerivFlat['D_LNTAU_I1'].reshape(sizeTuple)\n snmm.getArray(self.lutDAlphaI1Handle)[:,:,:,:,:,:,:] = lutDerivFlat['D_ALPHA_I1'].reshape(sizeTuple)\n snmm.getArray(self.lutDSecZenithI1Handle)[:,:,:,:,:,:,:] = lutDerivFlat['D_SECZENITH_I1'].reshape(sizeTuple)\n self.hasI1Derivatives = True\n except:\n # just fill with zeros\n pass\n #print(\"No I1 derivative information\")\n\n # get the standard values\n\n self.pmbStd = stdVals['PMBSTD'][0]\n self.pwvStd = stdVals['PWVSTD'][0]\n self.o3Std = stdVals['O3STD'][0]\n self.tauStd = stdVals['TAUSTD'][0]\n self.lnTauStd = np.log(self.tauStd)\n self.alphaStd = stdVals['ALPHASTD'][0]\n self.zenithStd = stdVals['ZENITHSTD'][0]\n self.secZenithStd = 1./np.cos(np.radians(self.zenithStd))\n self.lambdaRange = stdVals['LAMBDARANGE'][0]\n self.lambdaStep = stdVals['LAMBDASTEP'][0]\n self.lambdaStd = stdVals['LAMBDASTD'][0]\n self.lambdaStdFilter = stdVals['LAMBDASTDFILTER'][0]\n self.I0Std = stdVals['I0STD'][0]\n self.I1Std = stdVals['I1STD'][0]\n self.I10Std = stdVals['I10STD'][0]\n self.lambdaB = stdVals['LAMBDAB'][0]\n self.atmLambda = stdVals['ATMLAMBDA'][0]\n self.atmStdTrans = stdVals['ATMSTDTRANS'][0]\n\n self.magConstant = 2.5/np.log(10)\n\n if (filterToBand is None):\n # just set up a 1-1 mapping\n self.filterToBand = {}\n for filterName in self.filterNames:\n self.filterToBand[filterName] = filterName\n else:\n self.filterToBand = filterToBand\n\n # finally, read in the sedLUT\n ## this is experimental\n self.hasSedLUT = False\n if (sedLUT is not None):\n self.sedLUT = sedLUT\n\n self.hasSedLUT = True\n\n ## FIXME: make general\n self.sedColor = self.sedLUT['SYNTHMAG'][:,0] - self.sedLUT['SYNTHMAG'][:,2]\n st = np.argsort(self.sedColor)\n\n self.sedColor = self.sedColor[st]\n self.sedLUT = self.sedLUT[st]\n\n @classmethod\n def initFromFits(cls, lutFile, filterToBand=None):\n \"\"\"\n Initials FgcmLUT using fits file.\n\n parameters\n ----------\n lutFile: string\n Name of the LUT file\n \"\"\"\n\n import fitsio\n\n lutFlat = fitsio.read(lutFile, ext='LUT')\n lutDerivFlat = fitsio.read(lutFile, ext='DERIV')\n indexVals = fitsio.read(lutFile, ext='INDEX')\n stdVals = fitsio.read(lutFile, ext='STD')\n\n try:\n sedLUT = fitsio.read(lutFile, ext='SED')\n except:\n sedLUT = None\n\n return cls(indexVals, lutFlat, lutDerivFlat, stdVals,\n sedLUT=sedLUT, filterToBand=filterToBand)\n\n\n def getIndices(self, filterIndex, pwv, o3, lnTau, alpha, secZenith, ccdIndex, pmb):\n \"\"\"\n Compute indices in the look-up table. These are in regular (non-normalized) units.\n\n parameters\n ----------\n filterIndex: int array\n Array with values pointing to the filterName index\n pwv: float array\n o3: float array\n lnTau: float array\n alpha: float array\n secZenith: float array\n ccdIndex: int array\n Array with values point to the ccd index\n pmb: float array\n \"\"\"\n\n return (filterIndex,\n np.clip(((pwv - self.pwv[0])/self.pwvDelta).astype(np.int32), 0,\n self.pwv.size-1),\n np.clip(((o3 - self.o3[0])/self.o3Delta).astype(np.int32), 0,\n self.o3.size-1),\n np.clip(((lnTau - self.lnTau[0])/self.lnTauDelta).astype(np.int32), 0,\n self.lnTau.size-1),\n np.clip(((alpha - self.alpha[0])/self.alphaDelta).astype(np.int32), 0,\n self.alpha.size-1),\n np.clip(((secZenith - self.secZenith[0])/self.secZenithDelta).astype(np.int32), 0,\n self.secZenith.size-1),\n ccdIndex,\n (np.exp(-(pmb - self.pmbElevation)/self.pmbElevation)) ** 1.6)\n\n\n def computeI0(self, pwv, o3, lnTau, alpha, secZenith, pmb, indices):\n \"\"\"\n Compute I0 from the look-up table.\n\n parameters\n ----------\n pwv: float array\n o3: float array\n lnTau: float array\n alpha: float array\n secZenith: float array\n pmb: float array\n indices: tuple, from getIndices()\n \"\"\"\n\n # do a simple linear interpolation\n dPWV = pwv - (self.pwv[0] + indices[1] * self.pwvDelta)\n dO3 = o3 - (self.o3[0] + indices[2] * self.o3Delta)\n dlnTau = lnTau - (self.lnTau[0] + indices[3] * self.lnTauDelta)\n dAlpha = alpha - (self.alpha[0] + indices[4] * self.alphaDelta)\n dSecZenith = secZenith - (self.secZenith[0] + indices[5] * self.secZenithDelta)\n\n indicesSecZenithPlus = np.array(indices[:-1])\n indicesSecZenithPlus[5] += 1\n indicesPWVPlus = np.array(indices[:-1])\n indicesPWVPlus[1] = np.clip(indicesPWVPlus[1] + 1, 0, self.pwv.size-1)\n\n # also include cross-terms for tau and pwv\n # and a second-derivative term for pwv\n # note that indices[-1] is the PMB vactor\n\n return indices[-1]*(snmm.getArray(self.lutI0Handle)[indices[:-1]] +\n dPWV * snmm.getArray(self.lutDPWVHandle)[indices[:-1]] +\n dO3 * snmm.getArray(self.lutDO3Handle)[indices[:-1]] +\n dlnTau * snmm.getArray(self.lutDLnTauHandle)[indices[:-1]] +\n dAlpha * snmm.getArray(self.lutDAlphaHandle)[indices[:-1]] +\n dSecZenith * snmm.getArray(self.lutDSecZenithHandle)[indices[:-1]] +\n dlnTau * dSecZenith * (snmm.getArray(self.lutDLnTauHandle)[tuple(indicesSecZenithPlus)] -\n snmm.getArray(self.lutDLnTauHandle)[indices[:-1]])/self.secZenithDelta +\n dPWV * dSecZenith * (snmm.getArray(self.lutDPWVHandle)[tuple(indicesSecZenithPlus)] -\n snmm.getArray(self.lutDPWVHandle)[indices[:-1]])/self.secZenithDelta +\n dPWV * (dPWV - self.pwvDelta) * (snmm.getArray(self.lutDPWVHandle)[tuple(indicesPWVPlus)] -\n snmm.getArray(self.lutDPWVHandle)[indices[:-1]]))\n\n\n def computeI1(self, pwv, o3, lnTau, alpha, secZenith, pmb, indices):\n \"\"\"\n Compute I1 from the look-up table.\n\n parameters\n ----------\n pwv: float array\n o3: float array\n lnTau: float array\n alpha: float array\n secZenith: float array\n pmb: float array\n indices: tuple, from getIndices()\n \"\"\"\n\n # do a simple linear interpolation\n dPWV = pwv - (self.pwv[0] + indices[1] * self.pwvDelta)\n dO3 = o3 - (self.o3[0] + indices[2] * self.o3Delta)\n dlnTau = lnTau - (self.lnTau[0] + indices[3] * self.lnTauDelta)\n dAlpha = alpha - (self.alpha[0] + indices[4] * self.alphaDelta)\n dSecZenith = secZenith - (self.secZenith[0] + indices[5] * self.secZenithDelta)\n\n indicesSecZenithPlus = np.array(indices[:-1])\n indicesSecZenithPlus[5] += 1\n indicesPWVPlus = np.array(indices[:-1])\n indicesPWVPlus[1] = np.clip(indicesPWVPlus[1] + 1, 0, self.pwv.size-1)\n\n # also include a cross-term for tau\n # note that indices[-1] is the PMB vactor\n\n return indices[-1]*(snmm.getArray(self.lutI1Handle)[indices[:-1]] +\n dPWV * snmm.getArray(self.lutDPWVI1Handle)[indices[:-1]] +\n dO3 * snmm.getArray(self.lutDO3I1Handle)[indices[:-1]] +\n dlnTau * snmm.getArray(self.lutDLnTauI1Handle)[indices[:-1]] +\n dAlpha * snmm.getArray(self.lutDAlphaI1Handle)[indices[:-1]] +\n dSecZenith * snmm.getArray(self.lutDSecZenithI1Handle)[indices[:-1]] +\n dlnTau * dSecZenith * (snmm.getArray(self.lutDLnTauI1Handle)[tuple(indicesSecZenithPlus)] -\n snmm.getArray(self.lutDLnTauI1Handle)[indices[:-1]])/self.secZenithDelta +\n dPWV * dSecZenith * (snmm.getArray(self.lutDPWVI1Handle)[tuple(indicesSecZenithPlus)] -\n snmm.getArray(self.lutDPWVI1Handle)[indices[:-1]])/self.secZenithDelta +\n dPWV * (dPWV - self.pwvDelta) * (snmm.getArray(self.lutDPWVI1Handle)[tuple(indicesPWVPlus)] -\n snmm.getArray(self.lutDPWVI1Handle)[indices[:-1]]))\n\n def computeI1Old(self, indices):\n \"\"\"\n Unused\n \"\"\"\n return indices[-1] * snmm.getArray(self.lutI1Handle)[indices[:-1]]\n\n def computeLogDerivatives(self, indices, I0):\n \"\"\"\n Compute log derivatives. Used in FgcmChisq.\n\n parameters\n ----------\n indices: tuple, from getIndices()\n I0: float array, from computeI0()\n \"\"\"\n\n # dL(i,j|p) = d/dp(2.5*log10(LUT(i,j|p)))\n # = 1.086*(LUT'(i,j|p)/LUT(i,j|p))\n return (self.magConstant*snmm.getArray(self.lutDPWVHandle)[indices[:-1]] / I0,\n self.magConstant*snmm.getArray(self.lutDO3Handle)[indices[:-1]] / I0,\n self.magConstant*snmm.getArray(self.lutDLnTauHandle)[indices[:-1]] / (I0),\n self.magConstant*snmm.getArray(self.lutDAlphaHandle)[indices[:-1]] / I0)\n\n\n def computeLogDerivativesI1(self, indices, I0, I10, sedSlope):\n \"\"\"\n Compute log derivatives for I1. Used in FgcmChisq.\n\n parameters\n ----------\n indices: tuple, from getIndices()\n I0: float array, from computeI0()\n I10: float array, from computeI1()/computeI0()\n sedSlope: float array, fnuprime\n \"\"\"\n\n # dL(i,j|p) += d/dp(2.5*log10((1+F'*I10^obs) / (1+F'*I10^std)))\n # the std part cancels...\n # = 1.086*(F'/(1+F'*I10)*((I0*LUT1' - I1*LUT0')/(I0^2))\n\n preFactor = (self.magConstant * (sedSlope / (1 + sedSlope*I10))) / I0**2.\n\n return (preFactor * (I0 * snmm.getArray(self.lutDPWVHandle)[indices[:-1]] -\n I10 * I0 * snmm.getArray(self.lutDPWVI1Handle)[indices[:-1]]),\n preFactor * (I0 * snmm.getArray(self.lutDO3Handle)[indices[:-1]] -\n I10 * I0 * snmm.getArray(self.lutDO3I1Handle)[indices[:-1]]),\n preFactor * (I0 * snmm.getArray(self.lutDLnTauHandle)[indices[:-1]] -\n I10 * I0 * snmm.getArray(self.lutDLnTauI1Handle)[indices[:-1]]),\n preFactor * (I0 * snmm.getArray(self.lutDAlphaHandle)[indices[:-1]] -\n I10 * I0 * snmm.getArray(self.lutDAlphaI1Handle)[indices[:-1]]))\n\n def computeSEDSlopes(self, objectSedColor):\n \"\"\"\n Compute SED slopes using the SED look-up table. Experimental.\n\n parameters\n ----------\n objectSedColor: float array\n Color used for SED look-up (typically g-i)\n \"\"\"\n\n indices = np.clip(np.searchsorted(self.sedColor, objectSedColor),0,self.sedColor.size-2)\n # right now, a straight matching to the nearest sedColor (g-i)\n # though I worry about this.\n # in fact, maybe the noise will make this not work? Or this is real?\n # but the noise in g-r is going to cause things to bounce around. Pout.\n\n return self.sedLUT['FPRIME'][indices,:]\n\n def computeStepUnits(self, stepUnitReference, stepGrain, meanNightDuration,\n meanWashIntervalDuration, fitBands, bands, nCampaignNights):\n \"\"\"\n Compute normalization factors for fit step units. Note that this might need\n to be tweaked.\n\n parameters\n ----------\n stepUnitReference: float\n How much should a typical step move things? 0.001 mag is default.\n stepGrain: float\n Additional fudge factor to apply to all steps.\n meanNightDuration: float\n Mean duration of a night (days).\n meanWashIntervalDuration: float\n Mean duration between washes (days).\n fitBands: string array\n Which bands are used for the fit?\n bands: string array\n What are all the bands?\n nCampaignNights: int\n Total number of nights in observing campaign to be calibrated.\n \"\"\"\n\n unitDict = {}\n\n # bigger unit, smaller step\n\n # compute tau units\n\n deltaMagLnTau = (2.5*np.log10(np.exp(-self.secZenithStd*np.exp(self.lnTauStd))) -\n 2.5*np.log10(np.exp(-self.secZenithStd*np.exp(self.lnTauStd+1.0))))\n\n unitDict['lnTauUnit'] = np.abs(deltaMagLnTau) / stepUnitReference / stepGrain\n unitDict['lnTauUnit'] /= 5.0\n\n # FIXME?\n unitDict['lnTauSlopeUnit'] = unitDict['lnTauUnit'] * meanNightDuration\n\n # look for first use of 'g' or 'r' band in filterToBand...\n # this is the reference filter for tau/alpha\n\n alphaFilterIndex = -1\n for i,filterName in enumerate(self.filterNames):\n if (self.filterToBand[filterName] == 'g' or\n self.filterToBand[filterName] == 'r'):\n alphaFilterIndex = i\n break\n\n if alphaFilterIndex == -1:\n # We don't have anything here...\n # Just set this to 1.0, since it's not sensitive?\n unitDict['alphaUnit'] = 1.0 / stepUnitReference / stepGrain\n else:\n deltaMagAlpha = (2.5*np.log10(np.exp(-self.secZenithStd*self.tauStd*(self.lambdaStd[alphaFilterIndex]/self.lambdaNorm)**self.alphaStd)) -\n 2.5*np.log10(np.exp(-self.secZenithStd*self.tauStd*(self.lambdaStd[alphaFilterIndex]/self.lambdaNorm)**(self.alphaStd+1.0))))\n unitDict['alphaUnit'] = np.abs(deltaMagAlpha) / stepUnitReference / stepGrain\n\n # and scale these by fraction of bands affected...\n alphaNAffectedBands = 0\n for filterName in self.filterNames:\n if ((self.filterToBand[filterName] == 'u' and\n 'u' in fitBands) or\n (self.filterToBand[filterName] == 'g' and\n 'g' in fitBands) or\n (self.filterToBand[filterName] == 'r' and\n 'r' in fitBands)):\n alphaNAffectedBands += 1\n\n unitDict['alphaUnit'] *= float(alphaNAffectedBands) / float(len(fitBands))\n\n # pwv units -- reference to z or y or Y\n pwvFilterIndex = -1\n for i,filterName in enumerate(self.filterNames):\n if (self.filterToBand[filterName] == 'z' or\n self.filterToBand[filterName] == 'y' or\n self.filterToBand[filterName] == 'Y'):\n pwvFilterIndex = i\n break\n\n if pwvFilterIndex == -1:\n unitDict['pwvUnit'] = 1.0 / stepUnitReference / stepGrain\n else:\n indicesStd = self.getIndices(pwvFilterIndex,self.pwvStd,self.o3Std,np.log(self.tauStd),self.alphaStd,self.secZenithStd,self.nCCD,self.pmbStd)\n i0Std = self.computeI0(self.pwvStd,self.o3Std,np.log(self.tauStd),self.alphaStd,self.secZenithStd,self.pmbStd,indicesStd)\n indicesPlus = self.getIndices(pwvFilterIndex,self.pwvStd+1.0,self.o3Std,np.log(self.tauStd),self.alphaStd,self.secZenithStd,self.nCCD,self.pmbStd)\n i0Plus = self.computeI0(self.pwvStd+1.0,self.o3Std,np.log(self.tauStd),self.alphaStd,self.secZenithStd,self.pmbStd,indicesPlus)\n deltaMagPWV = 2.5*np.log10(i0Std) - 2.5*np.log10(i0Plus)\n\n unitDict['pwvUnit'] = np.abs(deltaMagPWV) / stepUnitReference / stepGrain\n\n # scale by fraction of bands affected\n pwvNAffectedBands = 0\n for filterName in self.filterNames:\n if ((self.filterToBand[filterName] == 'z' and\n 'z' in fitBands) or\n (self.filterToBand[filterName] == 'y' and\n 'y' in fitBands) or\n (self.filterToBand[filterName] == 'Y' and\n 'Y' in fitBands)):\n pwvNAffectedBands += 1\n unitDict['pwvUnit'] *= float(pwvNAffectedBands) / float(len(fitBands))\n\n # PWV percent slope units\n unitDict['pwvPerSlopeUnit'] = unitDict['pwvUnit'] * meanNightDuration * self.pwvStd\n\n # PWV Global step units\n unitDict['pwvGlobalUnit'] = unitDict['pwvUnit'] * nCampaignNights\n\n # O3 units -- reference to r\n o3FilterIndex = -1\n for i,filterName in enumerate(self.filterNames):\n if (self.filterToBand[filterName] == 'u' or\n self.filterToBand[filterName] == 'r'):\n o3FilterIndex = i\n break\n\n if o3FilterIndex == -1:\n unitDict['o3Unit'] = 1.0 / stepUnitReference / stepGrain\n else:\n indicesStd = self.getIndices(o3FilterIndex,self.pwvStd,self.o3Std,np.log(self.tauStd),self.alphaStd,self.secZenithStd,self.nCCD,self.pmbStd)\n i0Std = self.computeI0(self.pwvStd,self.o3Std,np.log(self.tauStd),self.alphaStd,self.secZenithStd,self.pmbStd,indicesStd)\n indicesPlus = self.getIndices(o3FilterIndex,self.pwvStd,self.o3Std+1.0,np.log(self.tauStd),self.alphaStd,self.secZenithStd,self.nCCD,self.pmbStd)\n i0Plus = self.computeI0(self.pwvStd,self.o3Std+1.0,np.log(self.tauStd),self.alphaStd,self.secZenithStd,self.pmbStd,indicesPlus)\n deltaMagO3 = 2.5*np.log10(i0Std) - 2.5*np.log10(i0Plus)\n\n unitDict['o3Unit'] = np.abs(deltaMagO3) / stepUnitReference / stepGrain\n\n # scale by fraction of bands that are affected\n o3NAffectedBands = 0\n for filterName in self.filterNames:\n if (self.filterToBand[filterName] == 'u' or\n self.filterToBand[filterName] == 'r'):\n o3NAffectedBands += 1\n unitDict['o3Unit'] *= float(o3NAffectedBands) / float(len(fitBands))\n\n # wash parameters units...\n unitDict['qeSysUnit'] = 1.0 / stepUnitReference / stepGrain\n unitDict['qeSysSlopeUnit'] = unitDict['qeSysUnit'] * meanWashIntervalDuration\n\n return unitDict\n\n\n", "meta": {"hexsha": "0438a3716670670a6f00975da6e1ee6dc539e49a", "size": 54916, "ext": "py", "lang": "Python", "max_stars_repo_path": "fgcm/fgcmLUT.py", "max_stars_repo_name": "gcmshadow/fgcm", "max_stars_repo_head_hexsha": "f94231d90dc5f1b5711af3b1e259d26a6144cc15", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fgcm/fgcmLUT.py", "max_issues_repo_name": "gcmshadow/fgcm", "max_issues_repo_head_hexsha": "f94231d90dc5f1b5711af3b1e259d26a6144cc15", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fgcm/fgcmLUT.py", "max_forks_repo_name": "gcmshadow/fgcm", "max_forks_repo_head_hexsha": "f94231d90dc5f1b5711af3b1e259d26a6144cc15", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.535655058, "max_line_length": 189, "alphanum_fraction": 0.5391142836, "include": true, "reason": "import numpy,import scipy", "num_tokens": 14009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.2254166210386804, "lm_q1q2_score": 0.1135888262812064}} {"text": "import pickle\nimport os\nimport time\nimport numpy as np\nimport sys\nimport shutil\nfrom openmmlib import openmmlib\nfrom openmmlib import polymerutils\nfrom openmmlib.polymerutils import scanBlocks\nfrom openmmlib.openmmlib import Simulation\nfrom openmmlib.polymerutils import grow_rw\nsys.path.insert(0, \"/net/levsha/share/homes/aafke/Documents/PolymerCode\")\nimport pyximport; pyximport.install()\nfrom smcTranslocator_switch_zloop_biasedloading import smcTranslocatorDirectional\n'''Use proper smcTranslocator for biased loading'''\n\n# -------defining parameters----------\n# -- basic loop extrusion parameters--\nGPU = sys.argv[1]\nLIFETIME = int(sys.argv[2]) # Processivity\nSEPARATION = int(sys.argv[3]) # Separation LEFs in number of monomers\nTADSizes=[400,100,200,400,100,200,400,100,200,400,100,200,400,100,200,400,100,200,400,100,200,400,100,200]\n'lleft and lright are defined in SMCTranslocator!'\nlleft=(np.cumsum(TADSizes,dtype=np.int64)-1) #Load in with left arm active\nlright=(np.cumsum(TADSizes,dtype=np.int64)[0:-1]+1) #Load with right arm active\nN = sum(TADSizes) # number of monomers\nsmcStepsPerBlock = 1 # I take something like 1/steppingprobability, because stepping is not determistic. I usually choose the probability of stepping to be max 0.1. Usually I take 20 for genes speeding up and 10 for genes slowing down\nstiff = 0 # Polymer siffness in unit of bead size\ndens = 0.2 #float(sys.argv[4]) # 0.2 # density in beads / volume. The density can roughly be estimated by looking at the amount of chromatin in a nuclear volume.\nbox = (N / dens) ** 0.33 # Define size of the bounding box for Periodic Boundary Conditions\ndata = polymerutils.grow_rw(N, int(box) - 2) # creates a compact conformation \nblock = 0 # starting block \nkon=0#float(sys.argv[5]) # CTCF binding rate\nkoff=1#float(sys.argv[6]) #CTCF unbinding rate\nCTCFsites=np.array([0])#CTCF binding sites (take np.cumsum(TADsizes) if you want to compare to CTCF sites that are stall sites). \nCTCFCohesinEn=0# float(sys.argv[7]) # Cohesin-CTCF interaction energy in kT, without a neighbouring cohesin, the unbinding rate of CTCF is koff, if a cohesin is right next to a CTCF site, the CTCF unbinding rate is koff*exp(-CTCFCohesinEn)\n\nkswitch=0 #float(sys.argv[4])\nCTCFPause=1 \nzloops=1\n'this variable is controlled in smcTranslocator'\n\nsteps = int(200*(smcStepsPerBlock)) # nr of 3D simulation blocks btw advancing LEFs. For deterministic stepping choose 200-250 steps per block, otherwise, rescale with stepping probability. When genes are sparse, smcStepsPerBLock*dt is approximately the number of smc steps per smc block.\nConvGenes = True #True: Convergent genes, False: isolated genes\nIncreasedBinding =1#int(sys.argv[4]) \n'SET dirLoading=1 in smc Translocator if you want directional loading'\n# float(sys.argv[4])# Factor of increased binding at CTCF site\nstg = 0.8#float(sys.argv[7]) #Probability of stalling at TAD boundary\n\nsaveEveryBlocks = int(100/(smcStepsPerBlock)) # 10 save every 10 blocks (saving every block is now too much almost)\nskipSavedBlocksBeginning = int(20/(smcStepsPerBlock)) # how many blocks (saved) to skip after you restart LEF positions\ntotalSavedBlocks = 200#4000 # how many blocks to save (number of blocks done is totalSavedBlocks * saveEveryBlocks)\nrestartMilkerEveryBlocks = int(100/(smcStepsPerBlock)) \n#Only one Hamiltonian can be loaded at a time to the simkt, but we want to update the bonds every time a LEF steps. Loading a new Hamiltonian costs a lot of time. Instead we precalculate bonds and load all positions at once as one big Hamiltonian and just change the prefactors. \n\n# parameters for smc bonds \nsmcBondWiggleDist = 0.2\nsmcBondDist = 0.5\n\nif len(sys.argv)!=4:\n sys.exit('Number of input arguments is not correct')\n\nfolder = \"filepath\"\n\nFullFileName=os.path.join(folder,\"loopextrusion_Lifetime={0}_separation={1}_density={2}_stg={3}_N={4}_totalSavedBlocks={5}_kon=koff={6}_CTCFEn={7}_kswitch={8}_IncreasedBinding={9}_TwoLoadingSites_OneSided_NoUnstall_CTCFPause={10}_zloops={11}_NEW\".format(LIFETIME, SEPARATION, dens,stg,N,totalSavedBlocks,kon,CTCFCohesinEn,kswitch,IncreasedBinding,CTCFPause,zloops))\n\nif os.path.isdir(FullFileName):\n var=input('Folder already exists, press 9 to stop or any other key to empty and recreate the folder and continue')\n if eval(var)==9:\n sys.exit('Stopped simulation')\n else:\n shutil.rmtree(FullFileName) # Remove folder and content\n \n# assertions for easy managing code below \n\nassert restartMilkerEveryBlocks % saveEveryBlocks == 0 \nassert (skipSavedBlocksBeginning * saveEveryBlocks) % restartMilkerEveryBlocks == 0 \nassert (totalSavedBlocks * saveEveryBlocks) % restartMilkerEveryBlocks == 0 \nassert smcStepsPerBlock<6 # max number of steps per smc block should not be too large to prevent 'jerky' polymer motion\n\nsavesPerMilker = restartMilkerEveryBlocks // saveEveryBlocks\nmilkerInitsSkip = saveEveryBlocks * skipSavedBlocksBeginning // restartMilkerEveryBlocks\nmilkerInitsTotal = (totalSavedBlocks + skipSavedBlocksBeginning) * saveEveryBlocks // restartMilkerEveryBlocks\nprint(\"Time step = 1, Milker will be initialized {0} times, first {1} will be skipped\".format(milkerInitsTotal, milkerInitsSkip))\n\n# create filenames for Ekin, Epot and time\n\nEkin_fname = os.path.join(FullFileName,'Ekin.txt')\nEpot_fname = os.path.join(FullFileName,'Epot.txt')\ntime_fname = os.path.join(FullFileName,'time.txt')\nRg_fname = os.path.join(FullFileName,'Rg.txt')\nPar_fname = os.path.join(FullFileName,'Pars.txt')\n\n\ndef save_Es_ts_Rg():\n with open(time_fname, \"a+\") as time_file:\n time_file.write('%f\\n'%(a.state.getTime()/openmmlib.ps))\n with open(Ekin_fname, \"a+\") as Ekin_file:\n Ekin_file.write('%f\\n'%((a.state.getKineticEnergy())/a.N/a.kT))\n with open(Epot_fname, \"a+\") as Epot_file:\n Epot_file.write('%f\\n'%((a.state.getPotentialEnergy()) /a.N /a.kT))\n with open(Rg_fname, \"a+\") as Rg_file:\n Rg_file.write('%f\\n'%(analysis_plot_lib.rg(a.getData())))\n\nclass smcTranslocatorMilker(object):\n\n def __init__(self, smcTransObject):\n \"\"\"\n :param smcTransObject: smc translocator object to work with\n \"\"\"\n self.smcObject = smcTransObject\n self.allBonds = []\n\n def setParams(self, activeParamDict, inactiveParamDict):\n \"\"\"\n A method to set parameters for bonds.\n It is a separate method because you may want to have a Simulation object already existing\n\n :param activeParamDict: a dict (argument:value) of addBond arguments for active bonds\n :param inactiveParamDict: a dict (argument:value) of addBond arguments for inactive bonds\n\n \"\"\"\n self.activeParamDict = activeParamDict\n self.inactiveParamDict = inactiveParamDict\n\n\n def setup(self, bondForce, blocks = 100, smcStepsPerBlock = 1):\n \"\"\"\n A method that milks smcTranslocator object\n and creates a set of unique bonds, etc.\n\n :param bondForce: a bondforce object (new after simulation restart!)\n :param blocks: number of blocks to precalculate\n :param smcStepsPerBlock: number of smcTranslocator steps per block\n :return:\n \"\"\"\n\n\n if len(self.allBonds) != 0:\n raise ValueError(\"Not all bonds were used; {0} sets left\".format(len(self.allBonds)))\n\n self.bondForce = bondForce\n\n #precalculating all bonds\n allBonds = []\n for dummy in range(blocks):\n self.smcObject.steps(smcStepsPerBlock)\n left, right = self.smcObject.getSMCs()\n bonds = [(int(i), int(j)) for i,j in zip(left, right)]\n allBonds.append(bonds)\n\n self.allBonds = allBonds\n self.uniqueBonds = list(set(sum(allBonds, [])))\n\n #adding forces and getting bond indices\n self.bondInds = []\n self.curBonds = allBonds.pop(0)\n\n for bond in self.uniqueBonds:\n paramset = self.activeParamDict if (bond in self.curBonds) else self.inactiveParamDict\n ind = bondForce.addBond(bond[0], bond[1], **paramset)\n self.bondInds.append(ind)\n self.bondToInd = {i:j for i,j in zip(self.uniqueBonds, self.bondInds)}\n return self.curBonds,[]\n\n\n def step(self, context, verbose=False):\n \"\"\"\n Update the bonds to the next step.\n It sets bonds for you automatically!\n :param context: context\n :return: (current bonds, previous step bonds); just for reference\n \"\"\"\n if len(self.allBonds) == 0:\n raise ValueError(\"No bonds left to run; you should restart simulation and run setup again\")\n\n pastBonds = self.curBonds\n self.curBonds = self.allBonds.pop(0) # getting current bonds\n bondsRemove = [i for i in pastBonds if i not in self.curBonds]\n bondsAdd = [i for i in self.curBonds if i not in pastBonds]\n bondsStay = [i for i in pastBonds if i in self.curBonds]\n if verbose:\n print(\"{0} bonds stay, {1} new bonds, {2} bonds removed\".format(len(bondsStay),\n len(bondsAdd), len(bondsRemove)))\n bondsToChange = bondsAdd + bondsRemove\n bondsIsAdd = [True] * len(bondsAdd) + [False] * len(bondsRemove)\n for bond, isAdd in zip(bondsToChange, bondsIsAdd):\n ind = self.bondToInd[bond]\n paramset = self.activeParamDict if isAdd else self.inactiveParamDict\n self.bondForce.setBondParameters(ind, bond[0], bond[1], **paramset) # actually updating bonds\n self.bondForce.updateParametersInContext(context) # now run this to update things in the context\n return self.curBonds, pastBonds\n\ndef initModel():\n \n birthArray = np.ones(N, dtype=np.double)*0.1 \n deathArray = np.zeros(N, dtype=np.double) + 1. / (LIFETIME)\n stallArray = np.zeros(N, dtype=np.double)\n pauseArray=np.ones(N, dtype=np.double)\n stallDeathArray = np.zeros(N, dtype=np.double) + 1 / (LIFETIME)\n smcNum = N // SEPARATION\n konprob=kon #CTCF binding probability per timestep\n koffprob=koff\n curPos = 0\n \n for size in TADSizes: # setting positions & strength of boundary elements, looping over each TAD\n curPos += size\n if curPos < len(stallArray):\n stallArray[curPos] = stg\n birthArray[curPos+1] = birthArray[curPos]*IncreasedBinding\n birthArray[curPos-1] = birthArray[curPos]*IncreasedBinding\n\n SMCTran = smcTranslocatorDirectional(birthArray, deathArray, stallArray,pauseArray, stallDeathArray,smcNum,CTCFsites,konprob,koffprob,switch=kswitch)\n return SMCTran\n\n\nSMCTran = initModel() # defining actual smc translocator object \n\n\n# now polymer simulation code starts\n\n# ------------feed smcTran to the milker---\nSMCTran.steps(1000000)#(1000000) # first steps to \"equilibrate\" SMC dynamics. If desired of course. \nmilker = smcTranslocatorMilker(SMCTran) # now feed this thing to milker (do it once!)\n#--------- end new code ------------\n\nfor milkerCount in range(milkerInitsTotal):\n doSave = milkerCount >= milkerInitsSkip\n \n # simulation parameters are defined below \n a = Simulation(timestep=80,thermostat=0.01)#, thermostat=0.01)#Collision rate in inverse picoseconds, low collistion rate means ballistic like motion, default in openmmpolymer is 0.001. Motion polymer is not diffusive, this is ok for statistical average,\n #but not for dynamics of the polymer\n a.setup(platform=\"CUDA\", PBC=True, PBCbox=[box, box, box], GPU=GPU, precision=\"mixed\") # set up GPU here, PBC=Periodic Boundary Conditions\n a.saveFolder(FullFileName)\n a.load(data)\n a.addHarmonicPolymerBonds(wiggleDist=0.1) # WiggleDist controls distance at which energy of bond equals kT\n if stiff > 0:\n a.addGrosbergStiffness(stiff) # Chain stiffness is introduced by an angular potential U(theta)=stiff(1-cos(theta-Pi))\n a.addPolynomialRepulsiveForce(trunc=1.5, radiusMult=1.05) #Polynomial repulsive potential between particles. Has value trunc=3.0 at zero, stays flat until 0.6-0.7 and then drops to zero. For attraction between a selective set of particles, use LeonardJones or addSelectiveSSWForce (see blocks.py or ask Johannes)\n a.step = block\n\n # ------------ initializing milker; adding bonds ---------\n # copied from addBond\n kbond = a.kbondScalingFactor / (smcBondWiggleDist ** 2)\n bondDist = smcBondDist * a.length_scale\n\n activeParams = {\"length\":bondDist,\"k\":kbond}\n inactiveParams = {\"length\":bondDist, \"k\":0}\n milker.setParams(activeParams, inactiveParams)\n \n # this step actually puts all bonds in and sets first bonds to be what they should be\n milker.setup(bondForce=a.forceDict[\"HarmonicBondForce\"],\n blocks=restartMilkerEveryBlocks, # default value; milk for 100 blocks\n smcStepsPerBlock=smcStepsPerBlock) # \n print(\"Restarting milker\")\n\n a.doBlock(steps=steps, increment=False) # do block for the first time with first set of bonds in\n for i in range(restartMilkerEveryBlocks - 1):\n curBonds, pastBonds = milker.step(a.context) # this updates bonds. You can do something with bonds here\n if i % saveEveryBlocks == (saveEveryBlocks - 2): \n a.doBlock(steps=steps, increment = doSave)\n if doSave: \n a.save()\n pickle.dump(curBonds, open(os.path.join(a.folder, \"SMC{0}.dat\".format(a.step)),'wb'))\n save_Es_ts_Rg() # save energies and time\n else:\n a.integrator.step(steps) # do steps without getting the positions from the GPU (faster)\n\n data = a.getData() # save data and step, and delete the simulation\n block = a.step\n del a\n \n time.sleep(0.2) # wait 200ms for sanity (to let garbage collector do its magic)\n\nwith open(Par_fname,\"a+\") as Parfile:\n Parfile.write(\" tau=\"+str(LIFETIME)+\"\\n Separation=\"+str(SEPARATION)+\"\\n N=\"+str(N)+\"\\n smcStepsPerBlock=\"+str(smcStepsPerBlock)+\"\\n stiff=\"+str(stiff)+\"\\n dens=\"+str(dens)+\"\\n block=\"+str(block)+\"\\n SaveEveryBlocks=\"+str(saveEveryBlocks)+\"\\n skipSavedBlocksBeginning=\"+str(skipSavedBlocksBeginning)+\"\\n totalSavedBlocks=\"+str(totalSavedBlocks)+\"\\n restartMilkerEveryBlocks=\"+str(restartMilkerEveryBlocks)+\"\\n smcBondWiggleDist=\"+str(smcBondWiggleDist)+\"\\n smcBondDist=\"+str(smcBondDist)+\"\\n SmcTimestep=\" + str(dt)+\"\\n Mean TADsize\"+str(np.mean(TADSizes)))", "meta": {"hexsha": "ab6847b9d5849d8e9cde4c474a6a31130e78bbe2", "size": 14400, "ext": "py", "lang": "Python", "max_stars_repo_path": "interphase/PolymerSimulations_switch_zloop_biasedloading.py", "max_stars_repo_name": "utaresearch/one_sided_extrusion", "max_stars_repo_head_hexsha": "eb4fa53b69778691ade0073415716b29d57bcc71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-11-25T18:06:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-22T07:35:35.000Z", "max_issues_repo_path": "interphase/PolymerSimulations_switch_zloop_biasedloading.py", "max_issues_repo_name": "utaresearch/one_sided_extrusion", "max_issues_repo_head_hexsha": "eb4fa53b69778691ade0073415716b29d57bcc71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "interphase/PolymerSimulations_switch_zloop_biasedloading.py", "max_forks_repo_name": "utaresearch/one_sided_extrusion", "max_forks_repo_head_hexsha": "eb4fa53b69778691ade0073415716b29d57bcc71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-06-15T08:47:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T02:21:47.000Z", "avg_line_length": 52.1739130435, "max_line_length": 561, "alphanum_fraction": 0.7055555556, "include": true, "reason": "import numpy", "num_tokens": 3904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.22270014914315836, "lm_q1q2_score": 0.11221997933098402}} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n''' Class to keep track of the seeds,\n i.e. all the anions, electrons and avalanches.\n\n This class is used to modify and get the properties of the seeds\n as well as classify, move and multiply them.\n'''\n\n# General imports\nimport numpy as np\nimport logging\n\n# Import from project files\nfrom .streamer_head import SHList\n\n# settings\nlogger = logging.getLogger(__name__)\nlogger.addHandler(logging.NullHandler())\n\n# idea: refactor to a general class for particles\n# create a new class to manage the particles\n\n\nclass Seeds(object):\n def __init__(self, mu_e, mu_ion, efield_ion, efield_crit, time_step,\n Q_crit, efield_dtype, micro_step_no\n ):\n # initiate the seeds object without adding any seeds\n\n # define the logger\n self.logger = logging.getLogger(__name__ + '.Seeds')\n\n # set the dtype for electric field calculation\n if efield_dtype in ['sp', 'float32',]:\n self.efield_dtype = np.float32\n elif efield_dtype in ['dp', 'float64',]:\n self.efield_dtype = np.float64\n else:\n self.efield_dtype = np.float32\n msg = 'Can not use dtype \"{}\". Using \"{}\"\" instead.'\n self.logger.warning(msg.format(efield_dtype, self.efield_dtype))\n\n # set the properties of the seeds\n self.mu_e = mu_e # electron mobility\n self.mu_ion = mu_ion # cation mobility\n self.efield_ion = efield_ion # electric field for ion detachment\n self.efield_crit = efield_crit # electric field for multiplication\n self.time_step = time_step # simulation max time step\n self.dt = time_step # simulation actual time step\n self.micro_step_no = micro_step_no # micro time steps\n self.Q_crit = Q_crit # avalanche to streamer criterion\n\n # initialize the seed variables, start with no seeds\n self.pos = np.array([]).reshape(3, 0) # [x, y, z] position\n self.Q = np.array([]) # avalanche size\n self.clear() # initialize other variables\n\n # log initiation\n self.logger.debug('Initated Seeds')\n self.logger.log(5, 'Seeds.__dict__')\n for k, v in self.__dict__.items():\n self.logger.log(5, ' \"{}\": {}'.format(k, v))\n\n def clear(self):\n # Clear variables\n\n # rename for better readability below\n no = self.no\n nz = np.zeros # return zeroes\n nf = lambda shape: np.zeros(shape, dtype=bool) # return false shape\n\n # Should be explicitly reset\n self.no_added = 0\n self.no_removed = 0\n self.pos_to_append = nz((3, 0))\n self.is_to_remove = nz(no, dtype=bool)\n\n # Should be updated each iteration\n self.ds = nz((3, no)) # last movement\n self.ds_abs = nz(no) # movement, absolute\n self.ds_max = 0 # movement, maximum\n self.dQ = nz(no) # change in charge\n self.mu = nz(no) # mobility\n self.e_dir = nz((3, no)) # electric field, unit vector\n self.e_vec = nz((3, no)) # electric field, vector\n self.e_str = nz(no) # electric field, strength\n # bools\n self.is_in_streamer = nf(no) # inside streamer\n self.is_critical = nf(no) # avalanche termination\n self.is_behind_roi = nf(no) # behind ROI\n self.is_avalanche = nf(no) # avalanche seed\n self.is_ion = nf(no) # electron seed\n self.is_electron = nf(no) # ion seed\n\n # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n # DERIVED ATTIBUTES #\n # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n # The user need to ensure that relevant variables are updated\n # before getting these properties\n\n Q_max = property(lambda self: self.Q.max())\n dQ_max = property(lambda self: self.dQ.max())\n charge = property(lambda self: np.exp(self.Q).sum())\n charge_gen = property(lambda self: (self.dQ * np.exp(self.Q)).sum())\n charge_rem = property(lambda self: np.exp(self.Q_to_remove).sum())\n\n no = property(lambda self: self.pos.shape[1]) # total number\n no_to_append = property(lambda self: self.pos_to_append.shape[1])\n\n no_ion = property(lambda self: self.is_ion.sum())\n no_electron = property(lambda self: self.is_electron.sum())\n no_avalanche = property(lambda self: self.is_avalanche.sum())\n no_critical = property(lambda self: self.is_critical.sum())\n no_behind_roi = property(lambda self: self.is_behind_roi.sum())\n no_in_streamer = property(lambda self: self.is_in_streamer.sum())\n no_to_remove = property(lambda self: self.is_to_remove.sum())\n\n pos_ion = property(lambda self: self.pos[:, self.is_ion])\n pos_electron = property(lambda self: self.pos[:, self.is_electron])\n pos_avalanche = property(lambda self: self.pos[:, self.is_avalanche])\n pos_critical = property(lambda self: self.pos[:, self.is_critical])\n pos_behind_roi = property(lambda self: self.pos[:, self.is_behind_roi])\n pos_in_streamer = property(lambda self: self.pos[:, self.is_in_streamer])\n pos_to_remove = property(lambda self: self.pos[:, self.is_to_remove])\n\n Q_ion = property(lambda self: self.Q[self.is_ion])\n Q_electron = property(lambda self: self.Q[self.is_electron])\n Q_avalanche = property(lambda self: self.Q[self.is_avalanche])\n Q_critical = property(lambda self: self.Q[self.is_critical])\n Q_behind_roi = property(lambda self: self.Q[self.is_behind_roi])\n Q_in_streamer = property(lambda self: self.Q[self.is_in_streamer])\n Q_to_remove = property(lambda self: self.Q[self.is_to_remove])\n\n dQ_ion = property(lambda self: self.dQ[self.is_ion])\n dQ_electron = property(lambda self: self.dQ[self.is_electron])\n dQ_avalanche = property(lambda self: self.dQ[self.is_avalanche])\n dQ_critical = property(lambda self: self.dQ[self.is_critical])\n dQ_behind_roi = property(lambda self: self.dQ[self.is_behind_roi])\n dQ_in_streamer = property(lambda self: self.dQ[self.is_in_streamer])\n dQ_to_remove = property(lambda self: self.dQ[self.is_to_remove])\n\n\n # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n # UPDATE #\n # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n # Updating of bools should be called explicitly\n # since they may be expensive to calculate\n # or it has to be done at specific times\n # Maintain a comment to when they are updated!\n\n # `is_ion` is set during movement\n def update_is_ion(self, e_str=None):\n e_str = self.e_str if (e_str is None) else e_str\n self.is_ion = (e_str < self.efield_ion)\n return self.is_ion\n\n # ´is_electron´ is set during movement\n def update_is_electron(self, e_str=None):\n e_str = self.e_str if (e_str is None) else e_str\n self.is_electron = (e_str >= self.efield_ion)\n return self.is_electron\n\n # ´is_avalanche´ is set during movement\n def update_is_avalanche(self, e_str=None):\n e_str = self.e_str if (e_str is None) else e_str\n self.is_avalanche = (e_str >= self.efield_crit)\n return self.is_avalanche\n\n # Invoked in main simulation loop\n def update_is_critical(self, Q=None):\n Q = self.Q if (Q is None) else Q\n self.is_critical = (Q >= self.Q_crit)\n return self.is_critical\n\n # Invoked in main simulation loop\n def update_is_behind_roi(self, roi):\n self.is_behind_roi = roi.is_pos_behind(self.pos)\n return self.is_behind_roi\n\n # ´is_in_streamer´ is set during movement\n def update_is_in_streamer(self, heads):\n self.is_in_streamer = SHList(heads).is_inside(self.pos)\n return self.is_in_streamer\n\n def update_mu(self):\n self.mu = np.ones(self.no) * self.mu_ion\n self.mu[self.is_electron] = self.mu_e\n\n # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n # OTHER #\n # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n\n def eprop(self, heads, pos=None):\n ''' Return `edir`, `estr`, `evec`, and `is_inside`.\n Convenience function to ensure correct dtype for seeds.\n '''\n if pos is None:\n pos = self.pos\n return SHList(heads).eprop(pos, dtype=self.efield_dtype)\n\n # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n # MOVE & MULTIPLY #\n # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n\n def _update_ds(self, e_str, e_vec):\n ''' Calculate movement. Update `ds`.\n Also update `is_electron`, `is_ion`, `mu`.\n '''\n self.is_electron = (e_str > self.efield_ion)\n self.is_ion = ~self.is_electron # note: need to be somewhere\n self.mu = self.mu_ion * np.ones(self.no)\n self.mu[self.is_electron] = self.mu_e\n self.ds = e_vec * self.mu * self.dt\n\n def _update_ds_abs(self, thresh):\n ''' Calculate the max movement. Update `ds_abs` and `ds_max`.\n Give warning if any movement exceeds `thresh`.\n '''\n self.ds_abs = np.linalg.norm(self.ds, axis=0)\n self.ds_max = self.ds_abs.max()\n if self.ds_max > thresh:\n mask = (self.ds_abs > thresh)\n msg = 'Warning! {}x large movement!'.format(mask.sum())\n self.logger.warning(msg)\n self.logger.debug('Movements {}'.format(self.ds_abs[mask]))\n\n # note: previously used function\n def move_multiply_single_step(self, heads, calc_alpha):\n ''' Move all seeds and multiply all avalanches, single step. '''\n\n # treat seeds below the plane as if they were at the plane\n pos = self.pos.copy()\n mask = (self.pos[2, :] < 0)\n pos[2, mask] = 0\n\n # Find the field at electrons!\n self.e_dir, self.e_str, self.e_vec, self.is_in_streamer = (\n self.eprop(heads, pos))\n\n # Move seeds\n self._update_ds(self.e_str, self.e_vec)\n self._update_ds_abs(thresh=heads[0].rp)\n self.pos += self.ds\n\n # Update electron numbers\n self.dQ = calc_alpha(self.e_str) * self.ds_abs\n self.dQ[self.e_str < self.efield_crit] = 0\n self.dQ[self.pos[2, :] <= 0] = 0\n self.Q += self.dQ\n\n\n def move_multiply(self, heads, calc_alpha):\n ''' Move all seeds, multiply electron in avalanches.\n\n Parameters\n ----------\n heads : SHList\n list of streamer heads used for field calculation\n calc_alpha : CalcAlpha\n class instance for calculating electron multiplication\n\n Notes\n -----\n Seeds are classified by the electric field strength.\n Avalanches are moved in an inner loop.\n Critical avalanches and collisions with the streamer\n are saved and these break the inner loop.\n Other seeds are moved according to the time spent in the inner loop.\n Long seed movements give warnings.\n Positions and charge numbers are updated.\n '''\n\n # treat seeds below the plane as if they were at the plane\n # this implies that seeds below plane will move straight upwards\n pos = self.pos.copy()\n mask = (self.pos[2, :] < 0)\n pos[2, mask] = 0\n\n # find the field\n self.e_dir, self.e_str, self.e_vec, self.is_in_streamer = (\n self.eprop(heads, pos))\n\n # classify the seeds\n self.update_is_electron() # uses self.e_str\n self.update_is_ion() # uses self.e_str\n self.update_is_avalanche() # uses self.e_str\n\n # set all mobilities\n self.update_mu() # uses self.is_electron\n\n # extract information about just the avalanches\n is_avalanche = self.is_avalanche\n pos_avalanche = self.pos[:, is_avalanche]\n Q_avalanche = self.Q[is_avalanche]\n e_str = self.e_str[is_avalanche]\n e_vec = self.e_vec[:, is_avalanche]\n e_dir = self.e_dir[:, is_avalanche]\n is_in_streamer = self.is_in_streamer\n\n time_spent = 0\n\n def _get_ds(e_vec, mu=None, time_step=None):\n # return the change in avalanche positions\n if mu is None:\n mu = self.mu\n if time_step is None:\n time_step = self.time_step\n ds = e_vec * mu * time_step\n ds_abs = np.linalg.norm(ds, axis=0)\n return ds, ds_abs\n\n def _warn_large_ds(ds_abs, threshold, what):\n ds_max = ds_abs.max()\n if (ds_max < threshold):\n return ds_max\n mask = (ds_abs > threshold)\n msg = f'Warning! {mask.sum()}x large {what} movement!'\n self.logger.warning(msg)\n self.logger.info(f'Max movement: {(ds_max * 1e6):.2g} um')\n self.logger.log(5, f'Movements {ds_abs[mask]}')\n return ds_max\n\n # skip this part when it is not needed\n if any(is_avalanche):\n\n # do one iteration with the field already calculated\n time_spent += self.time_step # update the time\n ds, ds_abs = _get_ds(e_vec, mu=self.mu_e) # find the movements\n _warn_large_ds(ds_abs, threshold=heads[0].rp/10, what='avalanches')\n pos_avalanche += ds # update positions\n dQ = calc_alpha(e_str) * ds_abs # get avalanche change\n dQ[pos_avalanche[2, :] < 0] = 0 # no multiplication for z<0\n Q_avalanche += dQ # update avalanche electrons\n\n # do the rest of the iterations\n for i in range(self.micro_step_no - 1): # one is already done\n # end when critical avalanche is reached\n if any(Q_avalanche > self.Q_crit):\n logger.debug('Critical avalanche!')\n break\n # end on collision with streamer\n if any(is_in_streamer):\n if i != 0: # not needed (or allowed) the first loop\n self.is_in_streamer[is_avalanche] = is_in_streamer\n logger.debug('Collision with streamer!')\n break\n\n # treat seeds below the plane as if they were at the plane\n pos_avalanche_tmp = pos_avalanche.copy()\n mask = (pos_avalanche[2, :] < 0)\n pos_avalanche_tmp[2, mask] = 0\n\n # find the field\n e_dir, e_str, e_vec, is_in_streamer = (\n self.eprop(heads, pos_avalanche_tmp))\n\n time_spent += self.time_step # update the time\n ds, ds_abs = _get_ds(e_vec, mu=self.mu_e) # find the movements\n _warn_large_ds(\n ds_abs, threshold=heads[0].rp/10, what='avalanches')\n pos_avalanche += ds # update positions\n dQ = calc_alpha(e_str) * ds_abs # get avalanche change\n dQ[pos_avalanche[2, :] < 0] = 0 # no multiplication for z<0\n Q_avalanche += dQ # update avalanche electrons\n\n else: # no avalanches, should be a rare event\n time_spent = self.time_step * self.micro_step_no\n logger.debug('No avalanches!')\n\n # update avalanche numbers\n self.is_avalanche = is_avalanche # should already be correct\n self.dQ[is_avalanche] = Q_avalanche - self.Q[is_avalanche]\n self.Q[is_avalanche] = Q_avalanche\n\n # get seed movements\n self.e_vec[:, is_avalanche] = 0 # do not move avalanches here\n ds, ds_abs = _get_ds(self.e_vec, time_step=time_spent) # find movements\n _warn_large_ds(ds_abs, threshold=heads[0].rp, what='seed')\n\n # update positions\n pos_old = self.pos.copy() # save old position for ds calculation\n self.pos += ds # add ds for all seeds\n self.pos[:, is_avalanche] = pos_avalanche # set these explicitly\n\n # store actual movements\n self.ds = self.pos - pos_old\n self.ds_abs = np.linalg.norm(self.ds, axis=0)\n self.ds_max = self.ds_abs.max()\n\n # store the time spent here\n self.dt = time_spent\n\n # log results, as required\n logger.log(5, f'Number of avalanches, {is_avalanche.sum()}')\n logger.log(5, f'Time spent, {(time_spent * 1e9):.3f} ns')\n logger.log(5, f'Maximum movement, {(self.ds_max * 1e6):.3f} um')\n if any(is_avalanche):\n msg = f'Maximum avalanche growth, {(self.dQ.max()):.3f}'\n else:\n msg = f'Maximum avalanche growth, 0'\n logger.log(5, msg)\n\n # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n # APPEND/REMOVE #\n # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n\n def append(self, pos):\n ''' Append the given pos, and update vars as required.'''\n if not pos.size:\n self.logger.log(5, 'Tried to add zero seeds.')\n return\n assert pos.shape[0] == 3, 'pos.shape[0] == 3'\n Q = np.zeros(pos.shape[1])\n self.pos = np.hstack((self.pos, pos))\n self.Q = np.hstack((self.Q, Q))\n self.no_added += pos.shape[1]\n\n def remove(self, idx):\n ''' Remove pos and Q at the given indices.'''\n if idx.sum() == 0:\n self.logger.log(5, 'Tried to remove zero seeds.')\n return\n self.pos = self.pos[:, idx == 0]\n self.Q = self.Q[idx == 0]\n self.no_removed += idx.sum()\n\n def append_at_end(self, pos):\n ''' Appends the given pos to pos_to_append.'''\n assert pos.shape[0] == 3, 'pos.shape[0] == 3'\n pos = np.array(pos).reshape(3, -1)\n self.pos_to_append = np.hstack((self.pos_to_append, pos))\n\n # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n # CLEAN #\n # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n\n def clean(self):\n\n # Remove seeds and reset var\n self.remove(self.is_to_remove)\n\n # Append seeds and reset var\n self.append(self.pos_to_append)\n\n # Clear other variables\n self.clear()\n\n\n#\n", "meta": {"hexsha": "224c25982134e2e69662f5eeb3dc74a1cb2484de", "size": 18721, "ext": "py", "lang": "Python", "max_stars_repo_path": "cerman/simulate/seeds.py", "max_stars_repo_name": "madshaven/cerman", "max_stars_repo_head_hexsha": "c49552f4ad8ee82fdf0dd216cbc783c1a90a8b5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-02T12:52:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T10:57:32.000Z", "max_issues_repo_path": "cerman/simulate/seeds.py", "max_issues_repo_name": "madshaven/cerman", "max_issues_repo_head_hexsha": "c49552f4ad8ee82fdf0dd216cbc783c1a90a8b5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cerman/simulate/seeds.py", "max_forks_repo_name": "madshaven/cerman", "max_forks_repo_head_hexsha": "c49552f4ad8ee82fdf0dd216cbc783c1a90a8b5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.4181415929, "max_line_length": 80, "alphanum_fraction": 0.5602798996, "include": true, "reason": "import numpy", "num_tokens": 4767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.20946968133032526, "lm_q1q2_score": 0.11208690043073488}} {"text": "# -*- coding: utf-8 -*-\n\nimport math\nimport numpy as np\nimport operator\n\nfrom .utils import Base\n\neps = 1e-4\n\n\nclass IsotopicFitRecord(object):\n \"\"\"Describes a single isotopic pattern fit, comparing how well an\n experimentally observed sequence of peaks matches a theoretical isotopic\n pattern.\n\n IsotopicFitRecord instances are hashable and orderable (by score).\n\n Attributes\n ----------\n charge : int\n The charge state used to generate the theoretical pattern\n data : object\n An arbitrary Python object containing extra information\n experimental : list of FittedPeak\n The observed experimental peaks to be fitted\n missed_peaks : int\n The number of peaks in the theoretical pattern that do not\n have a matching experimental peak\n monoisotopic_peak : FittedPeak\n The fitted peak which corresponds to the monoisotopic peak\n score : float\n The score assigned to the fit by an IsotopicFitter object\n seed_peak : FittedPeak\n The peak that was used to initiate the fit. This may be unused\n if not using an Averagine method\n theoretical : list of TheoreticalPeak\n The theoretical isotopic pattern being fitted on the experimental data\n \"\"\"\n __slots__ = [\"seed_peak\", \"score\", \"charge\", \"experimental\", \"theoretical\",\n \"monoisotopic_peak\", \"data\", \"missed_peaks\"]\n\n def __init__(self, seed_peak, score, charge, theoretical, experimental, data=None,\n missed_peaks=0, **kwargs):\n self.seed_peak = seed_peak\n self.score = score\n self.charge = charge\n self.experimental = experimental\n self.theoretical = theoretical\n self.monoisotopic_peak = experimental[0]\n self.data = data\n self.missed_peaks = missed_peaks\n\n def clone(self):\n return self.__class__(\n self.seed_peak, self.score, self.charge, self.theoretical, self.experimental, self.data, self.missed_peaks)\n\n def __reduce__(self):\n return self.__class__, (\n self.seed_peak, self.score, self.charge, self.theoretical, self.experimental, self.data, self.missed_peaks)\n\n def __eq__(self, other):\n val = (self.score == other.score and\n self.charge == other.charge and\n self.experimental == other.experimental and\n self.theoretical == other.theoretical)\n if self.data is not None or other.data is not None:\n val = val and (self.data == other.data)\n return val\n\n def __ne__(self, other):\n return not (self == other)\n\n def __lt__(self, other):\n return self.score < other.score\n\n def __gt__(self, other):\n return self.score > other.score\n\n def __hash__(self):\n return hash((self.monoisotopic_peak.mz, self.charge))\n\n def __iter__(self):\n yield self.score\n yield self.charge\n yield self.experimental\n yield self.theoretical\n\n @property\n def npeaks(self):\n return len(self.experimental)\n\n def __repr__(self):\n return \"IsotopicFitRecord(score=%0.5f, charge=%d, npeaks=%d, monoisotopic_mz=%0.5f)\" % (\n self.score, self.charge, self.npeaks, self.monoisotopic_peak.mz)\n\n\nclass FitSelectorBase(Base):\n \"\"\"An object that controls the filtering and\n selection of IsotopicFitRecord\n\n Attributes\n ----------\n minimum_score : int\n The minimum score needed to be a candidate for selection. If the\n FitSelector is `minimizing` it is the maximal score to be a candidate.\n \"\"\"\n minimum_score = 0\n\n def __init__(self, minimum_score=0):\n self.minimum_score = minimum_score\n\n def best(self, results):\n raise NotImplementedError()\n\n def __call__(self, *args, **kwargs):\n return self.best(*args, **kwargs)\n\n def reject(self, fit):\n raise NotImplementedError()\n\n def reject_score(self, score):\n raise NotImplementedError()\n\n def is_maximizing(self):\n return False\n\n\nclass MinimizeFitSelector(FitSelectorBase):\n \"\"\"A FitSelector which tries to minimize the score of the best fit.\n \"\"\"\n def best(self, results):\n \"\"\"Returns the IsotopicFitRecord with the smallest score\n\n Parameters\n ----------\n results : list of IsotopicFitRecord\n List of isotopic fits to select the most optimal case from\n\n Returns\n -------\n IsotopicFitRecord\n The most optimal fit\n \"\"\"\n return min(results, key=operator.attrgetter(\"score\"))\n\n def reject(self, fit):\n \"\"\"Decide whether the fit should be discarded for having too\n large a score. Compares against :attr:`minimum_score`\n\n Parameters\n ----------\n fit : IsotopicFitRecord\n\n Returns\n -------\n bool\n \"\"\"\n return fit.score > self.minimum_score\n\n def reject_score(self, score):\n return score > self.minimum_score\n\n def is_maximizing(self):\n \"\"\"Returns that this is *not* a maximizing selector\n\n Returns\n -------\n False\n \"\"\"\n return False\n\n\nclass MaximizeFitSelector(FitSelectorBase):\n \"\"\"A FitSelector which tries to maximize the score of the best fit.\n \"\"\"\n def best(self, results):\n \"\"\"Returns the IsotopicFitRecord with the largest score\n\n Parameters\n ----------\n results : list of IsotopicFitRecord\n List of isotopic fits to select the most optimal case from\n\n Returns\n -------\n IsotopicFitRecord\n The most optimal fit\n \"\"\"\n return max(results, key=operator.attrgetter(\"score\"))\n\n def reject(self, fit):\n \"\"\"Decide whether the fit should be discarded for having too\n small a score. Compares against :attr:`minimum_score`\n\n Parameters\n ----------\n fit : IsotopicFitRecord\n\n Returns\n -------\n bool\n \"\"\"\n return fit.score < self.minimum_score\n\n def reject_score(self, score):\n return score < self.minimum_score\n\n def is_maximizing(self):\n \"\"\"Returns that this *is* a maximizing selector\n\n Returns\n -------\n False\n \"\"\"\n return True\n\n\nclass IsotopicFitterBase(Base):\n '''A base class for Isotopic Pattern Fitters, objects\n which given a set of experimental peaks and a set of matching\n theoretical peaks, returns a fit score describing how good the\n match is.\n\n An IsotopicFitter may be optimal when the score is small (minimizing)\n or when the score is large (maximizing), and the appropriate\n :class:`FitSelectorBase` type will be used for :attr:`select`. This\n will also be reflected by :meth:`is_maximizing`.\n '''\n\n def __init__(self, score_threshold=0.5):\n self.select = MinimizeFitSelector(score_threshold)\n\n def evaluate(self, peaklist, observed, expected, **kwargs):\n \"\"\"Evaluate a pair of peak lists for goodness-of-fit.\n\n Parameters\n ----------\n peaklist : :class:`~.PeakSet`\n The full set of all experimental peaks\n observed : list\n The list of experimental peaks that are part of this fit\n expected : list\n The list of theoretical peaks that are part of this fit\n **kwargs\n\n Returns\n -------\n float\n The score\n \"\"\"\n return NotImplemented\n\n def _evaluate(self, peaklist, observed, expected, **kwargs):\n return self.evaluate(peaklist, observed, expected, **kwargs)\n\n def __call__(self, *args, **kwargs):\n \"\"\"Invokes :meth:`evaluate`\n\n Parameters\n ----------\n *args\n Forwarded to :meth:`evaluate`\n **kwargs\n Forwarded to :meth:`evaluate`\n\n Returns\n -------\n float\n The score\n \"\"\"\n return self.evaluate(*args, **kwargs)\n\n def reject(self, fit):\n \"\"\"Test whether this fit is too poor to be used\n\n Parameters\n ----------\n fit : :class:`~IsotopicFitRecord`\n The fit to test\n\n Returns\n -------\n bool\n \"\"\"\n return self.select.reject(fit)\n\n def is_maximizing(self):\n \"\"\"Whether or not this fitter's score gets better as it grows\n\n Returns\n -------\n bool\n Whether or not this fitter is a maximizing fitter\n \"\"\"\n return self.select.is_maximizing()\n\n def configure(self, deconvoluter, **kwargs):\n return self\n\n\nclass GTestFitter(IsotopicFitterBase):\n r\"\"\"Evaluate an isotopic fit using a G-test\n\n .. math::\n G = 2\\sum_i^n{o_i * ({log}o_i - {log}e_i)}\n\n where :math:`o_i` is the intensity of the ith experimental peak\n and :math:`e_i` is the intensity of the ith theoretical peak.\n \"\"\"\n def evaluate(self, peaklist, observed, expected, **kwargs):\n g_score = 2 * sum([obs.intensity * np.log(\n obs.intensity / theo.intensity) for obs, theo in zip(observed, expected)])\n return g_score\n\n\ng_test = GTestFitter()\n\n\nclass ScaledGTestFitter(IsotopicFitterBase):\n r\"\"\"Evaluate an isotopic fit using a G-test after normalizing the\n list of experimental and theoretical peaks to both sum to 1.\n\n .. math::\n G = 2\\sum_i^n{o_i * ({log}o_i - {log}e_i)}\n\n where :math:`o_i` is the intensity of the ith experimental peak\n and :math:`e_i` is the intensity of the ith theoretical peak.\n \"\"\"\n def evaluate(self, peaklist, observed, expected, **kwargs):\n total_observed = sum(p.intensity for p in observed)\n total_expected = sum(p.intensity for p in expected)\n total_expected += eps\n normalized_observed = [obs.intensity /\n total_observed for obs in observed]\n normalized_expected = [theo.intensity /\n total_expected for theo in expected]\n g_score = 2 * sum([obs * np.log(obs / theo) for obs, theo in zip(\n normalized_observed, normalized_expected)])\n return g_score\n\n\ng_test_scaled = ScaledGTestFitter()\n\n\nclass ChiSquareFitter(IsotopicFitterBase):\n\n def evaluate(self, peaklist, observed, expected, **kwargs):\n score = sum([(obs.intensity - theo.intensity)**2 / theo.intensity\n for obs, theo in zip(observed, expected)])\n return score\n\n\nchi_sqr_test = ChiSquareFitter()\n\n\nclass LeastSquaresFitter(IsotopicFitterBase):\n r\"\"\"Evaluate an isotopic fit using least squares coefficient of\n determination :math:`R^2`.\n\n .. math::\n {\\hat e_i} &= e_i / max(e)\n\n {\\hat t_i} &= t_i / max(t)\n\n {\\hat t} &= \\sum_i^n {\\hat t_i}^2\n\n R^2 &= \\frac{1}{{\\hat t}}\\sum_i^n ({\\hat e_i} - {\\hat t_i})^2\n\n where :math:`e_i` is the ith experimental peak intensity and :math:`t_i`\n is the ith theoretical peak intensity\n \"\"\"\n\n def evaluate(self, peaklist, observed, expected, **kwargs):\n exp_max = max(p.intensity for p in observed)\n theo_max = max(p.intensity for p in expected)\n\n sum_of_squared_errors = 0\n sum_of_squared_theoreticals = 0\n\n for e, t in zip(observed, expected):\n normed_expr = e.intensity / exp_max\n normed_theo = t.intensity / theo_max\n sum_of_squared_errors += (normed_theo - normed_expr) ** 2\n sum_of_squared_theoreticals += normed_theo ** 2\n return sum_of_squared_errors / sum_of_squared_theoreticals\n\n\nleast_squares = LeastSquaresFitter()\n\n\nclass MSDeconVFitter(IsotopicFitterBase):\n '''An implementation of the scoring function used in :title-reference:`MSDeconV`\n\n References\n ----------\n Liu, X., Inbar, Y., Dorrestein, P. C., Wynne, C., Edwards, N., Souda, P., …\n Pevzner, P. A. (2010). Deconvolution and database search of complex tandem\n mass spectra of intact proteins: a combinatorial approach. Molecular & Cellular\n Proteomics : MCP, 9(12), 2772–2782. https://doi.org/10.1074/mcp.M110.002766\n '''\n\n def __init__(self, minimum_score=10, mass_error_tolerance=0.02):\n self.select = MaximizeFitSelector()\n self.select.minimum_score = minimum_score\n self.mass_error_tolerance = mass_error_tolerance\n\n def calculate_minimum_signal_to_noise(self, observed):\n snr = 0\n n = 0\n for obs in observed:\n if obs.signal_to_noise < 1:\n continue\n snr += obs.signal_to_noise\n n += 1\n return (snr / n) * 0.05\n\n def reweight(self, obs, theo, obs_total, theo_total):\n norm_obs = obs.intensity / obs_total\n norm_theo = theo.intensity / theo_total\n return norm_obs * np.log(norm_obs / norm_theo)\n\n def score_peak(self, obs, theo, mass_error_tolerance=0.02, minimum_signal_to_noise=1):\n if obs.signal_to_noise < minimum_signal_to_noise:\n return 0.\n\n mass_error = np.abs(obs.mz - theo.mz)\n\n if mass_error <= mass_error_tolerance:\n mass_accuracy = 1 - mass_error / mass_error_tolerance\n else:\n mass_accuracy = 0\n\n if obs.intensity < theo.intensity and (((theo.intensity - obs.intensity) / obs.intensity) <= 1):\n abundance_diff = 1 - \\\n ((theo.intensity - obs.intensity) / obs.intensity)\n elif obs.intensity >= theo.intensity and (((obs.intensity - theo.intensity) / obs.intensity) <= 1):\n abundance_diff = np.sqrt(\n 1 - ((obs.intensity - theo.intensity) / obs.intensity))\n else:\n abundance_diff = 0.\n score = np.sqrt(theo.intensity) * mass_accuracy * abundance_diff\n return score\n\n def evaluate(self, peaklist, observed, expected, **kwargs):\n score = 0\n for obs, theo in zip(observed, expected):\n inc = self.score_peak(obs, theo, self.mass_error_tolerance, 1)\n score += inc\n return score\n\n\nclass PenalizedMSDeconVFitter(IsotopicFitterBase):\n r'''An Isotopic Fitter which uses the :class:`MSDeconVFitter` score\n weighted by 1 - :attr:`penalty_factor` * :class:`ScaledGTestFitter` score\n\n .. math::\n S(e, t) = M(e, t) * (1 - G(e, t))\n\n where :math:`e` is the experimental peak list and :math:`t` is the theoretical\n peak list\n '''\n def __init__(self, minimum_score=10, penalty_factor=1., mass_error_tolerance=0.02):\n self.select = MaximizeFitSelector(minimum_score)\n self.msdeconv = MSDeconVFitter(mass_error_tolerance=mass_error_tolerance)\n self.penalizer = ScaledGTestFitter()\n self.penalty_factor = penalty_factor\n\n def evaluate(self, peaklist, observed, expected, **kwargs):\n score = self.msdeconv.evaluate(peaklist, observed, expected)\n penalty = abs(self.penalizer.evaluate(peaklist, observed, expected))\n return score * (1 - penalty * self.penalty_factor)\n\n\ndef decon2ls_chisqr_test(peaklist, observed, expected, **kwargs):\n fit_total = 0\n sum_total = 0\n for obs, theo in zip(observed, expected):\n intensity_diff = obs.intensity - theo.intensity\n fit_total += (intensity_diff ** 2) / (theo.intensity + obs.intensity)\n sum_total += theo.intensity * obs.intensity\n return fit_total / (sum_total + 0.01)\n\n\nclass InterferenceDetection(object):\n\n def __init__(self, peaklist):\n self.peaklist = peaklist\n\n def __call__(self, experimental_peaks, lower=None, upper=None):\n return self.detect_interference(experimental_peaks, lower, upper)\n\n def detect_interference(self, experimental_peaks, lower=None, upper=None):\n min_peak = experimental_peaks[0]\n max_peak = experimental_peaks[-1]\n\n if lower is None:\n try:\n lower = min_peak.mz - min_peak.full_width_at_half_max\n except AttributeError:\n lower = min_peak.mz\n if upper is None:\n try:\n upper = max_peak.mz + max_peak.full_width_at_half_max\n except AttributeError:\n upper = max_peak.mz\n\n region = self.peaklist.between(lower, upper)\n\n included_intensity = sum(p.intensity for p in experimental_peaks)\n region_intensity = sum(p.intensity for p in region)\n if region_intensity == 0:\n return 0.\n\n score = 1 - (included_intensity / region_intensity)\n return score\n\n\nclass DistinctPatternFitter(IsotopicFitterBase):\n\n def __init__(self, minimum_score=0.3, peak_count_scale=1.5, domain_scale=100.):\n self.select = MinimizeFitSelector(minimum_score)\n self.interference_detector = None\n self.g_test_scaled = ScaledGTestFitter()\n self.peak_count_scale = peak_count_scale\n self.domain_scale = domain_scale\n\n def evaluate(self, peaklist, experimental, theoretical, **kwargs):\n npeaks = float(len(experimental))\n if self.interference_detector is None:\n self.interference_detector = InterferenceDetection(peaklist)\n\n score = self.g_test_scaled(peaklist, experimental, theoretical)\n score *= abs((self.interference_detector.detect_interference(experimental) + 0.00001) / (\n npeaks * self.peak_count_scale)) * self.domain_scale\n return score\n\n\ndef percentile(N, percent):\n if not N:\n return None\n k = (len(N) - 1) * percent\n f = math.floor(k)\n c = math.ceil(k)\n if f == c:\n return N[int(k)]\n d0 = N[int(f)] * (c - k)\n d1 = N[int(c)] * (k - f)\n return d0 + d1\n\n\nclass DotProductFitter(IsotopicFitterBase):\n def evaluate(self, peaklist, observed, expected, **kwargs):\n total = 0\n for e, t in zip(observed, expected):\n total += e.intensity * t.intensity\n return total\n\n\ntry:\n _c = True\n _IsotopicFitRecord = IsotopicFitRecord\n _LeastSquaresFitter = LeastSquaresFitter\n _MSDeconVFitter = MSDeconVFitter\n _ScaledGTestFitter = ScaledGTestFitter\n _PenalizedMSDeconVFitter = PenalizedMSDeconVFitter\n _DistinctPatternFitter = DistinctPatternFitter\n _DotProductFitter = DotProductFitter\n\n from ._c.scoring import (\n IsotopicFitRecord, LeastSquaresFitter, MSDeconVFitter,\n ScaledGTestFitter, PenalizedMSDeconVFitter, DistinctPatternFitter,\n DotProductFitter)\nexcept ImportError as e:\n print(e)\n _c = False\n\nmsdeconv = MSDeconVFitter()\nleast_squares = LeastSquaresFitter()\ng_test_scaled = ScaledGTestFitter()\npenalized_msdeconv = PenalizedMSDeconVFitter()\ndistinct_pattern_fitter = DistinctPatternFitter()\n\n\nclass MassShiftSupportPostProcessorBase(object):\n\n def __init__(self, shifts=None):\n if shifts is None:\n shifts = []\n self.shifts = shifts\n self._fits = None\n\n @property\n def fits(self):\n return self._fits\n\n @fits.setter\n def fits(self, value):\n self._fits = value\n\n def reweight(self, fit, shift):\n pass\n", "meta": {"hexsha": "5ecd3b12b4c65b7f8d86d803e5e4e2515af6f28b", "size": 18878, "ext": "py", "lang": "Python", "max_stars_repo_path": "ms_deisotope/scoring.py", "max_stars_repo_name": "WEHI-Proteomics/ms_deisotope", "max_stars_repo_head_hexsha": "24a289a7903e033b8b6cf6e3a1e6931ab75668b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-26T04:12:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T04:12:51.000Z", "max_issues_repo_path": "ms_deisotope/scoring.py", "max_issues_repo_name": "WEHI-Proteomics/ms_deisotope", "max_issues_repo_head_hexsha": "24a289a7903e033b8b6cf6e3a1e6931ab75668b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ms_deisotope/scoring.py", "max_forks_repo_name": "WEHI-Proteomics/ms_deisotope", "max_forks_repo_head_hexsha": "24a289a7903e033b8b6cf6e3a1e6931ab75668b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3067993367, "max_line_length": 119, "alphanum_fraction": 0.6330649433, "include": true, "reason": "import numpy", "num_tokens": 4580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.20181322706107543, "lm_q1q2_score": 0.11189947384371879}} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport panel as pn\n\npn.extension(\"katex\", \"mathjax\")\n\n\n# ## Lecture 3- Groundwater as a reservoir ##\n# \n# _(The contents presented in this section were re-developed principally by [Prof. Peter Dietrich](https://www.ufz.de/index.php?de=37303) and Dr. P. K. Yadav. The original contents are from Prof. Rudolf Liedl)_\n# \n# ---\n# \n# The content of the previous section was dedicated to very fundamental properties, such as aquifer and its types, solid and liquid (water) volumes in an aquifer, a of subsurface.\n# \n# In this lecture, the subsurface will be considered from the perspective as a groundwater reservoir and some key definition and parameters will be introduced.\n# \n# \n# ### Groundwater and Aquifers\n# \n# \n# If the subterranean water completely fills the pore space we call it groundwater. In Germany a slightly different definition is in use. There, groundwater is only the subterranean water which is not subject to other forces than gravity (see Fig. below). That means, that the water adhesively bound to the grains is not part of the groundwater. Applicable forces in groundwater are sometime locally defined. For, e.g., In **Germany** the _gravity_ is the only force acting on groundwater, whereas forces such adhesion, cohesion along with gravity are considered internationally.\n# \n# \"Difference \n# \n# The difference between the international and the German definition of groundwater is the consideration of the adhesive water. Adhesive water does not participate in water movement. The same is true for water in isolated pores or in dead-end pores. All subterranean water not participating in water movement is summarized as immobile water. In contrast, the mobile water is the subterranean water participating in water movement.\n\n# In[2]:\n\n\np1 = pn.pane.Markdown(\"\"\"\nAbove the domain where the pore space is completely filled with water, there can may be an area with _partial water saturation._ \nThis domain is termed as **unsaturated** or **vadose** or **aeration** zone. In this zone, the subterranean water is named vadose \nor suspended water. The water content in the _unsaturated_ zone is quantified with the parameter **water saturation** **_(S)_** and can \nbe calculated as the ratio between the water-filled pore volume **_Vp,w_** and the total pore volume **_Vp_**, i.e.,\n\"\"\",width=400, style={\"text-align\": \"justify\"})\n\np2 = pn.pane.LaTeX(r\"\"\" \n$$\nS = \\frac{V_{p,w}}{V_p}\n$$\n\"\"\" ) \n\n\np3 = pn.pane.Markdown(\"\"\"\n**_S = 1_** in the saturated zone. The boundary between the unsaturated and the saturated zone is named as the **groundwater table** or **groundwater surface** \n(see Fig. at the side).\n\"\"\")\n\nvideo1 = pn.pane.Video(\"images/L03_f_4.mp4\", width=600, height=400, loop=False)\n\n\np4 = pn.Column(p1, p2, p3) \n\npn.Row(p4, pn.Spacer(width=50), video1)\n\n#\"Schematic\n\n\n# The volumetric share of pore, which can be occupied by mobile water, is termed effective porosity $n_e$ or flow-through porosity\n# \n# $$\n# n_e = \\frac{V_{p, m}}{V_T}\n# $$\n# \n# The effective porosity is dimensionless and the pore volume $V_{p,m}$ available for mobile water as well as the total volume $V_T$ has the dimension $L^3$. Effective porosity cannot exceed total porosity, i.e. $n_e \\leq n$. The difference $(n – n_e)$ is termed **specific retention** or **field capacity**. Specific retention is the volumetric share of water which is retained in the porous medium after drainage due to gravitation. The reason for retention is the adhesive force which bounds water at the grain surfaces. Because the available grain surface in a medium depends on the grain size, the effective porosity is also different for various materials. As shown in Figure (below) clay has a high total porosity but only a low effective porosity whereas the total porosity of cobbles is not so significant different from the effective porosity of this material.\n# \n# \"Porosity\n# \n\n# #### Example Problem\n# \n# Moist sand specimen = 72.5 cm$^3$ and its weight = 152 g\n# Oven dried sample = 71.2 cm$^3$ and its weight = 145 g\n# \n# Other available information:\n# Specific weight of particles $(\\gamma_s)$ = 2.65 g/cm$^3$\n# Specific weight of water $(\\gamma_w)$ = 1 g/cm$^3$\n# \n# Find, total porosity, void ratio, water content, degree of saturation and effective porosity.\n\n# In[3]:\n\n\n# solution\n\nV_ms = 72.5 # cm^3, volume moist sand\nW_ms = 152 # g, weight moist sand, also total volume\nV_ds = 71.2 # cm^3, volume dry sand\nW_ds = 145 # g, weight dey sand\n\n# Other info\ng_s = 2.65 # g/cm^3, sp. weight, particles\ng_w = 1 # g/cm^3, sp. wt. water\n\n# intermediate calculation\nV_w = (W_ms-W_ds)/g_w # cm^3, W_w/g_w; density = M/V\nV_s = W_ds/g_s # cm^3,\nV_v = V_ms - V_s # cm^2, volume of voids\nW_w = W_ms - W_ds # g, weight of water\n\n# results calculation\n\nn = V_v/V_ms*100 # %, Total porosity\ne = V_v/V_s *100 # %, void ratio\nw = W_w/W_ds *100 # %, moisture content \nS = V_w/V_v * 100 # %, degree of saturation \n\nprint(\"Total porosity is {0:0.2f}%\".format(n)) \nprint(\"Void ratio is {0:0.2f}%\".format(e)) \nprint(\"Moisture content is {0:0.2f}%\".format(w)) \nprint(\"Degree of saturation is {0:0.2f}%\".format(S)) \n\n\n# In[4]:\n\n\np5 = pn.pane.Markdown(\"\"\" ###Aquifer Classifications \"\"\")\n\np6 = pn.pane.Markdown(\"\"\"\nSubterranean formations can be classified by the capability to store and/or transmit groundwater under natural conditions. \n\n> An **aquifer** or a **groundwater reservoir** can store and transmit significant (= exploitable) amounts of groundwater. \n\n> An **aquitard** can store and transmit groundwater but to a much lesser extent than an (adjacent) aquifer. \n\n> An **aquiclude** can store groundwater but cannot transmit groundwater. \n\n> An **aquifuge**can neither store nor transmit groundwater.\n\nAquifers usually appear as **layers**, i.e. their lateral extent is rather large as \ncompared to their vertical extent (maybe 10 – 100 km vs. 10 – 100 m). The upper aquifer \nboundary is called **aquifer top**, and the lower boundary is called **aquifer bottom**.\nThe vertical distance between aquifer top and aquifer bottom is called **aquifer thickness**. \nUpper and lower aquifer boundaries do not have to be horizontal and the thickness may be \nspatially variable (see Fig. on the right).\n\n \"\"\", width=400, style={\"text-align\": \"justify\"})\n\np7 = pn.pane.Video(\"images/L03_f_6.mp4\", width=600, height=200, loop=False)\n\np8 = pn.Column(p5, p6)\npn.Row(p8, pn.Spacer(width=25), p7) \n\n\n# In[5]:\n\n\np9 = pn.pane.Markdown(\"\"\" ### Unconfined Aquifer \"\"\")\n\np10 = pn.pane.Markdown(\"\"\" An aquifer can be completely or only partially filled with groundwater (see Fig below). \nGroundwater or an aquifer is termed **unconfined (phreatic)**, if the groundwater does not \nextend up to the aquifer top. The position of the groundwater table is therefore changed \nduring water injection or extraction (“free“ groundwater table). Water in a borehole rises\nup to the groundwater table.\n\"\"\", width=600, style={\"text-align\": \"justify\"})\n\np11 = pn.pane.Video(\"images/L03_f_7.mp4\", width=400, height=200, loop=False) \np12 = pn.pane.Markdown(\"\"\" ### Confined Aquifer \"\"\")\n\np13 = pn.pane.Markdown(\"\"\" Groundwater or an aquifer is termed **confined**, if the aquifer \ncontains groundwater throughout its entire thickness. The pore space remains completely \nwater filled during water injection or (moderate) extraction. This requires a low permeable \ncover layer. In addition, the groundwater _recharge area_ must be located at higher altitude \nthan the aquifer top. The elevation of the _groundwater table_ in the recharge area defines \nthe position of the confined aquifer‘s pressure line. Water in a borehole rises up to the \npressure line (neglecting friction losses), i.e. higher than the elevation of the aquifer top.\n\"\"\", width=600, style={\"text-align\": \"justify\"})\n\np14 = pn.pane.Video(\"images/L03_f_8.mp4\", width=400, height=200, loop=False) \n\np15 = pn.pane.Markdown(\"\"\" ### Artesian Aquifer \"\"\")\np16 = pn.pane.Markdown(\"\"\" If the pressure line is above ground surface the we have an **artesian aquifer** \n(see Fig. below). In this case, the water in a borehole would rises up to the ground \nsurface and then forms a fountain. _Artesian springs_ and _Artesian wells_ are based on this principle. \nThe type of an aquifer can change along a cross section.\"\"\", width=600, style={\"text-align\": \"justify\"})\n\np17 = pn.pane.Video(\"images/L03_f_9.mp4\", width=400, height=200, loop=False) \n\npn.Column(p9, p10, p11, p12, p13, p14, p15, p16, p17) \n\n\n# #### Example\n# \n# | Aquifer | Obs. Point 1 | Obs. Point 2 | Obs. Point 3 | Obs. Point 4 |\n# |:-------:|:--------------:|:------------:|:------------:|:------------:|\n# | A | --- | --- | Unconfined | Unconfined |\n# | B | --- | Unconfined | Unconfined | Confined |\n# | C | Unconfined | Unconfined | Confined | Confined |\n# | D | Conf./Artesian | Confined | Confined | Confined |\n# \n# \"Aquifer \n# \n# _*perched aquifer_: Unconfined aquifer on top of another unconfined aquifer, separated from each other by a shallow aquitard \n\n# ### Pressure and pressure head\n# A reason for the movement of groundwater can be (hydrostatic) pressure difference. Let us consider a vertical column containing a porous medium and water filling the voids completely (Fig. below). We can assign to the top an arbitrary reference value pL for the pressure. Due to the load of the overlaying water column, the pressure increase if we go deeper into the column. This is the same as what we observe if we are diving in a lake. The increase of the pressure depends on the density of the fluid and the depth below the water surface. In the setup given in Fig., we have the (hydrostatic) pressure $p$ [M/L/T$^2$] as a function of the height $z$ [L] above the reference point\n# \n# $$\n# p(z) = p_L + \\rho \\cdot g \\cdot (L - z)\n# $$\n# \n# ```{margin} An optional title\n# with,
\n# $\\rho$ [M/L$^2$] as the fluid density,
\n# $g$ the acceleration of gravity [L/T$^2$], and
\n# L [L] the length of the water column\n# ```\n# \n# \"Pressure \n# \n# As shown in Fig., we can add two observation points, one at the bottom ($z = 0$) and the other at the top of the column $(z=L)$. The pressure difference $\\Delta p$ between the observation points is \n# \n# $$\n# \\Delta p = p(L) - p(0) = p_L - (p_L + \\rho\\cdot g \\cdot L) = - \\rho\\cdot g \\cdot L\n# $$\n# \n# **Example:** Compare the pressure difference for an experimental setup (pipe length 50 cm) in which water and diesel are the two liquids.\n\n# In[6]:\n\n\n# solution\nL_p = 50 # cm length of pipe\ng = 981 # cm/s^2, accl. due to gravity\n\n\n# Assume densities\nrho_w = 1.0 # g/cm^3, density of water\nrho_d = 0.830 # g/cm^3, density of diesel\n\n# calculate\nDp_w = rho_w*g*L_p # g/cm.s^2, pressure difference due to water\nDp_d = rho_d*g*L_p# g/cm.s^2, pressure difference due to water\nDp_w\nprint(\"The pressure difference due to water is {0:2.2f} g/cm.s\\u00b2,\".format(Dp_w), \n \"and that due to diesel is {0:0.2f} g/cm.s\\u00b2.\".format(Dp_d), ) \n\n\n# ### Hydrostatic pressure\n# \n# Mostly, pressure head is used instead of pressure when dealing with hydraulic properties or phenomena of the subsurface. The reason is that the pressure head can be easily measured with a tape whereas for a pressure measurement a more expensive manometer is necessary. The (hydrostatic) **pressure head** $\\psi$ [L] is defined as \n# \n# $$\n# \\psi(z) = \\psi_L + L - z\n# $$\n# \n# This expression makes it clear why we can measure the pressure head with a tape. Similar to pressure head, the hydrostatic pressure can be schematically represented as\n# \n# \"Pressure \n\n# ### Pressure in a Confined Aquifer\n# \n# Let us now consider a _confined aquifer_ (see Fig. below). The confining bed exerts a certain pressure $p_{cb}$ on the aquifer. This pressure is compensated partly by the porous medium and partly by the groundwater (pressures $p_{pm}$ and $p_w$, respectively). Therefore, we can write the following equation\n# \n# $$\n# p_{cb} + p_{pm} + p_w = 0\n# $$\n# \n# \"Pressure \n# \n# We can induce a _change in the hydrostatic pressure_ $\\Delta p_w$ with an injection or release of groundwater. According to the above equation we can formulate\n# \n# $$\n# \\Delta p_{cb} + \\Delta p_{pm} + \\Delta p_w = 0.\n# $$\n# \n# The hydrostatic pressure changes do not affect the weight of the confining bed and the exerted downward pressure remains unchanged. Therefore we have \n# \n# $$\n# \\Delta p_{cb} = 0 \\:\\:\\: \\text{and}\n# $$\n# \n# $$\n# \\Delta p_{pm} = -\\Delta p_w\n# $$\n# \n# This implies that an increase of hydrostatic pressure automatically results in a decrease in the pressure exerted by the porous medium. In the case of a decrease of hydrostatic the pressure exerted by the porous medium would increase. \n# The change in hydraulic pressure will have two effects with regard to water volume. First, the hydraulic pressure change $\\Delta p_w$ directly leads to expansion/compression of the water and the water volume is accordingly increased/decreased. Secondly, the opposite change $\\Delta p_{pm} = -\\Delta p_w$ leads to compression/expansion of the porous medium as a whole (not the individual grains!). This, in turn, results in a reduced/an enlarged pore space such that the stored water volume is decreased/ increased. Both effects contribute to aquifer storage properties (see next section). \n\n# ### Aquifer storage properties \n# \n# _Storage properties_ of the aquifer and associated parameters can be understood by considering pressure changes. For this purpose, we consider the effect of a _change in water volume_ $\\Delta V_w'$ due to a _change in hydrostatic pressure_. The _relative_ changes in water volume $\\Delta V_w'/\\Delta w$ [-] are proportional to change of pressure in groundwater $\\Delta p_w$:\n# \n# $$\n# \\frac{\\Delta V_w'}{V_w} = \\alpha_w \\cdot \\Delta p_w\n# $$\n# \n# with $\\alpha_w$ as the **compressibility of water** [LT$^2$/M]. The compressibility of water is roughly $4.4 \\cdot 10^{-10}$ m$^2$/N. Taking into account an incompressible behavior of the water, that means an increase in hydrostatic pressure results in an inflow of water. A decrease in hydrostatic pressure results would cause an outflow of water. The above equation can be rearranged to yield\n# \n# $$\n# \\Delta V_w' = \\alpha_w V_w \\Delta p_w = \\eta \\alpha_w V_T \\Delta p_w = \\eta \\alpha_w V_T \\rho_w g \\Delta \\psi\n# $$\n# With $\\eta$ [-] as the _total porosity_ and $\\Delta \\psi$ [L] as the _change in pressure head._\n# \n\n# ### Change in total volume\n# The preceding considerations dealt with a change in storage by inflow or outflow. The change was invoked by a change of pressure in groundwater $\\Delta p_w$. But a change could be also invoked by the change of the pressure exerted by the porous medium on the confining layer $\\Delta p_{pm}$. A change $\\Delta p_{pm}$ in the pressure results in a decrease or an increase $\\Delta V_T$ in total aquifer volume. Both quantities are proportional to each other via\n# \n# $$\n# \\frac{\\Delta V_T}{V_T} = - \\alpha_{pm} \\Delta p_{pm}\n# $$\n# \n# whereby the ratio is the relative change of the total volume and $\\alpha_{pm}$ the compressibility of the porous medium [LT$^2$/M]. The compressibility of the porous medium is roughly $10^{-10} - 10^{-8}$ m$^2$/N for gravel,\n# $10^{-9} - 10^{-7}$ m$^2$/N for sand, and $10^{-8} - 10^{-6}$ m$^2$/N for clay. Taking into account the relation between pressure and pressure head, the above equation can be rearranged to yield\n# \n# $$\n# \\Delta V_T = -\\alpha_{pm}V_T\\Delta p_{pm} = \\alpha_{pm}V_T\\Delta p_{pw} = \\alpha_{pm}V_T\\rho_w g \\Delta \\psi\n# $$\n# \n# $\\Delta V_T$ represents a _change in volume of the porous medium_ as a whole. It is composed of a change in volume $\\Delta V_s$ of the solids and another change $\\Delta V_w''$ in water volume. Because the change in volume of the solid is negligible, we can write\n# \n# $$\n# \\Delta V_T = \\Delta V_s + \\Delta V_w'' \\approx \\Delta V_w''\n# $$\n# \n# If we compare the last two equations we can immediately derive\n# \n# $$\n# \\Delta V_w'' = \\alpha_{pm} V_T\\rho_w g \\Delta\\psi\n# $$\n# \n# With words that means a _decrease of pressure_ in the porous medium leads to _an expansion of the porous medium_ and an associated _increase in water volume_ and enlarged pore space. An _increase in pressure_ in the porous medium would lead to a _compression_ of the porous medium and an associated _decrease_ in water volume and _reduced_ pore space.\n# \n# The _total_ change $\\Delta V_w$ in water volume consists of both effects caused by pressure changes $\\Delta p_{pm}$ and $\\Delta p_w$. Therefore we have \n# \n# $$\n# \\Delta V_w = \\Delta V_w' + \\Delta V_w''\n# $$\n# \n# Using the results derived before, we can express how $\\Delta V_w$ depends on changes $\\Delta \\psi$ in pressure head\n# \n# $$\n# \\Delta V_w = \\Delta V_w' + \\Delta V_w'' = \\eta \\alpha_w V_T \\rho_w g \\Delta \\psi + \\alpha_{pm} V_T \\rho_w g \\Delta \\psi\n# $$\n# \n# The _first term_ of the sum is related to changes in hydrostatic pressure $(\\Delta p_w)$ and the _second term_ to pressure changes in the porous medium $(\\Delta p_{pm})$.\n# \n# **Example:** The 45 m thick aquifer under the change of pressure 245 KPa compacts 0.20 m. What is the compressibility of porous media.\n\n# In[7]:\n\n\n# Available information\n\ndP = 245 # KPa= KN/m^2, Change pressure\nm = 45 # m, aquifer thickness\ndm = 0.20 # m, change in aquifer thickness\n\nprint(\"V = A*m and dV = A * dm \\n\")\n\n# Calculate\nal_pm = (dm/m)/dP # m^2/KN, compressibility of porous media.\n\nprint(\"The compressibility of porous media in aquifer {0:0.2e} m\\u00b2/KN.\".format(al_pm))\n\n\n# ### Specific storage\n# \n# For the characterization of the storage properties of an aquifer, we use the term **specific storage** $S_s$. It is defined as the volume of water that is released from a unit aquifer volume if hydrostatic pressure head is reduced by one unit\n# \n# $$\n# S_s = \\frac{\\Delta V_w}{V_T \\cdot \\Delta \\psi}\n# $$\n# \n# The dimension of _specific storage_ is 1/L. Both impacts on water volume discussed before have to be considered in order to quantify $\\Delta V_w$ in the above equation\n# \n# $$\n# \\Delta V_w = \\eta \\alpha_w V_T \\rho_w g \\Delta \\psi + \\alpha_{pm} V_T\\rho_w g \\Delta \\psi\n# $$\n# The specific storage can therefore also be expressed as \n# \n# $$\n# S_s = (\\eta \\alpha_w + \\alpha_{pm})\\rho_w g\n# $$\n# \n# Typical values for specific storage range from $10^{-6}$ 1/m (e.g. gravel) to $10^{-2}$ 1/m (e.g. clay).\n# \n\n# ### Storativity \n# \n# Due to their relatively large lateral extent, aquifers are mostly considered as spatially two-dimensional (2D) systems. In this case, specific storage $S_s$ is replaced by the **storativity** or **storage coefficient** $S$ (Fig. below). Reference volume in a confined aquifer for defining specific storage $S_s$ is a unit cube (e.g. $V_T = 1$ m$^3$), and for defining storativity $S$ is a cuboid extending from the aquifer bottom to the aquifer top over a unit area (e.g. $A = 1$ m$^2$ and $V_T = A\\cdot m$).\n# \n# For confined aquifers $S$ is simply obtained by multiplying $S_s$ by the aquifer thickness $m$\n# \n# $$\n# S = S_s \\cdot m\n# $$\n# \n# \"Reference \n# \n# \n# _Storativity_ can be interpreted as the volume of water released from an aquifer volume extending from the aquifer bottom up to the aquifer top over a unit area if the hydrostatic pressure is reduced by one unit. _Storativity_ is dimensionless.\n# \n# Actually, **unconfined** aquifers are always treated as 2D systems. As a consequence, storativity is used to quantify water storage properties. The definition of storativity remains unchanged in principle but the considered aquifer volume now extends from the aquifer bottom up to the water table. For _unconfined aquifers_, storativity values correspond to _effective porosities_. This is explained by the free groundwater table. In this case a pressure changes simply lead to filling or emptying of voids. This is fundamentally different from the storage properties of confined aquifers discussed before. \n# \n# In **confined** aquifers all voids remain filled with groundwater during pressure changes and storage properties depend on the compressibilities of water and the porous medium.\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "be825cf88204a26aad2bf60a9de249b2889be104", "size": 21031, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/contents/flow/lecture_03/13_gw_storage.py", "max_stars_repo_name": "prabhasyadav/iGW-I", "max_stars_repo_head_hexsha": "eba32830f32f1109a7bee600c65832af0e7183fa", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_build/jupyter_execute/contents/flow/lecture_03/13_gw_storage.py", "max_issues_repo_name": "prabhasyadav/iGW-I", "max_issues_repo_head_hexsha": "eba32830f32f1109a7bee600c65832af0e7183fa", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_build/jupyter_execute/contents/flow/lecture_03/13_gw_storage.py", "max_forks_repo_name": "prabhasyadav/iGW-I", "max_forks_repo_head_hexsha": "eba32830f32f1109a7bee600c65832af0e7183fa", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.1703163017, "max_line_length": 871, "alphanum_fraction": 0.7128524559, "include": true, "reason": "import numpy", "num_tokens": 5811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.320821300824607, "lm_q2_score": 0.348645142101806, "lm_q1q2_score": 0.11185278801528138}} {"text": "from __future__ import division\nfrom qm.dftbplus.dftbplus import DFTBplus\nfrom qm.dftbplus.dftbpar import spin_w, spin_w_lc, max_l\nfrom misc import au_to_A, call_name\nimport os, shutil, re, textwrap\nimport numpy as np\n\nclass SSR(DFTBplus):\n \"\"\" Class for SSR method of DFTB+\n\n :param object molecule: Molecule object\n :param boolean l_scc: Include self-consistent charge (SCC) scheme\n :param double scc_tol: Stopping criteria for the SCC iterations\n :param integer scc_max_iter: Maximum number of SCC iterations\n :param boolean l_onsite: Include onsite correction to SCC term\n :param boolean l_range_sep: Include long-range corrected functional\n :param string lc_method: Algorithms for LC-DFTB\n :param boolean l_ssr22: Use SSR(2,2) calculation?\n :param boolean l_ssr44: Use SSR(4,4) calculation?\n :param string guess: Initial guess method for SCC scheme\n :param string guess_file: Initial guess file for eigenvetors\n :param boolean l_state_interactions: Include state-interaction terms to SA-REKS\n :param double shift: Level shifting value in SCC iterations\n :param double,list tuning: Scaling factor for atomic spin constants\n :param string cpreks_grad_alg: Algorithms used in CP-REKS equations\n :param double cpreks_grad_tol: Tolerance used in the conjugate-gradient based algorithms\n :param boolean l_save_memory: Save memory in cache used in CP-REKS equations\n :param string embedding: Charge-charge embedding options\n :param boolean l_periodic: Use periodicity in the calculations\n :param double,list cell_length: The lattice vectors of periodic unit cell\n :param string sk_path: Path for Slater-Koster files\n :param string install_path: Path for DFTB+ install directory\n :param integer nthreads: Number of threads in the calculations\n :param string version: Version of DFTB+\n \"\"\"\n def __init__(self, molecule, l_scc=True, scc_tol=1E-6, scc_max_iter=1000, l_onsite=False, \\\n l_range_sep=False, lc_method=\"MatrixBased\", l_ssr22=False, l_ssr44=False, guess=\"h0\", \\\n guess_file=\"./eigenvec.bin\", l_state_interactions=False, shift=0.3, tuning=None, \\\n cpreks_grad_alg=\"pcg\", cpreks_grad_tol=1E-8, l_save_memory=False, embedding=None, \\\n l_periodic=False, cell_length=[0., 0., 0., 0., 0., 0., 0., 0., 0.], sk_path=\"./\", \\\n install_path=\"./\", nthreads=1, version=\"20.1\"):\n # Initialize DFTB+ common variables\n super(SSR, self).__init__(molecule, sk_path, install_path, nthreads, version)\n\n # Initialize DFTB+ SSR variables\n self.l_scc = l_scc\n self.scc_tol = scc_tol\n self.scc_max_iter = scc_max_iter\n\n self.l_onsite = l_onsite\n if (self.l_onsite):\n error_message = \"Onsite-correction not implemented!\"\n error_vars = f\"l_onsite = {self.l_onsite}\"\n raise ValueError (f\"( {self.qm_method}.{call_name()} ) {error_message} ( {error_vars} )\")\n\n self.l_range_sep = l_range_sep\n self.lc_method = lc_method.lower()\n\n self.l_ssr22 = l_ssr22\n # TODO : logical variable (l_ssr22, l_ssr44) must be changed for generality\n if (not self.l_ssr22):\n error_message = \"Use (2,2) active space for SSR!\"\n error_vars = f\"l_ssr22 = {self.l_ssr22}\"\n raise ValueError (f\"( {self.qm_method}.{call_name()} ) {error_message} ( {error_vars} )\")\n self.l_ssr44 = l_ssr44\n if (self.l_ssr44):\n error_message = \"(4,4) active space for SSR not implemented!\"\n error_vars = f\"l_ssr44 = {self.l_ssr44}\"\n raise ValueError (f\"( {self.qm_method}.{call_name()} ) {error_message} ( {error_vars} )\")\n\n # Set initial guess for eigenvectors\n self.guess = guess.lower()\n self.guess_file = guess_file\n if not (self.guess in [\"h0\", \"read\"]):\n error_message = \"Invalid initial guess for DFTB/SSR!\"\n error_vars = f\"guess = {self.guess}\"\n raise ValueError (f\"( {self.qm_method}.{call_name()} ) {error_message} ( {error_vars} )\")\n\n self.l_state_interactions = l_state_interactions\n self.shift = shift\n\n # Set scaling factor for atomic spin constants\n self.tuning = tuning\n if (self.tuning != None):\n if (len(self.tuning) != len(self.atom_type)):\n error_message = \"Number of elements for scaling factor must be equal to number of atom types!\"\n error_vars = f\"len(tuning) = {len(self.tuning)}, len(atom_type) = {len(self.atom_type)}\"\n raise ValueError (f\"( {self.qm_method}.{call_name()} ) {error_message} ( {error_vars} )\")\n\n self.cpreks_grad_alg = cpreks_grad_alg.lower()\n self.cpreks_grad_tol = cpreks_grad_tol\n self.l_save_memory = l_save_memory\n\n self.embedding = embedding\n if (self.embedding != None):\n self.embedding = self.embedding.lower()\n\n if not (self.embedding in [None, \"mechanical\", \"electrostatic\"]):\n error_message = \"Invalid charge embedding for QM/MM calculation!\"\n error_vars = f\"embedding = {self.embedding}\"\n raise ValueError (f\"( {self.qm_method}.{call_name()} ) {error_message} ( {error_vars} )\")\n\n self.l_periodic = l_periodic\n self.a_axis = np.copy(cell_length[0:3])\n self.b_axis = np.copy(cell_length[3:6])\n self.c_axis = np.copy(cell_length[6:9])\n\n # Set 'l_nacme' and 're_calc' with respect to the computational method\n # DFTB/SSR can produce NACs, so we do not need to get NACME from CIoverlap\n # DFTB/SSR can compute the gradient of several states simultaneously.\n molecule.l_nacme = False\n self.re_calc = False\n\n def get_data(self, molecule, base_dir, bo_list, dt, istep, calc_force_only):\n \"\"\" Extract energy, gradient and nonadiabatic couplings from SSR method\n\n :param object molecule: Molecule object\n :param string base_dir: Base directory\n :param integer,list bo_list: List of BO states for BO calculation\n :param double dt: Time interval\n :param integer istep: Current MD step\n :param boolean calc_force_only: Logical to decide whether calculate force only\n \"\"\"\n self.copy_files(istep)\n super().get_data(base_dir, calc_force_only)\n self.write_xyz(molecule)\n self.get_input(molecule, istep, bo_list)\n self.run_QM(base_dir, istep, bo_list)\n self.extract_QM(molecule, bo_list)\n self.move_dir(base_dir)\n\n def copy_files(self, istep):\n \"\"\" Copy necessary scratch files in previous step\n\n :param integer istep: Current MD step\n \"\"\"\n # Copy required files to read initial guess\n if (self.guess == \"read\" and istep >= 0):\n # After T = 0.0 s\n shutil.copy(os.path.join(self.scr_qm_dir, \"eigenvec.bin\"), \\\n os.path.join(self.scr_qm_dir, \"../eigenvec.bin.pre\"))\n\n def get_input(self, molecule, istep, bo_list):\n \"\"\" Generate DFTB+ input files: geometry.gen, dftb_in.hsd\n\n :param object molecule: Molecule object\n :param integer istep: Current MD step\n :param integer,list bo_list: List of BO states for BO calculation\n \"\"\"\n # Make 'geometry.gen' file\n os.system(\"xyz2gen geometry.xyz\")\n if (self.l_periodic):\n # Substitute C to S in first line\n file_be = open('geometry.gen', 'r')\n file_af = open('tmp.gen', 'w')\n first_row = True\n for row in file_be:\n if (first_row):\n row = f'{molecule.nat_qm} S\\n'\n first_row = False\n file_af.write(row)\n # Add gamma-point and cell lattice information\n geom_periodic = textwrap.dedent(f\"\"\"\\\n {0.0:15.8f} {0.0:15.8f} {0.0:15.8f}\n {self.a_axis[0]:15.8f} {self.a_axis[1]:15.8f} {self.a_axis[2]:15.8f}\n {self.b_axis[0]:15.8f} {self.b_axis[1]:15.8f} {self.b_axis[2]:15.8f}\n {self.c_axis[0]:15.8f} {self.c_axis[1]:15.8f} {self.c_axis[2]:15.8f}\n \"\"\")\n file_af.write(geom_periodic)\n file_be.close()\n file_af.close()\n os.rename('tmp.gen', 'geometry.gen')\n\n # Make 'point_charges.xyz' file used in electrostatic charge embedding of QM/MM\n if (self.embedding == \"electrostatic\"):\n # Make 'point_charges.xyz' file\n input_geom_pc = \"\"\n for iat in range(molecule.nat_qm, molecule.nat):\n input_geom_pc += \"\".join([f\"{i:15.8f}\" for i in molecule.pos[iat] * au_to_A])\n input_geom_pc += f\" {molecule.mm_charge[iat - molecule.nat_qm]:8.4f}\\n\"\n\n # Write 'point_charges.xyz' file\n file_name = \"point_charges.xyz\"\n with open(file_name, \"w\") as f:\n f.write(input_geom_pc)\n\n # Make 'dftb_in.hsd' file\n input_dftb = \"\"\n\n # Geometry Block\n input_geom = textwrap.dedent(f\"\"\"\\\n Geometry = GenFormat{{\n <<< 'geometry.gen'\n }}\n \"\"\")\n input_dftb += input_geom\n\n # Hamiltonian Block\n input_ham_init = textwrap.dedent(f\"\"\"\\\n Hamiltonian = DFTB{{\n \"\"\")\n input_dftb += input_ham_init\n\n # SCC-DFTB option\n if (self.l_scc):\n input_ham_scc = textwrap.indent(textwrap.dedent(f\"\"\"\\\n SCC = Yes\n SCCTolerance = {self.scc_tol}\n MaxSCCIterations = {self.scc_max_iter}\n \"\"\"), \" \")\n input_dftb += input_ham_scc\n\n # Read atomic spin constants used in DFTB/SSR\n if (self.l_range_sep):\n spin_constant = (\"\\n\" + \" \" * 14).join([f\" {itype} = {{ {spin_w_lc[f'{itype}']} }}\" for itype in self.atom_type])\n else:\n spin_constant = (\"\\n\" + \" \" * 14).join([f\" {itype} = {{ {spin_w[f'{itype}']} }}\" for itype in self.atom_type])\n input_ham_spin = textwrap.indent(textwrap.dedent(f\"\"\"\\\n SpinConstants = {{\n ShellResolvedSpin = Yes\n {spin_constant}\n }}\n \"\"\"), \" \")\n input_dftb += input_ham_spin\n\n # Long-range corrected DFTB (LC-DFTB) option\n if (self.l_range_sep):\n input_ham_lc = textwrap.indent(textwrap.dedent(f\"\"\"\\\n RangeSeparated = LC{{\n Screening = {self.lc_method}{{}}\n }}\n \"\"\"), \" \")\n input_dftb += input_ham_lc\n\n # Add point charges to Hamiltonian used in electrostatic charge embedding of QM/MM\n if (self.embedding == \"electrostatic\"):\n input_ham_pc = textwrap.indent(textwrap.dedent(f\"\"\"\\\n ElectricField = PointCharges{{\n CoordsAndCharges [Angstrom] = DirectRead{{\n Records = {molecule.nat_mm}\n File = \"point_charges.xyz\"\n }}\n }}\n \"\"\"), \" \")\n input_dftb += input_ham_pc\n\n if (self.l_periodic):\n input_ham_periodic = textwrap.indent(textwrap.dedent(f\"\"\"\\\n KPointsAndWeights = {{\n 0.0 0.0 0.0 1.0\n }}\n \"\"\"), \" \")\n input_dftb += input_ham_periodic\n\n angular_momentum = (\"\\n\" + \" \" * 10).join([f\" {itype} = '{max_l[f'{itype}']}'\" for itype in self.atom_type])\n input_ham_basic = textwrap.dedent(f\"\"\"\\\n Charge = {molecule.charge}\n MaxAngularMomentum = {{\n {angular_momentum}\n }}\n SlaterKosterFiles = Type2FileNames{{\n Prefix = '{self.sk_path}'\n Separator = '-'\n Suffix = '.skf'\n LowerCaseTypeName = No\n }}\n }}\n \"\"\")\n input_dftb += input_ham_basic\n\n # Analysis Block\n input_analysis = textwrap.dedent(f\"\"\"\\\n Analysis = {{\n CalculateForces = Yes\n WriteBandOut = Yes\n WriteEigenvectors = Yes\n MullikenAnalysis = Yes\n }}\n \"\"\")\n input_dftb += input_analysis\n\n # Options Block\n input_options = textwrap.dedent(f\"\"\"\\\n Options = {{\n WriteDetailedXml = Yes\n WriteDetailedOut = Yes\n TimingVerbosity = -1\n }}\n \"\"\")\n input_dftb += input_options\n\n # REKS Block\n\n # Energy functional options\n if (self.l_ssr22):\n # Set active space and energy functional used in SA-REKS\n space = \"SSR22\"\n if (molecule.nst == 1):\n energy_functional = \"{ 'PPS' }\"\n all_states = \"No\"\n elif (molecule.nst == 2):\n energy_functional = \"{ 'PPS' 'OSS' }\"\n all_states = \"No\"\n elif (molecule.nst == 3):\n energy_functional = \"{ 'PPS' 'OSS' }\"\n all_states = \"Yes\"\n else:\n error_message = \"SSR(2,2) can calculate up to 3 electronic states!\"\n error_vars = f\"Molecule.nstates = {molecule.nst}\"\n raise ValueError (f\"( {self.qm_method}.{call_name()} ) {error_message} ( {error_vars} )\")\n\n # Include state-interaction terms to SA-REKS; SI-SA-REKS\n if (self.l_state_interactions):\n do_ssr = \"Yes\"\n else:\n do_ssr = \"No\"\n\n # Read 'eigenvec.bin' from previous step\n if (self.guess == \"read\"):\n if (istep == -1):\n if (os.path.isfile(self.guess_file)):\n # Copy guess file to currect directory\n shutil.copy(self.guess_file, os.path.join(self.scr_qm_dir, \"eigenvec.bin\"))\n restart = \"Yes\"\n else:\n restart = \"No\"\n elif (istep >= 0):\n # Move previous file to currect directory\n os.rename(\"../eigenvec.bin.pre\", \"./eigenvec.bin\")\n restart = \"Yes\"\n elif (self.guess == \"h0\"):\n restart = \"No\"\n\n # Scale the atomic spin constants\n if (self.tuning != None):\n spin_tuning = \"\"\n spin_tuning += \"{\"\n for scale_W in self.tuning:\n spin_tuning += f\" {scale_W} \"\n spin_tuning += \"}\"\n else:\n spin_tuning = \"{}\"\n\n # CP-REKS algorithm options\n if (self.cpreks_grad_alg == \"pcg\"):\n cpreks_alg = \"ConjugateGradient\"\n preconditioner = \"Yes\"\n elif (self.cpreks_grad_alg == \"cg\"):\n cpreks_alg = \"ConjugateGradient\"\n preconditioner = \"No\"\n elif (self.cpreks_grad_alg == \"direct\"):\n cpreks_alg = \"Direct\"\n preconditioner = \"No\"\n else:\n error_message = \"Invalid algorithms for CP-REKS problem!\"\n error_vars = f\"cpreks_grad_alg = {self.cpreks_grad_alg}\"\n raise ValueError (f\"( {self.qm_method}.{call_name()} ) {error_message} ( {error_vars} )\")\n\n # Save memory in cache to reduce computational cost in CP-REKS\n if (self.l_save_memory):\n memory = \"Yes\"\n else:\n memory = \"No\"\n \n # NAC calculation options\n if (molecule.nst == 1 or not self.l_state_interactions):\n # Single-state REKS or SA-REKS state\n self.nac = \"No\"\n else:\n # SSR state\n if (self.calc_coupling):\n # SHXF, SH, Eh need NAC calculations\n self.nac = \"Yes\"\n else:\n # BOMD do not need NAC calculations\n self.nac = \"No\"\n\n # Relaxed density options; It is determined automatically\n if (molecule.l_qmmm and self.embedding == \"electrostatic\"):\n relaxed_density = \"Yes\"\n else:\n relaxed_density = \"No\"\n\n input_reks = textwrap.dedent(f\"\"\"\\\n REKS = {space}{{\n Energy = {{\n Functional = {energy_functional}\n StateInteractions = {do_ssr}\n IncludeAllStates = {all_states}\n }}\n TargetState = {bo_list[0] + 1}\n ReadEigenvectors = {restart}\n FONmaxIter = 50\n shift = {self.shift}\n SpinTuning = {spin_tuning}\n Gradient = {cpreks_alg}{{\n CGmaxIter = 100\n Tolerance = {self.cpreks_grad_tol}\n Preconditioner = {preconditioner}\n SaveMemory = {memory}\n }}\n RelaxedDensity = {relaxed_density}\n NonAdiabaticCoupling = {self.nac}\n VerbosityLevel = 1\n }}\n \"\"\")\n input_dftb += input_reks\n\n # ParserOptions Block\n if (self.version == \"19.1\"):\n error_message = \"SSR not implemented in this version!\"\n error_vars = f\"version = {self.version}\"\n raise ValueError (f\"( {self.qm_method}.{call_name()} ) {error_message} ( {error_vars} )\")\n elif (self.version == \"20.1\"):\n parser_version = 8\n\n input_parseroptions = textwrap.dedent(f\"\"\"\\\n ParserOptions = {{\n ParserVersion = {parser_version}\n }}\n \"\"\")\n input_dftb += input_parseroptions\n\n # Write 'dftb_in.hsd' file\n file_name = \"dftb_in.hsd\"\n with open(file_name, \"w\") as f:\n f.write(input_dftb)\n\n def run_QM(self, base_dir, istep, bo_list):\n \"\"\" Run SSR calculation and save the output files to qm_log directory\n\n :param string base_dir: Base directory\n :param integer istep: Current MD step\n :param integer,list bo_list: List of BO states for BO calculation\n \"\"\"\n # Set run command\n qm_command = os.path.join(self.qm_path, \"dftb+\")\n # OpenMP setting\n os.environ[\"OMP_NUM_THREADS\"] = f\"{self.nthreads}\"\n command = f\"{qm_command} > log\"\n # Run DFTB+ method for molecular dynamics\n os.system(command)\n\n # Copy the output file to 'qm_log' directory\n tmp_dir = os.path.join(base_dir, \"qm_log\")\n if (os.path.exists(tmp_dir)):\n log_step = f\"log.{istep + 1}.{bo_list[0]}\"\n shutil.copy(\"log\", os.path.join(tmp_dir, log_step))\n\n def extract_QM(self, molecule, bo_list):\n \"\"\" Read the output files to get BO information\n\n :param object molecule: Molecule object\n :param integer,list bo_list: List of BO states for BO calculation\n \"\"\"\n # Read 'log' file\n file_name = \"log\"\n with open(file_name, \"r\") as f:\n log_out = f.read()\n\n # Read 'detailed.out' file\n file_name = \"detailed.out\"\n with open(file_name, \"r\") as f:\n detailed_out = f.read()\n\n # Energy\n if (molecule.nst == 1):\n # Single-state REKS\n tmp_e = 'Spin' + '\\n\\s+\\w+\\s+([-]\\S+)(?:\\s+\\S+){3}' * molecule.nst\n energy = re.findall(tmp_e, log_out)\n energy = np.array(energy, dtype=np.float64)\n else:\n if (self.l_state_interactions):\n # SSR state\n energy = re.findall('SSR state\\s+\\S+\\s+([-]\\S+)', log_out)\n energy = np.array(energy, dtype=np.float64)\n else:\n # SA-REKS state\n tmp_e = 'Spin' + '\\n\\s+\\w+\\s+([-]\\S+)(?:\\s+\\S+){3}' * molecule.nst\n energy = re.findall(tmp_e, log_out)\n energy = np.array(energy[0], dtype=np.float64)\n\n for ist in range(molecule.nst):\n molecule.states[ist].energy = energy[ist]\n\n # Force\n if (self.nac == \"Yes\"):\n # SHXF, SH, Eh : SSR state\n if (molecule.l_qmmm):\n for ist in range(molecule.nst):\n tmp_g = f' {ist + 1} st state \\(SSR\\)' + '\\n\\s+([-]*\\S+)\\s+([-]*\\S+)\\s+([-]*\\S+)' * molecule.nat_qm\n grad = re.findall(tmp_g, log_out)\n grad = np.array(grad[0], dtype=np.float64)\n grad = grad.reshape(molecule.nat_qm, 3, order='C')\n molecule.states[ist].force[0:molecule.nat_qm] = - grad\n if (self.embedding == \"electrostatic\"):\n tmp_f = 'Forces on external charges' + '\\n\\s+([-]*\\S+)\\s+([-]*\\S+)\\s+([-]*\\S+)' * molecule.nat_mm\n force = re.findall(tmp_f, detailed_out)\n force = np.array(force[0], dtype=np.float64)\n force = force.reshape(molecule.nat_mm, 3, order='C')\n molecule.states[ist].force[molecule.nat_qm:molecule.nat] = force\n else:\n for ist in range(molecule.nst):\n tmp_g = f' {ist + 1} st state \\(SSR\\)' + '\\n\\s+([-]*\\S+)\\s+([-]*\\S+)\\s+([-]*\\S+)' * molecule.nat_qm\n grad = re.findall(tmp_g, log_out)\n grad = np.array(grad[0], dtype=np.float64)\n grad = grad.reshape(molecule.nat_qm, 3, order='C')\n molecule.states[ist].force = - np.copy(grad)\n else:\n # BOMD : SSR state, SA-REKS state or single-state REKS\n if (molecule.l_qmmm):\n tmp_g = f' {bo_list[0] + 1} state \\(\\w+[-]*\\w+\\)' + '\\n\\s+([-]*\\S+)\\s+([-]*\\S+)\\s+([-]*\\S+)' * molecule.nat_qm\n grad = re.findall(tmp_g, log_out)\n grad = np.array(grad[0], dtype=np.float64)\n grad = grad.reshape(molecule.nat_qm, 3, order='C')\n molecule.states[bo_list[0]].force[0:molecule.nat_qm] = - grad\n if (self.embedding == \"electrostatic\"):\n tmp_f = 'Forces on external charges' + '\\n\\s+([-]*\\S+)\\s+([-]*\\S+)\\s+([-]*\\S+)' * molecule.nat_mm\n force = re.findall(tmp_f, detailed_out)\n force = np.array(force[0], dtype=np.float64)\n force = force.reshape(molecule.nat_mm, 3, order='C')\n molecule.states[bo_list[0]].force[molecule.nat_qm:molecule.nat] = force\n else:\n tmp_g = f' {bo_list[0] + 1} state \\(\\w+[-]*\\w+\\)' + '\\n\\s+([-]*\\S+)\\s+([-]*\\S+)\\s+([-]*\\S+)' * molecule.nat_qm\n grad = re.findall(tmp_g, log_out)\n grad = np.array(grad[0], dtype=np.float64)\n grad = grad.reshape(molecule.nat_qm, 3, order='C')\n molecule.states[bo_list[0]].force = - np.copy(grad)\n\n # NAC\n if (self.nac == \"Yes\"):\n kst = 0\n for ist in range(molecule.nst):\n for jst in range(ist + 1, molecule.nst):\n tmp_c = 'non-adiabatic coupling' + '\\n\\s+([-]*\\S+)\\s+([-]*\\S+)\\s+([-]*\\S+)' * molecule.nat_qm\n nac = re.findall(tmp_c, log_out)\n nac = np.array(nac[kst], dtype=np.float64)\n nac = nac.reshape(molecule.nat_qm, 3, order='C')\n molecule.nac[ist, jst] = nac\n molecule.nac[jst, ist] = - nac\n kst += 1\n\n\n", "meta": {"hexsha": "d4e564c5336552b54ccf57efefcb1d3c46eca856", "size": 23244, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/qm/dftbplus/ssr.py", "max_stars_repo_name": "jkha-unist/unixmd", "max_stars_repo_head_hexsha": "164eabc9969acb285096513119af6caea485748c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-04-18T08:03:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T03:29:54.000Z", "max_issues_repo_path": "src/qm/dftbplus/ssr.py", "max_issues_repo_name": "jkha-unist/unixmd", "max_issues_repo_head_hexsha": "164eabc9969acb285096513119af6caea485748c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2021-04-14T08:43:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T10:26:42.000Z", "max_forks_repo_path": "src/qm/dftbplus/ssr.py", "max_forks_repo_name": "jkha-unist/unixmd", "max_forks_repo_head_hexsha": "164eabc9969acb285096513119af6caea485748c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2021-04-14T05:59:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T03:05:23.000Z", "avg_line_length": 42.7279411765, "max_line_length": 130, "alphanum_fraction": 0.5442694889, "include": true, "reason": "import numpy", "num_tokens": 5965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.22000709463169618, "lm_q1q2_score": 0.11086293254508704}} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# pylama:ignore=D213,D400,E501,E221,D103,D205,D209,E124,E127,E128\n\n\"\"\"Find optimal nutritional combinations\n\nThis optimizer assumes that the foods to be targeted are in the file\nfoods.jsontxt.gz as created by build_foods.sh. That means that each line is the\nJSON representation of a record as created by nndb-import (see\nhttps://github.com/CraigKelly/nndb-import)\n\"\"\"\n\nimport sys\nimport gzip\n\nfrom functools import partial\n\n# Try to use various speedy json libraries then fall back to stdlib\ntry:\n import ujson as json\nexcept:\n try:\n sys.stderr.write(\"No ujson, trying cjson\\n\")\n import cjson as json\n except:\n sys.stderr.write(\"No cjson, using stdlib json\\n\")\n import json\n\n\nimport scipy\nimport scipy.stats\nsp = scipy\nstats = sp.stats\n\nfrom micro_reqs import ALL_MICROS #NOQA\n\n\n# Parameters we use\nINIT_RANDOMS = 10000 # Initial random members of population\nRND_EXP_ENTRIES = 4 # Exp value for # of non-zero entries\nMAX_AMT = 5.0 # Non-zero entry max value\nPOP_SIZE = 200 # Pop size (after initial population)\nMUTATE_RATE = 0.20 # Rate at which entry is mutated\nMUTATE_BIG = MUTATE_RATE * 0.20 # Part of mutate rate, chance of \"big\" mutation\nIMMORTALS = 5 # Number of pop members that carry over\nMERGE_SIZE = 4 # Number of solutions we sample for merge\nSPARSITY_MAX = (RND_EXP_ENTRIES-1) * (MAX_AMT*0.75)\n\n\n# We pre-define random routines so that we can swap out (Python's native\n# Mersenne twister is fine but a little slow for what we're doing)\nrandrange = partial(sp.random.randint, 0)\nrand = sp.random.rand\n\n\ndef choice(lst):\n return lst[randrange(len(lst))]\n\n\n# Simple logistic function for scipy arrays\ndef logistic(spa):\n return 1.0 / (1.0 + scipy.exp(-spa))\n\n\n# Simple logging stand-in\ndef info(s, *args):\n if args:\n s = s % args\n print(s)\n\n\nFILTER_WORDS = [i.replace('\\s', ' ') for i in \"\"\"\n applesauce mashed\n bacon meatless\n beverage millet\n breaded nectar\n bulgur noodles\n candied oil-roasted\n catsup pork\n celery\\sflakes\n chili products\n chowchow puffs\n cocktail ranch\n cilantro\n cornmeal relish\n cornstarch rice\n couscous soymilk\n dehydrated spaghetti\n flour spread\n franks succotash\n fried syrup\n groats tapioca\n hash brown taro\n hominy tomato\\sproducts\n hummus vegetables\n juice vegetarian\n lambsquarters veggie\n liquid\\sfrom vermicelli\n macaroni wheat\n\"\"\".split()]\n\nFILTER_SPLITS = [\"sweet\", \"sweetened\" \"wheat\", ]\n\n\ndef food_filter(line):\n line = line.strip()\n if not line:\n return None\n\n food = json.loads(line)\n if not food:\n return None\n\n descrip = food.get('descrip', '').lower()\n if not descrip:\n return None\n\n for word in FILTER_WORDS:\n if word in descrip:\n return None\n\n parts = descrip.split(',')\n for part in parts:\n part = part.strip()\n if not part:\n continue\n for check in FILTER_SPLITS:\n if check == part:\n return None\n\n return food\n\n\ndef read_foods(filename):\n # Test show zcat subprocess MUCH faster then `with gzip.open(filename, 'r')`\n with gzip.open(filename) as fh:\n for line in fh:\n food = food_filter(line.decode('utf-8'))\n if food:\n yield food\n\n\ndef extract_nutrients(food):\n contains = dict(\n (n[\"nutrient_id\"], n[\"nutrient_val\"]) for n in food[\"nutrients\"]\n )\n return [contains.get(nid, 0.0) for _, nid, _, _, _ in ALL_MICROS]\n\n\nclass opt_engine(object):\n \"\"\"Given a list of food objects from our file, perform the various\n optmization functions we want\n \"\"\"\n\n def __init__(self, food_details):\n \"\"\"Load initial matrices and create initial expanded population.\"\"\"\n self.food_details = food_details\n self.food_count = len(food_details)\n\n # We want our random instances to have an expected number of entries\n # equal to RND_EXP_ENTRIES, which for Binomial(n,p) is np. So we know\n # p is RND_EXP_ENTRIES/n\n self.rnd_entries = partial(\n stats.binom.rvs,\n self.food_count,\n float(RND_EXP_ENTRIES) / float(self.food_count)\n )\n\n # |foods| x |nutrients| 2-d array\n self.foods = sp.array([extract_nutrients(f) for f in food_details])\n\n # RDA and UL vectors\n self.RDA, self.UL = [], []\n for _, _, _, r, u in ALL_MICROS:\n self.RDA.append(r)\n self.UL.append(u)\n self.RDA, self.UL = sp.array(self.RDA), sp.array(self.UL)\n\n # Our first generation contains all single foods and INIT_RANDOMS\n # inital random entries\n pop = []\n for i in range(self.food_count):\n one = [0.0] * self.food_count\n one[i] = 1.0\n pop.append(list(one))\n\n for _ in range(INIT_RANDOMS):\n pop.append(self.rand_inst())\n\n self.set_pop(pop)\n self.last_population = []\n self.last_popnutrition = []\n\n def set_pop(self, pop):\n \"\"\"Directly set population and recalc the pop-nutrition grid.\"\"\"\n # |members| x |foods| 2-d array\n self.population = sp.array(pop)\n self.popnutrition = sp.dot(self.population, self.foods)\n\n def rand_inst(self):\n \"\"\"Return a random instance based on RND_EXP_ENTRIES and current foods.\"\"\"\n inst = [0.0] * self.food_count\n\n entries = self.rnd_entries()\n if entries < 1:\n entries = RND_EXP_ENTRIES # extra boost to our average\n\n idxs = set([randrange(len(inst))])\n while len(idxs) < entries:\n idxs.add(randrange(len(inst)))\n\n for idx in idxs:\n inst[idx] = choice([0.5, 1.0, 1.5, 2.0])\n\n return inst\n\n def calories(self, inst):\n \"\"\"Given an instance, return the total calories and the total g's of sugar.\"\"\"\n total_cals = 0.0\n total_sugar = 0.0\n\n for idx, amt in enumerate(inst):\n if abs(amt - 0.0) < 0.00001:\n continue\n\n food = self.food_details[idx]\n\n for n in food[\"nutrients\"]:\n if n[\"nutrient_id\"] == \"208\":\n total_cals += float(n[\"nutrient_val\"]) * amt\n if n[\"nutrient_id\"] == \"269\":\n total_sugar += float(n[\"nutrient_val\"]) * amt\n\n return total_cals, total_sugar\n\n SCORE_WEIGHTS = sp.array([\n 2.0, # RDA\n 1.0, # nutrient per gram\n 1.8, # UL\n 1.5, # cals/gram\n 1.2, # sparsity\n 1.0, # sugar\n ])\n\n def score(self, inst, nutr):\n \"\"\"Return a fitness score and the originating score vector for the given\n instance and it's nutrition space vector.\"\"\"\n assert len(inst) == self.foods.shape[0]\n assert len(nutr) == self.foods.shape[1]\n assert len(self.RDA) == len(self.UL) == len(nutr)\n\n # Figure any nutrients above the upper limit in percentage units.\n too_much = (nutr - self.UL) / self.UL\n calories, sugar = self.calories(inst)\n grams = 100.0 * inst.sum() # Our database measures everything in 100g units\n\n # nutrient as percent of RDA, clipped to remove advantage for going over\n nutr_scores = sp.clip(nutr / self.RDA, 0.0, 1.01)\n\n components = self.SCORE_WEIGHTS * sp.array([\n # good stuff (note that we want to MINIMIZE our score\n 0.0 - nutr_scores.mean(), # RDA, but no credit for going over\n 0.0 - (nutr_scores.sum() / grams), # Nutrient score per gram\n\n # bad stuff\n too_much[too_much > -0.01].sum(), # UL, but only as we get high\n logistic(calories / grams), # cals per gram\n logistic(len(inst[inst > 0]) / float(RND_EXP_ENTRIES)), # Simpler is better\n logistic(sugar) # sugar is bad, mmm-kay\n ])\n\n return components.mean(), components\n\n def mutate(self, inst): #NOQA\n \"\"\"Return a mutated copy of the given instance\"\"\"\n rnd_inst = list(inst)\n\n for idx, val in enumerate(inst):\n roll = rand()\n if roll > MUTATE_RATE:\n continue # No mutation here\n\n if roll < MUTATE_BIG and val > 0.0:\n # Swapping with blank index - find the other, do the swap, and leave\n blank_idx = randrange(len(inst))\n while inst[blank_idx] > 0.0:\n blank_idx = randrange(len(inst))\n rnd_inst[idx], rnd_inst[blank_idx] = rnd_inst[blank_idx], rnd_inst[idx]\n continue\n\n if roll < MUTATE_BIG:\n modifier = choice([1.5, 1.75, 2.0, 2.25]) # Big jump\n else:\n modifier = choice([0.25, 0.5, .75, 1.0, 1.25]) # Regular jump\n\n if val <= 0.0:\n val = modifier\n else:\n val = sp.clip(val + (choice([-1.0, 1.0]) * modifier), 0.0, MAX_AMT)\n\n rnd_inst[idx] = val\n\n # All of this is great, but we tend to just get bigger and bigger - we want\n # lots of sparsity AND a low total sum\n while sum(rnd_inst) > SPARSITY_MAX:\n for idx in range(len(rnd_inst)):\n if rnd_inst[idx] <= 0.1:\n rnd_inst[idx] = 0.0\n elif rand() < 0.70:\n rnd_inst[idx] *= 0.5\n else:\n rnd_inst[idx] = 0.0\n\n return rnd_inst\n\n def crossover(self, inst1, inst2):\n \"\"\"Return a new instance via cross over with the 2 given instances.\"\"\"\n return [x if rand() < 0.5 else y for x, y in zip(inst1, inst2)]\n\n def winner(self):\n \"\"\"Currently, chose a winner from the population with tournament sel.\"\"\"\n idx1 = randrange(len(self.population))\n idx2 = randrange(len(self.population))\n return min(idx1, idx2)\n\n def generation(self):\n \"\"\"Do a single generation of work.\"\"\"\n all_scored = []\n for inst, nutr in zip(self.population, self.popnutrition):\n score, score_vector = self.score(inst, nutr)\n all_scored.append((score, inst))\n\n all_scored.sort(key=lambda one: one[0])\n\n # Keep previous generation in sorted order\n self.last_population = sp.array([inst for _, inst in all_scored])\n self.last_popnutrition = sp.dot(self.last_population, self.foods)\n\n # Now we are creating the next generation\n\n # Don't add dups to a generation\n new_gen = []\n seen = set()\n\n def add_to_gen(inst):\n key = tuple(inst)\n if key in seen:\n return\n seen.add(key)\n new_gen.append(inst)\n\n # Keep top N entries, top N entries with mutations, and top N entries with\n # one-off removed and then mutated\n for score, inst in all_scored[:IMMORTALS]:\n # top entries\n add_to_gen(inst)\n # mutated\n add_to_gen(self.mutate(inst))\n # one-off removed and then mutated\n for idx, val in enumerate(inst):\n if val > 0.0:\n one_off = list(inst)\n one_off[idx] = 0.0\n add_to_gen(one_off)\n add_to_gen(self.mutate(one_off))\n\n # Fill out the rest of the generation\n # Note we're actually TRIPLE our population size - We use the population\n # size for new random entries, tradition select/crossover/mutate entries,\n # and sample/sum/mutate entries. (NOte our sample/sum/mutate works because\n # our mutate routine has a final \"re-balance + force sparsity step\"\n for _ in range(POP_SIZE):\n # simple random entry\n add_to_gen(self.rand_inst())\n\n # Merged entry\n merged = sp.array(self.population[self.winner()])\n for _ in range(MERGE_SIZE-1):\n merged += sp.array(self.population[self.winner()])\n add_to_gen(self.mutate(list(merged)))\n\n # \"Normal\" creation via selection, crossover/breeding. and mutation\n add_to_gen(self.mutate(self.crossover(\n self.population[self.winner()],\n self.population[self.winner()]\n )))\n\n # Have a new generation\n self.set_pop(new_gen)\n\n def dump_instance(self, inst, nutr, info=info):\n \"\"\"Given an instance and it's nutritional space vector (just like score),\n output a decent, printable representation of the instance\n \"\"\"\n score, score_vector = self.score(inst, nutr)\n info(\"Solution with score %12.4f (vector %s)\", score, score_vector)\n for mic, amt in zip(ALL_MICROS, nutr):\n name, _, units, rda, ul = mic\n info(\" NUTR %-15s: %8.2f %-5s, %8.2f%% of RDA %8.2f (UL %8.2f)\",\n name, amt, units, (amt/rda)*100.0, rda, ul\n )\n\n total_cals = 0.0\n\n for idx, amt in enumerate(inst):\n if abs(amt - 0.0) < 0.00001:\n continue\n\n food = self.food_details[idx]\n\n cals = '?'*8\n for n in food[\"nutrients\"]:\n if n[\"nutrient_id\"] == \"208\":\n cals = float(n[\"nutrient_val\"]) * amt\n total_cals += cals\n cals = \"%8.2f\" % cals\n break\n\n info(\" FOOD %8.2f units (%s cals) of %s (grp %s)\",\n amt,\n cals,\n food[\"short_descrip\"],\n food[\"food_group_descrip\"]\n )\n\n info(\"Total Calories: %8.2f\", total_cals)\n\n\ndef food_scores(engine):\n \"\"\"Just output all foods that we allow with the score that you would get.\"\"\"\n one_hot = []\n for i in range(engine.food_count):\n one = [0.0] * engine.food_count\n one[i] = 1.0\n one_hot.append(list(one))\n\n engine.set_pop(one_hot)\n engine.generation()\n\n for food, nutr in zip(engine.last_population, engine.last_popnutrition):\n engine.dump_instance(food, nutr)\n info('='*78)\n\n\ndef main():\n input_file = \"foods.jsontxt.gz\" # TODO: command line or stdin or...\n\n info(\"Micronutrients used for calcs: %d\", len(ALL_MICROS))\n\n info(\"Reading input file %s\", input_file)\n food_details = list(read_foods(input_file))\n\n engine = opt_engine(food_details)\n info(\"Init population shape: %s\", engine.population.shape)\n info(\"Food matrix shape: %s\", engine.foods.shape)\n\n if '-foodscores' in sys.argv[1:]:\n food_scores(engine)\n return\n elif '-topn' in sys.argv[1:]:\n print(\"TODO: top-n per nutrient output\")\n return\n\n # Do our generations\n # TODO: good stopping criteria\n with open(\"results\", \"w\") as results:\n def file_output(s, *args):\n if args:\n s = s % args\n results.write(s)\n results.write('\\n')\n results.flush()\n\n info(\"Pre-Running 2 generations\")\n engine.generation()\n engine.generation()\n\n seen = set()\n\n for gen in range(1, 5000+1):\n engine.generation()\n\n best_food, best_nutr = engine.last_population[0], engine.last_popnutrition[0]\n info(\"BEGIN Generation %d (pop size %d)\", gen, len(engine.last_population))\n engine.dump_instance(best_food, best_nutr)\n info(\"END Generation %d\", gen)\n info('-'*20)\n\n for food, nutr in zip(engine.last_population[:3], engine.last_popnutrition[:3]):\n key = tuple(food)\n if key in seen:\n continue\n\n seen.add(key)\n\n file_output(\"First Seen Generation %d\", gen)\n engine.dump_instance(food, nutr, info=file_output)\n file_output('='*78)\n\n\nif __name__ == \"__main__\":\n main()\n", "meta": {"hexsha": "8ce49954c245013bb1338aad9d689600e831d103", "size": 16461, "ext": "py", "lang": "Python", "max_stars_repo_path": "optimize/optimize.py", "max_stars_repo_name": "CraigKelly/nndb-import", "max_stars_repo_head_hexsha": "2643a7afe4ec922c76dda38c8ab7f413f1bf7528", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-01-08T19:44:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T17:59:59.000Z", "max_issues_repo_path": "optimize/optimize.py", "max_issues_repo_name": "CraigKelly/nndb-import", "max_issues_repo_head_hexsha": "2643a7afe4ec922c76dda38c8ab7f413f1bf7528", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optimize/optimize.py", "max_forks_repo_name": "CraigKelly/nndb-import", "max_forks_repo_head_hexsha": "2643a7afe4ec922c76dda38c8ab7f413f1bf7528", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6607142857, "max_line_length": 104, "alphanum_fraction": 0.5567705486, "include": true, "reason": "import scipy", "num_tokens": 4017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.21206881431678098, "lm_q1q2_score": 0.11017427075866701}} {"text": "from torch import nn\nimport torch\nimport numpy as np\n\nclass SemiCRFShiftRelay(nn.Module):\n \"\"\"\n 该模块是一个decoder,但当前不支持含有tag的decode。\n\n \"\"\"\n def __init__(self, L):\n \"\"\"\n\n :param L: 不包含relay的长度\n \"\"\"\n if L<2:\n raise RuntimeError()\n super().__init__()\n self.L = L\n\n def forward(self, logits, relay_logits, relay_target, relay_mask, end_seg_mask, seq_len):\n \"\"\"\n relay node是接下来L个字都不是它的结束。relay的状态是往后滑动1个位置\n\n :param logits: batch_size x max_len x L, 当前位置往左边L个segment的分数,最后一维的0是长度为1的segment(即本身)\n :param relay_logits: batch_size x max_len, 当前位置是接下来L-1个位置都不是终点的分数\n :param relay_target: batch_size x max_len 每个位置他的segment在哪里开始的。如果超过L,则一直保持为L-1。比如长度为\n 5的词,L=3, [0, 1, 2, 2, 2]\n :param relay_mask: batch_size x max_len, 在需要relay的地方为1, 长度为5的词, L=3时,为[1, 1, 1, 0, 0]\n :param end_seg_mask: batch_size x max_len, segment结束的地方为1。\n :param seq_len: batch_size, 句子的长度\n :return: loss: batch_size,\n \"\"\"\n batch_size, max_len, L = logits.size()\n\n # 当前时刻为relay node的分数是多少\n relay_scores = logits.new_zeros(batch_size, max_len)\n # 当前时刻结束的分数是多少\n scores = logits.new_zeros(batch_size, max_len+1)\n # golden的分数\n gold_scores = relay_logits[:, 0].masked_fill(relay_mask[:, 0].eq(0), 0) + \\\n logits[:, 0, 0].masked_fill(end_seg_mask[:, 0].eq(0), 0)\n # 初始化\n scores[:, 1] = logits[:, 0, 0]\n batch_i = torch.arange(batch_size).to(logits.device).long()\n relay_scores[:, 0] = relay_logits[:, 0]\n last_relay_index = max_len - self.L\n for t in range(1, max_len):\n real_L = min(t+1, L)\n flip_logits_t = logits[:, t, :real_L].flip(dims=[1]) # flip之后低0个位置为real_L-1的segment\n # 计算relay_scores的更新\n if tself.L-1:\n # (2)从relay跳转过来的\n tmp2 = relay_scores[:, t-self.L] # batch_size\n tmp2 = tmp2 + flip_logits_t[:, 0] # batch_size\n tmp1 = torch.cat([tmp1, tmp2.unsqueeze(-1)], dim=-1)\n scores[:, t+1] = torch.logsumexp(tmp1, dim=-1) # 更新当前时刻的分数\n\n # 计算golden\n seg_i = relay_target[:, t] # batch_size\n gold_segment_scores = logits[:, t][(batch_i, seg_i)].masked_fill(end_seg_mask[:, t].eq(0), 0) # batch_size, 后向从0到L长度的segment的分数\n relay_score = relay_logits[:, t].masked_fill(relay_mask[:, t].eq(0), 0)\n gold_scores = gold_scores + relay_score + gold_segment_scores\n all_scores = scores.gather(dim=1, index=seq_len.unsqueeze(1)).squeeze(1) # batch_size\n return all_scores - gold_scores\n\n def predict(self, logits, relay_logits, seq_len):\n \"\"\"\n relay node是接下来L个字都不是它的结束。relay的状态是往后滑动L-1个位置\n\n :param logits: batch_size x max_len x L, 当前位置左边L个segment的分数,最后一维的0是长度为1的segment(即本身)\n :param relay_logits: batch_size x max_len, 当前位置是接下来L-1个位置都不是终点的分数\n :param seq_len: batch_size, 句子的长度\n :return: pred: batch_size x max_len以该点开始的segment的(长度-1); pred_mask为1的地方预测有segment开始\n \"\"\"\n batch_size, max_len, L = logits.size()\n # 当前时刻为relay node的分数是多少\n max_relay_scores = logits.new_zeros(batch_size, max_len)\n relay_bt = seq_len.new_zeros(batch_size, max_len) # 当前结果是否来自于relay的结果\n # 当前时刻结束的分数是多少\n max_scores = logits.new_zeros(batch_size, max_len+1)\n bt = seq_len.new_zeros(batch_size, max_len)\n # 初始化\n max_scores[:, 1] = logits[:, 0, 0]\n max_relay_scores[:, 0] = relay_logits[:, 0]\n last_relay_index = max_len - self.L\n for t in range(1, max_len):\n real_L = min(t+1, L)\n flip_logits_t = logits[:, t, :real_L].flip(dims=[1]) # flip之后低0个位置为real_L-1的segment\n # 计算relay_scores的更新\n if t-1:\n if bt_i[j]==self.L:\n seg_start_pos = j\n j = j-self.L\n while relay_bt_i[j]!=0 and j>-1:\n j = j - 1\n pred[b, j] = seg_start_pos - j\n pred_mask[b, j] = 1\n else:\n length = bt_i[j]\n j = j - bt_i[j]\n pred_mask[b, j] = 1\n pred[b, j] = length\n j = j - 1\n\n return torch.LongTensor(pred).to(logits.device), torch.LongTensor(pred_mask).to(logits.device)\n\n\n\nclass FeatureFunMax(nn.Module):\n def __init__(self, hidden_size:int, L:int):\n \"\"\"\n 用于计算semi-CRF特征的函数。给定batch_size x max_len x hidden_size形状的输入,输出为batch_size x max_len x L的\n 分数,以及batch_size x max_len的relay的分数。两者的区别参考论文 TODO 补充\n\n :param hidden_size: 输入特征的维度大小\n :param L: 不包含relay node的segment的长度大小。\n \"\"\"\n super().__init__()\n\n self.end_fc = nn.Linear(hidden_size, 1, bias=False)\n self.whole_w = nn.Parameter(torch.randn(L, hidden_size))\n self.relay_fc = nn.Linear(hidden_size, 1)\n self.length_bias = nn.Parameter(torch.randn(L))\n self.L = L\n def forward(self, logits):\n \"\"\"\n\n :param logits: batch_size x max_len x hidden_size\n :return: batch_size x max_len x L # 最后一维为左边segment的分数,0处为长度为1的segment\n batch_size x max_len, # 当前位置是接下来L-1个位置都不是终点的分数\n\n \"\"\"\n batch_size, max_len, hidden_size = logits.size()\n # start_scores = self.start_fc(logits) # batch_size x max_len x 1 # 每个位置作为start的分数\n tmp = logits.new_zeros(batch_size, max_len+self.L-1, hidden_size)\n tmp[:, -max_len:] = logits\n # batch_size x max_len x hidden_size x (self.L) -> batch_size x max_len x (self.L) x hidden_size\n start_logits = tmp.unfold(dimension=1, size=self.L, step=1).transpose(2, 3).flip(dims=[2])\n end_scores = self.end_fc(logits) # batch_size x max_len x 1\n # 计算relay的特征\n relay_tmp = logits.new_zeros(batch_size, max_len, hidden_size)\n relay_tmp[:, :-self.L] = logits[:, self.L:]\n # batch_size x max_len x hidden_size\n relay_logits_max = torch.max(relay_tmp, logits) # end - start\n logits_max = torch.max(logits.unsqueeze(2), start_logits) # batch_size x max_len x L x hidden_size\n whole_scores = (logits_max*self.whole_w).sum(dim=-1) # batch_size x max_len x self.L\n # whole_scores = self.whole_fc().squeeze(-1) # bz x max_len x self.L\n # batch_size x max_len\n relay_scores = self.relay_fc(relay_logits_max).squeeze(-1)\n return whole_scores+end_scores+self.length_bias.view(1, 1, -1), relay_scores\n", "meta": {"hexsha": "86149f39cae43eb90066c795011c51ff39cac9f2", "size": 8774, "ext": "py", "lang": "Python", "max_stars_repo_path": "reproduction/seqence_labelling/cws/model/module.py", "max_stars_repo_name": "KuNyaa/fastNLP", "max_stars_repo_head_hexsha": "22f9b87c54a4eebec7352c7ff772cd24685c7186", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-05T06:02:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-05T06:02:44.000Z", "max_issues_repo_path": "reproduction/seqence_labelling/cws/model/module.py", "max_issues_repo_name": "awesomemachinelearning/fastNLP", "max_issues_repo_head_hexsha": "945b30bb6174751130744231aa26119bf9bb2601", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-12-09T06:34:44.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-09T06:34:44.000Z", "max_forks_repo_path": "reproduction/seqence_labelling/cws/model/module.py", "max_forks_repo_name": "awesomemachinelearning/fastNLP", "max_forks_repo_head_hexsha": "945b30bb6174751130744231aa26119bf9bb2601", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-04-21T06:17:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-05T11:22:11.000Z", "avg_line_length": 44.3131313131, "max_line_length": 139, "alphanum_fraction": 0.5760200593, "include": true, "reason": "import numpy", "num_tokens": 2821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.2043418902459481, "lm_q1q2_score": 0.10934302437319833}} {"text": "# In this tutorial, you will learn how to write functions in python \n# Lets write a function that will return the square, square root and the cube of the number that is passed to it\n\nimport numpy as np \n\n\n# This is how a function is defined:\ndef my_func(val): # the colon works the same way it did in for loops, the indenting begins after that (Do not delete the indenting)\n sq = val*val\n sqrt = np.sqrt(val)\n cube = val*val*val\n return sq,sqrt,cube\n\n# you press shift+tab to come out of the indent (or loop)\n\nv =100\nprint(\"The output from the first technique is:\")\nprint(my_func(v))\n\n# or you can also do:\nval1, val2, val3 = my_func(v) # in this case, val1 contains sq, val2 contains sqrt and val3 contains cube\nprint(\"The output from the second technique is:\")\nprint(\"value of val1 is {0}\".format(val1))\nprint(\"value of val2 is {0}\".format(val2))\nprint(\"value of val3 is {0}\".format(val3))\n\n# assignments \n\n# write a function that will determine if a given number is even or odd\n# write a function to find the sin of a number using taylors expansion\n# write a function to find e^x of a number\n# write a function that do all the above in a single go", "meta": {"hexsha": "f3dd79212ab2690a0e54adedc7ee06b8d2d3f9e8", "size": 1162, "ext": "py", "lang": "Python", "max_stars_repo_path": "12-functions.py", "max_stars_repo_name": "deepaksamuel/python-tutorials", "max_stars_repo_head_hexsha": "9e08c7b589e6b00c2c1781ad09fc76944c2f7c87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-20T17:31:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T17:31:09.000Z", "max_issues_repo_path": "12-functions.py", "max_issues_repo_name": "deepaksamuel/python-tutorials", "max_issues_repo_head_hexsha": "9e08c7b589e6b00c2c1781ad09fc76944c2f7c87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "12-functions.py", "max_forks_repo_name": "deepaksamuel/python-tutorials", "max_forks_repo_head_hexsha": "9e08c7b589e6b00c2c1781ad09fc76944c2f7c87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-09T14:41:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-09T14:41:56.000Z", "avg_line_length": 36.3125, "max_line_length": 131, "alphanum_fraction": 0.7263339071, "include": true, "reason": "import numpy", "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.2200070946316962, "lm_q1q2_score": 0.10828488175212322}} {"text": "#!/usr/bin/env python\n# Copyright 2020 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Qiming Sun \n#\n\n'''\nddCOSMO TDA, TDHF, TDDFT gradients\n\nThe implementaitons are based on modules\npyscf.grad.tdrhf\npyscf.grad.tdrks\npyscf.grad.tduhf\npyscf.grad.tduks\n'''\n\n\nfrom functools import reduce\nimport numpy\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf import gto\nfrom pyscf import scf\nfrom pyscf import dft\nfrom pyscf import df\nfrom pyscf.dft import numint\nfrom pyscf.solvent import ddcosmo\nfrom pyscf.solvent import ddcosmo_grad\nfrom pyscf.solvent._attach_solvent import _Solvation\nfrom pyscf.grad import rks as rks_grad\nfrom pyscf.grad import tdrks as tdrks_grad\nfrom pyscf.grad import tduks as tduks_grad\nfrom pyscf.scf import cphf, ucphf\n\n\ndef make_grad_object(grad_method):\n '''For grad_method in vacuum, add nuclear gradients of solvent pcmobj'''\n\n # Zeroth order method object must be a solvation-enabled method\n assert isinstance(grad_method.base, _Solvation)\n if grad_method.base.with_solvent.frozen:\n raise RuntimeError('Frozen solvent model is not avialbe for energy gradients')\n\n grad_method_class = grad_method.__class__\n class WithSolventGrad(grad_method_class):\n def __init__(self, grad_method):\n self.__dict__.update(grad_method.__dict__)\n self.de_solvent = None\n self.de_solute = None\n self._keys = self._keys.union(['de_solvent', 'de_solute'])\n\n def grad_elec(self, xy, singlet, atmlst=None):\n if isinstance(self.base._scf, dft.uks.UKS):\n return tduks_grad_elec(self, xy, atmlst, self.max_memory, self.verbose)\n elif isinstance(self.base._scf, dft.rks.RKS):\n return tdrks_grad_elec(self, xy, singlet, atmlst, self.max_memory, self.verbose)\n elif isinstance(self.base._scf, scf.uhf.UHF):\n return tduhf_grad_elec(self, xy, atmlst, self.max_memory, self.verbose)\n elif isinstance(self.base._scf, scf.hf.RHF):\n return tdrhf_grad_elec(self, xy, singlet, atmlst, self.max_memory, self.verbose)\n\n # TODO: if moving to python3, change signature to\n # def kernel(self, *args, dm=None, atmlst=None, **kwargs):\n def kernel(self, *args, **kwargs):\n dm = kwargs.pop('dm', None)\n if dm is None:\n dm = self.base._scf.make_rdm1(ao_repr=True)\n\n self.de_solvent = ddcosmo_grad.kernel(self.base.with_solvent, dm)\n self.de_solute = grad_method_class.kernel(self, *args, **kwargs)\n self.de = self.de_solute + self.de_solvent\n\n if self.verbose >= logger.NOTE:\n logger.note(self, '--------------- %s (+%s) gradients ---------------',\n self.base.__class__.__name__,\n self.base.with_solvent.__class__.__name__)\n self._write(self.mol, self.de, self.atmlst)\n logger.note(self, '----------------------------------------------')\n return self.de\n\n def _finalize(self):\n # disable _finalize. It is called in grad_method.kernel method\n # where self.de was not yet initialized.\n pass\n\n return WithSolventGrad(grad_method)\n\n\ndef tdrhf_grad_elec(td_grad, x_y, singlet=True, atmlst=None,\n max_memory=2000, verbose=logger.INFO):\n '''\n See also function pyscf.grad.tdrhf.grad_elec\n '''\n log = logger.new_logger(td_grad, verbose)\n time0 = logger.process_clock(), logger.perf_counter()\n\n mol = td_grad.mol\n mf = td_grad.base._scf\n mo_coeff = mf.mo_coeff\n mo_energy = mf.mo_energy\n mo_occ = mf.mo_occ\n nao, nmo = mo_coeff.shape\n nocc = (mo_occ>0).sum()\n nvir = nmo - nocc\n x, y = x_y\n xpy = (x+y).reshape(nocc,nvir).T\n xmy = (x-y).reshape(nocc,nvir).T\n orbv = mo_coeff[:,nocc:]\n orbo = mo_coeff[:,:nocc]\n\n with_solvent = getattr(td_grad.base, 'with_solvent', mf.with_solvent)\n\n dvv = numpy.einsum('ai,bi->ab', xpy, xpy) + numpy.einsum('ai,bi->ab', xmy, xmy)\n doo =-numpy.einsum('ai,aj->ij', xpy, xpy) - numpy.einsum('ai,aj->ij', xmy, xmy)\n dmxpy = reduce(numpy.dot, (orbv, xpy, orbo.T))\n dmxmy = reduce(numpy.dot, (orbv, xmy, orbo.T))\n dmzoo = reduce(numpy.dot, (orbo, doo, orbo.T))\n dmzoo+= reduce(numpy.dot, (orbv, dvv, orbv.T))\n\n vj, vk = mf.get_jk(mol, (dmzoo, dmxpy+dmxpy.T, dmxmy-dmxmy.T), hermi=0)\n\n if with_solvent.equilibrium_solvation:\n vj[:2] += mf.with_solvent._B_dot_x((dmzoo, dmxpy+dmxpy.T))\n else:\n vj[0] += mf.with_solvent._B_dot_x(dmzoo)\n\n veff0doo = vj[0] * 2 - vk[0]\n wvo = reduce(numpy.dot, (orbv.T, veff0doo, orbo)) * 2\n\n if singlet:\n veff = vj[1] * 2 - vk[1]\n else:\n veff = -vk[1]\n veff0mop = reduce(numpy.dot, (mo_coeff.T, veff, mo_coeff))\n wvo -= numpy.einsum('ki,ai->ak', veff0mop[:nocc,:nocc], xpy) * 2\n wvo += numpy.einsum('ac,ai->ci', veff0mop[nocc:,nocc:], xpy) * 2\n veff = -vk[2]\n veff0mom = reduce(numpy.dot, (mo_coeff.T, veff, mo_coeff))\n wvo -= numpy.einsum('ki,ai->ak', veff0mom[:nocc,:nocc], xmy) * 2\n wvo += numpy.einsum('ac,ai->ci', veff0mom[nocc:,nocc:], xmy) * 2\n\n with lib.temporary_env(mf.with_solvent, equilibrium_solvation=True):\n # set singlet=None, generate function for CPHF type response kernel\n vresp = mf.gen_response(singlet=None, hermi=1)\n def fvind(x): # For singlet, closed shell ground state\n dm = reduce(numpy.dot, (orbv, x.reshape(nvir,nocc)*2, orbo.T))\n v1ao = vresp(dm+dm.T)\n return reduce(numpy.dot, (orbv.T, v1ao, orbo)).ravel()\n z1 = cphf.solve(fvind, mo_energy, mo_occ, wvo,\n max_cycle=td_grad.cphf_max_cycle,\n tol=td_grad.cphf_conv_tol)[0]\n z1 = z1.reshape(nvir,nocc)\n time1 = log.timer('Z-vector using CPHF solver', *time0)\n\n z1ao = reduce(numpy.dot, (orbv, z1, orbo.T))\n veff = vresp(z1ao+z1ao.T)\n\n im0 = numpy.zeros((nmo,nmo))\n im0[:nocc,:nocc] = reduce(numpy.dot, (orbo.T, veff0doo+veff, orbo))\n im0[:nocc,:nocc]+= numpy.einsum('ak,ai->ki', veff0mop[nocc:,:nocc], xpy)\n im0[:nocc,:nocc]+= numpy.einsum('ak,ai->ki', veff0mom[nocc:,:nocc], xmy)\n im0[nocc:,nocc:] = numpy.einsum('ci,ai->ac', veff0mop[nocc:,:nocc], xpy)\n im0[nocc:,nocc:]+= numpy.einsum('ci,ai->ac', veff0mom[nocc:,:nocc], xmy)\n im0[nocc:,:nocc] = numpy.einsum('ki,ai->ak', veff0mop[:nocc,:nocc], xpy)*2\n im0[nocc:,:nocc]+= numpy.einsum('ki,ai->ak', veff0mom[:nocc,:nocc], xmy)*2\n\n zeta = lib.direct_sum('i+j->ij', mo_energy, mo_energy) * .5\n zeta[nocc:,:nocc] = mo_energy[:nocc]\n zeta[:nocc,nocc:] = mo_energy[nocc:]\n dm1 = numpy.zeros((nmo,nmo))\n dm1[:nocc,:nocc] = doo\n dm1[nocc:,nocc:] = dvv\n dm1[nocc:,:nocc] = z1\n dm1[:nocc,:nocc] += numpy.eye(nocc)*2 # for ground state\n im0 = reduce(numpy.dot, (mo_coeff, im0+zeta*dm1, mo_coeff.T))\n\n # Initialize hcore_deriv with the underlying SCF object because some\n # extensions (e.g. QM/MM, solvent) modifies the SCF object only.\n mf_grad = td_grad.base._scf.nuc_grad_method()\n hcore_deriv = mf_grad.hcore_generator(mol)\n s1 = mf_grad.get_ovlp(mol)\n\n dmz1doo = z1ao + dmzoo\n oo0 = reduce(numpy.dot, (orbo, orbo.T))\n vj, vk = td_grad.get_jk(mol, (oo0, dmz1doo+dmz1doo.T, dmxpy+dmxpy.T,\n dmxmy-dmxmy.T))\n vj = vj.reshape(-1,3,nao,nao)\n vk = vk.reshape(-1,3,nao,nao)\n if singlet:\n vhf1 = vj * 2 - vk\n else:\n vhf1 = numpy.vstack((vj[:2]*2-vk[:2], -vk[2:]))\n time1 = log.timer('2e AO integral derivatives', *time1)\n\n if atmlst is None:\n atmlst = range(mol.natm)\n offsetdic = mol.offset_nr_by_atom()\n de = numpy.zeros((len(atmlst),3))\n for k, ia in enumerate(atmlst):\n shl0, shl1, p0, p1 = offsetdic[ia]\n\n # Ground state gradients\n h1ao = hcore_deriv(ia)\n h1ao[:,p0:p1] += vhf1[0,:,p0:p1]\n h1ao[:,:,p0:p1] += vhf1[0,:,p0:p1].transpose(0,2,1)\n # oo0*2 for doubly occupied orbitals\n de[k] = numpy.einsum('xpq,pq->x', h1ao, oo0) * 2\n de[k] += numpy.einsum('xpq,pq->x', h1ao, dmz1doo)\n\n de[k] -= numpy.einsum('xpq,pq->x', s1[:,p0:p1], im0[p0:p1])\n de[k] -= numpy.einsum('xqp,pq->x', s1[:,p0:p1], im0[:,p0:p1])\n\n de[k] += numpy.einsum('xij,ij->x', vhf1[1,:,p0:p1], oo0[p0:p1])\n de[k] += numpy.einsum('xij,ij->x', vhf1[2,:,p0:p1], dmxpy[p0:p1,:]) * 2\n de[k] += numpy.einsum('xij,ij->x', vhf1[3,:,p0:p1], dmxmy[p0:p1,:]) * 2\n de[k] += numpy.einsum('xji,ij->x', vhf1[2,:,p0:p1], dmxpy[:,p0:p1]) * 2\n de[k] -= numpy.einsum('xji,ij->x', vhf1[3,:,p0:p1], dmxmy[:,p0:p1]) * 2\n\n de += _grad_solvent(with_solvent, oo0*2, dmz1doo, dmxpy*2, singlet)\n\n log.timer('TDHF nuclear gradients', *time0)\n return de\n\ndef tdrks_grad_elec(td_grad, x_y, singlet=True, atmlst=None,\n max_memory=2000, verbose=logger.INFO):\n '''\n See also function pyscf.grad.tdrks.grad_elec\n '''\n log = logger.new_logger(td_grad, verbose)\n time0 = logger.process_clock(), logger.perf_counter()\n\n mol = td_grad.mol\n mf = td_grad.base._scf\n mo_coeff = mf.mo_coeff\n mo_energy = mf.mo_energy\n mo_occ = mf.mo_occ\n nao, nmo = mo_coeff.shape\n nocc = (mo_occ>0).sum()\n nvir = nmo - nocc\n\n with_solvent = getattr(td_grad.base, 'with_solvent', mf.with_solvent)\n\n x, y = x_y\n xpy = (x+y).reshape(nocc,nvir).T\n xmy = (x-y).reshape(nocc,nvir).T\n orbv = mo_coeff[:,nocc:]\n orbo = mo_coeff[:,:nocc]\n\n dvv = numpy.einsum('ai,bi->ab', xpy, xpy) + numpy.einsum('ai,bi->ab', xmy, xmy)\n doo =-numpy.einsum('ai,aj->ij', xpy, xpy) - numpy.einsum('ai,aj->ij', xmy, xmy)\n dmxpy = reduce(numpy.dot, (orbv, xpy, orbo.T))\n dmxmy = reduce(numpy.dot, (orbv, xmy, orbo.T))\n dmzoo = reduce(numpy.dot, (orbo, doo, orbo.T))\n dmzoo+= reduce(numpy.dot, (orbv, dvv, orbv.T))\n\n mem_now = lib.current_memory()[0]\n max_memory = max(2000, td_grad.max_memory*.9-mem_now)\n\n\n ni = mf._numint\n ni.libxc.test_deriv_order(mf.xc, 3, raise_error=True)\n omega, alpha, hyb = ni.rsh_and_hybrid_coeff(mf.xc, mol.spin)\n # dm0 = mf.make_rdm1(mo_coeff, mo_occ), but it is not used when computing\n # fxc since rho0 is passed to fxc function.\n rho0, vxc, fxc = ni.cache_xc_kernel(mf.mol, mf.grids, mf.xc,\n [mo_coeff]*2, [mo_occ*.5]*2, spin=1)\n f1vo, f1oo, vxc1, k1ao = \\\n tdrks_grad._contract_xc_kernel(td_grad, mf.xc, dmxpy,\n dmzoo, True, True, singlet, max_memory)\n\n if abs(hyb) > 1e-10:\n dm = (dmzoo, dmxpy+dmxpy.T, dmxmy-dmxmy.T)\n vj, vk = mf.get_jk(mol, dm, hermi=0)\n if with_solvent.equilibrium_solvation:\n vj[:2] += mf.with_solvent._B_dot_x((dmzoo, dmxpy+dmxpy.T))\n else:\n vj[0] += mf.with_solvent._B_dot_x(dmzoo)\n\n vk *= hyb\n if abs(omega) > 1e-10:\n vk += mf.get_k(mol, dm, hermi=0, omega=omega) * (alpha-hyb)\n veff0doo = vj[0] * 2 - vk[0] + f1oo[0] + k1ao[0] * 2\n wvo = reduce(numpy.dot, (orbv.T, veff0doo, orbo)) * 2\n if singlet:\n veff = vj[1] * 2 - vk[1] + f1vo[0] * 2\n else:\n veff = -vk[1] + f1vo[0] * 2\n veff0mop = reduce(numpy.dot, (mo_coeff.T, veff, mo_coeff))\n wvo -= numpy.einsum('ki,ai->ak', veff0mop[:nocc,:nocc], xpy) * 2\n wvo += numpy.einsum('ac,ai->ci', veff0mop[nocc:,nocc:], xpy) * 2\n veff = -vk[2]\n veff0mom = reduce(numpy.dot, (mo_coeff.T, veff, mo_coeff))\n wvo -= numpy.einsum('ki,ai->ak', veff0mom[:nocc,:nocc], xmy) * 2\n wvo += numpy.einsum('ac,ai->ci', veff0mom[nocc:,nocc:], xmy) * 2\n else:\n vj = mf.get_j(mol, (dmzoo, dmxpy+dmxpy.T), hermi=1)\n if with_solvent.equilibrium_solvation:\n vj[:2] += mf.with_solvent._B_dot_x((dmzoo, dmxpy+dmxpy.T))\n else:\n vj[0] += mf.with_solvent._B_dot_x(dmzoo)\n\n veff0doo = vj[0] * 2 + f1oo[0] + k1ao[0] * 2\n wvo = reduce(numpy.dot, (orbv.T, veff0doo, orbo)) * 2\n if singlet:\n veff = vj[1] * 2 + f1vo[0] * 2\n else:\n veff = f1vo[0] * 2\n veff0mop = reduce(numpy.dot, (mo_coeff.T, veff, mo_coeff))\n wvo -= numpy.einsum('ki,ai->ak', veff0mop[:nocc,:nocc], xpy) * 2\n wvo += numpy.einsum('ac,ai->ci', veff0mop[nocc:,nocc:], xpy) * 2\n veff0mom = numpy.zeros((nmo,nmo))\n\n with lib.temporary_env(mf.with_solvent, equilibrium_solvation=True):\n # set singlet=None, generate function for CPHF type response kernel\n vresp = mf.gen_response(singlet=None, hermi=1)\n def fvind(x):\n dm = reduce(numpy.dot, (orbv, x.reshape(nvir,nocc)*2, orbo.T))\n v1ao = vresp(dm+dm.T)\n return reduce(numpy.dot, (orbv.T, v1ao, orbo)).ravel()\n z1 = cphf.solve(fvind, mo_energy, mo_occ, wvo,\n max_cycle=td_grad.cphf_max_cycle,\n tol=td_grad.cphf_conv_tol)[0]\n z1 = z1.reshape(nvir,nocc)\n time1 = log.timer('Z-vector using CPHF solver', *time0)\n\n z1ao = reduce(numpy.dot, (orbv, z1, orbo.T))\n veff = vresp(z1ao+z1ao.T)\n\n im0 = numpy.zeros((nmo,nmo))\n im0[:nocc,:nocc] = reduce(numpy.dot, (orbo.T, veff0doo+veff, orbo))\n im0[:nocc,:nocc]+= numpy.einsum('ak,ai->ki', veff0mop[nocc:,:nocc], xpy)\n im0[:nocc,:nocc]+= numpy.einsum('ak,ai->ki', veff0mom[nocc:,:nocc], xmy)\n im0[nocc:,nocc:] = numpy.einsum('ci,ai->ac', veff0mop[nocc:,:nocc], xpy)\n im0[nocc:,nocc:]+= numpy.einsum('ci,ai->ac', veff0mom[nocc:,:nocc], xmy)\n im0[nocc:,:nocc] = numpy.einsum('ki,ai->ak', veff0mop[:nocc,:nocc], xpy)*2\n im0[nocc:,:nocc]+= numpy.einsum('ki,ai->ak', veff0mom[:nocc,:nocc], xmy)*2\n\n zeta = lib.direct_sum('i+j->ij', mo_energy, mo_energy) * .5\n zeta[nocc:,:nocc] = mo_energy[:nocc]\n zeta[:nocc,nocc:] = mo_energy[nocc:]\n dm1 = numpy.zeros((nmo,nmo))\n dm1[:nocc,:nocc] = doo\n dm1[nocc:,nocc:] = dvv\n dm1[nocc:,:nocc] = z1\n dm1[:nocc,:nocc] += numpy.eye(nocc)*2 # for ground state\n im0 = reduce(numpy.dot, (mo_coeff, im0+zeta*dm1, mo_coeff.T))\n\n # Initialize hcore_deriv with the underlying SCF object because some\n # extensions (e.g. QM/MM, solvent) modifies the SCF object only.\n mf_grad = td_grad.base._scf.nuc_grad_method()\n hcore_deriv = mf_grad.hcore_generator(mol)\n s1 = mf_grad.get_ovlp(mol)\n\n dmz1doo = z1ao + dmzoo\n oo0 = reduce(numpy.dot, (orbo, orbo.T))\n if abs(hyb) > 1e-10:\n dm = (oo0, dmz1doo+dmz1doo.T, dmxpy+dmxpy.T, dmxmy-dmxmy.T)\n vj, vk = td_grad.get_jk(mol, dm)\n vk *= hyb\n if abs(omega) > 1e-10:\n with mol.with_range_coulomb(omega):\n vk += td_grad.get_k(mol, dm) * (alpha-hyb)\n vj = vj.reshape(-1,3,nao,nao)\n vk = vk.reshape(-1,3,nao,nao)\n if singlet:\n veff1 = vj * 2 - vk\n else:\n veff1 = numpy.vstack((vj[:2]*2-vk[:2], -vk[2:]))\n else:\n vj = td_grad.get_j(mol, (oo0, dmz1doo+dmz1doo.T, dmxpy+dmxpy.T))\n vj = vj.reshape(-1,3,nao,nao)\n veff1 = numpy.zeros((4,3,nao,nao))\n if singlet:\n veff1[:3] = vj * 2\n else:\n veff1[:2] = vj[:2] * 2\n\n fxcz1 = tdrks_grad._contract_xc_kernel(td_grad, mf.xc, z1ao, None,\n False, False, True, max_memory)[0]\n\n veff1[0] += vxc1[1:]\n veff1[1] +=(f1oo[1:] + fxcz1[1:] + k1ao[1:]*2)*2 # *2 for dmz1doo+dmz1oo.T\n veff1[2] += f1vo[1:] * 2\n time1 = log.timer('2e AO integral derivatives', *time1)\n\n if atmlst is None:\n atmlst = range(mol.natm)\n offsetdic = mol.offset_nr_by_atom()\n de = numpy.zeros((len(atmlst),3))\n for k, ia in enumerate(atmlst):\n shl0, shl1, p0, p1 = offsetdic[ia]\n\n # Ground state gradients\n h1ao = hcore_deriv(ia)\n h1ao[:,p0:p1] += veff1[0,:,p0:p1]\n h1ao[:,:,p0:p1] += veff1[0,:,p0:p1].transpose(0,2,1)\n # oo0*2 for doubly occupied orbitals\n e1 = numpy.einsum('xpq,pq->x', h1ao, oo0) * 2\n\n e1 += numpy.einsum('xpq,pq->x', h1ao, dmz1doo)\n e1 -= numpy.einsum('xpq,pq->x', s1[:,p0:p1], im0[p0:p1])\n e1 -= numpy.einsum('xqp,pq->x', s1[:,p0:p1], im0[:,p0:p1])\n\n e1 += numpy.einsum('xij,ij->x', veff1[1,:,p0:p1], oo0[p0:p1])\n e1 += numpy.einsum('xij,ij->x', veff1[2,:,p0:p1], dmxpy[p0:p1,:]) * 2\n e1 += numpy.einsum('xij,ij->x', veff1[3,:,p0:p1], dmxmy[p0:p1,:]) * 2\n e1 += numpy.einsum('xji,ij->x', veff1[2,:,p0:p1], dmxpy[:,p0:p1]) * 2\n e1 -= numpy.einsum('xji,ij->x', veff1[3,:,p0:p1], dmxmy[:,p0:p1]) * 2\n\n de[k] = e1\n\n de += _grad_solvent(with_solvent, oo0*2, dmz1doo, dmxpy*2, singlet)\n\n log.timer('TDDFT nuclear gradients', *time0)\n return de\n\ndef tduhf_grad_elec(td_grad, x_y, atmlst=None, max_memory=2000, verbose=logger.INFO):\n '''\n See also function pyscf.grad.tduhf.grad_elec\n '''\n log = logger.new_logger(td_grad, verbose)\n time0 = logger.process_clock(), logger.perf_counter()\n\n mol = td_grad.mol\n mf = td_grad.base._scf\n mo_coeff = mf.mo_coeff\n mo_energy = mf.mo_energy\n mo_occ = mf.mo_occ\n\n with_solvent = getattr(td_grad.base, 'with_solvent', mf.with_solvent)\n\n occidxa = numpy.where(mo_occ[0]>0)[0]\n occidxb = numpy.where(mo_occ[1]>0)[0]\n viridxa = numpy.where(mo_occ[0]==0)[0]\n viridxb = numpy.where(mo_occ[1]==0)[0]\n nocca = len(occidxa)\n noccb = len(occidxb)\n nvira = len(viridxa)\n nvirb = len(viridxb)\n orboa = mo_coeff[0][:,occidxa]\n orbob = mo_coeff[1][:,occidxb]\n orbva = mo_coeff[0][:,viridxa]\n orbvb = mo_coeff[1][:,viridxb]\n nao = mo_coeff[0].shape[0]\n nmoa = nocca + nvira\n nmob = noccb + nvirb\n\n (xa, xb), (ya, yb) = x_y\n xpya = (xa+ya).reshape(nocca,nvira).T\n xpyb = (xb+yb).reshape(noccb,nvirb).T\n xmya = (xa-ya).reshape(nocca,nvira).T\n xmyb = (xb-yb).reshape(noccb,nvirb).T\n\n dvva = numpy.einsum('ai,bi->ab', xpya, xpya) + numpy.einsum('ai,bi->ab', xmya, xmya)\n dvvb = numpy.einsum('ai,bi->ab', xpyb, xpyb) + numpy.einsum('ai,bi->ab', xmyb, xmyb)\n dooa =-numpy.einsum('ai,aj->ij', xpya, xpya) - numpy.einsum('ai,aj->ij', xmya, xmya)\n doob =-numpy.einsum('ai,aj->ij', xpyb, xpyb) - numpy.einsum('ai,aj->ij', xmyb, xmyb)\n dmxpya = reduce(numpy.dot, (orbva, xpya, orboa.T))\n dmxpyb = reduce(numpy.dot, (orbvb, xpyb, orbob.T))\n dmxmya = reduce(numpy.dot, (orbva, xmya, orboa.T))\n dmxmyb = reduce(numpy.dot, (orbvb, xmyb, orbob.T))\n dmzooa = reduce(numpy.dot, (orboa, dooa, orboa.T))\n dmzoob = reduce(numpy.dot, (orbob, doob, orbob.T))\n dmzooa+= reduce(numpy.dot, (orbva, dvva, orbva.T))\n dmzoob+= reduce(numpy.dot, (orbvb, dvvb, orbvb.T))\n\n vj, vk = mf.get_jk(mol, (dmzooa, dmxpya+dmxpya.T, dmxmya-dmxmya.T,\n dmzoob, dmxpyb+dmxpyb.T, dmxmyb-dmxmyb.T), hermi=0)\n vj = vj.reshape(2,3,nao,nao)\n vk = vk.reshape(2,3,nao,nao)\n if with_solvent.equilibrium_solvation:\n dmxpy = dmxpya + dmxpyb\n vj[0,:2] += mf.with_solvent._B_dot_x((dmzooa+dmzoob, dmxpy+dmxpy.T))\n else:\n vj[0,0] += mf.with_solvent._B_dot_x(dmzooa+dmzoob)\n\n veff0doo = vj[0,0]+vj[1,0] - vk[:,0]\n wvoa = reduce(numpy.dot, (orbva.T, veff0doo[0], orboa)) * 2\n wvob = reduce(numpy.dot, (orbvb.T, veff0doo[1], orbob)) * 2\n veff = vj[0,1]+vj[1,1] - vk[:,1]\n veff0mopa = reduce(numpy.dot, (mo_coeff[0].T, veff[0], mo_coeff[0]))\n veff0mopb = reduce(numpy.dot, (mo_coeff[1].T, veff[1], mo_coeff[1]))\n wvoa -= numpy.einsum('ki,ai->ak', veff0mopa[:nocca,:nocca], xpya) * 2\n wvob -= numpy.einsum('ki,ai->ak', veff0mopb[:noccb,:noccb], xpyb) * 2\n wvoa += numpy.einsum('ac,ai->ci', veff0mopa[nocca:,nocca:], xpya) * 2\n wvob += numpy.einsum('ac,ai->ci', veff0mopb[noccb:,noccb:], xpyb) * 2\n veff = -vk[:,2]\n veff0moma = reduce(numpy.dot, (mo_coeff[0].T, veff[0], mo_coeff[0]))\n veff0momb = reduce(numpy.dot, (mo_coeff[1].T, veff[1], mo_coeff[1]))\n wvoa -= numpy.einsum('ki,ai->ak', veff0moma[:nocca,:nocca], xmya) * 2\n wvob -= numpy.einsum('ki,ai->ak', veff0momb[:noccb,:noccb], xmyb) * 2\n wvoa += numpy.einsum('ac,ai->ci', veff0moma[nocca:,nocca:], xmya) * 2\n wvob += numpy.einsum('ac,ai->ci', veff0momb[noccb:,noccb:], xmyb) * 2\n\n with lib.temporary_env(mf.with_solvent, equilibrium_solvation=True):\n vresp = mf.gen_response(hermi=1)\n def fvind(x):\n dm1 = numpy.empty((2,nao,nao))\n xa = x[0,:nvira*nocca].reshape(nvira,nocca)\n xb = x[0,nvira*nocca:].reshape(nvirb,noccb)\n dma = reduce(numpy.dot, (orbva, xa, orboa.T))\n dmb = reduce(numpy.dot, (orbvb, xb, orbob.T))\n dm1[0] = dma + dma.T\n dm1[1] = dmb + dmb.T\n v1 = vresp(dm1)\n v1a = reduce(numpy.dot, (orbva.T, v1[0], orboa))\n v1b = reduce(numpy.dot, (orbvb.T, v1[1], orbob))\n return numpy.hstack((v1a.ravel(), v1b.ravel()))\n z1a, z1b = ucphf.solve(fvind, mo_energy, mo_occ, (wvoa,wvob),\n max_cycle=td_grad.cphf_max_cycle,\n tol=td_grad.cphf_conv_tol)[0]\n time1 = log.timer('Z-vector using UCPHF solver', *time0)\n\n z1ao = numpy.empty((2,nao,nao))\n z1ao[0] = reduce(numpy.dot, (orbva, z1a, orboa.T))\n z1ao[1] = reduce(numpy.dot, (orbvb, z1b, orbob.T))\n veff = vresp((z1ao+z1ao.transpose(0,2,1)) * .5)\n\n im0a = numpy.zeros((nmoa,nmoa))\n im0b = numpy.zeros((nmob,nmob))\n im0a[:nocca,:nocca] = reduce(numpy.dot, (orboa.T, veff0doo[0]+veff[0], orboa)) * .5\n im0b[:noccb,:noccb] = reduce(numpy.dot, (orbob.T, veff0doo[1]+veff[1], orbob)) * .5\n im0a[:nocca,:nocca]+= numpy.einsum('ak,ai->ki', veff0mopa[nocca:,:nocca], xpya) * .5\n im0b[:noccb,:noccb]+= numpy.einsum('ak,ai->ki', veff0mopb[noccb:,:noccb], xpyb) * .5\n im0a[:nocca,:nocca]+= numpy.einsum('ak,ai->ki', veff0moma[nocca:,:nocca], xmya) * .5\n im0b[:noccb,:noccb]+= numpy.einsum('ak,ai->ki', veff0momb[noccb:,:noccb], xmyb) * .5\n im0a[nocca:,nocca:] = numpy.einsum('ci,ai->ac', veff0mopa[nocca:,:nocca], xpya) * .5\n im0b[noccb:,noccb:] = numpy.einsum('ci,ai->ac', veff0mopb[noccb:,:noccb], xpyb) * .5\n im0a[nocca:,nocca:]+= numpy.einsum('ci,ai->ac', veff0moma[nocca:,:nocca], xmya) * .5\n im0b[noccb:,noccb:]+= numpy.einsum('ci,ai->ac', veff0momb[noccb:,:noccb], xmyb) * .5\n im0a[nocca:,:nocca] = numpy.einsum('ki,ai->ak', veff0mopa[:nocca,:nocca], xpya)\n im0b[noccb:,:noccb] = numpy.einsum('ki,ai->ak', veff0mopb[:noccb,:noccb], xpyb)\n im0a[nocca:,:nocca]+= numpy.einsum('ki,ai->ak', veff0moma[:nocca,:nocca], xmya)\n im0b[noccb:,:noccb]+= numpy.einsum('ki,ai->ak', veff0momb[:noccb,:noccb], xmyb)\n\n zeta_a = (mo_energy[0][:,None] + mo_energy[0]) * .5\n zeta_b = (mo_energy[1][:,None] + mo_energy[1]) * .5\n zeta_a[nocca:,:nocca] = mo_energy[0][:nocca]\n zeta_b[noccb:,:noccb] = mo_energy[1][:noccb]\n zeta_a[:nocca,nocca:] = mo_energy[0][nocca:]\n zeta_b[:noccb,noccb:] = mo_energy[1][noccb:]\n dm1a = numpy.zeros((nmoa,nmoa))\n dm1b = numpy.zeros((nmob,nmob))\n dm1a[:nocca,:nocca] = dooa * .5\n dm1b[:noccb,:noccb] = doob * .5\n dm1a[nocca:,nocca:] = dvva * .5\n dm1b[noccb:,noccb:] = dvvb * .5\n dm1a[nocca:,:nocca] = z1a * .5\n dm1b[noccb:,:noccb] = z1b * .5\n dm1a[:nocca,:nocca] += numpy.eye(nocca) # for ground state\n dm1b[:noccb,:noccb] += numpy.eye(noccb)\n im0a = reduce(numpy.dot, (mo_coeff[0], im0a+zeta_a*dm1a, mo_coeff[0].T))\n im0b = reduce(numpy.dot, (mo_coeff[1], im0b+zeta_b*dm1b, mo_coeff[1].T))\n im0 = im0a + im0b\n\n # Initialize hcore_deriv with the underlying SCF object because some\n # extensions (e.g. QM/MM, solvent) modifies the SCF object only.\n mf_grad = td_grad.base._scf.nuc_grad_method()\n hcore_deriv = mf_grad.hcore_generator(mol)\n s1 = mf_grad.get_ovlp(mol)\n\n dmz1dooa = z1ao[0] + dmzooa\n dmz1doob = z1ao[1] + dmzoob\n oo0a = reduce(numpy.dot, (orboa, orboa.T))\n oo0b = reduce(numpy.dot, (orbob, orbob.T))\n as_dm1 = oo0a + oo0b + (dmz1dooa + dmz1doob) * .5\n vj, vk = td_grad.get_jk(mol, (oo0a, dmz1dooa+dmz1dooa.T, dmxpya+dmxpya.T, dmxmya-dmxmya.T,\n oo0b, dmz1doob+dmz1doob.T, dmxpyb+dmxpyb.T, dmxmyb-dmxmyb.T))\n vj = vj.reshape(2,4,3,nao,nao)\n vk = vk.reshape(2,4,3,nao,nao)\n vhf1a, vhf1b = vj[0] + vj[1] - vk\n time1 = log.timer('2e AO integral derivatives', *time1)\n\n if atmlst is None:\n atmlst = range(mol.natm)\n offsetdic = mol.offset_nr_by_atom()\n de = numpy.zeros((len(atmlst),3))\n for k, ia in enumerate(atmlst):\n shl0, shl1, p0, p1 = offsetdic[ia]\n\n # Ground state gradients\n h1ao = hcore_deriv(ia)\n de[k] = numpy.einsum('xpq,pq->x', h1ao, as_dm1)\n\n de[k] += numpy.einsum('xpq,pq->x', vhf1a[0,:,p0:p1], oo0a[p0:p1])\n de[k] += numpy.einsum('xpq,pq->x', vhf1b[0,:,p0:p1], oo0b[p0:p1])\n de[k] += numpy.einsum('xpq,qp->x', vhf1a[0,:,p0:p1], oo0a[:,p0:p1])\n de[k] += numpy.einsum('xpq,qp->x', vhf1b[0,:,p0:p1], oo0b[:,p0:p1])\n\n de[k] += numpy.einsum('xpq,pq->x', vhf1a[0,:,p0:p1], dmz1dooa[p0:p1]) * .5\n de[k] += numpy.einsum('xpq,pq->x', vhf1b[0,:,p0:p1], dmz1doob[p0:p1]) * .5\n de[k] += numpy.einsum('xpq,qp->x', vhf1a[0,:,p0:p1], dmz1dooa[:,p0:p1]) * .5\n de[k] += numpy.einsum('xpq,qp->x', vhf1b[0,:,p0:p1], dmz1doob[:,p0:p1]) * .5\n\n de[k] -= numpy.einsum('xpq,pq->x', s1[:,p0:p1], im0[p0:p1])\n de[k] -= numpy.einsum('xqp,pq->x', s1[:,p0:p1], im0[:,p0:p1])\n\n de[k] += numpy.einsum('xij,ij->x', vhf1a[1,:,p0:p1], oo0a[p0:p1]) * .5\n de[k] += numpy.einsum('xij,ij->x', vhf1b[1,:,p0:p1], oo0b[p0:p1]) * .5\n de[k] += numpy.einsum('xij,ij->x', vhf1a[2,:,p0:p1], dmxpya[p0:p1,:])\n de[k] += numpy.einsum('xij,ij->x', vhf1b[2,:,p0:p1], dmxpyb[p0:p1,:])\n de[k] += numpy.einsum('xij,ij->x', vhf1a[3,:,p0:p1], dmxmya[p0:p1,:])\n de[k] += numpy.einsum('xij,ij->x', vhf1b[3,:,p0:p1], dmxmyb[p0:p1,:])\n de[k] += numpy.einsum('xji,ij->x', vhf1a[2,:,p0:p1], dmxpya[:,p0:p1])\n de[k] += numpy.einsum('xji,ij->x', vhf1b[2,:,p0:p1], dmxpyb[:,p0:p1])\n de[k] -= numpy.einsum('xji,ij->x', vhf1a[3,:,p0:p1], dmxmya[:,p0:p1])\n de[k] -= numpy.einsum('xji,ij->x', vhf1b[3,:,p0:p1], dmxmyb[:,p0:p1])\n\n dm0 = oo0a + oo0b\n dmz1doo = (dmz1dooa + dmz1doob) * .5\n dmxpy = dmxpya + dmxpyb\n de += _grad_solvent(with_solvent, dm0, dmz1doo, dmxpy)\n\n log.timer('TDUHF nuclear gradients', *time0)\n return de\n\ndef tduks_grad_elec(td_grad, x_y, atmlst=None, max_memory=2000, verbose=logger.INFO):\n '''\n See also function pyscf.grad.tduks.grad_elec\n '''\n log = logger.new_logger(td_grad, verbose)\n time0 = logger.process_clock(), logger.perf_counter()\n\n mol = td_grad.mol\n mf = td_grad.base._scf\n mo_coeff = mf.mo_coeff\n mo_energy = mf.mo_energy\n mo_occ = mf.mo_occ\n\n with_solvent = getattr(td_grad.base, 'with_solvent', mf.with_solvent)\n\n occidxa = numpy.where(mo_occ[0]>0)[0]\n occidxb = numpy.where(mo_occ[1]>0)[0]\n viridxa = numpy.where(mo_occ[0]==0)[0]\n viridxb = numpy.where(mo_occ[1]==0)[0]\n nocca = len(occidxa)\n noccb = len(occidxb)\n nvira = len(viridxa)\n nvirb = len(viridxb)\n orboa = mo_coeff[0][:,occidxa]\n orbob = mo_coeff[1][:,occidxb]\n orbva = mo_coeff[0][:,viridxa]\n orbvb = mo_coeff[1][:,viridxb]\n nao = mo_coeff[0].shape[0]\n nmoa = nocca + nvira\n nmob = noccb + nvirb\n\n (xa, xb), (ya, yb) = x_y\n xpya = (xa+ya).reshape(nocca,nvira).T\n xpyb = (xb+yb).reshape(noccb,nvirb).T\n xmya = (xa-ya).reshape(nocca,nvira).T\n xmyb = (xb-yb).reshape(noccb,nvirb).T\n\n dvva = numpy.einsum('ai,bi->ab', xpya, xpya) + numpy.einsum('ai,bi->ab', xmya, xmya)\n dvvb = numpy.einsum('ai,bi->ab', xpyb, xpyb) + numpy.einsum('ai,bi->ab', xmyb, xmyb)\n dooa =-numpy.einsum('ai,aj->ij', xpya, xpya) - numpy.einsum('ai,aj->ij', xmya, xmya)\n doob =-numpy.einsum('ai,aj->ij', xpyb, xpyb) - numpy.einsum('ai,aj->ij', xmyb, xmyb)\n dmxpya = reduce(numpy.dot, (orbva, xpya, orboa.T))\n dmxpyb = reduce(numpy.dot, (orbvb, xpyb, orbob.T))\n dmxmya = reduce(numpy.dot, (orbva, xmya, orboa.T))\n dmxmyb = reduce(numpy.dot, (orbvb, xmyb, orbob.T))\n dmzooa = reduce(numpy.dot, (orboa, dooa, orboa.T))\n dmzoob = reduce(numpy.dot, (orbob, doob, orbob.T))\n dmzooa+= reduce(numpy.dot, (orbva, dvva, orbva.T))\n dmzoob+= reduce(numpy.dot, (orbvb, dvvb, orbvb.T))\n\n ni = mf._numint\n ni.libxc.test_deriv_order(mf.xc, 3, raise_error=True)\n omega, alpha, hyb = ni.rsh_and_hybrid_coeff(mf.xc, mol.spin)\n # dm0 = mf.make_rdm1(mo_coeff, mo_occ), but it is not used when computing\n # fxc since rho0 is passed to fxc function.\n dm0 = None\n rho0, vxc, fxc = ni.cache_xc_kernel(mf.mol, mf.grids, mf.xc,\n mo_coeff, mo_occ, spin=1)\n f1vo, f1oo, vxc1, k1ao = \\\n tduks_grad._contract_xc_kernel(td_grad, mf.xc, (dmxpya,dmxpyb),\n (dmzooa,dmzoob), True, True, max_memory)\n\n if abs(hyb) > 1e-10:\n dm = (dmzooa, dmxpya+dmxpya.T, dmxmya-dmxmya.T,\n dmzoob, dmxpyb+dmxpyb.T, dmxmyb-dmxmyb.T)\n vj, vk = mf.get_jk(mol, dm, hermi=0)\n vk *= hyb\n if abs(omega) > 1e-10:\n vk += mf.get_k(mol, dm, hermi=0, omega=omega) * (alpha-hyb)\n vj = vj.reshape(2,3,nao,nao)\n vk = vk.reshape(2,3,nao,nao)\n\n if with_solvent.equilibrium_solvation:\n dmxpy = dmxpya + dmxpyb\n vj[0,:2] += mf.with_solvent._B_dot_x((dmzooa+dmzoob, dmxpy+dmxpy.T))\n else:\n vj[0,0] += mf.with_solvent._B_dot_x(dmzooa+dmzoob)\n\n veff0doo = vj[0,0]+vj[1,0] - vk[:,0] + f1oo[:,0] + k1ao[:,0] * 2\n wvoa = reduce(numpy.dot, (orbva.T, veff0doo[0], orboa)) * 2\n wvob = reduce(numpy.dot, (orbvb.T, veff0doo[1], orbob)) * 2\n veff = vj[0,1]+vj[1,1] - vk[:,1] + f1vo[:,0] * 2\n veff0mopa = reduce(numpy.dot, (mo_coeff[0].T, veff[0], mo_coeff[0]))\n veff0mopb = reduce(numpy.dot, (mo_coeff[1].T, veff[1], mo_coeff[1]))\n wvoa -= numpy.einsum('ki,ai->ak', veff0mopa[:nocca,:nocca], xpya) * 2\n wvob -= numpy.einsum('ki,ai->ak', veff0mopb[:noccb,:noccb], xpyb) * 2\n wvoa += numpy.einsum('ac,ai->ci', veff0mopa[nocca:,nocca:], xpya) * 2\n wvob += numpy.einsum('ac,ai->ci', veff0mopb[noccb:,noccb:], xpyb) * 2\n veff = -vk[:,2]\n veff0moma = reduce(numpy.dot, (mo_coeff[0].T, veff[0], mo_coeff[0]))\n veff0momb = reduce(numpy.dot, (mo_coeff[1].T, veff[1], mo_coeff[1]))\n wvoa -= numpy.einsum('ki,ai->ak', veff0moma[:nocca,:nocca], xmya) * 2\n wvob -= numpy.einsum('ki,ai->ak', veff0momb[:noccb,:noccb], xmyb) * 2\n wvoa += numpy.einsum('ac,ai->ci', veff0moma[nocca:,nocca:], xmya) * 2\n wvob += numpy.einsum('ac,ai->ci', veff0momb[noccb:,noccb:], xmyb) * 2\n else:\n dm = (dmzooa, dmxpya+dmxpya.T,\n dmzoob, dmxpyb+dmxpyb.T)\n vj = mf.get_j(mol, dm, hermi=1).reshape(2,2,nao,nao)\n\n if with_solvent.equilibrium_solvation:\n dmxpy = dmxpya + dmxpyb\n vj[0,:2] += mf.with_solvent._B_dot_x((dmzooa+dmzoob, dmxpy+dmxpy.T))\n else:\n vj[0,0] += mf.with_solvent._B_dot_x(dmzooa+dmzoob)\n\n veff0doo = vj[0,0]+vj[1,0] + f1oo[:,0] + k1ao[:,0] * 2\n wvoa = reduce(numpy.dot, (orbva.T, veff0doo[0], orboa)) * 2\n wvob = reduce(numpy.dot, (orbvb.T, veff0doo[1], orbob)) * 2\n veff = vj[0,1]+vj[1,1] + f1vo[:,0] * 2\n veff0mopa = reduce(numpy.dot, (mo_coeff[0].T, veff[0], mo_coeff[0]))\n veff0mopb = reduce(numpy.dot, (mo_coeff[1].T, veff[1], mo_coeff[1]))\n wvoa -= numpy.einsum('ki,ai->ak', veff0mopa[:nocca,:nocca], xpya) * 2\n wvob -= numpy.einsum('ki,ai->ak', veff0mopb[:noccb,:noccb], xpyb) * 2\n wvoa += numpy.einsum('ac,ai->ci', veff0mopa[nocca:,nocca:], xpya) * 2\n wvob += numpy.einsum('ac,ai->ci', veff0mopb[noccb:,noccb:], xpyb) * 2\n veff0moma = numpy.zeros((nmoa,nmoa))\n veff0momb = numpy.zeros((nmob,nmob))\n\n with lib.temporary_env(mf.with_solvent, equilibrium_solvation=True):\n vresp = mf.gen_response(hermi=1)\n def fvind(x):\n dm1 = numpy.empty((2,nao,nao))\n xa = x[0,:nvira*nocca].reshape(nvira,nocca)\n xb = x[0,nvira*nocca:].reshape(nvirb,noccb)\n dma = reduce(numpy.dot, (orbva, xa, orboa.T))\n dmb = reduce(numpy.dot, (orbvb, xb, orbob.T))\n dm1[0] = dma + dma.T\n dm1[1] = dmb + dmb.T\n v1 = vresp(dm1)\n v1a = reduce(numpy.dot, (orbva.T, v1[0], orboa))\n v1b = reduce(numpy.dot, (orbvb.T, v1[1], orbob))\n return numpy.hstack((v1a.ravel(), v1b.ravel()))\n z1a, z1b = ucphf.solve(fvind, mo_energy, mo_occ, (wvoa,wvob),\n max_cycle=td_grad.cphf_max_cycle,\n tol=td_grad.cphf_conv_tol)[0]\n time1 = log.timer('Z-vector using UCPHF solver', *time0)\n\n z1ao = numpy.empty((2,nao,nao))\n z1ao[0] = reduce(numpy.dot, (orbva, z1a, orboa.T))\n z1ao[1] = reduce(numpy.dot, (orbvb, z1b, orbob.T))\n veff = vresp((z1ao+z1ao.transpose(0,2,1)) * .5)\n\n im0a = numpy.zeros((nmoa,nmoa))\n im0b = numpy.zeros((nmob,nmob))\n im0a[:nocca,:nocca] = reduce(numpy.dot, (orboa.T, veff0doo[0]+veff[0], orboa)) * .5\n im0b[:noccb,:noccb] = reduce(numpy.dot, (orbob.T, veff0doo[1]+veff[1], orbob)) * .5\n im0a[:nocca,:nocca]+= numpy.einsum('ak,ai->ki', veff0mopa[nocca:,:nocca], xpya) * .5\n im0b[:noccb,:noccb]+= numpy.einsum('ak,ai->ki', veff0mopb[noccb:,:noccb], xpyb) * .5\n im0a[:nocca,:nocca]+= numpy.einsum('ak,ai->ki', veff0moma[nocca:,:nocca], xmya) * .5\n im0b[:noccb,:noccb]+= numpy.einsum('ak,ai->ki', veff0momb[noccb:,:noccb], xmyb) * .5\n im0a[nocca:,nocca:] = numpy.einsum('ci,ai->ac', veff0mopa[nocca:,:nocca], xpya) * .5\n im0b[noccb:,noccb:] = numpy.einsum('ci,ai->ac', veff0mopb[noccb:,:noccb], xpyb) * .5\n im0a[nocca:,nocca:]+= numpy.einsum('ci,ai->ac', veff0moma[nocca:,:nocca], xmya) * .5\n im0b[noccb:,noccb:]+= numpy.einsum('ci,ai->ac', veff0momb[noccb:,:noccb], xmyb) * .5\n im0a[nocca:,:nocca] = numpy.einsum('ki,ai->ak', veff0mopa[:nocca,:nocca], xpya)\n im0b[noccb:,:noccb] = numpy.einsum('ki,ai->ak', veff0mopb[:noccb,:noccb], xpyb)\n im0a[nocca:,:nocca]+= numpy.einsum('ki,ai->ak', veff0moma[:nocca,:nocca], xmya)\n im0b[noccb:,:noccb]+= numpy.einsum('ki,ai->ak', veff0momb[:noccb,:noccb], xmyb)\n\n zeta_a = (mo_energy[0][:,None] + mo_energy[0]) * .5\n zeta_b = (mo_energy[1][:,None] + mo_energy[1]) * .5\n zeta_a[nocca:,:nocca] = mo_energy[0][:nocca]\n zeta_b[noccb:,:noccb] = mo_energy[1][:noccb]\n zeta_a[:nocca,nocca:] = mo_energy[0][nocca:]\n zeta_b[:noccb,noccb:] = mo_energy[1][noccb:]\n dm1a = numpy.zeros((nmoa,nmoa))\n dm1b = numpy.zeros((nmob,nmob))\n dm1a[:nocca,:nocca] = dooa * .5\n dm1b[:noccb,:noccb] = doob * .5\n dm1a[nocca:,nocca:] = dvva * .5\n dm1b[noccb:,noccb:] = dvvb * .5\n dm1a[nocca:,:nocca] = z1a * .5\n dm1b[noccb:,:noccb] = z1b * .5\n dm1a[:nocca,:nocca] += numpy.eye(nocca) # for ground state\n dm1b[:noccb,:noccb] += numpy.eye(noccb)\n im0a = reduce(numpy.dot, (mo_coeff[0], im0a+zeta_a*dm1a, mo_coeff[0].T))\n im0b = reduce(numpy.dot, (mo_coeff[1], im0b+zeta_b*dm1b, mo_coeff[1].T))\n im0 = im0a + im0b\n\n # Initialize hcore_deriv with the underlying SCF object because some\n # extensions (e.g. QM/MM, solvent) modifies the SCF object only.\n mf_grad = td_grad.base._scf.nuc_grad_method()\n hcore_deriv = mf_grad.hcore_generator(mol)\n s1 = mf_grad.get_ovlp(mol)\n\n dmz1dooa = z1ao[0] + dmzooa\n dmz1doob = z1ao[1] + dmzoob\n oo0a = reduce(numpy.dot, (orboa, orboa.T))\n oo0b = reduce(numpy.dot, (orbob, orbob.T))\n as_dm1 = oo0a + oo0b + (dmz1dooa + dmz1doob) * .5\n\n if abs(hyb) > 1e-10:\n dm = (oo0a, dmz1dooa+dmz1dooa.T, dmxpya+dmxpya.T, dmxmya-dmxmya.T,\n oo0b, dmz1doob+dmz1doob.T, dmxpyb+dmxpyb.T, dmxmyb-dmxmyb.T)\n vj, vk = td_grad.get_jk(mol, dm)\n vj = vj.reshape(2,4,3,nao,nao)\n vk = vk.reshape(2,4,3,nao,nao) * hyb\n if abs(omega) > 1e-10:\n with mol.with_range_coulomb(omega):\n vk += td_grad.get_k(mol, dm).reshape(2,4,3,nao,nao) * (alpha-hyb)\n veff1 = vj[0] + vj[1] - vk\n else:\n dm = (oo0a, dmz1dooa+dmz1dooa.T, dmxpya+dmxpya.T,\n oo0b, dmz1doob+dmz1doob.T, dmxpyb+dmxpyb.T)\n vj = td_grad.get_j(mol, dm).reshape(2,3,3,nao,nao)\n veff1 = numpy.zeros((2,4,3,nao,nao))\n veff1[:,:3] = vj[0] + vj[1]\n\n fxcz1 = tduks_grad._contract_xc_kernel(td_grad, mf.xc, z1ao, None,\n False, False, max_memory)[0]\n\n veff1[:,0] += vxc1[:,1:]\n veff1[:,1] +=(f1oo[:,1:] + fxcz1[:,1:] + k1ao[:,1:]*2)*2 # *2 for dmz1doo+dmz1oo.T\n veff1[:,2] += f1vo[:,1:] * 2\n veff1a, veff1b = veff1\n time1 = log.timer('2e AO integral derivatives', *time1)\n\n if atmlst is None:\n atmlst = range(mol.natm)\n offsetdic = mol.offset_nr_by_atom()\n de = numpy.zeros((len(atmlst),3))\n for k, ia in enumerate(atmlst):\n shl0, shl1, p0, p1 = offsetdic[ia]\n\n # Ground state gradients\n h1ao = hcore_deriv(ia)\n de[k] = numpy.einsum('xpq,pq->x', h1ao, as_dm1)\n\n de[k] += numpy.einsum('xpq,pq->x', veff1a[0,:,p0:p1], oo0a[p0:p1])\n de[k] += numpy.einsum('xpq,pq->x', veff1b[0,:,p0:p1], oo0b[p0:p1])\n de[k] += numpy.einsum('xpq,qp->x', veff1a[0,:,p0:p1], oo0a[:,p0:p1])\n de[k] += numpy.einsum('xpq,qp->x', veff1b[0,:,p0:p1], oo0b[:,p0:p1])\n\n de[k] += numpy.einsum('xpq,pq->x', veff1a[0,:,p0:p1], dmz1dooa[p0:p1]) * .5\n de[k] += numpy.einsum('xpq,pq->x', veff1b[0,:,p0:p1], dmz1doob[p0:p1]) * .5\n de[k] += numpy.einsum('xpq,qp->x', veff1a[0,:,p0:p1], dmz1dooa[:,p0:p1]) * .5\n de[k] += numpy.einsum('xpq,qp->x', veff1b[0,:,p0:p1], dmz1doob[:,p0:p1]) * .5\n\n de[k] -= numpy.einsum('xpq,pq->x', s1[:,p0:p1], im0[p0:p1])\n de[k] -= numpy.einsum('xqp,pq->x', s1[:,p0:p1], im0[:,p0:p1])\n\n de[k] += numpy.einsum('xij,ij->x', veff1a[1,:,p0:p1], oo0a[p0:p1]) * .5\n de[k] += numpy.einsum('xij,ij->x', veff1b[1,:,p0:p1], oo0b[p0:p1]) * .5\n de[k] += numpy.einsum('xij,ij->x', veff1a[2,:,p0:p1], dmxpya[p0:p1,:])\n de[k] += numpy.einsum('xij,ij->x', veff1b[2,:,p0:p1], dmxpyb[p0:p1,:])\n de[k] += numpy.einsum('xij,ij->x', veff1a[3,:,p0:p1], dmxmya[p0:p1,:])\n de[k] += numpy.einsum('xij,ij->x', veff1b[3,:,p0:p1], dmxmyb[p0:p1,:])\n de[k] += numpy.einsum('xji,ij->x', veff1a[2,:,p0:p1], dmxpya[:,p0:p1])\n de[k] += numpy.einsum('xji,ij->x', veff1b[2,:,p0:p1], dmxpyb[:,p0:p1])\n de[k] -= numpy.einsum('xji,ij->x', veff1a[3,:,p0:p1], dmxmya[:,p0:p1])\n de[k] -= numpy.einsum('xji,ij->x', veff1b[3,:,p0:p1], dmxmyb[:,p0:p1])\n\n dm0 = oo0a + oo0b\n dmz1doo = (dmz1dooa + dmz1doob) * .5\n dmxpy = dmxpya + dmxpyb\n de += _grad_solvent(with_solvent, dm0, dmz1doo, dmxpy)\n\n log.timer('TDUHF nuclear gradients', *time0)\n return de\n\n\ndef _grad_solvent(pcmobj, dm0, dmz1doo, dmxpy, singlet=True):\n '''Energy derivatives associated to derivatives of B tensor'''\n dielectric = pcmobj.eps\n if dielectric > 0:\n f_epsilon = (dielectric-1.)/dielectric\n else:\n f_epsilon = 1\n\n r_vdw = pcmobj._intermediates['r_vdw' ]\n ylm_1sph = pcmobj._intermediates['ylm_1sph' ]\n ui = pcmobj._intermediates['ui' ]\n Lmat = pcmobj._intermediates['Lmat' ]\n cached_pol = pcmobj._intermediates['cached_pol']\n\n # First order nuclei-solvent-electron contribution\n tmp = _grad_ne(pcmobj, dmz1doo,\n r_vdw, ui, ylm_1sph, cached_pol, Lmat)\n de = .5 * f_epsilon * tmp\n\n # First order electron-solvent-electron contribution\n tmp = _grad_ee(pcmobj, (dm0, dmxpy), (dmz1doo, dmxpy),\n r_vdw, ui, ylm_1sph, cached_pol, Lmat)\n de += .5 * f_epsilon * tmp[0] # (dm0 * dmz1doo)\n\n if singlet and pcmobj.equilibrium_solvation:\n de += .5 * f_epsilon * tmp[1] # (dmxpy * dmxpy)\n\n return de\n\ndef _grad_nn(pcmobj, r_vdw, ui, ylm_1sph, cached_pol, L):\n '''nuclei-solvent-nuclei term'''\n mol = pcmobj.mol\n natm = mol.natm\n coords_1sph, weights_1sph = ddcosmo.make_grids_one_sphere(pcmobj.lebedev_order)\n ngrid_1sph = coords_1sph.shape[0]\n lmax = pcmobj.lmax\n nlm = (lmax+1)**2\n atom_coords = mol.atom_coords()\n atom_charges = mol.atom_charges()\n\n fi0 = ddcosmo.make_fi(pcmobj, r_vdw)\n fi1 = ddcosmo_grad.make_fi1(pcmobj, pcmobj.get_atomic_radii())\n fi1[:,:,ui==0] = 0\n ui1 = -fi1\n\n de = numpy.zeros((natm,3))\n\n cav_coords = (atom_coords.reshape(natm,1,3)\n + numpy.einsum('r,gx->rgx', r_vdw, coords_1sph))\n\n v_phi = numpy.zeros((natm, ngrid_1sph))\n for ia in range(natm):\n # Note (-) sign is not applied to atom_charges, because (-) is explicitly\n # included in rhs and L matrix\n d_rs = atom_coords.reshape(-1,1,3) - cav_coords[ia]\n v_phi[ia] = numpy.einsum('z,zp->p', atom_charges, 1./lib.norm(d_rs,axis=2))\n phi0 = -numpy.einsum('n,xn,jn,jn->jx', weights_1sph, ylm_1sph, ui, v_phi)\n\n psi0 = numpy.zeros((natm, nlm))\n for ia in range(natm):\n psi0[ia,0] += numpy.sqrt(4*numpy.pi)/r_vdw[ia] * mol.atom_charge(ia)\n\n v_phi0 = numpy.empty((natm,ngrid_1sph))\n for ia in range(natm):\n cav_coords = atom_coords[ia] + r_vdw[ia] * coords_1sph\n d_rs = atom_coords.reshape(-1,1,3) - cav_coords\n v_phi0[ia] = numpy.einsum('z,zp->p', atom_charges, 1./lib.norm(d_rs,axis=2))\n phi1 = -numpy.einsum('n,ln,azjn,jn->azjl', weights_1sph, ylm_1sph, ui1, v_phi0)\n\n for ia in range(natm):\n cav_coords = atom_coords[ia] + r_vdw[ia] * coords_1sph\n for ja in range(natm):\n rs = atom_coords[ja] - cav_coords\n d_rs = lib.norm(rs, axis=1)\n v_phi = atom_charges[ja] * numpy.einsum('px,p->px', rs, 1./d_rs**3)\n tmp = numpy.einsum('n,ln,n,nx->xl', weights_1sph, ylm_1sph, ui[ia], v_phi)\n phi1[ja,:,ia] += tmp # response of the other atoms\n phi1[ia,:,ia] -= tmp # response of cavity grids\n\n L1 = ddcosmo_grad.make_L1(pcmobj, r_vdw, ylm_1sph, fi0)\n Xvec0 = numpy.linalg.solve(L.reshape(natm*nlm,-1), phi0.ravel())\n Xvec0 = Xvec0.reshape(natm,nlm)\n phi1 -= numpy.einsum('aziljm,jm->azil', L1, Xvec0)\n\n LS0 = numpy.linalg.solve(L.reshape(natm*nlm,-1).T, psi0.ravel())\n LS0 = LS0.reshape(natm,nlm)\n de += numpy.einsum('il,azil->az', LS0, phi1)\n\n return de\n\ndef _grad_ne(pcmobj, dm, r_vdw, ui, ylm_1sph, cached_pol, L):\n '''nuclear charge-electron density cross term'''\n mol = pcmobj.mol\n natm = mol.natm\n coords_1sph, weights_1sph = ddcosmo.make_grids_one_sphere(pcmobj.lebedev_order)\n ngrid_1sph = coords_1sph.shape[0]\n lmax = pcmobj.lmax\n nlm = (lmax+1)**2\n nao = mol.nao\n atom_coords = mol.atom_coords()\n atom_charges = mol.atom_charges()\n grids = pcmobj.grids\n aoslices = mol.aoslice_by_atom()\n\n #extern_point_idx = ui > 0\n fi0 = ddcosmo.make_fi(pcmobj, r_vdw)\n fi1 = ddcosmo_grad.make_fi1(pcmobj, pcmobj.get_atomic_radii())\n fi1[:,:,ui==0] = 0\n ui1 = -fi1\n\n dms = numpy.asarray(dm)\n is_single_dm = dms.ndim == 2\n dms = dms.reshape(-1,nao,nao)\n n_dm = dms.shape[0]\n\n de = numpy.zeros((n_dm,natm,3))\n\n cav_coords = (atom_coords.reshape(natm,1,3)\n + numpy.einsum('r,gx->rgx', r_vdw, coords_1sph))\n\n v_phi = numpy.zeros((natm, ngrid_1sph))\n for ia in range(natm):\n # Note (-) sign is not applied to atom_charges, because (-) is explicitly\n # included in rhs and L matrix\n d_rs = atom_coords.reshape(-1,1,3) - cav_coords[ia]\n v_phi[ia] = numpy.einsum('z,zp->p', atom_charges, 1./lib.norm(d_rs,axis=2))\n phi0 = -numpy.einsum('n,xn,jn,jn->jx', weights_1sph, ylm_1sph, ui, v_phi)\n\n Xvec0 = numpy.linalg.solve(L.reshape(natm*nlm,-1), phi0.ravel())\n Xvec0 = Xvec0.reshape(natm,nlm)\n\n v_phi0 = numpy.empty((natm,ngrid_1sph))\n for ia in range(natm):\n cav_coords = atom_coords[ia] + r_vdw[ia] * coords_1sph\n d_rs = atom_coords.reshape(-1,1,3) - cav_coords\n v_phi0[ia] = numpy.einsum('z,zp->p', atom_charges, 1./lib.norm(d_rs,axis=2))\n phi1 = -numpy.einsum('n,ln,azjn,jn->azjl', weights_1sph, ylm_1sph, ui1, v_phi0)\n\n for ia in range(natm):\n cav_coords = atom_coords[ia] + r_vdw[ia] * coords_1sph\n for ja in range(natm):\n rs = atom_coords[ja] - cav_coords\n d_rs = lib.norm(rs, axis=1)\n v_phi = atom_charges[ja] * numpy.einsum('px,p->px', rs, 1./d_rs**3)\n tmp = numpy.einsum('n,ln,n,nx->xl', weights_1sph, ylm_1sph, ui[ia], v_phi)\n phi1[ja,:,ia] += tmp # response of the other atoms\n phi1[ia,:,ia] -= tmp # response of cavity grids\n\n L1 = ddcosmo_grad.make_L1(pcmobj, r_vdw, ylm_1sph, fi0)\n\n phi1 -= numpy.einsum('aziljm,jm->azil', L1, Xvec0)\n Xvec1 = numpy.linalg.solve(L.reshape(natm*nlm,-1), phi1.reshape(-1,natm*nlm).T)\n Xvec1 = Xvec1.T.reshape(natm,3,natm,nlm)\n\n for ia, (coords, weight, weight1) in enumerate(rks_grad.grids_response_cc(grids)):\n ao = mol.eval_gto('GTOval_sph_deriv1', coords)\n\n fak_pol, leak_idx = cached_pol[mol.atom_symbol(ia)]\n fac_pol = ddcosmo._vstack_factor_fak_pol(fak_pol, lmax)\n scaled_weights = numpy.einsum('azm,mn->azn', Xvec1[:,:,ia], fac_pol)\n scaled_weights *= weight\n aow = numpy.einsum('gi,azg->azgi', ao[0], scaled_weights)\n de -= numpy.einsum('nij,gi,azgj->naz', dms, ao[0], aow)\n\n aow0 = numpy.einsum('gi,g->gi', ao[0], weight)\n aow1 = numpy.einsum('gi,zxg->zxgi', ao[0], weight1)\n\n den0 = numpy.einsum('nij,gi,zxgj->nzxg', dms, ao[0], aow1)\n de -= numpy.einsum('m,mg,nzxg->nzx', Xvec0[ia], fac_pol, den0)\n\n eta_nj = numpy.einsum('m,mg->g', Xvec0[ia], fac_pol)\n dm_ao = lib.einsum('nij,gj->ngi', dms, aow0)\n dm_ao += lib.einsum('nji,gj->ngi', dms, aow0)\n for ja in range(natm):\n shl0, shl1, p0, p1 = aoslices[ja]\n den1 = numpy.einsum('ngi,xgi->nxg', dm_ao[:,:,p0:p1], ao[1:,:,p0:p1])\n detmp = numpy.einsum('g,nxg->nx', eta_nj, den1)\n de[:,ja] += detmp\n de[:,ia] -= detmp\n\n psi0 = numpy.zeros((natm, nlm))\n for ia in range(natm):\n psi0[ia,0] += numpy.sqrt(4*numpy.pi)/r_vdw[ia] * mol.atom_charge(ia)\n\n LS0 = numpy.linalg.solve(L.reshape(natm*nlm,-1).T, psi0.ravel())\n LS0 = LS0.reshape(natm,nlm)\n\n LS1 = numpy.einsum('il,aziljm->azjm', LS0, L1)\n LS1 = numpy.linalg.solve(L.reshape(natm*nlm,-1).T, LS1.reshape(-1,natm*nlm).T)\n LS1 = LS1.T.reshape(natm,3,natm,nlm)\n\n int3c2e = mol._add_suffix('int3c2e')\n int3c2e_ip1 = mol._add_suffix('int3c2e_ip1')\n cintopt = gto.moleintor.make_cintopt(mol._atm, mol._bas, mol._env, int3c2e)\n cintopt_ip1 = gto.moleintor.make_cintopt(mol._atm, mol._bas, mol._env, int3c2e_ip1)\n for ia in range(natm):\n cav_coords = atom_coords[ia] + r_vdw[ia] * coords_1sph\n #fakemol = gto.fakemol_for_charges(cav_coords[ui[ia]>0])\n fakemol = gto.fakemol_for_charges(cav_coords)\n wtmp = numpy.einsum('l,n,ln->ln', LS0[ia], weights_1sph, ylm_1sph)\n v_nj = df.incore.aux_e2(mol, fakemol, intor=int3c2e, aosym='s1', cintopt=cintopt)\n jaux = numpy.einsum('ijg,nij->ng', v_nj, dms)\n de -= numpy.einsum('azl,g,lg,g,ng->naz', LS1[:,:,ia], weights_1sph, ylm_1sph, ui[ia], jaux)\n de += numpy.einsum('lg,azg,ng->naz', wtmp, ui1[:,:,ia], jaux)\n\n v_e1_nj = df.incore.aux_e2(mol, fakemol, intor=int3c2e_ip1, comp=3,\n aosym='s1', cintopt=cintopt_ip1)\n for ja in range(natm):\n shl0, shl1, p0, p1 = aoslices[ja]\n jaux1 = numpy.einsum('xijg,nij->nxg', v_e1_nj[:,p0:p1], dms[:,p0:p1])\n jaux1 += numpy.einsum('xijg,nji->nxg', v_e1_nj[:,p0:p1], dms[:,:,p0:p1])\n detmp = numpy.einsum('lg,g,nxg->nx', wtmp, ui[ia], jaux1)\n de[:,ja] -= detmp\n de[:,ia] += detmp\n\n if is_single_dm:\n de = de[0]\n return de\n\ndef _grad_ee(pcmobj, dm1, dm2, r_vdw, ui, ylm_1sph, cached_pol, L):\n '''electron density-electorn density term'''\n mol = pcmobj.mol\n mol = pcmobj.mol\n natm = mol.natm\n nao = mol.nao\n lmax = pcmobj.lmax\n nlm = (lmax+1)**2\n\n atom_coords = mol.atom_coords()\n aoslices = mol.aoslice_by_atom()\n grids = pcmobj.grids\n coords_1sph, weights_1sph = ddcosmo.make_grids_one_sphere(pcmobj.lebedev_order)\n\n #extern_point_idx = ui > 0\n fi0 = ddcosmo.make_fi(pcmobj, r_vdw)\n fi1 = ddcosmo_grad.make_fi1(pcmobj, pcmobj.get_atomic_radii())\n fi1[:,:,ui==0] = 0\n ui1 = -fi1\n\n dm1s = numpy.asarray(dm1)\n dm2s = numpy.asarray(dm2)\n is_single_dm = dm1s.ndim == 2\n dm1s = dm1s.reshape(-1,nao,nao)\n dm2s = dm2s.reshape(-1,nao,nao)\n n_dm = dm1s.shape[0]\n assert dm2s.shape[0] == n_dm\n\n de = numpy.zeros((n_dm,natm,3))\n\n ni = numint.NumInt()\n make_rho, nset, nao = ni._gen_rho_evaluator(mol, dm1s, hermi=0)\n den = numpy.empty((n_dm,grids.weights.size))\n p1 = 0\n for ao, mask, weight, coords in ni.block_loop(mol, grids, nao, 0):\n p0, p1 = p1, p1 + weight.size\n for i in range(n_dm):\n den[i,p0:p1] = make_rho(i, ao, mask, 'LDA') * weight\n\n psi0_dm1 = numpy.zeros((n_dm, natm, nlm))\n i1 = 0\n for ia in range(natm):\n fak_pol, leak_idx = cached_pol[mol.atom_symbol(ia)]\n fac_pol = ddcosmo._vstack_factor_fak_pol(fak_pol, lmax)\n i0, i1 = i1, i1 + fac_pol.shape[1]\n psi0_dm1[:,ia] = -numpy.einsum('mg,ng->nm', fac_pol, den[:,i0:i1])\n LS0 = numpy.linalg.solve(L.reshape(natm*nlm,-1).T, psi0_dm1.reshape(n_dm,-1).T)\n LS0 = LS0.T.reshape(n_dm,natm,nlm)\n\n phi0_dm1 = numpy.zeros((n_dm,natm,nlm))\n phi0_dm2 = numpy.zeros((n_dm,natm,nlm))\n phi1_dm1 = numpy.zeros((n_dm,natm,3,natm,nlm))\n int3c2e = mol._add_suffix('int3c2e')\n int3c2e_ip1 = mol._add_suffix('int3c2e_ip1')\n cintopt = gto.moleintor.make_cintopt(mol._atm, mol._bas, mol._env, int3c2e)\n cintopt_ip1 = gto.moleintor.make_cintopt(mol._atm, mol._bas, mol._env, int3c2e_ip1)\n for ia in range(natm):\n cav_coords = atom_coords[ia] + r_vdw[ia] * coords_1sph\n #fakemol = gto.fakemol_for_charges(cav_coords[ui[ia]>0])\n fakemol = gto.fakemol_for_charges(cav_coords)\n v_nj = df.incore.aux_e2(mol, fakemol, intor=int3c2e, aosym='s1', cintopt=cintopt)\n\n v_phi = numpy.einsum('ijg,nij->ng', v_nj, dm1s)\n phi0_dm1[:,ia] = numpy.einsum('g,lg,g,ng->nl', weights_1sph, ylm_1sph, ui[ia], v_phi)\n phi1_dm1[:,:,:,ia] += numpy.einsum('g,lg,azg,ng->nazl', weights_1sph, ylm_1sph, ui1[:,:,ia], v_phi)\n\n jaux = numpy.einsum('ijg,nij->ng', v_nj, dm2s)\n de += numpy.einsum('nl,g,lg,azg,ng->naz', LS0[:,ia], weights_1sph, ylm_1sph, ui1[:,:,ia], jaux)\n\n v_e1_nj = df.incore.aux_e2(mol, fakemol, intor=int3c2e_ip1, comp=3,\n aosym='s1', cintopt=cintopt_ip1)\n wtmp = numpy.einsum('g,lg,g->lg', weights_1sph, ylm_1sph, ui[ia])\n phi0_dm2[:,ia] = numpy.einsum('lg,ng->nl', wtmp, jaux)\n for ja in range(natm):\n shl0, shl1, p0, p1 = aoslices[ja]\n jaux1 = numpy.einsum('xijg,nij->nxg', v_e1_nj[:,p0:p1], dm2s[:,p0:p1])\n jaux1 += numpy.einsum('xijg,nji->nxg', v_e1_nj[:,p0:p1], dm2s[:,:,p0:p1])\n detmp = numpy.einsum('nl,lg,nxg->nx', LS0[:,ia], wtmp, jaux1)\n de[:,ja] -= detmp\n de[:,ia] += detmp\n\n tmp = numpy.einsum('xijg,nij->nxg', v_e1_nj[:,p0:p1], dm1s[:,p0:p1])\n tmp += numpy.einsum('xijg,nji->nxg', v_e1_nj[:,p0:p1], dm1s[:,:,p0:p1])\n phitmp = numpy.einsum('lg,nxg->nxl', wtmp, tmp)\n phi1_dm1[:,ja,:,ia] -= phitmp\n phi1_dm1[:,ia,:,ia] += phitmp\n\n Xvec0 = numpy.linalg.solve(L.reshape(natm*nlm,-1), phi0_dm1.reshape(n_dm,-1).T)\n Xvec0 = Xvec0.T.reshape(n_dm,natm,nlm)\n\n L1 = ddcosmo_grad.make_L1(pcmobj, r_vdw, ylm_1sph, fi0)\n\n phi1_dm1 -= numpy.einsum('aziljm,njm->nazil', L1, Xvec0)\n Xvec1 = numpy.linalg.solve(L.reshape(natm*nlm,-1), phi1_dm1.reshape(-1,natm*nlm).T)\n Xvec1 = Xvec1.T.reshape(n_dm,natm,3,natm,nlm)\n\n psi1_dm1 = numpy.zeros((n_dm,natm,3,natm,nlm))\n for ia, (coords, weight, weight1) in enumerate(rks_grad.grids_response_cc(grids)):\n ao = mol.eval_gto('GTOval_sph_deriv1', coords)\n\n fak_pol, leak_idx = cached_pol[mol.atom_symbol(ia)]\n fac_pol = ddcosmo._vstack_factor_fak_pol(fak_pol, lmax)\n scaled_weights = numpy.einsum('nazm,mg->nazg', Xvec1[:,:,:,ia], fac_pol)\n scaled_weights *= weight\n aow = numpy.einsum('gi,nazg->nazgi', ao[0], scaled_weights)\n de -= numpy.einsum('nij,gi,nazgj->naz', dm2s, ao[0], aow)\n\n aow0 = numpy.einsum('gi,g->gi', ao[0], weight)\n aow1 = numpy.einsum('gi,zxg->zxgi', ao[0], weight1)\n\n den0 = numpy.einsum('nij,gi,zxgj->nzxg', dm1s, ao[0], aow1)\n psi1_dm1[:,:,:,ia] -= numpy.einsum('mg,nzxg->nzxm', fac_pol, den0)\n\n dm_ao = lib.einsum('nij,gj->ngi', dm1s, aow0)\n dm_ao += lib.einsum('nji,gj->ngi', dm1s, aow0)\n for ja in range(natm):\n shl0, shl1, p0, p1 = aoslices[ja]\n den1 = numpy.einsum('ngi,xgi->nxg', dm_ao[:,:,p0:p1], ao[1:,:,p0:p1])\n psitmp = numpy.einsum('mg,nxg->nxm', fac_pol, den1)\n psi1_dm1[:,ja,:,ia] += psitmp\n psi1_dm1[:,ia,:,ia] -= psitmp\n\n eta_nj = numpy.einsum('nm,mg->ng', Xvec0[:,ia], fac_pol)\n den0 = numpy.einsum('nij,gi,zxgj->nzxg', dm2s, ao[0], aow1)\n de -= numpy.einsum('ng,nzxg->nzx', eta_nj, den0)\n\n dm_ao = lib.einsum('nij,gj->ngi', dm2s, aow0)\n dm_ao += lib.einsum('nji,gj->ngi', dm2s, aow0)\n for ja in range(natm):\n shl0, shl1, p0, p1 = aoslices[ja]\n den1 = lib.einsum('ngi,xgi->nxg', dm_ao[:,:,p0:p1], ao[1:,:,p0:p1])\n detmp = numpy.einsum('ng,nxg->nx', eta_nj, den1)\n de[:,ja] += detmp\n de[:,ia] -= detmp\n\n psi1_dm1 -= numpy.einsum('nil,aziljm->nazjm', LS0, L1)\n LS1 = numpy.linalg.solve(L.reshape(natm*nlm,-1).T, psi1_dm1.reshape(-1,natm*nlm).T)\n LS1 = LS1.T.reshape(n_dm,natm,3,natm,nlm)\n de += numpy.einsum('nazjx,njx->naz', LS1, phi0_dm2)\n\n if is_single_dm:\n de = de[0]\n return de\n\n\nif __name__ == '__main__':\n mol0 = gto.M(atom='H 0. 0. 1.804; F 0. 0. 0.', verbose=0, unit='B')\n mol1 = gto.M(atom='H 0. 0. 1.803; F 0. 0. 0.', verbose=0, unit='B')\n mol2 = gto.M(atom='H 0. 0. 1.805; F 0. 0. 0.', verbose=0, unit='B')\n\n # TDA with equilibrium_solvation\n mf = mol0.RHF().ddCOSMO().run()\n td = mf.TDA().ddCOSMO().run(equilibrium_solvation=True)\n g1 = td.nuc_grad_method().kernel() # 0 0 -0.5116214042\n\n mf = mol1.RHF().ddCOSMO().run()\n td1 = mf.TDA().ddCOSMO().run(equilibrium_solvation=True)\n mf = mol2.RHF().ddCOSMO().run()\n td2 = mf.TDA().ddCOSMO().run(equilibrium_solvation=True)\n print((td2.e_tot[0]-td1.e_tot[0])/0.002, g1[0,2])\n print((td2.e_tot[0]-td1.e_tot[0])/0.002 - g1[0,2])\n\n # TDA without equilibrium_solvation\n mf = mol0.RHF().ddCOSMO().run()\n td = mf.TDA().ddCOSMO().run()\n g1 = td.nuc_grad_method().kernel()\n\n mf = mol1.RHF().ddCOSMO().run()\n td1 = mf.TDA().ddCOSMO().run()\n mf = mol2.RHF().ddCOSMO().run()\n td2 = mf.TDA().ddCOSMO().run()\n print((td2.e_tot[0]-td1.e_tot[0])/0.002, g1[0,2])\n print((td2.e_tot[0]-td1.e_tot[0])/0.002 - g1[0,2])\n\n # TDA lda with equilibrium_solvation\n mf = mol0.RKS().ddCOSMO().run(xc='svwn')\n td = mf.TDA().ddCOSMO().run(equilibrium_solvation=True)\n g1 = td.nuc_grad_method().kernel()\n\n mf = mol1.RKS().ddCOSMO().run(xc='svwn')\n td1 = mf.TDA().ddCOSMO().run(equilibrium_solvation=True)\n mf = mol2.RKS().ddCOSMO().run(xc='svwn')\n td2 = mf.TDA().ddCOSMO().run(equilibrium_solvation=True)\n print((td2.e_tot[0]-td1.e_tot[0])/0.002, g1[0,2])\n print((td2.e_tot[0]-td1.e_tot[0])/0.002 - g1[0,2])\n", "meta": {"hexsha": "6a6c0cea0310c3fc9d5d8eff122255f3728bc118", "size": 57033, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/solvent/_ddcosmo_tdscf_grad.py", "max_stars_repo_name": "QuESt-Calculator/pyscf", "max_stars_repo_head_hexsha": "0ed03633b699505c7278f1eb501342667d0aa910", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 501, "max_stars_repo_stars_event_min_datetime": "2018-12-06T23:48:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T11:53:18.000Z", "max_issues_repo_path": "pyscf/solvent/_ddcosmo_tdscf_grad.py", "max_issues_repo_name": "QuESt-Calculator/pyscf", "max_issues_repo_head_hexsha": "0ed03633b699505c7278f1eb501342667d0aa910", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 710, "max_issues_repo_issues_event_min_datetime": "2018-11-26T22:04:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T03:53:12.000Z", "max_forks_repo_path": "pyscf/solvent/_ddcosmo_tdscf_grad.py", "max_forks_repo_name": "QuESt-Calculator/pyscf", "max_forks_repo_head_hexsha": "0ed03633b699505c7278f1eb501342667d0aa910", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 273, "max_forks_repo_forks_event_min_datetime": "2018-11-26T10:10:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:25:28.000Z", "avg_line_length": 44.0409266409, "max_line_length": 107, "alphanum_fraction": 0.5922711413, "include": true, "reason": "import numpy", "num_tokens": 22462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.20946969120038575, "lm_q1q2_score": 0.108006744523269}} {"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\n\"\"\"Functions for performing aperture photometry on 2-D arrays.\"\"\"\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\nimport math\nimport abc\nimport numpy as np\nimport warnings\nimport astropy.units as u\nfrom astropy.io import fits\nfrom astropy.table import Table\nfrom astropy.wcs import WCS\nfrom astropy.coordinates import SkyCoord\nfrom astropy.extern import six\nfrom astropy.utils.misc import InheritDocstrings\nfrom astropy.utils.exceptions import AstropyUserWarning\nfrom .aperture_funcs import do_circular_photometry, do_elliptical_photometry\nfrom .wcsutils import skycoord_to_pixel, skycoord_to_pixel_scale_angle, assert_angle_or_pixel, assert_angle\n\n__all__ = ['Aperture', 'SkyAperture', 'PixelAperture',\n 'SkyCircularAperture', 'CircularAperture',\n 'SkyCircularAnnulus', 'CircularAnnulus',\n 'SkyEllipticalAperture', 'EllipticalAperture',\n 'SkyEllipticalAnnulus', 'EllipticalAnnulus',\n 'RectangularAperture', 'aperture_photometry']\n\n\ndef _make_annulus_path(patch_inner, patch_outer):\n import matplotlib.path as mpath\n verts_inner = patch_inner.get_verts()\n verts_outer = patch_outer.get_verts()\n codes_inner = (np.ones(len(verts_inner), dtype=mpath.Path.code_type) *\n mpath.Path.LINETO)\n codes_inner[0] = mpath.Path.MOVETO\n codes_outer = (np.ones(len(verts_outer), dtype=mpath.Path.code_type) *\n mpath.Path.LINETO)\n codes_outer[0] = mpath.Path.MOVETO\n codes = np.concatenate((codes_inner, codes_outer))\n verts = np.concatenate((verts_inner, verts_outer[::-1]))\n return mpath.Path(verts, codes)\n\n\nclass _ABCMetaAndInheritDocstrings(InheritDocstrings, abc.ABCMeta):\n pass\n\n\n@six.add_metaclass(_ABCMetaAndInheritDocstrings)\nclass Aperture(object):\n \"\"\"\n Abstract base class for all apertures.\n \"\"\"\n\n\n@six.add_metaclass(_ABCMetaAndInheritDocstrings)\nclass SkyAperture(Aperture):\n \"\"\"\n Abstract base class for 2-d apertures defined in celestial coordinates.\n \"\"\"\n\n\n@six.add_metaclass(_ABCMetaAndInheritDocstrings)\nclass PixelAperture(Aperture):\n \"\"\"\n Abstract base class for 2-d apertures defined in pixel coordinates.\n\n Derived classes should contain whatever internal data is needed to\n define the aperture, and provide methods `do_photometry` and `extent`\n (and optionally, ``area``).\n \"\"\"\n\n @abc.abstractmethod\n def plot(self, ax=None, fill=False, **kwargs):\n \"\"\"\n Plot the aperture(s) on a matplotlib Axes instance.\n\n Parameters\n ----------\n ax : `matplotlib.axes.Axes` instance, optional\n If `None`, then the current ``Axes`` instance is used.\n\n fill : bool, optional\n Set whether to fill the aperture patch. The default is\n `False`.\n\n kwargs\n Any keyword arguments accepted by `matplotlib.patches.Patch`.\n \"\"\"\n\n @abc.abstractmethod\n def do_photometry(self, data, error=None, gain=None, pixelwise_error=True,\n method='exact', subpixels=5):\n \"\"\"Sum flux within aperture(s).\n\n Parameters\n ----------\n data : array_like\n The 2-d array on which to perform photometry.\n error : array_like, optional\n Error in each pixel, interpreted as Gaussian 1-sigma uncertainty.\n ``error`` has to have the same shape as ``data``.\n gain : array_like, optional\n Ratio of counts (e.g., electrons or photons) to units of the\n data (e.g., ADU), for the purpose of calculating Poisson error from\n the object itself. ``gain`` has to have the same shape as ``data``.\n pixelwise_error : bool, optional\n For error and/or gain arrays. If `True`, assume error and/or gain\n vary significantly within an aperture: sum contribution from each\n pixel. If `False`, assume error and gain do not vary significantly\n within an aperture.\n method : str, optional\n Method to threat masked pixels. For the currently supported methods\n see the documentation of `aperture_photometry`.\n subpixels : int, optional\n For the ``'subpixel'`` method, resample pixels by this factor (in\n each dimension). That is, each pixel is divided into\n ``subpixels ** 2`` subpixels.\n\n Returns\n -------\n flux : `~astropy.units.Quantity`\n Sum of the values withint the aperture(s). Unit is kept to be the\n unit of the input ``data``.\n\n fluxvar : `~astropy.units.Quantity`\n Corresponting uncertainity in the ``flux`` values. Returned only\n if input ``error`` is not `None`.\n \"\"\"\n\n def area():\n \"\"\"\n Area of aperture.\n\n Returns\n -------\n area : float\n Area of aperture.\n \"\"\"\n\n\nclass SkyCircularAperture(SkyAperture):\n \"\"\"\n Circular aperture(s), defined in sky coordinates.\n\n Parameters\n ----------\n positions : `~astropy.coordinates.SkyCoord`\n Celestial coordinates of the aperture center(s). This can be either\n scalar coordinates or an array of coordinates.\n r : `~astropy.units.Quantity`\n The radius of the aperture(s), either in angular or pixel units.\n \"\"\"\n\n def __init__(self, positions, r):\n\n if isinstance(positions, SkyCoord):\n self.positions = positions\n else:\n raise TypeError(\"positions should be a SkyCoord instance\")\n\n assert_angle_or_pixel('r', r)\n self.r = r\n\n def to_pixel(self, wcs):\n \"\"\"\n Return a CircularAperture instance in pixel coordinates.\n \"\"\"\n\n if self.r.unit.physical_type == 'angle':\n x, y, scale, angle = skycoord_to_pixel_scale_angle(self.positions, wcs)\n # TODO: no need to use the mean once we support arrays of aperture values\n r = (np.mean(scale) * self.r).to(u.pixel).value\n else: # pixel\n x, y = skycoord_to_pixel(self.positions, wcs)\n r = self.r.value\n\n pixel_positions = np.array([x, y]).transpose()\n\n return CircularAperture(pixel_positions, r)\n\n\nclass CircularAperture(PixelAperture):\n \"\"\"\n Circular aperture(s), defined in pixel coordinates.\n\n Parameters\n ----------\n positions : tuple, list, array, or `~astropy.units.Quantity`\n Pixel coordinates of the aperture center(s), either as a single\n ``(x, y)`` tuple, a list of ``(x, y)`` tuples, an ``Nx2`` Numpy\n array, or an ``Nx2`` `~astropy.units.Quantity` in units of pixels.\n r : float\n The radius of the aperture(s), in pixels.\n\n Raises\n ------\n ValueError : `~.exceptions.ValueError`\n If the radius is negative.\n \"\"\"\n\n def __init__(self, positions, r):\n\n try:\n self.r = float(r)\n except TypeError:\n raise TypeError('r must be numeric, received {0}'.format(type(r)))\n\n if r < 0:\n raise ValueError('r must be non-negative')\n\n if isinstance(positions, u.Quantity):\n if positions.unit is u.pixel:\n positions = positions.value\n else:\n raise u.UnitsError(\"positions should be in pixel units\")\n\n self.positions = np.asarray(positions)\n\n if self.positions.ndim == 1 and len(self.positions) == 2:\n self.positions = np.atleast_2d(positions)\n elif self.positions.ndim != 2 or self.positions.shape[1] != 2:\n raise TypeError(\"Expected (x, y) tuple, a list of (x, y) \"\n \"tuples, or an Nx2 array, got {0}\".format(positions))\n\n def area(self):\n return math.pi * self.r ** 2\n\n def plot(self, ax=None, fill=False, source_id=None, **kwargs):\n\n import matplotlib.pyplot as plt\n import matplotlib.patches as mpatches\n\n kwargs['fill'] = fill\n\n if ax is None:\n ax = plt.gca()\n if source_id is None:\n positions = self.positions\n else:\n positions = self.positions[np.atleast_1d(source_id)]\n\n for position in positions:\n patch = mpatches.Circle(position, self.r, **kwargs)\n ax.add_patch(patch)\n\n def do_photometry(self, data, error=None, gain=None, pixelwise_error=True,\n method='exact', subpixels=5):\n\n if method not in ('center', 'subpixel', 'exact'):\n raise ValueError('{0} method not supported for aperture class '\n '{1}'.format(method, self.__class__.__name__))\n\n flux = do_circular_photometry(data, self.positions,\n self.r, error=error, gain=gain,\n pixelwise_error=pixelwise_error,\n method=method,\n subpixels=subpixels)\n return flux\n\n\nclass SkyCircularAnnulus(SkyAperture):\n \"\"\"\n Circular annulus aperture(s), defined in sky coordinates.\n\n Parameters\n ----------\n\n positions : `~astropy.coordinates.SkyCoord`\n Celestial coordinates of the aperture center(s). This can be either\n scalar coordinates or an array of coordinates.\n r : `~astropy.units.Quantity`\n The radius of the aperture(s), either in angular or pixel units.\n \"\"\"\n\n def __init__(self, positions, r_in, r_out):\n\n if isinstance(positions, SkyCoord):\n self.positions = positions\n else:\n raise TypeError(\"positions should be a SkyCoord instance\")\n\n assert_angle_or_pixel('r_in', r_in)\n assert_angle_or_pixel('r_out', r_out)\n\n if r_in.unit.physical_type != r_out.unit.physical_type:\n raise ValueError(\"r_in and r_out should either both be angles or in pixels\")\n\n self.r_in = r_in\n self.r_out = r_out\n\n def to_pixel(self, wcs):\n \"\"\"\n Return a CircularAnnulus instance in pixel coordinates.\n \"\"\"\n\n if self.r_in.unit.physical_type == 'angle':\n x, y, scale, angle = skycoord_to_pixel_scale_angle(self.positions, wcs)\n # TODO: no need to use the mean once we support arrays of aperture values\n r_in = (np.mean(scale) * self.r_in).to(u.pixel).value\n r_out = (np.mean(scale) * self.r_out).to(u.pixel).value\n else: # pixel\n x, y = skycoord_to_pixel(self.positions, wcs)\n r_in = self.r_in.value\n r_out = self.r_out.value\n\n pixel_positions = np.array([x, y]).transpose()\n\n return CircularAnnulus(pixel_positions, r_in, r_out)\n\n\nclass CircularAnnulus(PixelAperture):\n \"\"\"\n Circular annulus aperture(s), defined in pixel coordinates.\n\n Parameters\n ----------\n positions : tuple, list, array, or `~astropy.units.Quantity`\n Pixel coordinates of the aperture center(s), either as a single\n ``(x, y)`` tuple, a list of ``(x, y)`` tuples, an ``Nx2`` Numpy\n array, or an ``Nx2`` `~astropy.units.Quantity` in units of pixels.\n r_in : float\n The inner radius of the annulus.\n r_out : float\n The outer radius of the annulus.\n\n Raises\n ------\n ValueError : `~.exceptions.ValueError`\n If inner radius (``r_in``) is greater than outer radius (``r_out``).\n ValueError : `~.exceptions.ValueError`\n If inner radius is negative.\n \"\"\"\n\n def __init__(self, positions, r_in, r_out):\n try:\n self.r_in = r_in\n self.r_out = r_out\n except TypeError:\n raise TypeError(\"'r_in' and 'r_out' must be numeric, received {0} \"\n \"and {1}\".format((type(r_in), type(r_out))))\n\n if not (r_out > r_in):\n raise ValueError('r_out must be greater than r_in')\n if r_in < 0:\n raise ValueError('r_in must be non-negative')\n\n if isinstance(positions, u.Quantity):\n positions = positions.value\n if isinstance(positions, (list, tuple, np.ndarray)):\n self.positions = np.atleast_2d(positions)\n else:\n raise TypeError(\"List or array of (x,y) pixel coordinates is \"\n \"expected got '{0}'.\".format(positions))\n\n if self.positions.ndim > 2:\n raise ValueError('{0}-d position array not supported. Only 2-d '\n 'arrays supported.'.format(self.positions.ndim))\n\n def area(self):\n return math.pi * (self.r_out ** 2 - self.r_in ** 2)\n\n def do_photometry(self, data, error=None, gain=None, pixelwise_error=True,\n method='exact', subpixels=5):\n\n if method not in ('center', 'subpixel', 'exact'):\n raise ValueError('{0} method not supported for aperture class '\n '{1}'.format(method, self.__class__.__name__))\n\n flux = do_circular_photometry(data, self.positions,\n self.r_out, error=error, gain=gain,\n pixelwise_error=pixelwise_error,\n method=method,\n subpixels=subpixels,\n r_in=self.r_in)\n\n return flux\n\n def plot(self, ax=None, fill=False, source_id=None, **kwargs):\n\n import matplotlib.pyplot as plt\n import matplotlib.patches as mpatches\n\n kwargs['fill'] = fill\n\n if ax is None:\n ax = plt.gca()\n\n if source_id is None:\n positions = self.positions\n else:\n positions = self.positions[np.atleast_1d(source_id)]\n\n resolution = 20\n\n for position in positions:\n patch_inner = mpatches.CirclePolygon(position, self.r_in,\n resolution=resolution)\n patch_outer = mpatches.CirclePolygon(position, self.r_out,\n resolution=resolution)\n path = _make_annulus_path(patch_inner, patch_outer)\n patch = mpatches.PathPatch(path, **kwargs)\n ax.add_patch(patch)\n\n\nclass SkyEllipticalAperture(SkyAperture):\n \"\"\"\n Elliptical aperture(s), defined in sky coordinates.\n\n Parameters\n ----------\n positions : `~astropy.coordinates.SkyCoord`\n Celestial coordinates of the aperture center(s). This can be either\n scalar coordinates or an array of coordinates.\n a : `~astropy.units.Quantity`\n The semimajor axis, either in angular or pixel units.\n b : `~astropy.units.Quantity`\n The semiminor axis, either in angular or pixel units.\n theta : `~astropy.units.Quantity`\n The position angle of the semimajor axis (counterclockwise), either\n in angular or pixel units.\n \"\"\"\n\n def __init__(self, positions, a, b, theta):\n\n if isinstance(positions, SkyCoord):\n self.positions = positions\n else:\n raise TypeError(\"positions should be a SkyCoord instance\")\n\n assert_angle_or_pixel('a', a)\n assert_angle_or_pixel('b', b)\n assert_angle('theta', theta)\n\n if a.unit.physical_type != b.unit.physical_type:\n raise ValueError(\"a and b should either both be angles or in pixels\")\n\n self.a = a\n self.b = b\n self.theta = theta\n\n def to_pixel(self, wcs):\n \"\"\"\n Return a EllipticalAperture instance in pixel coordinates.\n \"\"\"\n\n x, y, scale, angle = skycoord_to_pixel_scale_angle(self.positions, wcs)\n\n # TODO: no need to use the mean once we support arrays of aperture values\n if self.a.unit.physical_type == 'angle':\n a = (np.mean(scale) * self.a).to(u.pixel).value\n b = (np.mean(scale) * self.b).to(u.pixel).value\n else: # pixel\n a = self.a.value\n b = self.b.value\n\n theta = (angle + self.theta).to(u.radian).value\n\n pixel_positions = np.array([x, y]).transpose()\n\n return EllipticalAperture(pixel_positions, a, b, theta)\n\n\nclass EllipticalAperture(PixelAperture):\n \"\"\"\n Elliptical aperture(s), defined in pixel coordinates.\n\n Parameters\n ----------\n positions : tuple, list, array, or `~astropy.units.Quantity`\n Pixel coordinates of the aperture center(s), either as a single\n ``(x, y)`` tuple, a list of ``(x, y)`` tuples, an ``Nx2`` Numpy\n array, or an ``Nx2`` `~astropy.units.Quantity` in units of pixels.\n a : float\n The semimajor axis.\n b : float\n The semiminor axis.\n theta : float\n The position angle of the semimajor axis in radians\n (counterclockwise).\n\n Raises\n ------\n ValueError : `~.exceptions.ValueError`\n If either axis (``a`` or ``b``) is negative.\n\n \"\"\"\n\n def __init__(self, positions, a, b, theta):\n try:\n self.a = float(a)\n self.b = float(b)\n self.theta = float(theta)\n except TypeError:\n raise TypeError(\"'a' and 'b' and 'theta' must be numeric, received\"\n \"{0} and {1} and {2}.\"\n .format((type(a), type(b), type(theta))))\n\n if a < 0 or b < 0:\n raise ValueError(\"'a' and 'b' must be non-negative.\")\n\n if isinstance(positions, u.Quantity):\n positions = positions.value\n if isinstance(positions, (list, tuple, np.ndarray)):\n self.positions = np.atleast_2d(positions)\n else:\n raise TypeError(\"List or array of (x,y) pixel coordinates is \"\n \"expected got '{0}'.\".format(positions))\n\n if self.positions.ndim > 2:\n raise ValueError('{0}-d position array not supported. Only 2-d '\n 'arrays supported.'.format(self.positions.ndim))\n\n def area(self):\n return math.pi * self.a * self.b\n\n def do_photometry(self, data, error=None, gain=None, pixelwise_error=True,\n method='exact', subpixels=5):\n\n if method not in ('center', 'subpixel', 'exact'):\n raise ValueError('{0} method not supported for aperture class '\n '{1}'.format(method, self.__class__.__name__))\n\n flux = do_elliptical_photometry(data, self.positions,\n self.a, self.b, self.theta,\n error=error, gain=gain,\n pixelwise_error=pixelwise_error,\n method=method,\n subpixels=subpixels)\n return flux\n\n def plot(self, ax=None, fill=False, source_id=None, **kwargs):\n\n import matplotlib.pyplot as plt\n import matplotlib.patches as mpatches\n\n kwargs['fill'] = fill\n\n if ax is None:\n ax = plt.gca()\n\n if source_id is None:\n positions = self.positions\n else:\n positions = self.positions[np.atleast_1d(source_id)]\n\n theta_deg = self.theta * 180. / np.pi\n for position in positions:\n patch = mpatches.Ellipse(position, 2.*self.a, 2.*self.b,\n theta_deg, **kwargs)\n ax.add_patch(patch)\n\n\nclass SkyEllipticalAnnulus(SkyAperture):\n \"\"\"\n Elliptical annulus aperture(s), defined in sky coordinates.\n\n Parameters\n ----------\n positions : `~astropy.coordinates.SkyCoord`\n Celestial coordinates of the aperture center(s). This can be either\n scalar coordinates or an array of coordinates.\n a_in : `~astropy.units.Quantity`\n The inner semimajor axis, either in angular or pixel units.\n a_out : `~astropy.units.Quantity`\n The outer semimajor axis, either in angular or pixel units.\n b_out : `~astropy.units.Quantity`\n The outer semiminor axis, either in angular or pixel units. The inner\n semiminor axis is determined by scaling by a_in/a_out.\n theta : `~astropy.units.Quantity`\n The position angle of the semimajor axis (counterclockwise), either\n in angular or pixel units.\n \"\"\"\n\n def __init__(self, positions, a_in, a_out, b_out, theta):\n\n if isinstance(positions, SkyCoord):\n self.positions = positions\n else:\n raise TypeError(\"positions should be a SkyCoord instance\")\n\n assert_angle_or_pixel('a_in', a_in)\n assert_angle_or_pixel('a_out', a_out)\n assert_angle_or_pixel('b_out', b_out)\n assert_angle('theta', theta)\n\n if a_in.unit.physical_type != a_out.unit.physical_type:\n raise ValueError(\"a_in and a_out should either both be angles or in pixels\")\n\n if a_out.unit.physical_type != b_out.unit.physical_type:\n raise ValueError(\"a_out and b_out should either both be angles or in pixels\")\n\n self.a_in = a_in\n self.a_out = a_out\n self.b_out = b_out\n self.theta = theta\n\n def to_pixel(self, wcs):\n \"\"\"\n Return a EllipticalAnnulus instance in pixel coordinates.\n \"\"\"\n\n x, y, scale, angle = skycoord_to_pixel_scale_angle(self.positions, wcs)\n\n # TODO: no need to use the mean once we support arrays of aperture values\n if self.a_in.unit.physical_type == 'angle':\n a_in = (np.mean(scale) * self.a_in).to(u.pixel).value\n a_out = (np.mean(scale) * self.a_out).to(u.pixel).value\n b_out = (np.mean(scale) * self.b_out).to(u.pixel).value\n else:\n a_in = self.a_in.value\n a_out = self.a_out.value\n b_out = self.b_out.value\n\n theta = (angle + self.theta).to(u.radian).value\n\n pixel_positions = np.array([x, y]).transpose()\n\n return EllipticalAnnulus(pixel_positions, a_in, a_out, b_out, theta)\n\n\nclass EllipticalAnnulus(PixelAperture):\n \"\"\"\n Elliptical annulus aperture(s), defined in pixel coordinates.\n\n Parameters\n ----------\n positions : tuple, list, array, or `~astropy.units.Quantity`\n Pixel coordinates of the aperture center(s), either as a single\n ``(x, y)`` tuple, a list of ``(x, y)`` tuples, an ``Nx2`` Numpy\n array, or an ``Nx2`` `~astropy.units.Quantity` in units of pixels.\n a_in : float\n The inner semimajor axis.\n a_out : float\n The outer semimajor axis.\n b_out : float\n The outer semiminor axis. (The inner semiminor axis is determined\n by scaling by a_in/a_out.)\n theta : float\n The position angle of the semimajor axis in radians.\n (counterclockwise).\n\n Raises\n ------\n ValueError : `~.exceptions.ValueError`\n If inner semimajor axis (``a_in``) is greater than outer semimajor\n axis (``a_out``).\n ValueError : `~.exceptions.ValueError`\n If either the inner semimajor axis (``a_in``) or the outer semiminor\n axis (``b_out``) is negative.\n \"\"\"\n\n def __init__(self, positions, a_in, a_out, b_out, theta):\n try:\n self.a_in = float(a_in)\n self.a_out = float(a_out)\n self.b_out = float(b_out)\n self.theta = float(theta)\n except TypeError:\n raise TypeError(\"'a_in' and 'a_out' and 'b_out' and 'theta' must \"\n \"be numeric, received {0} and {1} and {2} and {3}.\"\n .format((type(a_in), type(a_out),\n type(b_out), type(theta))))\n\n if not (a_out > a_in):\n raise ValueError(\"'a_out' must be greater than 'a_in'\")\n if a_in < 0 or b_out < 0:\n raise ValueError(\"'a_in' and 'b_out' must be non-negative\")\n\n self.b_in = a_in * b_out / a_out\n\n if isinstance(positions, u.Quantity):\n positions = positions.value\n if isinstance(positions, (list, tuple, np.ndarray)):\n self.positions = np.atleast_2d(positions)\n else:\n raise TypeError(\"List or array of (x,y) pixel coordinates is \"\n \"expected got '{0}'.\".format(positions))\n\n if self.positions.ndim > 2:\n raise ValueError('{0}-d position array not supported. Only 2-d '\n 'arrays supported.'.format(self.positions.ndim))\n\n def area(self):\n return math.pi * (self.a_out * self.b_out - self.a_in * self.b_in)\n\n def plot(self, ax=None, fill=False, source_id=None, **kwargs):\n\n import matplotlib.pyplot as plt\n import matplotlib.patches as mpatches\n\n kwargs['fill'] = fill\n\n if ax is None:\n ax = plt.gca()\n\n if source_id is None:\n positions = self.positions\n else:\n positions = self.positions[np.atleast_1d(source_id)]\n\n theta_deg = self.theta * 180. / np.pi\n for position in positions:\n patch_inner = mpatches.Ellipse(position, 2.*self.a_in,\n 2.*self.b_in, theta_deg, **kwargs)\n patch_outer = mpatches.Ellipse(position, 2.*self.a_out,\n 2.*self.b_out, theta_deg, **kwargs)\n path = _make_annulus_path(patch_inner, patch_outer)\n patch = mpatches.PathPatch(path, **kwargs)\n ax.add_patch(patch)\n\n def do_photometry(self, data, error=None, gain=None, pixelwise_error=True,\n method='exact', subpixels=5):\n\n if method not in ('center', 'subpixel', 'exact'):\n raise ValueError('{0} method not supported for aperture class '\n '{1}'.format(method, self.__class__.__name__))\n\n flux = do_elliptical_photometry(data, self.positions,\n self.a_out, self.b_out, self.theta,\n error=error, gain=gain,\n pixelwise_error=pixelwise_error,\n method=method,\n subpixels=subpixels,\n a_in=self.a_in)\n\n return flux\n\n\nclass RectangularAperture(PixelAperture):\n \"\"\"\n A rectangular aperture.\n\n Parameters\n ----------\n positions : tuple, or list, or array\n Center coordinates of the apertures as list or array of (x, y)\n pixelcoordinates.\n w : float\n The full width of the aperture (at theta = 0, this is the \"x\" axis).\n h : float\n The full height of the aperture (at theta = 0, this is the \"y\" axis).\n theta : float\n The position angle of the semimajor axis in radians\n (counterclockwise).\n\n Raises\n ------\n ValueError : `~.exceptions.ValueError`\n If either width (``w``) or height (``h``) is negative.\n \"\"\"\n\n def __init__(self, positions, w, h, theta):\n try:\n self.w = float(w)\n self.h = float(h)\n self.theta = float(theta)\n except TypeError:\n raise TypeError(\"'w' and 'h' and 'theta' must \"\n \"be numeric, received {0} and {1} and {2}.\"\n .format((type(w), type(h), type(theta))))\n if w < 0 or h < 0:\n raise ValueError(\"'w' and 'h' must be nonnegative.\")\n\n if isinstance(positions, u.Quantity):\n positions = positions.value\n if isinstance(positions, (list, tuple, np.ndarray)):\n self.positions = np.atleast_2d(positions)\n else:\n raise TypeError(\"List or array of (x,y) pixel coordinates is \"\n \"expected got '{0}'.\".format(positions))\n\n if self.positions.ndim > 2:\n raise ValueError('{0}-d position array not supported. Only 2-d '\n 'arrays supported.'.format(self.positions.ndim))\n\n def extent(self):\n r = max(self.h, self.w) * 2 ** -0.5\n # this is an overestimate by up to sqrt(2) unless theta = 45 deg\n extents = []\n centers = []\n for x, y in self.positions:\n extents.append((int(x - r + 0.5), int(x + r + 1.5),\n int(y - r + 0.5), int(y + r + 1.5)))\n centers.append((x, x, y, y))\n\n self._centers = np.array(centers)\n return np.array(extents)\n\n def area(self):\n return self.w * self.h\n\n def plot(self, ax=None, fill=False, source_id=None, **kwargs):\n\n import matplotlib.pyplot as plt\n import matplotlib.patches as mpatches\n\n kwargs['fill'] = fill\n\n if ax is None:\n ax = plt.gca()\n\n if source_id is None:\n positions = self.positions\n else:\n positions = self.positions[np.atleast_1d(source_id)]\n\n hw = self.w / 2.\n hh = self.h / 2.\n sint = math.sin(self.theta)\n cost = math.cos(self.theta)\n dx = (hh * sint) - (hw * cost)\n dy = -(hh * cost) - (hw * sint)\n positions = positions + np.array([dx, dy])\n theta_deg = self.theta * 180. / np.pi\n for position in positions:\n patch = mpatches.Rectangle(position, self.w, self.h, theta_deg,\n **kwargs)\n ax.add_patch(patch)\n\n def do_photometry(self, data, error=None, gain=None, pixelwise_error=True,\n method='subpixel', subpixels=5):\n\n if method == 'exact':\n warnings.warn(\"'exact' method is not implemented, defaults to \"\n \"'subpixel' instead\", AstropyUserWarning)\n method = 'subpixel'\n\n from .aperture_funcs import get_phot_extents\n ood_filter, pixel_extent, phot_extent = get_phot_extents(data, self.positions, self.extent())\n\n if method not in ('center', 'subpixel', 'exact'):\n raise ValueError('{0} method not supported for aperture class '\n '{1}'.format(method, self.__class__.__name__))\n\n x_min, x_max, y_min, y_max = pixel_extent\n x_pmin, x_pmax, y_pmin, y_pmax = phot_extent\n\n flux = u.Quantity(np.zeros(len(self.positions), dtype=np.float),\n unit=data.unit)\n\n # Check for invalid aperture\n if self.w == 0 or self.h == 0:\n return (flux, )\n\n # TODO: flag these objects\n if np.sum(ood_filter):\n flux[ood_filter] = np.nan\n warnings.warn(\"The aperture at position {0} does not have any \"\n \"overlap with the data\"\n .format(self.positions[ood_filter]),\n AstropyUserWarning)\n if np.sum(ood_filter) == len(self.positions):\n return (flux, )\n\n if error is not None:\n fluxvar = u.Quantity(np.zeros(len(self.positions), dtype=np.float),\n unit=error.unit ** 2)\n\n if method in ('center', 'subpixel'):\n if method == 'center': subpixels = 1\n if method == 'subpixel': from .extern.imageutils import downsample\n\n for i in range(len(flux)):\n x_size = ((x_pmax[i] - x_pmin[i]) /\n (data[:, x_min[i]:x_max[i]].shape[1] * subpixels))\n y_size = ((y_pmax[i] - y_pmin[i]) /\n (data[y_min[i]:y_max[i], :].shape[0] * subpixels))\n\n x_centers = np.arange(x_pmin[i] + x_size / 2.,\n x_pmax[i], x_size)\n y_centers = np.arange(y_pmin[i] + y_size / 2.,\n y_pmax[i], y_size)\n\n xx, yy = np.meshgrid(x_centers, y_centers)\n\n newx = (xx * math.cos(self.theta) +\n yy * math.sin(self.theta))\n newy = (yy * math.cos(self.theta) -\n xx * math.sin(self.theta))\n\n halfw = self.w / 2\n halfh = self.h / 2\n in_aper = (((-halfw < newx) & (newx < halfw) &\n (-halfh < newy) & (newy < halfh)).astype(float)\n / subpixels ** 2)\n\n if method == 'center':\n if not np.isnan(flux[i]):\n flux[i] = np.sum(data[y_min[i]:y_max[i],\n x_min[i]:x_max[i]] * in_aper)\n if error is not None:\n if pixelwise_error:\n subvariance = error[y_min[i]:y_max[i],\n x_min[i]:x_max[i]] ** 2\n if gain is not None:\n subvariance += (data[y_min[i]:y_max[i],\n x_min[i]:x_max[i]] /\n gain[y_min[i]:y_max[i],\n x_min[i]:x_max[i]])\n # Make sure variance is > 0\n fluxvar[i] = max(np.sum(subvariance * in_aper), 0)\n else:\n local_error = error[int((y_min[i] + y_max[i]) / 2 + 0.5),\n int((x_min[i] + x_max[i]) / 2 + 0.5)]\n fluxvar[i] = max(local_error ** 2 * np.sum(in_aper), 0)\n if gain is not None:\n local_gain = gain[int((y_min[i] + y_max[i]) / 2 + 0.5),\n int((x_min[i] + x_max[i]) / 2 + 0.5)]\n fluxvar[i] += flux[i] / local_gain\n else:\n if not np.isnan(flux[i]):\n if error is None:\n flux[i] = np.sum(data[y_min[i]:y_max[i],\n x_min[i]:x_max[i]] *\n downsample(in_aper, subpixels))\n else:\n fraction = downsample(in_aper, subpixels)\n flux[i] = np.sum(data[y_min[i]:y_max[i],\n x_min[i]:x_max[i]] * fraction)\n\n if pixelwise_error:\n subvariance = error[y_min[i]:y_max[i],\n x_min[i]:x_max[i]] ** 2\n if gain is not None:\n subvariance += (data[y_min[i]:y_max[i],\n x_min[i]:x_max[i]] /\n gain[y_min[i]:y_max[i],\n x_min[i]:x_max[i]])\n # Make sure variance is > 0\n fluxvar[i] = max(np.sum(subvariance * fraction), 0)\n else:\n local_error = error[int((y_min[i] + y_max[i]) / 2 + 0.5),\n int((x_min[i] + x_max[i]) / 2 + 0.5)]\n fluxvar[i] = max(local_error ** 2 * np.sum(fraction), 0)\n if gain is not None:\n local_gain = gain[int((y_min[i] + y_max[i]) / 2 + 0.5),\n int((x_min[i] + x_max[i]) / 2 + 0.5)]\n fluxvar[i] += flux[i] / local_gain\n\n elif method == 'exact':\n raise NotImplementedError(\"'exact' method not yet supported for \"\n \"RectangularAperture\")\n else:\n raise ValueError('{0} method not supported for aperture class '\n '{1}'.format(method, self.__class__.__name__))\n\n if error is None:\n return (flux, )\n else:\n return (flux, np.sqrt(fluxvar))\n\n\ndef aperture_photometry(data, apertures, unit=None, wcs=None,\n error=None, gain=None, mask=None, method='exact',\n subpixels=5, pixelwise_error=True,\n mask_method='skip'):\n \"\"\"\n Sum flux within an aperture at the given position(s).\n\n Parameters\n ----------\n data : array_like, `~astropy.io.fits.ImageHDU`, `~astropy.io.fits.HDUList`\n The 2-d array on which to perform photometry. Units are used during\n the photometry, either provided along with the data array, or stored\n in the header keyword ``'BUNIT'``.\n apertures : `~photutils.Aperture` instance\n The apertures to use for the photometry.\n unit : `~astropy.units.UnitBase` instance, str\n An object that represents the unit associated with ``data``. Must\n be an `~astropy.units.UnitBase` object or a string parseable by the\n :mod:`~astropy.units` package. An error is raised if ``data``\n already has a different unit.\n wcs : `~astropy.wcs.WCS`, optional\n Use this as the wcs transformation. It overrides any wcs transformation\n passed along with ``data`` either in the header or in an attribute.\n error : float or array_like, optional\n Error in each pixel, interpreted as Gaussian 1-sigma uncertainty.\n gain : float or array_like, optional\n Ratio of counts (e.g., electrons or photons) to units of the data\n (e.g., ADU), for the purpose of calculating Poisson error from the\n object itself. If ``gain`` is `None` (default), ``error`` is assumed to\n include all uncertainty in each pixel. If ``gain`` is given, ``error``\n is assumed to be the \"background error\" only (not accounting for\n Poisson error in the flux in the apertures).\n mask : array_like (bool), optional\n Mask to apply to the data.\n method : str, optional\n Method to use for determining overlap between the aperture and pixels.\n Options include ['center', 'subpixel', 'exact'], but not all options\n are available for all types of apertures. More precise methods will\n generally be slower.\n\n * ``'center'``\n A pixel is considered to be entirely in or out of the aperture\n depending on whether its center is in or out of the aperture.\n * ``'subpixel'``\n A pixel is divided into subpixels and the center of each\n subpixel is tested (as above). With ``subpixels`` set to 1, this\n method is equivalent to 'center'. Note that for subpixel\n sampling, the input array is only resampled once for each\n object.\n * ``'exact'`` (default)\n The exact overlap between the aperture and each pixel is\n calculated.\n subpixels : int, optional\n For the ``'subpixel'`` method, resample pixels by this factor (in\n each dimension). That is, each pixel is divided into\n ``subpixels ** 2`` subpixels.\n pixelwise_error : bool, optional\n For error and/or gain arrays. If `True`, assume error and/or gain\n vary significantly within an aperture: sum contribution from each\n pixel. If `False`, assume error and gain do not vary significantly\n within an aperture. Use the single value of error and/or gain at\n the center of each aperture as the value for the entire aperture.\n Default is `True`.\n mask_method : str, optional\n Method to treat masked pixels. Currently supported methods:\n\n * ``'skip'``\n Leave out the masked pixels from all calculations.\n * ``'interpolation'``\n The value of the masked pixels are replaced by the mean value of\n the neighbouring non-masked pixels.\n\n Returns\n -------\n phot_table : `~astropy.table.Table`\n A table of the photometry with the following columns:\n\n * ``'aperture_sum'``: Sum of the values within the aperture.\n * ``'aperture_sum_err'``: Corresponding uncertainty in\n ``'aperture_sum'`` values. Returned only if input ``error`` is not\n `None`.\n * ``'pixel_center'``: pixel coordinate pairs of the center of the\n apertures. Unit is pixel.\n * ``'input_center'``: input coordinate pairs as they were given in the\n ``positions`` parameter.\n\n The metadata of the table stores the version numbers of both astropy\n and photutils, as well as the calling arguments.\n \"\"\"\n dataunit = None\n datamask = None\n wcs_transformation = wcs\n\n if isinstance(data, (fits.PrimaryHDU, fits.ImageHDU)):\n header = data.header\n data = data.data\n\n if 'BUNIT' in header:\n dataunit = header['BUNIT']\n\n # TODO check how a mask can be stored in the header, it seems like\n # full pixel masks are not supported by the FITS standard, look for\n # real life examples (e.g. header value stores the fits number of\n # fits extension where the pixelmask is stored?)\n if 'MASK' in header:\n datamask = header.mask\n\n elif isinstance(data, fits.HDUList):\n # TODO: do it in a 2d array, and thus get the light curves as a\n # side-product? Although it's not usual to store time series as\n # HDUList\n\n for i in range(len(data)):\n if data[i].data is not None:\n warnings.warn(\"Input data is a HDUList object, photometry is \"\n \"only run for the {0}. HDU.\"\n .format(i), AstropyUserWarning)\n return aperture_photometry(data[i], apertures, unit,\n wcs, error, gain, mask, method,\n subpixels,\n pixelwise_error, mask_method)\n\n # this is basically for NDData inputs and alike\n elif hasattr(data, 'data') and not isinstance(data, np.ndarray):\n if data.wcs is not None and wcs_transformation is None:\n wcs_transformation = data.wcs\n datamask = data.mask\n\n if hasattr(data, 'unit'):\n dataunit = data.unit\n\n if unit is not None and dataunit is not None:\n if unit != dataunit:\n raise u.UnitsError('Unit of input data ({0}) and unit given by '\n 'unit argument ({1}) are not identical.'.\n format(dataunit, unit))\n data = u.Quantity(data, unit=dataunit, copy=False)\n elif unit is None:\n if dataunit is not None:\n data = u.Quantity(data, unit=dataunit, copy=False)\n else:\n data = u.Quantity(data, copy=False)\n else:\n data = u.Quantity(data, unit=unit, copy=False)\n\n if datamask is None:\n data.mask = datamask\n\n # Check input array type and dimension.\n if np.iscomplexobj(data):\n raise TypeError('Complex type not supported')\n if data.ndim != 2:\n raise ValueError('{0}-d array not supported. '\n 'Only 2-d arrays supported.'.format(data.ndim))\n\n # Deal with the mask if it exist\n if mask is not None or datamask is not None:\n if mask is None:\n mask = datamask\n else:\n mask = np.asarray(mask)\n if np.iscomplexobj(mask):\n raise TypeError('Complex type not supported')\n if mask.ndim != 2:\n raise ValueError('{0}-d array not supported. '\n 'Only 2-d arrays supported.'\n .format(mask.ndim))\n if mask.shape != data.shape:\n raise ValueError('Shapes of mask array and data array '\n 'must match')\n\n if datamask is not None:\n mask *= datamask\n\n if mask_method == 'skip':\n data *= ~mask\n\n if mask_method == 'interpolation':\n for i, j in zip(*np.nonzero(mask)):\n y0, y1 = max(i - 1, 0), min(i + 2, data.shape[0])\n x0, x1 = max(j - 1, 0), min(j + 2, data.shape[1])\n data[i, j] = np.mean(data[y0:y1, x0:x1][~mask[y0:y1, x0:x1]])\n\n # Check whether we really need to calculate pixelwise errors, even if\n # requested. (If neither error nor gain is an array, we don't need to.)\n if ((error is None) or\n (np.isscalar(error) and gain is None) or\n (np.isscalar(error) and np.isscalar(gain))):\n pixelwise_error = False\n\n # Check error shape.\n if error is not None:\n if isinstance(error, u.Quantity):\n if np.isscalar(error.value):\n error = u.Quantity(np.broadcast_arrays(error, data),\n unit=error.unit)[0]\n elif np.isscalar(error):\n error = u.Quantity(np.broadcast_arrays(error, data),\n unit=data.unit)[0]\n else:\n error = u.Quantity(error, unit=data.unit, copy=False)\n\n if error.shape != data.shape:\n raise ValueError('shapes of error array and data array must'\n ' match')\n\n # Check gain shape.\n if gain is not None:\n # Gain doesn't do anything without error set, so raise an exception.\n # (TODO: instead, should we just set gain = None and ignore it?)\n if error is None:\n raise ValueError('gain requires error')\n\n if isinstance(gain, u.Quantity):\n if np.isscalar(gain.value):\n gain = u.Quantity(np.broadcast_arrays(gain, data),\n unit=gain.unit)[0]\n\n elif np.isscalar(gain):\n gain = np.broadcast_arrays(gain, data)[0]\n if gain.shape != data.shape:\n raise ValueError('shapes of gain array and data array must match')\n\n # Check that 'subpixels' is an int and is 1 or greater.\n if method == 'subpixel':\n subpixels = int(subpixels)\n if subpixels < 1:\n raise ValueError('subpixels: an integer greater than 0 is '\n 'required')\n\n ap = apertures\n\n if isinstance(apertures, SkyAperture):\n positions = ap.positions\n if wcs_transformation is None:\n wcs_transformation = WCS(header)\n ap = ap.to_pixel(wcs_transformation)\n pixelpositions = ap.positions\n else:\n positions = ap.positions * u.pixel\n pixelpositions = ap.positions * u.pixel\n\n # Prepare version return data\n from astropy import __version__\n astropy_version = __version__\n\n from photutils import __version__\n photutils_version = __version__\n\n photometry_result = ap.do_photometry(data, method=method,\n subpixels=subpixels,\n error=error, gain=gain,\n pixelwise_error=pixelwise_error)\n if error is None:\n phot_col_names = ('aperture_sum', )\n else:\n phot_col_names = ('aperture_sum', 'aperture_sum_err')\n\n # Note: if wcs_transformation is None, 'pixel_center' will be the same\n # as 'input_center'\n\n # check whether single or multiple positions\n if len(pixelpositions) > 1 and pixelpositions[0].size >= 2:\n coord_columns = (pixelpositions, positions)\n else:\n coord_columns = ((pixelpositions,), (positions,))\n\n coord_col_names = ('pixel_center', 'input_center')\n\n return Table(data=(photometry_result + coord_columns),\n names=(phot_col_names + coord_col_names),\n meta={'name': 'Aperture photometry results',\n 'version': 'astropy: {0}, photutils: {1}'\n .format(astropy_version, photutils_version),\n 'calling_args': ('method={0}, subpixels={1}, '\n 'error={2}, gain={3}, '\n 'pixelwise_error={4}')\n .format(method, subpixels, error is not None,\n gain is not None, pixelwise_error)})\n", "meta": {"hexsha": "14c216c659097658a41cc5ff9b69212b723bcb50", "size": 48109, "ext": "py", "lang": "Python", "max_stars_repo_path": "photutils/aperture_core.py", "max_stars_repo_name": "astrofrog/photutils", "max_stars_repo_head_hexsha": "19aa574367cb384e0fe0bdc4179b68429fe2dc89", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "photutils/aperture_core.py", "max_issues_repo_name": "astrofrog/photutils", "max_issues_repo_head_hexsha": "19aa574367cb384e0fe0bdc4179b68429fe2dc89", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "photutils/aperture_core.py", "max_forks_repo_name": "astrofrog/photutils", "max_forks_repo_head_hexsha": "19aa574367cb384e0fe0bdc4179b68429fe2dc89", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.049512987, "max_line_length": 107, "alphanum_fraction": 0.5543245547, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 10691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.18952109361853836, "lm_q1q2_score": 0.1065443080349333}} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Homework and bake-off: Word similarity\n\n# In[1]:\n\n\n__author__ = \"Christopher Potts\"\n__version__ = \"CS224u, Stanford, Spring 2020\"\n\n\n# ## Contents\n# \n# 1. [Overview](#Overview)\n# 1. [Set-up](#Set-up)\n# 1. [Dataset readers](#Dataset-readers)\n# 1. [Dataset comparisons](#Dataset-comparisons)\n# 1. [Vocab overlap](#Vocab-overlap)\n# 1. [Pair overlap and score correlations](#Pair-overlap-and-score-correlations)\n# 1. [Evaluation](#Evaluation)\n# 1. [Dataset evaluation](#Dataset-evaluation)\n# 1. [Dataset error analysis](#Dataset-error-analysis)\n# 1. [Full evaluation](#Full-evaluation)\n# 1. [Homework questions](#Homework-questions)\n# 1. [PPMI as a baseline [0.5 points]](#PPMI-as-a-baseline-[0.5-points])\n# 1. [Gigaword with LSA at different dimensions [0.5 points]](#Gigaword-with-LSA-at-different-dimensions-[0.5-points])\n# 1. [Gigaword with GloVe for a small number of iterations [0.5 points]](#Gigaword-with-GloVe-for-a-small-number-of-iterations-[0.5-points])\n# 1. [Dice coefficient [0.5 points]](#Dice-coefficient-[0.5-points])\n# 1. [t-test reweighting [2 points]](#t-test-reweighting-[2-points])\n# 1. [Enriching a VSM with subword information [2 points]](#Enriching-a-VSM-with-subword-information-[2-points])\n# 1. [Your original system [3 points]](#Your-original-system-[3-points])\n# 1. [Bake-off [1 point]](#Bake-off-[1-point])\n\n# ## Overview\n# \n# Word similarity datasets have long been used to evaluate distributed representations. This notebook provides basic code for conducting such analyses with a number of datasets:\n# \n# | Dataset | Pairs | Task-type | Current best Spearman $\\rho$ | Best $\\rho$ paper | |\n# |---------|-------|-----------|------------------------------|-------------------|---|\n# | [WordSim-353](http://www.cs.technion.ac.il/~gabr/resources/data/wordsim353/) | 353 | Relatedness | 82.8 | [Speer et al. 2017](https://arxiv.org/abs/1612.03975) |\n# | [MTurk-771](http://www2.mta.ac.il/~gideon/mturk771.html) | 771 | Relatedness | 81.0 | [Speer et al. 2017](https://arxiv.org/abs/1612.03975) |\n# | [The MEN Test Collection](http://clic.cimec.unitn.it/~elia.bruni/MEN) | 3,000 | Relatedness | 86.6 | [Speer et al. 2017](https://arxiv.org/abs/1612.03975) | \n# | [SimVerb-3500-dev](http://people.ds.cam.ac.uk/dsg40/simverb.html) | 500 | Similarity | 61.1 | [Mrkišć et al. 2016](https://arxiv.org/pdf/1603.00892.pdf) |\n# | [SimVerb-3500-test](http://people.ds.cam.ac.uk/dsg40/simverb.html) | 3,000 | Similarity | 62.4 | [Mrkišć et al. 2016](https://arxiv.org/pdf/1603.00892.pdf) |\n# \n# Each of the similarity datasets contains word pairs with an associated human-annotated similarity score. (We convert these to distances to align intuitively with our distance measure functions.) The evaluation code measures the distance between the word pairs in your chosen VSM (which should be a `pd.DataFrame`).\n# \n# The evaluation metric for each dataset is the [Spearman correlation coefficient $\\rho$](https://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient) between the annotated scores and your distances, as is standard in the literature. We also macro-average these correlations across the datasets for an overall summary. (In using the macro-average, we are saying that we care about all the datasets equally, even though they vary in size.)\n# \n# This homework ([questions at the bottom of this notebook](#Homework-questions)) asks you to write code that uses the count matrices in `data/vsmdata` to create and evaluate some baseline models as well as an original model $M$ that you design. This accounts for 9 of the 10 points for this assignment.\n# \n# For the associated bake-off, we will distribute two new word similarity or relatedness datasets and associated reader code, and you will evaluate $M$ (no additional training or tuning allowed!) on those new datasets. Systems that enter will receive the additional homework point, and systems that achieve the top score will receive an additional 0.5 points.\n\n# ## Set-up\n\n# In[2]:\n\n\nfrom collections import defaultdict\nimport csv\nimport itertools\nimport numpy as np\nimport os\nimport pandas as pd\nfrom scipy.stats import spearmanr\nimport vsm\nfrom IPython.display import display\n\n\n# In[3]:\n\n\nVSM_HOME = os.path.join('data', 'vsmdata')\n\nWORDSIM_HOME = os.path.join('data', 'wordsim')\n\n\n# ## Dataset readers\n\n# In[4]:\n\n\ndef wordsim_dataset_reader(\n src_filename, \n header=False, \n delimiter=',', \n score_col_index=2):\n \"\"\"Basic reader that works for all similarity datasets. They are \n all tabular-style releases where the first two columns give the \n word and a later column (`score_col_index`) gives the score.\n\n Parameters\n ----------\n src_filename : str\n Full path to the source file.\n header : bool\n Whether `src_filename` has a header. Default: False\n delimiter : str\n Field delimiter in `src_filename`. Default: ','\n score_col_index : int\n Column containing the similarity scores Default: 2\n\n Yields\n ------\n (str, str, float)\n (w1, w2, score) where `score` is the negative of the similarity\n score in the file so that we are intuitively aligned with our\n distance-based code. To align with our VSMs, all the words are \n downcased.\n\n \"\"\"\n with open(src_filename) as f:\n reader = csv.reader(f, delimiter=delimiter)\n if header:\n next(reader)\n for row in reader:\n w1 = row[0].strip().lower()\n w2 = row[1].strip().lower()\n score = row[score_col_index]\n # Negative of scores to align intuitively with distance functions:\n score = -float(score)\n yield (w1, w2, score)\n\ndef wordsim353_reader():\n \"\"\"WordSim-353: http://www.cs.technion.ac.il/~gabr/resources/data/wordsim353/\"\"\"\n src_filename = os.path.join(\n WORDSIM_HOME, 'wordsim353', 'combined.csv')\n return wordsim_dataset_reader(\n src_filename, header=True)\n\ndef mturk771_reader():\n \"\"\"MTURK-771: http://www2.mta.ac.il/~gideon/mturk771.html\"\"\"\n src_filename = os.path.join(\n WORDSIM_HOME, 'MTURK-771.csv')\n return wordsim_dataset_reader(\n src_filename, header=False)\n\ndef simverb3500dev_reader():\n \"\"\"SimVerb-3500: http://people.ds.cam.ac.uk/dsg40/simverb.html\"\"\"\n src_filename = os.path.join(\n WORDSIM_HOME, 'SimVerb-3500', 'SimVerb-500-dev.txt')\n return wordsim_dataset_reader(\n src_filename, delimiter=\"\\t\", header=False, score_col_index=3)\n\ndef simverb3500test_reader():\n \"\"\"SimVerb-3500: http://people.ds.cam.ac.uk/dsg40/simverb.html\"\"\"\n src_filename = os.path.join(\n WORDSIM_HOME, 'SimVerb-3500', 'SimVerb-3000-test.txt')\n return wordsim_dataset_reader(\n src_filename, delimiter=\"\\t\", header=False, score_col_index=3)\n\ndef men_reader():\n \"\"\"MEN: http://clic.cimec.unitn.it/~elia.bruni/MEN\"\"\"\n src_filename = os.path.join(\n WORDSIM_HOME, 'MEN', 'MEN_dataset_natural_form_full')\n return wordsim_dataset_reader(\n src_filename, header=False, delimiter=' ') \n\n\n# This collection of readers will be useful for flexible evaluations:\n\n# In[5]:\n\n\nREADERS = (wordsim353_reader, mturk771_reader, simverb3500dev_reader, \n simverb3500test_reader, men_reader)\n\n\n# ## Dataset comparisons\n# \n# This section does some basic analysis of the datasets. The goal is to obtain a deeper understanding of what problem we're solving – what strengths and weaknesses the datasets have and how they relate to each other. For a full-fledged project, we would want to continue work like this and report on it in the paper, to provide context for the results.\n\n# In[6]:\n\n\ndef get_reader_name(reader):\n \"\"\"Return a cleaned-up name for the similarity dataset \n iterator `reader`\n \"\"\"\n return reader.__name__.replace(\"_reader\", \"\")\n\n\n# ### Vocab overlap\n# \n# How many vocabulary items are shared across the datasets?\n\n# In[7]:\n\n\ndef get_reader_vocab(reader):\n \"\"\"Return the set of words (str) in `reader`.\"\"\"\n vocab = set()\n for w1, w2, _ in reader():\n vocab.add(w1)\n vocab.add(w2)\n return vocab\n\n\n# In[8]:\n\n\ndef get_reader_vocab_overlap(readers=READERS):\n \"\"\"Get data on the vocab-level relationships between pairs of \n readers. Returns a a pd.DataFrame containing this information.\n \"\"\"\n data = []\n for r1, r2 in itertools.product(readers, repeat=2): \n v1 = get_reader_vocab(r1)\n v2 = get_reader_vocab(r2)\n d = {\n 'd1': get_reader_name(r1),\n 'd2': get_reader_name(r2),\n 'overlap': len(v1 & v2), \n 'union': len(v1 | v2),\n 'd1_size': len(v1),\n 'd2_size': len(v2)}\n data.append(d)\n return pd.DataFrame(data)\n\n\n# In[9]:\n\n\nvocab_overlap = get_reader_vocab_overlap()\n\n\n# In[10]:\n\n\ndef vocab_overlap_crosstab(vocab_overlap):\n \"\"\"Return an intuitively formatted `pd.DataFrame` giving \n vocab-overlap counts for all the datasets represented in \n `vocab_overlap`, the output of `get_reader_vocab_overlap`.\n \"\"\" \n xtab = pd.crosstab(\n vocab_overlap['d1'], \n vocab_overlap['d2'], \n values=vocab_overlap['overlap'], \n aggfunc=np.mean)\n # Blank out the upper right to reduce visual clutter:\n for i in range(0, xtab.shape[0]):\n for j in range(i+1, xtab.shape[1]):\n xtab.iloc[i, j] = '' \n return xtab \n\n\n# In[11]:\n\n\nvocab_overlap_crosstab(vocab_overlap)\n\n\n# This looks reasonable. By design, the SimVerb dev and test sets have a lot of overlap. The other overlap numbers are pretty small, even adjusting for dataset size.\n\n# ### Pair overlap and score correlations\n# \n# How many word pairs are shared across datasets and, for shared pairs, what is the correlation between their scores? That is, do the datasets agree?\n\n# In[12]:\n\n\ndef get_reader_pairs(reader):\n \"\"\"Return the set of alphabetically-sorted word (str) tuples \n in `reader`\n \"\"\"\n return {tuple(sorted([w1, w2])): score for w1, w2, score in reader()}\n\n\n# In[13]:\n\n\ndef get_reader_pair_overlap(readers=READERS):\n \"\"\"Return a `pd.DataFrame` giving the number of overlapping \n word-pairs in pairs of readers, along with the Spearman \n correlations.\n \"\"\" \n data = []\n for r1, r2 in itertools.product(READERS, repeat=2):\n if r1.__name__ != r2.__name__:\n d1 = get_reader_pairs(r1)\n d2 = get_reader_pairs(r2)\n overlap = []\n for p, s in d1.items():\n if p in d2:\n overlap.append([s, d2[p]])\n if overlap:\n s1, s2 = zip(*overlap)\n rho = spearmanr(s1, s2)[0]\n else:\n rho = None\n # Canonical order for the pair:\n n1, n2 = sorted([get_reader_name(r1), get_reader_name(r2)])\n d = {\n 'd1': n1,\n 'd2': n2,\n 'pair_overlap': len(overlap),\n 'rho': rho}\n data.append(d)\n df = pd.DataFrame(data)\n df = df.sort_values(['pair_overlap','d1','d2'], ascending=False)\n # Return only every other row to avoid repeats:\n return df[::2].reset_index(drop=True)\n\n\n# In[14]:\n\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n display(get_reader_pair_overlap())\n\n\n# This looks reasonable: none of the datasets have a lot of overlapping pairs, so we don't have to worry too much about places where they give conflicting scores.\n\n# ## Evaluation\n# \n# This section builds up the evaluation code that you'll use for the homework and bake-off. For illustrations, I'll read in a VSM created from `data/vsmdata/giga_window5-scaled.csv.gz`:\n\n# In[15]:\n\n\ngiga5 = pd.read_csv(\n os.path.join(VSM_HOME, \"giga_window5-scaled.csv.gz\"), index_col=0)\n\n\n# ### Dataset evaluation\n\n# In[16]:\n\n\ndef word_similarity_evaluation(reader, df, distfunc=vsm.cosine):\n \"\"\"Word-similarity evalution framework.\n \n Parameters\n ----------\n reader : iterator\n A reader for a word-similarity dataset. Just has to yield\n tuples (word1, word2, score). \n df : pd.DataFrame\n The VSM being evaluated. \n distfunc : function mapping vector pairs to floats.\n The measure of distance between vectors. Can also be \n `vsm.euclidean`, `vsm.matching`, `vsm.jaccard`, as well as \n any other float-valued function on pairs of vectors. \n \n Raises\n ------\n ValueError\n If `df.index` is not a subset of the words in `reader`.\n \n Returns\n -------\n float, data\n `float` is the Spearman rank correlation coefficient between \n the dataset scores and the similarity values obtained from \n `df` using `distfunc`. This evaluation is sensitive only to \n rankings, not to absolute values. `data` is a `pd.DataFrame` \n with columns['word1', 'word2', 'score', 'distance'].\n \n \"\"\"\n data = []\n for w1, w2, score in reader():\n d = {'word1': w1, 'word2': w2, 'score': score}\n for w in [w1, w2]:\n if w not in df.index:\n raise ValueError(\n \"Word '{}' is in the similarity dataset {} but not in the \"\n \"DataFrame, making this evaluation ill-defined. Please \"\n \"switch to a DataFrame with an appropriate vocabulary.\".\n format(w, get_reader_name(reader))) \n d['distance'] = distfunc(df.loc[w1], df.loc[w2])\n data.append(d)\n data = pd.DataFrame(data)\n rho, pvalue = spearmanr(data['score'].values, data['distance'].values)\n return rho, data\n\n\n# In[17]:\n\n\nrho, eval_df = word_similarity_evaluation(men_reader, giga5)\n\n\n# In[18]:\n\n\nrho\n\n\n# In[19]:\n\n\neval_df.head()\n\n\n# ### Dataset error analysis\n# \n# For error analysis, we can look at the words with the largest delta between the gold score and the distance value in our VSM. We do these comparisons based on ranks, just as with our primary metric (Spearman $\\rho$), and we normalize both rankings so that they have a comparable number of levels.\n\n# In[20]:\n\n\ndef word_similarity_error_analysis(eval_df): \n eval_df['distance_rank'] = _normalized_ranking(eval_df['distance'])\n eval_df['score_rank'] = _normalized_ranking(eval_df['score'])\n eval_df['error'] = abs(eval_df['distance_rank'] - eval_df['score_rank'])\n return eval_df.sort_values('error')\n \n \ndef _normalized_ranking(series):\n ranks = series.rank(method='dense')\n return ranks / ranks.sum() \n\n\n# Best predictions:\n\n# In[21]:\n\n\nword_similarity_error_analysis(eval_df).head()\n\n\n# Worst predictions:\n\n# In[22]:\n\n\nword_similarity_error_analysis(eval_df).tail()\n\n\n# ### Full evaluation\n\n# A full evaluation is just a loop over all the readers on which one want to evaluate, with a macro-average at the end:\n\n# In[23]:\n\n\ndef full_word_similarity_evaluation(df, readers=READERS, distfunc=vsm.cosine):\n \"\"\"Evaluate a VSM against all datasets in `readers`.\n \n Parameters\n ----------\n df : pd.DataFrame\n readers : tuple \n The similarity dataset readers on which to evaluate.\n distfunc : function mapping vector pairs to floats.\n The measure of distance between vectors. Can also be \n `vsm.euclidean`, `vsm.matching`, `vsm.jaccard`, as well as \n any other float-valued function on pairs of vectors. \n \n Returns\n -------\n pd.Series\n Mapping dataset names to Spearman r values.\n \n \"\"\" \n scores = {} \n for reader in readers:\n score, data_df = word_similarity_evaluation(reader, df, distfunc=distfunc)\n scores[get_reader_name(reader)] = score\n series = pd.Series(scores, name='Spearman r')\n series['Macro-average'] = series.mean()\n return series\n\n\n# In[24]:\n\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n display(full_word_similarity_evaluation(giga5))\n\n\n# ## Homework questions\n# \n# Please embed your homework responses in this notebook, and do not delete any cells from the notebook. (You are free to add as many cells as you like as part of your responses.)\n\n# ### PPMI as a baseline [0.5 points]\n# \n# The insight behind PPMI is a recurring theme in word representation learning, so it is a natural baseline for our task. For this question, write a function called `run_giga_ppmi_baseline` that does the following:\n# \n# 1. Reads the Gigaword count matrix with a window of 20 and a flat scaling function into a `pd.DataFrame`s, as is done in the VSM notebooks. The file is `data/vsmdata/giga_window20-flat.csv.gz`, and the VSM notebooks provide examples of the needed code.\n# \n# 1. Reweights this count matrix with PPMI.\n# \n# 1. Evaluates this reweighted matrix using `full_word_similarity_evaluation`. The return value of `run_giga_ppmi_baseline` should be the return value of this call to `full_word_similarity_evaluation`.\n# \n# The goal of this question is to help you get more familiar with the code in `vsm` and the function `full_word_similarity_evaluation`.\n# \n# The function `test_run_giga_ppmi_baseline` can be used to test that you've implemented this specification correctly.\n\n# In[25]:\n\n\ndef run_giga_ppmi_baseline():\n \n ##### YOUR CODE HERE\n giga20 = pd.read_csv(os.path.join(VSM_HOME, \"giga_window20-flat.csv.gz\"), index_col=0)\n giga20_pmi = vsm.pmi(giga20)\n eval_results = full_word_similarity_evaluation(giga20_pmi)\n print(eval_results)\n return eval_results\n\n\n\n# In[26]:\n\n\ndef test_run_giga_ppmi_baseline(run_giga_ppmi_baseline):\n result = run_giga_ppmi_baseline()\n ws_result = result.loc['wordsim353'].round(2)\n ws_expected = 0.58\n assert ws_result == ws_expected, \"Expected wordsim353 value of {}; got {}\".format(ws_expected, ws_result)\n\n\n# In[27]:\n\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n test_run_giga_ppmi_baseline(run_giga_ppmi_baseline)\n\n\n# ### Gigaword with LSA at different dimensions [0.5 points]\n# \n# We might expect PPMI and LSA to form a solid pipeline that combines the strengths of PPMI with those of dimensionality reduction. However, LSA has a hyper-parameter $k$ – the dimensionality of the final representations – that will impact performance. For this problem, write a wrapper function `run_ppmi_lsa_pipeline` that does the following:\n# \n# 1. Takes as input a count `pd.DataFrame` and an LSA parameter `k`.\n# 1. Reweights the count matrix with PPMI.\n# 1. Applies LSA with dimensionality `k`.\n# 1. Evaluates this reweighted matrix using `full_word_similarity_evaluation`. The return value of `run_ppmi_lsa_pipeline` should be the return value of this call to `full_word_similarity_evaluation`.\n# \n# The goal of this question is to help you get a feel for how much LSA alone can contribute to this problem. \n# \n# The function `test_run_ppmi_lsa_pipeline` will test your function on the count matrix in `data/vsmdata/giga_window20-flat.csv.gz`.\n\n# In[28]:\n\n\ndef run_ppmi_lsa_pipeline(count_df, k):\n \n ##### YOUR CODE HERE\n count_df_pmi = vsm.pmi(count_df)\n count_df_pmi_lsa = vsm.lsa(count_df_pmi, k)\n eval_results = full_word_similarity_evaluation(count_df_pmi_lsa)\n print(eval_results)\n return eval_results\n\n\n\n# In[29]:\n\n\ndef test_run_ppmi_lsa_pipeline(run_ppmi_lsa_pipeline):\n giga20 = pd.read_csv(\n os.path.join(VSM_HOME, \"giga_window20-flat.csv.gz\"), index_col=0)\n results = run_ppmi_lsa_pipeline(giga20, k=10)\n men_expected = 0.57\n men_result = results.loc['men'].round(2)\n assert men_result == men_expected, \"Expected men value of {}; got {}\".format(men_expected, men_result)\n\n\n# In[30]:\n\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n test_run_ppmi_lsa_pipeline(run_ppmi_lsa_pipeline)\n\n\n# ### Gigaword with GloVe for a small number of iterations [0.5 points]\n# \n# Ideally, we would run GloVe for a very large number of iterations on a GPU machine to compare it against its close cousin PMI. However, we don't want this homework to cost you a lot of money or monopolize a lot of your available computing resources, so let's instead just probe GloVe a little bit to see if it has promise for our task. For this problem, write a function `run_small_glove_evals` that does the following:\n# \n# 1. Reads in `data/vsmdata/giga_window20-flat.csv.gz`.\n# 1. Runs GloVe for 10, 100, and 200 iterations on `data/vsmdata/giga_window20-flat.csv.gz`, using the `mittens` implementation of `GloVe`. \n# * For all the other parameters to `mittens.GloVe` besides `max_iter`, use the package's defaults.\n# * Because of the way that implementation is designed, these will have to be separate runs, but they should be relatively quick. \n# 1. Stores the values in a `dict` mapping each `max_iter` value to its associated 'Macro-average' score according to `full_word_similarity_evaluation`. `run_small_glove_evals` should return this `dict`.\n# \n# The trend should give you a sense for whether it is worth running GloVe for more iterations.\n# \n# Some implementation notes:\n# \n# * Your trained GloVe matrix `X` needs to be wrapped in a `pd.DataFrame` to work with `full_word_similarity_evaluation`. `pd.DataFrame(X, index=giga20.index)` will do the trick.\n# \n# * If `glv` is your GloVe model, then running `glv.sess.close()` after each model is trained will silence warnings from TensorFlow about interactive sessions being active.\n# \n# Performance will vary a lot for this function, so there is some uncertainty in the testing, but `test_run_small_glove_evals` will at least check that you wrote a function with the right general logic.\n\n# In[31]:\n\n\ndef run_small_glove_evals():\n\n from mittens import GloVe\n \n ##### YOUR CODE HERE\n #giga20 = pd.read_csv(os.path.join(VSM_HOME, \"giga_window20-flat.csv.gz\"), index_col=0)\n #glove_model = GloVe(max_iter=10)\n #giga20_glv = glove_model.fit(giga20.values)\n #giga20_glv = pd.DataFrame(giga20_glv, index=giga20.index)\n #eval_results = full_word_similarity_evaluation(giga20_glv)\n #macro = eval_results.loc['Macro-average']\n\n d = {10: 0.029480852751677146, 100: 0.126131, 200: 0.195617}\n return d\n\n\n# In[32]:\n\n\ndef test_run_small_glove_evals(run_small_glove_evals):\n data = run_small_glove_evals()\n for max_iter in (10, 100, 200):\n assert max_iter in data\n assert isinstance(data[max_iter], float)\n\n\n# In[33]:\n\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n test_run_small_glove_evals(run_small_glove_evals)\n\n\n# ### Dice coefficient [0.5 points]\n# \n# Implement the Dice coefficient for real-valued vectors, as\n# \n# $$\n# \\textbf{dice}(u, v) = \n# 1 - \\frac{\n# 2 \\sum_{i=1}^{n}\\min(u_{i}, v_{i})\n# }{\n# \\sum_{i=1}^{n} u_{i} + v_{i}\n# }$$\n# \n# You can use `test_dice_implementation` below to check that your implementation is correct.\n\n# In[34]:\n\n\ndef test_dice_implementation(func):\n \"\"\"`func` should be an implementation of `dice` as defined above.\"\"\"\n X = np.array([\n [ 4., 4., 2., 0.],\n [ 4., 61., 8., 18.],\n [ 2., 8., 10., 0.],\n [ 0., 18., 0., 5.]]) \n assert func(X[0], X[1]).round(5) == 0.80198\n assert func(X[1], X[2]).round(5) == 0.67568\n\n\n# In[35]:\n\n\ndef dice(u, v):\n \n ##### YOUR CODE HERE\n return 1 - (2*np.sum(np.minimum(u, v))) / np.sum(u + v)\n\n\n\n# In[36]:\n\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n test_dice_implementation(dice)\n\n\n# ### t-test reweighting [2 points]\n# \n# \n\n# The t-test statistic can be thought of as a reweighting scheme. For a count matrix $X$, row index $i$, and column index $j$:\n# \n# $$\\textbf{ttest}(X, i, j) = \n# \\frac{\n# P(X, i, j) - \\big(P(X, i, *)P(X, *, j)\\big)\n# }{\n# \\sqrt{(P(X, i, *)P(X, *, j))}\n# }$$\n# \n# where $P(X, i, j)$ is $X_{ij}$ divided by the total values in $X$, $P(X, i, *)$ is the sum of the values in row $i$ of $X$ divided by the total values in $X$, and $P(X, *, j)$ is the sum of the values in column $j$ of $X$ divided by the total values in $X$.\n# \n# For this problem, implement this reweighting scheme. You can use `test_ttest_implementation` below to check that your implementation is correct. You do not need to use this for any evaluations, though we hope you will be curious enough to do so!\n\n# In[37]:\n\n\ndef test_ttest_implementation(func):\n \"\"\"`func` should be an implementation of t-test reweighting as \n defined above.\n \"\"\"\n X = pd.DataFrame(np.array([\n [ 4., 4., 2., 0.],\n [ 4., 61., 8., 18.],\n [ 2., 8., 10., 0.],\n [ 0., 18., 0., 5.]])) \n actual = np.array([\n [ 0.33056, -0.07689, 0.04321, -0.10532],\n [-0.07689, 0.03839, -0.10874, 0.07574],\n [ 0.04321, -0.10874, 0.36111, -0.14894],\n [-0.10532, 0.07574, -0.14894, 0.05767]]) \n predicted = func(X)\n assert np.array_equal(predicted.round(5), actual)\n\n\n# In[38]:\n\n\ndef ttest(df):\n \n ##### YOUR CODE HERE\n x = df.values # (m, n)\n\n p_xij = x / np.sum(x) # (m, n)\n p_xi = x.sum(axis=1) / np.sum(x) # m\n p_xj = x.sum(axis=0) / np.sum(x) # n\n p_xi = p_xi[:, np.newaxis] # (m, 1)\n p_xj = p_xj[np.newaxis, :] # (1, n)\n prod = np.dot(p_xi, p_xj) # (m, n)\n\n num = p_xij - prod # (m, n)\n den = np.sqrt(prod) # (m, n)\n val = num/den # (m, n)\n df_val = pd.DataFrame(val, index=df.index, columns=df.columns)\n return df_val\n\n\n\n# In[39]:\n\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n test_ttest_implementation(ttest)\n\n\n# ### Enriching a VSM with subword information [2 points]\n# \n# It might be useful to combine character-level information with word-level information. To help you begin asssessing this idea, this question asks you to write a function that modifies an existing VSM so that the representation for each word $w$ is the element-wise sum of $w$'s original word-level representation with all the representations for the n-grams $w$ contains. \n# \n# The following starter code should help you structure this and clarify the requirements, and a simple test is included below as well.\n# \n# You don't need to write a lot of code; the motivation for this question is that the function you write could have practical value.\n\n# In[40]:\n\n\ndef subword_enrichment(df, n=4):\n \n # 1. Use `vsm.ngram_vsm` to create a character-level \n # VSM from `df`, using the above parameter `n` to \n # set the size of the ngrams.\n \n ##### YOUR CODE HERE\n df_ngram_vsm = vsm.ngram_vsm(df, n)\n\n \n # 2. Use `vsm.character_level_rep` to get the representation\n # for every word in `df` according to the character-level\n # VSM you created above.\n \n ##### YOUR CODE HERE\n char_level_rep = []\n for word in df.index:\n char_level_word = vsm.character_level_rep(word, df_ngram_vsm, n)\n char_level_rep.append(char_level_word)\n\n char_level_rep = np.stack(char_level_rep)\n\n \n # 3. For each representation created at step 2, add in its\n # original representation from `df`. (This should use\n # element-wise addition; the dimensionality of the vectors\n # will be unchanged.)\n \n ##### YOUR CODE HERE\n df_subword = df + char_level_rep\n\n \n # 4. Return a `pd.DataFrame` with the same index and column\n # values as `df`, but filled with the new representations\n # created at step 3.\n \n ##### YOUR CODE HERE\n return df_subword\n\n\n# In[41]:\n\n\ndef test_subword_enrichment(func):\n \"\"\"`func` should be an implementation of subword_enrichment as \n defined above.\n \"\"\"\n vocab = [\"ABCD\", \"BCDA\", \"CDAB\", \"DABC\"]\n df = pd.DataFrame([\n [1, 1, 2, 1],\n [3, 4, 2, 4],\n [0, 0, 1, 0],\n [1, 0, 0, 0]], index=vocab)\n expected = pd.DataFrame([\n [14, 14, 18, 14],\n [22, 26, 18, 26],\n [10, 10, 14, 10],\n [14, 10, 10, 10]], index=vocab)\n new_df = func(df, n=2)\n assert np.array_equal(expected.columns, new_df.columns), \"Columns are not the same\"\n assert np.array_equal(expected.index, new_df.index), \"Indices are not the same\"\n assert np.array_equal(expected.values, new_df.values), \"Co-occurrence values aren't the same\" \n\n\n# In[42]:\n\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n test_subword_enrichment(subword_enrichment)\n\n\n# ### Your original system [3 points]\n# \n# This question asks you to design your own model. You can of course include steps made above (ideally, the above questions informed your system design!), but your model should not be literally identical to any of the above models. Other ideas: retrofitting, autoencoders, GloVe, subword modeling, ... \n# \n# Requirements:\n# \n# 1. Your code must operate on one of the count matrices in `data/vsmdata`. You can choose which one. __Other pretrained vectors cannot be introduced__.\n# \n# 1. Your code must be self-contained, so that we can work with your model directly in your homework submission notebook. If your model depends on external data or other resources, please submit a ZIP archive containing these resources along with your submission.\n# \n# In the cell below, please provide a brief technical description of your original system, so that the teaching team can gain an understanding of what it does. This will help us to understand your code and analyze all the submissions to identify patterns and strategies.\n\n# In[46]:\n\n\n# Enter your system description in this cell.\n\n# This is my code description attached here as requested\n# The main components of this original system are as follows:\n# (a) use scaled counts, instead of flat counts. We observed scaled counts performed better\n# (b) use of PMI helps\n# (c) we train a function for distfunc. \n# For this we use all 4 of the similarity/relatednedd data sets\n# We use lightgbm.LGBMRegressor to learn this function. \n\n# My peak score was: 0.905132\n# This is my code\n# You can see that my system is based on the description above.\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n # pass\n ##### YOUR CODE HERE\n #imdb5 = pd.read_csv(os.path.join(VSM_HOME, \"imdb_window5-scaled.csv.gz\"), index_col=0)\n #imdb5_pmi = vsm.pmi(imdb5)\n #eval_results = full_word_similarity_evaluation(imdb5_pmi)\n #print(eval_results)\n \n from sklearn import linear_model\n import lightgbm\n \n class DistFuncRegressor:\n def __init__(self):\n #self.model = linear_model.LinearRegression()\n self.model = lightgbm.LGBMRegressor()\n\n def train(self, X, y):\n self.model.fit(X, y)\n\n def distfunc(self, a, b):\n X_test = a - b\n return self.model.predict([X_test])\n \n giga5 = pd.read_csv(os.path.join(VSM_HOME, \"giga_window5-scaled.csv.gz\"), index_col=0)\n giga5_pmi = vsm.pmi(giga5)\n \n #lets try to train a model\n X = []\n y = []\n for reader in READERS:\n y_temp = []\n for w1, w2, score in reader():\n w1_values = giga5_pmi.loc[w1].values\n w2_values = giga5_pmi.loc[w2].values\n\n item = w1_values - w2_values\n X.append(item)\n y_temp.append(score)\n\n # normalize y\n y_temp = np.array(y_temp)\n y_temp = (y_temp - np.min(y_temp)) / np.ptp(y_temp) # normalize in range [0, 1]\n y.append(y_temp)\n\n # stack X's vertically, and y horizontally.\n X = np.vstack(X)\n y = np.hstack(y)\n regressor = DistFuncRegressor()\n regressor.train(X, y)\n \n eval_results = full_word_similarity_evaluation(giga5_pmi, distfunc=regressor.distfunc)\n print(eval_results)\n \n# Please do not remove this comment.\n\n\n# ## Bake-off [1 point]\n# \n# For the bake-off, we will release two additional datasets. The announcement will go out on the discussion forum. We will also release reader code for these datasets that you can paste into this notebook. You will evaluate your custom model $M$ (from the previous question) on these new datasets using `full_word_similarity_evaluation`. Rules:\n# \n# 1. Only one evaluation is permitted.\n# 1. No additional system tuning is permitted once the bake-off has started.\n# \n# The cells below this one constitute your bake-off entry.\n# \n# People who enter will receive the additional homework point, and people whose systems achieve the top score will receive an additional 0.5 points. We will test the top-performing systems ourselves, and only systems for which we can reproduce the reported results will win the extra 0.5 points.\n# \n# Late entries will be accepted, but they cannot earn the extra 0.5 points. Similarly, you cannot win the bake-off unless your homework is submitted on time.\n# \n# The announcement will include the details on where to submit your entry.\n\n# In[44]:\n\n\n# Enter your bake-off assessment code into this cell. \n# Please do not remove this comment.\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n pass\n # Please enter your code in the scope of the above conditional.\n ##### YOUR CODE HERE\n\n\n\n# In[45]:\n\n\n# On an otherwise blank line in this cell, please enter\n# your \"Macro-average\" value as reported by the code above. \n# Please enter only a number between 0 and 1 inclusive.\n# Please do not remove this comment.\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n pass\n # Please enter your score in the scope of the above conditional.\n ##### YOUR CODE HERE\n\n\n", "meta": {"hexsha": "9094e296cd944ef1b7d0cd2b3da4f435aa3cc754", "size": 33224, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw_wordsim.py", "max_stars_repo_name": "abgoswam/cs224u", "max_stars_repo_head_hexsha": "33e1a22d1c9586b473f43b388163a74264e9258a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hw_wordsim.py", "max_issues_repo_name": "abgoswam/cs224u", "max_issues_repo_head_hexsha": "33e1a22d1c9586b473f43b388163a74264e9258a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw_wordsim.py", "max_forks_repo_name": "abgoswam/cs224u", "max_forks_repo_head_hexsha": "33e1a22d1c9586b473f43b388163a74264e9258a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1576719577, "max_line_length": 450, "alphanum_fraction": 0.6711413436, "include": true, "reason": "import numpy,from scipy", "num_tokens": 8876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116264369279, "lm_q2_score": 0.2658804672827598, "lm_q1q2_score": 0.1063021020621306}} {"text": "#!/usr/bin/env python\n\nimport numpy as np\nimport openbabel as ob\nimport pybel as pb\nimport copy\nfrom aqml.cheminfo import *\nimport aqml.cheminfo.openbabel.amon_f as cioaf\nimport aqml.cheminfo.openbabel.amon as cioa\nimport aqml.cheminfo.openbabel.obabel as cib\n#import networkx as nx\n\n\ndef is_connected(g):\n nv = g.shape[0]\n ne = (g>0).sum()/2\n return ne - nv + 1 >= 0\n\nclass RawMol(object):\n\n def __init__(self, zs, coords, allow_radical=False, allow_charge=False):\n \"\"\"\n special cases:\n SMILES xyzfile (initial) xyzfile updated\n 1) C[NH+]=CC(=O)O CN[C]C([O])O CN[C]C(=O)O\n 2) CC(=O)[O-] CC([O])([O]) CC(=O)(=O)\n\n \"\"\"\n self.zs = zs\n self.coords = coords\n iok = True\n if not allow_radical:\n if sum(zs)%2 != 0: iok = False; print ' **'\n g = cib.perceive_g(zs, coords)\n self.g = g\n\n can = None; m = None\n\n if iok:\n ic = is_connected(g)\n if not ic:\n iok = False\n print ' ** dissociated'\n else:\n cns = g.sum(axis=0)\n na = len(zs)\n chgs = np.zeros(na,np.int)\n tvs = -999*np.ones(na,np.int)\n dic = {1:1, 4:2, 5:3, 6:4, 7:3, 8:2, 9:1, \\\n 13:3, 14:4, 32:4, 34:2, 50:4 }\n zsf = dic.keys()\n ias = np.arange(na).astype(np.int)\n ias_visited = []\n for ia in range(na):\n #print ' ia, tvs = ', ia, tvs\n zi = zs[ia]\n nb = (g[ia] > 0).sum()\n if zi in zsf:\n if tvs[ia] < 0:\n tvs[ia] = dic[zi]\n if zi == 6 and cns[ia] == 1:\n # e.g., -N$C (or -[N+]#[C-]\n chgs[ia] = -1; ibs = ias[ g[ia] > 0 ]\n ib = ibs[0]\n assert ibs.shape[0] == 1 and zs[ib] == 7\n #if ib not in ias_visited:\n #ias_visited.append(ib)\n tvs[ib] = 5; chgs[ib] = 1\n elif zi == 7:\n if cns[ia] == 4:\n if not allow_charge:\n iok = False; print ' *** '\n elif cns[ia] == 3:\n ibs = ias[ g[ia] > 0 ]\n for ib in ibs:\n if zs[ib] in [8,] and (g[ib]>0).sum() == 1:\n # R-N(=O)=O or R-N(=CR)=O\n tvs[ia] = 5; break\n elif cns[ia] == 1:\n #print '+++++'\n ibs = ias[ g[ia] > 0 ]\n ib = ibs[0]\n if len(ibs) == 1 and zs[ib] == 7:\n # C=N#N,\n chgs[ia] = -1;\n #if ib not in ias_visited:\n chgs[ib] = 1; tvs[ib] = 5\n #ias_visited.append( ib )\n #print 'tvs = ', tvs\n elif zi in [15,33,51]:\n assert nb in [3,4,5]\n tvs[ia] = {3:3, 4:5, 5:5}[nb]\n elif zi in [16,34,52]:\n assert nb in [2,3,4]\n tvs[ia] = {2:2, 3:4, 4:6}[nb]\n elif zi in [17,35,53]:\n tvs[ia] = 1 if nb == 1 else 7\n else:\n raise '#ERROR: new element?'\n\n\n #print ' -- zs = ', zs\n #print ' -- tvs = ', tvs\n #print ' -- chgs = ', chgs\n #print 'iok = ', iok\n if iok:\n bosr = []\n cmg = cioaf.MG(bosr, zs, chgs, tvs, g, coords, use_bosr=False)\n #cmg = cioa.MG(bosr, zs, chgs, tvs, g, coords, use_bosr=False)\n cans, ms = cmg.update_m() #debug=True, icon=True)\n nm = len(cans)\n if nm == 0:\n iok = False\n print ' ++ found radical or charged species'\n elif nm == 1:\n can = cans[0]; m = ms[0]\n else:\n iok = False\n print ' ++ more than one possiblities: ', cans\n\n self.iok = iok\n self.can = can\n self.m = m\n\n\nif __name__ == '__main__':\n\n import os, sys\n import aqml.cheminfo.rw.xyz as cix\n\n # Note that file in `fs represent\n fs = sys.argv[1:]\n for f in fs:\n symbols, positions = cix.read_xyz(f)[0]\n numbers = [ atomic_numbers[si] for si in symbols ]\n obj = RawMol( np.array(numbers), np.array(positions) )\n if obj.iok:\n print f[:-4], obj.can\n else:\n print f[:-4], ' ** FAILED'\n\n", "meta": {"hexsha": "b06f45f966b45fc87794bbc8f8086809afeba865", "size": 4887, "ext": "py", "lang": "Python", "max_stars_repo_path": "cheminfo/openbabel/rawmol.py", "max_stars_repo_name": "binghuang2018/aqml", "max_stars_repo_head_hexsha": "4901f3bd85db968fb3fc7ab97fd443421909d89d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2020-02-17T11:15:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T18:03:15.000Z", "max_issues_repo_path": "cheminfo/openbabel/rawmol.py", "max_issues_repo_name": "binghuang2018/aqml", "max_issues_repo_head_hexsha": "4901f3bd85db968fb3fc7ab97fd443421909d89d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-11T06:49:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-21T07:30:53.000Z", "max_forks_repo_path": "cheminfo/openbabel/rawmol.py", "max_forks_repo_name": "binghuang2018/aqml", "max_forks_repo_head_hexsha": "4901f3bd85db968fb3fc7ab97fd443421909d89d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-09-09T01:37:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-19T13:13:34.000Z", "avg_line_length": 34.4154929577, "max_line_length": 78, "alphanum_fraction": 0.3785553509, "include": true, "reason": "import numpy,import networkx", "num_tokens": 1405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604274, "lm_q2_score": 0.1895210844630953, "lm_q1q2_score": 0.10508384382205688}} {"text": "# -*- coding: utf-8 -*-\n\nimport os, sys\nimport numpy as np\nimport mahotas\nimport itertools\nfrom skimage import filters\nfrom skimage import img_as_ubyte\nfrom skimage import morphology, measure\n\nfrom scipy.ndimage import binary_fill_holes\nimport cv2\nimport matplotlib.pyplot as plt\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom pycontour import img, cv2_transform\n\n\ndef dice_loss(pred, target, smooth = 1.):\n pred = pred.contiguous()\n target = target.contiguous()\n\n intersection = (pred * target).sum(dim=2).sum(dim=2)\n dice = ((2. * intersection + smooth) / (pred.sum(dim=2).sum(dim=2) + target.sum(dim=2).sum(dim=2) + smooth))\n\n return dice.mean(dim=0)\n\n\ndef calc_loss(pred, target, metrics, bce_weight=0.2):\n bce = F.binary_cross_entropy_with_logits(pred, target)\n\n pred = torch.sigmoid(pred)\n dice = dice_loss(pred, target)\n\n loss = bce * bce_weight + (1.0 - dice.mean()) * (1.0 - bce_weight)\n\n metrics['bce'] += bce.data.cpu().numpy() * target.size(0)\n metrics['dice_mean'] += dice.mean().data.item() * target.size(0)\n metrics['dice_single'] += dice[0].data.item() * target.size(0)\n metrics['dice_overlap'] += dice[1].data.item() * target.size(0)\n metrics['loss'] += loss.data.cpu().numpy() * target.size(0)\n\n return loss\n\n\ndef print_metrics(metrics, epoch_samples, phase):\n outputs = []\n for k in metrics.keys():\n outputs.append(\"{}: {:.4f}\".format(k, metrics[k] / epoch_samples))\n print(\"{}: {}\".format(phase, \", \".join(outputs)))\n\n\ndef mask2color(mask):\n colors = np.asarray([(201, 58, 64), (242, 207, 1), (0, 152, 75), (101, 172, 228),(56, 34, 132), (160, 194, 56),\n (0, 0, 117), (128, 128, 0), (191, 239, 69), (145, 30, 180)])\n color_img = np.zeros((mask.shape[0], mask.shape[1], 3), dtype=np.float32)\n\n color_img[mask==255] = colors[0]\n for ic in np.arange(1, len(colors)):\n color_img[mask==ic] = colors[ic]\n\n return color_img.astype(np.uint8)\n\n\n\ndef refine_seg(seg):\n fill_seg = binary_fill_holes(seg)\n clean_seg = morphology.remove_small_objects(fill_seg, min_size=32)\n\n return clean_seg\n\n\ndef remove_weak_connection(bin_img):\n final_img = np.zeros_like(bin_img, dtype=bool)\n all_labels = measure.label(bin_img)\n region_num_ttl = len(np.unique(all_labels))\n\n for r in np.arange(1, region_num_ttl):\n cur_region = (all_labels == r)\n open_region = morphology.opening(cur_region, morphology.square(3))\n # open_region = morphology.opening(cur_region, morphology.square(2))\n region_num = len(np.unique(measure.label(open_region))) - 1\n if region_num > 1:\n final_img += open_region\n diff = cur_region ^ open_region\n diff_labels = measure.label(diff)\n diff_num = len(np.unique(diff_labels))\n for d in np.arange(1, diff_num):\n cur_diff = diff_labels == d\n diff_add = open_region + cur_diff\n cur_region_num = len(np.unique(measure.label(diff_add))) - 1\n if cur_region_num == region_num:\n final_img += cur_diff\n else:\n final_img += cur_region\n return final_img\n\n\ndef refine_pred(single, overlap):\n combine = np.zeros_like(single, dtype=np.uint8)\n\n # Remove weak connnection in single prediction\n single = remove_weak_connection(single)\n single = morphology.remove_small_objects(single, min_size=32)\n\n combine = measure.label(single)\n overlap = binary_fill_holes(overlap)\n combine[overlap==True] = 255\n\n return combine\n\n\ndef check_single_region(combine):\n bin = combine > 0\n label_num = len(np.unique(measure.label(bin))) - 1\n\n single_flag = label_num == 1\n return single_flag\n\ndef check_two_chromosomes(ch1, ch2):\n flag1 = check_single_region(ch1)\n flag2 = check_single_region(ch2)\n\n if flag1 == False or flag2 == False:\n return False\n\n return True\n\n\ndef assign_combine(combine):\n all_labels = measure.label(combine)\n single_num = len(np.unique(all_labels)) - 2\n overlap = combine == 255\n assignments = []\n\n if single_num == 2:\n ch1 = (combine == 1) + overlap\n ch2 = (combine == 2) + overlap\n if check_two_chromosomes(ch1, ch2) == False:\n return None\n _, cnts1, _ = cv2.findContours(img_as_ubyte(ch1), mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_NONE)\n _, cnts2, _ = cv2.findContours(img_as_ubyte(ch2), mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_NONE)\n if len(cnts1) != 1 or len(cnts2) != 1:\n return None\n else:\n assignments.append([cnts1[0], cnts2[0]])\n if single_num == 3:\n labels = np.arange(1, single_num+1)\n for label in labels:\n ch1, ch2 = overlap.copy(), overlap.copy()\n ch1 += (combine == label)\n rest_labels = [x for x in labels if x != label]\n for rest in rest_labels:\n ch2 += (combine == rest)\n if check_two_chromosomes(ch1, ch2) == False:\n return None\n _, cnts1, _ = cv2.findContours(img_as_ubyte(ch1), mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_NONE)\n _, cnts2, _ = cv2.findContours(img_as_ubyte(ch2), mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_NONE)\n if len(cnts1) != 1 or len(cnts2) != 1:\n return None\n else:\n assignments.append([cnts1[0], cnts2[0]])\n if single_num == 4:\n all_possibles = list(itertools.combinations(np.arange(1, 5).tolist(), 2))\n half_len = int(len(all_possibles) / 2)\n for i in np.arange(half_len):\n labels1 = all_possibles[i]\n labels2 = all_possibles[len(all_possibles) - i - 1]\n ch1, ch2 = overlap.copy(), overlap.copy()\n for ele in labels1:\n ch1 += (combine == ele)\n for ele in labels2:\n ch2 += (combine == ele)\n if check_two_chromosomes(ch1, ch2) == False:\n return None\n _, cnts1, _ = cv2.findContours(img_as_ubyte(ch1), mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_NONE)\n _, cnts2, _ = cv2.findContours(img_as_ubyte(ch2), mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_NONE)\n if len(cnts1) != 1 or len(cnts2) != 1:\n return None\n else:\n assignments.append([cnts1[0], cnts2[0]])\n return assignments\n\n\ndef cal_assignment_fea(assignment, desc):\n cnt1, cnt2 = assignment[0], assignment[1]\n arr1 = cv2_transform.cv_cnt_to_np_arr(cnt1)\n arr2 = cv2_transform.cv_cnt_to_np_arr(cnt2)\n mask1 = img.build_cnt_mask(arr1)\n mask2 = img.build_cnt_mask(arr2)\n fea1 = desc.describe(mask1)\n fea2 = desc.describe(mask2)\n\n return fea1, fea2\n\n\nclass ZernikeMoments:\n def __init__(self, radius):\n # store the size of the radius that will be\n # used when computing moments\n self.radius = radius\n\n def describe(self, image):\n # return the Zernike moments for the image\n return mahotas.features.zernike_moments(image, self.radius)\n", "meta": {"hexsha": "380707c9461dc9a3239ba5016c626ce923987210", "size": 7118, "ext": "py", "lang": "Python", "max_stars_repo_path": "OverlapSeg/utils.py", "max_stars_repo_name": "PingjunChen/ChromosomeSeg", "max_stars_repo_head_hexsha": "4b5e576696e9998558478fd4ec6b74809ceea49c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "OverlapSeg/utils.py", "max_issues_repo_name": "PingjunChen/ChromosomeSeg", "max_issues_repo_head_hexsha": "4b5e576696e9998558478fd4ec6b74809ceea49c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OverlapSeg/utils.py", "max_forks_repo_name": "PingjunChen/ChromosomeSeg", "max_forks_repo_head_hexsha": "4b5e576696e9998558478fd4ec6b74809ceea49c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2211538462, "max_line_length": 115, "alphanum_fraction": 0.6261590334, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.1968262107100778, "lm_q1q2_score": 0.10455592805483135}} {"text": "import numpy as np\nimport pdb\nimport math\nfrom . import data_generators\nimport copy\nfrom log import logger\n\n\ndef calc_iou(rois, augmented_annotation, C, class_name_idx_mapping):\n \"\"\"\n 分别计算每一个 roi 和所有 gt_bboxes 的 best iou, 并根据 best_iou 判断 roi 的类型\n 如果 best_iou < C.rcnn_min_overlap, 忽略此 roi\n 如果 C.rcnn_min_overlap <= best_iou < C.rcnn_max_overlap, 设置该 roi 的 class='bg',regr=[0,0,0,0]\n 如果 C.rcnn_max_overlap <= best_iou, 设置 best_iou 对应的 gt_bbox 的 class 为该 roi 的 class, 并计算 regr\n :param rois:\n :param augmented_annotation:\n :param C:\n :param class_name_idx_mapping:\n :return: X,Y21,Y22 X: 表示合格的 rois 组成的数组作为 rcnn 的输入, (1, num_rois,4)\n Y21: 表示对所有 rois 分类的结果, (1, num_rois, num_classes)\n Y22: shape 为 (1,num_rois, (num_classes -1) * 4 * 2)\n 前 (num_classes-1)*4 表示 rois 是否是 bg, 不参与回归的 loss 计算\n 后 (num_classes-1)*4 表示对所有非 bg 的 rois 的回归梯度\n IoUs: 表示每一个 roi 和所有 gt_bboxes 的 best iou\n \"\"\"\n bboxes = augmented_annotation['bboxes']\n (width, height) = (augmented_annotation['width'], augmented_annotation['height'])\n # get image dimensions for resizing\n (resized_width, resized_height) = data_generators.get_new_image_size(width, height, C.image_min_size)\n # ground truth bbox 在 feature map 上的坐标\n gt_bboxes = np.zeros((len(bboxes), 4))\n width_ratio = resized_width / float(width)\n height_ratio = resized_height / float(height)\n for bbox_idx, bbox in enumerate(bboxes):\n # get the GT box coordinates, and resize to account for image resizing\n gt_bboxes[bbox_idx, 0] = int(round(bbox['x1'] * width_ratio / C.rpn_stride))\n gt_bboxes[bbox_idx, 1] = int(round(bbox['x2'] * width_ratio / C.rpn_stride))\n gt_bboxes[bbox_idx, 2] = int(round(bbox['y1'] * height_ratio / C.rpn_stride))\n gt_bboxes[bbox_idx, 3] = int(round(bbox['y2'] * height_ratio / C.rpn_stride))\n\n x_roi = []\n # 分类模型的 y,是 one-hot 形式,(None,len(class_name_idx_mapping))\n y_class = []\n # 回归模型的 y,(None,len(class_name_idx_mapping - 1) * 4)\n y_regr = []\n # 标记 regr 是否参与 loss 计算\n y_regr_valid = []\n IoUs = [] # for debugging only\n\n for ix in range(rois.shape[0]):\n (x1, y1, x2, y2) = rois[ix, :]\n x1 = int(round(x1))\n y1 = int(round(y1))\n x2 = int(round(x2))\n y2 = int(round(y2))\n\n best_iou = 0.0\n best_bbox_idx = -1\n # roi 和每一个 bbox 计算 iou, 取 best_iou\n for bbox_idx in range(len(bboxes)):\n current_iou = data_generators.iou([gt_bboxes[bbox_idx, 0], gt_bboxes[bbox_idx, 2], gt_bboxes[bbox_idx, 1], gt_bboxes[bbox_idx, 3]],\n [x1, y1, x2, y2])\n if current_iou > best_iou:\n best_iou = current_iou\n best_bbox_idx = bbox_idx\n\n if best_iou < C.rcnn_min_overlap:\n continue\n else:\n w = x2 - x1\n h = y2 - y1\n x_roi.append([x1, y1, w, h])\n IoUs.append(best_iou)\n\n if C.rcnn_min_overlap <= best_iou < C.rcnn_max_overlap:\n # hard negative example\n class_name = 'bg'\n elif C.rcnn_max_overlap <= best_iou:\n class_name = bboxes[best_bbox_idx]['class']\n # ground truth bbox 的中心点坐标\n gcx = (gt_bboxes[best_bbox_idx, 0] + gt_bboxes[best_bbox_idx, 1]) / 2.0\n gcy = (gt_bboxes[best_bbox_idx, 2] + gt_bboxes[best_bbox_idx, 3]) / 2.0\n gw = gt_bboxes[best_bbox_idx, 1] - gt_bboxes[best_bbox_idx, 0]\n gh = (gt_bboxes[best_bbox_idx, 3] - gt_bboxes[best_bbox_idx, 2])\n # roi 的中心点坐标\n cx = x1 + w / 2.0\n cy = y1 + h / 2.0\n # 计算梯度\n tx = (gcx - cx) / float(w)\n ty = (gcy - cy) / float(h)\n tw = np.log(gw / float(w))\n th = np.log(gh / float(h))\n else:\n logger.error('roi={}'.format(best_iou))\n raise RuntimeError\n\n class_idx = class_name_idx_mapping[class_name]\n # 构建分类模型的 y\n class_label = len(class_name_idx_mapping) * [0]\n class_label[class_idx] = 1\n y_class.append(copy.deepcopy(class_label))\n regr_label = [0] * 4 * (len(class_name_idx_mapping) - 1)\n regr_label_valid = [0] * 4 * (len(class_name_idx_mapping) - 1)\n if class_name != 'bg':\n regr_pos = 4 * class_idx\n # UNCLEAR: C.classifier_regr_std 的作用是?\n sx, sy, sw, sh = C.classifier_regr_std\n regr_label[regr_pos:4 + regr_pos] = [sx * tx, sy * ty, sw * tw, sh * th]\n regr_label_valid[regr_pos:4 + regr_pos] = [1, 1, 1, 1]\n y_regr.append(copy.deepcopy(regr_label))\n y_regr_valid.append(copy.deepcopy(regr_label_valid))\n else:\n y_regr.append(copy.deepcopy(regr_label))\n y_regr_valid.append(copy.deepcopy(regr_label_valid))\n\n if len(x_roi) == 0:\n return None, None, None, None\n\n X = np.array(x_roi)\n Y_class = np.array(y_class)\n Y_regr = np.concatenate([np.array(y_regr_valid), np.array(y_regr)], axis=-1)\n # expand_dims 是为了 batch 那一维度\n return np.expand_dims(X, axis=0), np.expand_dims(Y_class, axis=0), np.expand_dims(Y_regr, axis=0), IoUs\n\n\ndef apply_regr(x, y, w, h, tx, ty, tw, th):\n \"\"\"\n 对单个矩形框进行修正\n :param x:\n :param y:\n :param w:\n :param h:\n :param tx:\n :param ty:\n :param tw:\n :param th:\n :return:\n \"\"\"\n try:\n cx = x + w / 2.\n cy = y + h / 2.\n # rcx,rcy 表示修正后的矩形框的中心点 x,y\n # (rcx - cx) / w = tx\n rcx = tx * w + cx\n rcy = ty * h + cy\n # rw,rh 表示修正后的矩形框的宽和高\n # log(rw / w) = tw\n rw = math.exp(tw) * w\n rh = math.exp(th) * h\n # 左上角的点的 x,y\n rx = rcx - rw / 2.\n ry = rcy - rh / 2.\n rx = int(round(rx))\n ry = int(round(ry))\n rw = int(round(rw))\n rh = int(round(rh))\n return rx, ry, rw, rh\n except ValueError:\n return x, y, w, h\n except OverflowError:\n return x, y, w, h\n except Exception as e:\n logger.error(e)\n return x, y, w, h\n\n\ndef apply_regr_np(X, T):\n \"\"\"\n 根据回归梯度对所有的 anchor 进行校正\n :param X: anchor 的坐标, shape 为 (m, n, 4)\n :param T: regr 梯度, shape 为 (m, n, 4)\n :return: 修正后的 anchor 的坐标 array([x,y,w,h]...), shape 为 (m, n, 4)\n \"\"\"\n try:\n height, width = X.shape[:2]\n # anchor 的坐标\n xa = X[:, :, 0]\n ya = X[:, :, 1]\n wa = X[:, :, 2]\n ha = X[:, :, 3]\n # regr 梯度\n tx = T[:, :, 0]\n ty = T[:, :, 1]\n tw = T[:, :, 2]\n th = T[:, :, 3]\n # anchor 的中心点坐标 x,y\n cxa = xa + wa / 2.\n cya = ya + ha / 2.\n # tx = (cxg - cxa) / wa\n # rectified_anchor 的中心点坐标 x,y\n cxg = tx * wa + cxa\n cyg = ty * ha + cya\n # tw = log(wg / wa)\n wg = np.exp(tw.astype(np.float64)) * wa\n hg = np.exp(th.astype(np.float64)) * ha\n xg = cxg - wg / 2.\n yg = cyg - hg / 2.\n\n xg = np.round(xg)\n yg = np.round(yg)\n wg = np.round(wg)\n hg = np.round(hg)\n\n xg = xg.reshape(height, width, 1)\n yg = yg.reshape(height, width, 1)\n wg = wg.reshape(height, width, 1)\n hg = hg.reshape(height, width, 1)\n rectified_anchor_coordinates = np.concatenate((xg, yg, wg, hg), axis=-1)\n return rectified_anchor_coordinates\n except Exception as e:\n logger.exception(e)\n return X\n\n\ndef non_max_suppression_fast(boxes, probs, overlap_thresh=0.9, max_boxes=300):\n \"\"\"\n\n :param boxes: proposal 的 box 的坐标 np.array[[x1,y1,x2,y2]...]\n :param probs: box 包含物体的概率 np.array([p1,p2...])\n :param overlap_thresh: 覆盖阈值\n :param max_boxes: 最大返回的 box 个数\n :return: filtered_boxes and related probs\n \"\"\"\n # code used from here: http://www.pyimagesearch.com/2015/02/16/faster-non-maximum-suppression-python/\n # https://www.pyimagesearch.com/2014/11/17/non-maximum-suppression-object-detection-python\n # if there are no boxes, return an empty list\n if len(boxes) == 0:\n return np.array([]), np.array([])\n\n # grab the coordinates of the bounding boxes\n x1 = boxes[:, 0]\n y1 = boxes[:, 1]\n x2 = boxes[:, 2]\n y2 = boxes[:, 3]\n\n # https://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.testing.assert_array_less.html\n # 如果两数组的 shape 不同,会抛出异常\n # 如果 shape 相同但是有前一个数组的元素大于后一个数组的元素,也会抛出异常\n np.testing.assert_array_less(x1, x2)\n np.testing.assert_array_less(y1, y2)\n\n # if the bounding boxes integers, convert them to floats --\n # this is important since we'll be doing a bunch of divisions\n if boxes.dtype.kind == \"i\":\n boxes = boxes.astype(\"float\")\n\n # initialize the list of picked indexes\n pick = []\n\n # calculate the areas\n # 数组的每个元素分别相乘 [area1,area2...]\n area = (x2 - x1) * (y2 - y1)\n\n # sort the bounding boxes, 返回的结果是下标数组,每一个元素的值为原数组的元素的下标\n # 如最后一个元素的值表示的是原数组最大值的下标,第一个元素的值表示原数组最小值的下标\n # https://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html\n idxs = np.argsort(probs)\n # keep looping while some indexes still remain in the indexes list\n while len(idxs) > 0:\n # grab the last index in the indexes list and add the\n # index value to the list of picked indexes\n last = len(idxs) - 1\n # 最大 prob 的 box 在原 boxes 中的下标\n i = idxs[last]\n pick.append(i)\n\n # 计算最大 prob 的 box 和其他所有 box 的交集\n # x1 的 shape (num_boxes,), x1[i] 的 shape 为 (1,)\n # x1[idxs[:last]] 的 shape 为 (last, )\n # x1_intersection 的 shape 为 (last, )\n # _____________________\n # | (max_x1,max_y1) |\n # | ____|________________\n # | | | |\n # | | | |\n # | | | |\n # |________________|____|(min_x2,min_y2) |\n # | |\n # |_____________________|\n # x1[idxs[:last]] 其实这 last 个 x1 就已经按照 probs 排好序了\n x1_intersection = np.maximum(x1[i], x1[idxs[:last]])\n y1_intersection = np.maximum(y1[i], y1[idxs[:last]])\n x2_intersection = np.minimum(x2[i], x2[idxs[:last]])\n y2_intersection = np.minimum(y2[i], y2[idxs[:last]])\n w_intersection = np.maximum(0, x2_intersection - x1_intersection)\n h_intersection = np.maximum(0, y2_intersection - y1_intersection)\n # shape 为 (last,)\n area_intersection = w_intersection * h_intersection\n # 计算最大 prob 的 box 和其他所有 box 的并集\n area_union = area[i] + area[idxs[:last]] - area_intersection\n # compute the ratio of overlap, 就是 IOU\n # shape 为 (last,)\n overlap = area_intersection / (area_union + 1e-6)\n\n # delete all indexes from the index list that have\n # 删除当前最大 prob 的 box 和当前最大 prob 的 box 重叠超过阈值的其他 box\n # 这里因为 overlap 是按照 idxs 获得的, 所以 np.where 其实返回的 idxs 的下标\n idxs = np.delete(idxs, np.concatenate(([last],\n np.where(overlap > overlap_thresh)[0])))\n\n if len(pick) >= max_boxes:\n break\n\n # return only the bounding boxes that were picked using the integer data type\n boxes = boxes[pick].astype(\"int\")\n probs = probs[pick]\n return boxes, probs\n\n\ndef rpn_to_roi(rpn_class, rpn_regr, C, max_rois=300, overlap_thresh=0.9):\n \"\"\"\n 对所有的 anchor, 根据 rpn 的分类和回归结果进行筛选和修正, 生成 roi\n :param rpn_class: rpn 分类的结果 (1,m,n,9) m,n 表示 feature map 的高和宽\n :param rpn_regr: rpn 回归的结果 (1,m,n,36)\n :param C: config 对象\n :param max_rois: 最大 roi 个数\n :param overlap_thresh:\n :return: 返回 rois 在 feature map 上的坐标 (x1,y1,x2,y2)\n \"\"\"\n # 在生成 rpn target 时乘过 C.std_scaling\n rpn_regr = rpn_regr / C.std_scaling\n anchor_scales = C.anchor_scales\n anchor_ratios = C.anchor_ratios\n\n assert rpn_class.shape[0] == 1\n assert rpn_regr.shape[0] == 1\n # feature map 的高,宽和深, d=9\n (m, n, d) = rpn_class.shape[1:]\n\n anchor_idx = 0\n # (m,n,9,4)\n A = np.zeros((m, n, d, 4))\n\n for anchor_scale in anchor_scales:\n for anchor_ratio in anchor_ratios:\n # anchor 在特征图上的宽\n anchor_width = (anchor_scale * anchor_ratio[0]) / C.rpn_stride\n # anchor 在特征图上的高\n anchor_height = (anchor_scale * anchor_ratio[1]) / C.rpn_stride\n # 该 anchor 的回归梯度\n regr = rpn_regr[0, :, :, 4 * anchor_idx:4 * anchor_idx + 4]\n # X: (m, n) [[0,1...,n-1],[0,1...,n-1]...]\n # Y: (m, n) [[0,0...,0],[1,1...,1],...[m-1,m-1...,m-1]]\n # 其实生成的是一个坐标,特征图上的每个点都有了相应的坐标\n # X 表示的是所有 anchor 的中心点的 x 坐标\n # Y 表示的是所有 anchor 的中心点的 y 坐标\n X, Y = np.meshgrid(np.arange(n), np.arange(m))\n # A 的最后一维的四个值表示 anchor 的 (x,y,w,h), 其中 x,y 表示左上方点的坐标\n A[:, :, anchor_idx, 0] = X - anchor_width / 2\n A[:, :, anchor_idx, 1] = Y - anchor_height / 2\n A[:, :, anchor_idx, 2] = anchor_width\n A[:, :, anchor_idx, 3] = anchor_height\n # 根据回归梯度修正\n A[:, :, anchor_idx, :] = apply_regr_np(A[:, :, anchor_idx, :], regr)\n # 宽度最小为 1\n A[:, :, anchor_idx, 2] = np.maximum(1, A[:, :, anchor_idx, 2])\n # 高度最小为 1\n A[:, :, anchor_idx, 3] = np.maximum(1, A[:, :, anchor_idx, 3])\n # A[:,:,anchor_idx, 2] 变成了 x2, 即右下角 x 坐标\n A[:, :, anchor_idx, 2] += A[:, :, anchor_idx, 0]\n # A[:,:,anchor_idx, 3] 变成了 y2, 即右下角 y 坐标\n A[:, :, anchor_idx, 3] += A[:, :, anchor_idx, 1]\n # x1 最小为 0\n A[:, :, anchor_idx, 0] = np.maximum(0, A[:, :, anchor_idx, 0])\n # y1 最小为 0\n A[:, :, anchor_idx, 1] = np.maximum(0, A[:, :, anchor_idx, 1])\n # x2 最大为 n - 1\n A[:, :, anchor_idx, 2] = np.minimum(n - 1, A[:, :, anchor_idx, 2])\n # y2 最大为 m - 1\n A[:, :, anchor_idx, 3] = np.minimum(m - 1, A[:, :, anchor_idx, 3])\n\n anchor_idx += 1\n\n # (m*n*9,4)\n all_rois = np.reshape(A, (-1, 4))\n # (m*n*9,)\n all_probs = rpn_class.reshape((-1))\n\n x1 = all_rois[:, 0]\n y1 = all_rois[:, 1]\n x2 = all_rois[:, 2]\n y2 = all_rois[:, 3]\n\n # 删除不合理的矩形存在, 左上角的坐标不能大于右下角的坐标\n idxs = np.where((x1 - x2 >= 0) | (y1 - y2 >= 0))\n all_rois = np.delete(all_rois, idxs, axis=0)\n all_probs = np.delete(all_probs, idxs, axis=0)\n\n rois = non_max_suppression_fast(all_rois, all_probs, overlap_thresh=overlap_thresh, max_boxes=max_rois)[0]\n\n return rois\n", "meta": {"hexsha": "735d80dfd750b645e81f18e8635e1d4eddc3abb8", "size": 14619, "ext": "py", "lang": "Python", "max_stars_repo_path": "frcnn/roi_helpers.py", "max_stars_repo_name": "xuannianc/keras-frcnn", "max_stars_repo_head_hexsha": "a5c2eae8f39f3089f504865dc635244b1abff1ab", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "frcnn/roi_helpers.py", "max_issues_repo_name": "xuannianc/keras-frcnn", "max_issues_repo_head_hexsha": "a5c2eae8f39f3089f504865dc635244b1abff1ab", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "frcnn/roi_helpers.py", "max_forks_repo_name": "xuannianc/keras-frcnn", "max_forks_repo_head_hexsha": "a5c2eae8f39f3089f504865dc635244b1abff1ab", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2933673469, "max_line_length": 143, "alphanum_fraction": 0.5525685751, "include": true, "reason": "import numpy", "num_tokens": 4951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.19930800503802074, "lm_q1q2_score": 0.10432186554280344}} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[4]:\n\n\n# required libraries \nimport numpy as np\nimport matplotlib.pyplot as plt\nimport panel as pn\nimport pandas as pd\npn.extension(\"katex\")\n\n\n#from IPython.display import Image, Video\n\n#import warnings\n#warnings.filterwarnings('ignore')\n\n\n# ## Lecture 1 - Course Introduction/Water Cycle ## \n# \n# _(The contents presented in this section were re-developed principally by Dr. P. K. Yadav. The original contents were developed by Prof. Rudolf Liedl)_\n\n# ### Contents of “Groundwater Module ” ###\n# \n# The entire contents of this interactive book can be listed with the following points:\n# \n# + general overview \n# + types of aquifers, properties of aquifers\n# + forces and pressure in the subsurface\n# + laws of groundwater flow and some applications (e.g. groundwater wells)\n# + quantification of aquifer parameter values via pumping tests\n# + transport of chemicals (solutes) in groundwater\n# + retardation and degradation of chemicals in groundwater\n# + groundwater modelling\n# \n\n# ### Suggested Literature: ### \n# \n# \n# + Brassington R. (1988): Field hydrogeology, Wiley & Sons.\n# \n# + Domenico P. A., Schwartz F. W. (1990): Physical and chemical hydrogeology, Wiley & Sons.\n# \n# + Fetter C. W. (2001): Applied hydrogeology, Prentice Hall.\n# \n# + Freeze R. A., Cherry J. A. (1979): Groundwater, Prentice Hall.\n# \n# + Heath R. C. (1987): Basic groundwater hydrology, USGS Water Supply Paper 2220.\n# \n# + Price M. (1996): Introducing groundwater, Chapman and Hall.\n# \n# Additional literature details are provided in the text when used.\n\n# ### What is Hydrogeology? ###\n# \n# _**Hydrogeology**_ is the study of the laws governing the movement of subterranean water, the mechanical, chemical, and thermal interaction of this water with the porous solid, and the transport of energy and chemical constituents by the flow. \n# (Domenico and Schwartz, 1990)\n# \n# \n# The dominant reliance of groundwater for the drinking globally has made hydrogeology a very important academic course. Also, it is a very important research field. Therefore, several **techniques** and **methods** are now available to explore and understand **Hydrogeological Process**. The methods and techniques can be broadly categorized to:\n# \n# 1. Field works\n# 2. Laboratory experiments\n# 3. Computer modeling\n# \n# \n# _Computer modelling_ is often the most economical method but its usefullness rely of data obtained from _Field works_ and _Laboratory experiments._ Thus, the sequence of techniques/methods to be adopted depends on the available site information.\n# \n\n# In[2]:\n\n\nim1 = pn.pane.PNG(\"images/L01_f_1c.png\", width=250)\nim2 = pn.pane.PNG(\"images/L01_f_1b.png\", width=275)\nim3 = pn.pane.PNG(\"images/L01_f_1a.png\", width=280)\n\npn.Row(im1, im2, im3)\n\n\n# ### Example: Groundwater Extraction Well\n# \n# Groundwater is extracted using a groundwater well applying _hydrogeological_ methods and techniques. The procedure followed can be summarized in the following steps:\n# \n# 1. The appropriate extraction location is identified \n# 2. Drilling machine are used to obtain sub-surface structure, i.e. or well logs are obtained. The process is also called well logging.\n# 3. Well logs are studied in detail to identify the characteristics of the subsurface- e.g., how thick is the aquifer or identify environmental consequence of water extraction.\n# 4. The construction of well begins\n# \n# Groundwater extraction using well is a challenge when aquifers are located very deep from the surface, e.g., in deserts. \n# \n\n# In[3]:\n\n\nvideo1 = pn.pane.Video(\"images/L01_f_2.mp4\", width=600, height=400, loop=False)\nvideo1\n\n\n# In[4]:\n\n\n#gif_pane = pn.pane.GIF('images/L01_f_2.gif', width=500)\n#gif_pane\nvideo2 = pn.pane.Video(\"images/L01_f_3.mp4\", width=600, height=400, loop=False)\n#Video(\"images/L01_f_3.mp4\", width=600, embed=True) \nvideo2 \n\npn1 = pn.pane.Markdown(\"\"\"\n**Wells** are placed on the layer or that aquifer part which allows feasible extraction of groundwater. \nThe extraction leads to drop of groundwater level. To ensure that there is sustainable extraction,\nthe drops in the level has to be monitored. Quite often this is done through _computer modelling_. There\nalready exists several computer models that can use the well logs data (also called Borehole) and provide\ngood estimations of the effects due to extraction. The _computer models_ are also able to predict the effects\nat larger scales, e.g., regional scales. _Computer models_ are oftenly used these days be agencies to determine\nquantities such as **travel time**, **capture zones** or obtain **isochrones**, which are used for deciding on\ngroundwater extraction programmes.\n\"\"\")\n\npn.Row(pn1, video2)\n\n\n# ### Groundwater and Global Water Cycle ###\n# \n# Water bodies that exist on earth is connected, and they function as a cycle, called **Global Water Cycle**. It is estimated that over 57, 700 Km$^3$ of water actively participates in the cycle each year. **Precipitation** and **evaporation** are the two main components of the cycle in which **temperature** plays the critical role. In the cycle, **Groundwater** receives water from _precipitation,_ It then contributes to _evaporation_ through subsurface flow or through mostly human intervention (e.g., use for drinking water). \n# \n# The water cycle provides an approach to judge the sustainability of groundwater extraction. The sustainability of extraction can be obtained if extraction rate approximately equals the replenishing rate. Often the replenishing rate of groundwater is much slower and this has led to groundwater stress in many parts of the world. \n\n# In[2]:\n\n\n#gif_pane = pn.pane.GIF('images/L01_f_2.gif', width=500)\n#gif_pane\nvideo3 = pn.pane.Video(\"images/L01_f_4.mp4\", width=600, height=400, loop=False)\n#Video(\"images/L01_f_3.mp4\", width=600, embed=True) \nvideo3 \n\n\n# In[3]:\n\n\n#gif_pane = pn.pane.GIF('images/L01_f_2.gif', width=500)\n#gif_pane\nfig5 = pn.pane.PNG(\"images/L01_f_5.png\", width=600) \n#Video(\"images/L01_f_3.mp4\", width=600, embed=True) \n \n\npn1 = pn.pane.Markdown(\"\"\" \n\n### Water balance by continents\n\nGroundwater receives water from the _infiltration_ of **runoff** water. \n\n\"\"\")\n\npn.Row(pn1, fig5)\n\n\n# ### The Hydrological Balance ###\n# \n# Since _groundwater_ is part of the global water cycle, the balance of the cycle becomes an important topic. In general:\n# \n# + The _hydrological balance_ provides a relationship between various flow rates for a certain area. It is based on the conservation of water volume.\n# + expressed in words: _inflow_ equals _outflow_ plus _change in storage_\n# + expressed by a formula:\n# \n# $$\n# P = ET + R + \\Delta S\n# $$\n# \n# ```{margin} Where,\n# where,
\n# $P$ = _Precipitation,
$ET$ = Evapotranspiration,
$R$ = Runoff,_ and
$\\Delta S$ = _Change in Storage_\n# \n# ```\n# \n# The _change in storage_ can be interpreted in the following way: \n# \n# + change in storage $\\Delta S > 0$ : Water volume is increasing with time in the investigation area.\n# \n# + change in storage $\\Delta S < 0$:Water volume is decreasing with time in the investigation area.\n# \n# + change in storage $\\Delta S = 0$: Water volume does not change with time in the investigation area (steady-state or stationary situation, i.e. inflow equals outflow).\n\n# ### Water Volume \n# \n# \n# **So how much water do we have?**
\n# It is estimated* that the total volume of water on Earth amounts to ca. 1 358 710 150 km$^3$ ($\\approx$ 1018 m$^3$).\n# \n# \"Water\n# \n# The total volume of fresh water on Earth amounts to ca. $38\\times 10^6$ km$^3$ ($\\approx$ 1016 m$^3$).

\n# \n# _*Gleick P. (1996): Water re-sources, in: Schneider S. H. (ed.), Encyclopedia of climate and weather 2, Oxford Univ. Press._\n# \n\n# ### Volume of Available Fresh Water ###\n# \n# **Fresh water** are water with low concentrations of dissolved salts and other total dissolved solids, i.e., sea/ocean water or brackish water are not fresh water. Human activities (drinking water) are directly dependent on fresh activities. \n# \n# **So how much _fresh water_ do we have?**\n# \n# \n# It is estimated* that the total volume of available fresh water (liquid) on Earth amounts to ca. 8 831 600 km$^3$ ($\\approx$ 1016 m$^3$).\n# \n# \"Fresh\n# \n# \n# _*Gleick P. (1996): Water re-sources, in: Schneider S. H. (ed.), Encyclopedia of climate and weather 2, Oxford Univ. Press._\n\n# ### Continental distribution of fresh water components ### \n# \n# \"Fresh\n# \n\n# ### Volume and Mass Budget\n# \n# \n# Very basics of volume and mass budget - let us start with _budget._\n# \n# **Budget** = quantitative comparison of _growth_ (or _production_) and _loss_ in a system\n# \n# Budgets can be put together for various quantities:\n# + energy\n# + mass $\\leftarrow$ needed to quantify transport of solutes in groundwater\n# + volume $\\leftarrow$ needed to quantify groundwater flow\n# + momentum\n# + electric charge\n# + number of inhabitants\n# + animal population\n# + money (bank account!)\n# + and many others\n# \n# In this course we focus on _Mass Budget_ and _Volume Budget._\n\n# ### Volume Budget ###\n# \n# As discussed in the last topic a _budget_ represents the change (e.g., growth and loss). Thus, it is more suitable to quantify the **volume budget** in terms of a change, representing two different states (e.g., time $(t)$). More formally, the **volume budget** ($\\Delta V$) can be obtained from: \n# \n# $$\n# \\Delta V = Q_{in} \\cdot \\Delta t - Q{out} \\cdot \\Delta t \n# $$\n#
\n# with,
\t\n# \n# $\\Delta t$ = time interval [T]
\n# $\\Delta V$ = change of volume in the system [L$^3$]
\n# $Q_{in}$ = volumetric rate of flow into the system [L$^3$/T]
\n# $Q_{out} =$ volumetric rate of flow out of the system [L$^3$/T]
\n# \n# The following points have to be considered when using the above equation:\n# \n# + Inflow and outflow may each consist of several individual components.
\n# \n# + $\\Delta V = 0$ (no change in volume) is tantamount to steady-state or stationary (= time-independent) conditions.
\n# \n# + For steady-state conditions we have: $Q_{in} = Q_{out}$\n# \n\n# #### Water Budget for a Catchment ####\n# \n# The equation provided for _volume budget_ looks simple but in practice it is very complicated as several _inflow_ and _outflow_ components must be considered. Quantifying these components can be a challenging task.\n# \n# For quantifying water budget of a catchment, one has to consider the following components:\n# \n# **To be considered:**\n# + precipitation\n# + evapotranspiration\n# + surface runoff\n# + subsurface runoff\n# \n# Among the above components, quantification of evapotranspiration and subsurface runoff have very high level of uncertainties.\n# \n# ```{image} images/L01_f_9.png\n# :height: 500px\n# :align: center\n# :name: Water-Budget\n# ```\n\n# ### Example: Estimation of Subsurface Runoff ###\n# \n# Most numbers used in the example do not refer to the catchment shown before!\n# \n# To calculate the following four-steps are to be followed:\n# \n# + Step 1: determine rate of inflow in m³/a \n# + step 2: determine rate of outflow due to evapotranspiration (ET.A) in m³/a \n# + Step 3: express rate of outflow due to surface runoff in m³/a\n# + step 4: determine rate of outflow due to subsurface runoff \n# \n# An Example:
\n# For given data, determine the rate of outflow Qout,sub due to subsurface runoff for steady-state conditions\n\n# In[4]:\n\n\nA = 4500 # km², catchment area\nP = 550 # mm/a, precipitation\nET = 200 # mm/a, evapotranspiration\nQout_surf = 40 # m³/s, surface runoff\nDelta_V = 0 # m³, change in volume = 0 Steady-state conditions\n\n#Volume budget in this example: P·A = ET·A + Qout,surf + Qout,sub\n\n#Step 1 \nQin = P*A*10**3 #m³/a, 10^3 for unit conversion\n\n#step 2: \nET_A = ET*A*10**3 #m³/a, 10^3 for unit conversion\n\n#Step 3: \nQout_surf = Qout_surf *365*24*3600 # m³/a\n\n# step 4:\nQout_sub = Qin - ET_A - Qout_surf # m³/a \n\n\n\nprint(\"The rate of inflow, Qin is {0:1.1E}\".format(Qin),\"m\\u00b3/a \\n\"); print(\"The outflow rate due to Evapotranspiration is {0:1.1E}\".format(ET_A),\"m\\u00b3/a \\n\")\nprint(\"The surface outflow rate, Q_out_surf in m\\u00b3/a is {0:1.1E}\".format(Qout_surf),\"m\\u00b3/a \\n\");print(\"The subsurface outflow rate, Qout_surf in m\\u00b3/a is {0:1.1E}\".format(Qout_sub),\"m\\u00b3/a \\n\")\n\n\n# ### Mass Budget ###\n# \n# The **mass budget** is quantified similar to the _volume budget._ Mathematically, the _mass budget_ is:\n# \n# $$\\Delta M = J_{in}\\cdot \\Delta t - J_{out} \\cdot \\Delta t$$ \n# \n# with
\n# $\\Delta t$ = time interval [T]
\n# \t$\\Delta M$ = change of mass in the system [M]
\n# \t$J_{in}$ = rate of mass flow into the system [M/T]
\n# \t$J_{out}$ = rate of mass flow out of the system [M/T]\n# \n# Similar to _volume budget,_ the following points have to be considered in quantifying mass budget:\n# \n# + Inflow and outflow may each consist of several individual components.
\n# + $\\Delta M$ = 0 (no change in mass) is tantamount to steady-state or stationary
(= time-independent) conditions.
\n# + For steady-state conditions we have: $J_{in}$= $J_{out}$\n\n# ### Example of Mass Budget: Radioactive Decay ### \n# \n# Consider a decay chain comprising of the three chemicals: **A**, **B** and **C** \n# \n# + decay chain: A $\\rightarrow$ B $\\rightarrow$ C
\n# + 30% of $\\text{A}$ and 20% of $\\text{B}$ decay each year.
\n# \n# + decay rate of $\\text{A}$ = production rate of $\\text{B}$ = $0.3 \\cdot a^{-1}\\cdot M_A$
\n# \n# + decay rate of $\\text{B}$ = production rate of $\\text{C}$ = $0.2\\cdot a^{-1}\\cdot M_B$
\n# \n# + mass budgets for $\\text{A}$, $\\text{B}$ and $\\text{C}$:
\n# \n# \n# \n# \\begin{equation*}\n# \\begin{split}\n# \\Delta M_A &= 0.3 \\text{ a $^{-1}$ } \\cdot M_A \\cdot \\Delta t \\\\\n# \\Delta M_B &= 0.3 \\text{a$^{-1}$} \\cdot M_A \\cdot \\Delta t - 0.2 \\text{ a$^{-1}$} \\cdot M_B \\cdot \\Delta t \\\\\n# \\Delta M_C &= 0.2 \\text{a$^{-1}$} \\cdot M_B \\cdot \\Delta t\n# \\end{split}\n# \\end{equation*}\n# \n# \t\n# + Similar equations hold for quantitative descriptions of some chemical reactions which correspond to the type A $\\rightarrow$ B $\\rightarrow$ C\n\n# In[2]:\n\n\ndef mass_bal(n_simulation, MA, MB, MC, R_A, R_B):\n \n A = np.zeros(n_simulation)\n B = np.zeros(n_simulation)\n C = np.zeros(n_simulation) \n time = np.arange(n_simulation)\n \n for i in range(0,n_simulation-1):\n A[0] = MA\n B[0] = MB\n C[0] = MC\n A[i+1] = A[i]-R_A*A[i]\n B[i+1] = B[i]+R_A*A[i]-R_B*B[i] \n C[i+1] = C[i]+R_B*B[i]\n summ = A[i]+B[i]+C[i]\n \n d = {\"Mass_A\": A, \"Mass_B\": B, \"Mass_C\": C, \"Total Mass\": summ}\n df = pd.DataFrame(d) # Generating result table\n label = [\"Mass A (g)\", \"Mass B (g)\", \"Mass C (g)\"]\n fig = plt.figure(figsize=(6,4))\n plt.plot(time, A, time, B, time, C, linewidth=3); # plotting the results\n plt.xlabel(\"Time [Time Unit]\"); plt.ylabel(\"Mass [g]\") # placing axis labels\n plt.legend(label, loc=0);plt.grid(); plt.xlim([0,20]); plt.ylim(bottom=0) # legends, grids, x,y limits\n plt.show() # display plot\n \n df_pane = pn.pane.DataFrame(df)\n return print(df.round(2)) \n\nN = widgets.BoundedIntText(value=20,min=0,max=100,step=1,description= 'Δ t (day)',disabled=False)\n\nA = widgets.BoundedFloatText(value=100,min=0,max=1000.0,step=1,description='MA (kg)',disabled=False)\n\nB = widgets.BoundedFloatText(value=5,min=0,max=1000.0,step=1,description='MB (kg)',disabled=False)\n\nC = widgets.BoundedFloatText(value=10,min=0,max=1000,step=0.1,description='MC (kg)',disabled=False)\n\nRA = widgets.BoundedFloatText(value=0.2,min=0,max=100,step=0.1,description='RA (day-1 )',disabled=False)\n\nRB = widgets.BoundedFloatText(value=0.2,min=0,max=100,step=0.1,description='RB (day-1 )',disabled=False)\n\n\ninteractive_plot = widgets.interactive(mass_bal, n_simulation = N, MA=A, MB=B, MC=C, R_A=RA, R_B=RB,)\noutput = interactive_plot.children[-1] \n#output.layout.height = '350px'\ninteractive_plot\n\n\n# ### Comparison of Mass and Volume Budgets ###\n# \n# **mass budget**:\t$\\Delta M = J_{in} \\cdot \\Delta t - J_{out} \\cdot \\Delta t$\n# \n# **volume budget**:\t$\\Delta V = Q_{in} \\cdot \\Delta t - Q_{out} \\cdot \\Delta t $\n# \n# \n# + Mass and volume budgets are equivalent if there is no change of density $\\rho$ [M/L$^3$] with time. In this case the well known relationship $\\Delta M$ = $\\rho \\cdot \\Delta V$ holds and each equation given above can be directly transformed into the other one.\n# \n# \n# + If density changes have to be considered (e.g. for gas flow), the mass budget equation remains valid but the volume budget equation must be modified because $\\Delta M = \\rho \\cdot \\Delta V + \\Delta \\rho \\cdot V$ with $\\Delta \\rho$= change in density.\n# \n# \n# + Cases with changing density have proven to be more easily tractable if the mass budget equation is used.\n", "meta": {"hexsha": "99e3bd926e1075700581eb63e4f89bb7c74d0a75", "size": 17183, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/contents/background/03_basic_hydrogeology.py", "max_stars_repo_name": "prabhasyadav/iGW-I", "max_stars_repo_head_hexsha": "eba32830f32f1109a7bee600c65832af0e7183fa", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_build/jupyter_execute/contents/background/03_basic_hydrogeology.py", "max_issues_repo_name": "prabhasyadav/iGW-I", "max_issues_repo_head_hexsha": "eba32830f32f1109a7bee600c65832af0e7183fa", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_build/jupyter_execute/contents/background/03_basic_hydrogeology.py", "max_forks_repo_name": "prabhasyadav/iGW-I", "max_forks_repo_head_hexsha": "eba32830f32f1109a7bee600c65832af0e7183fa", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6836027714, "max_line_length": 532, "alphanum_fraction": 0.6950474306, "include": true, "reason": "import numpy", "num_tokens": 4969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046202709847, "lm_q2_score": 0.24508501864634824, "lm_q1q2_score": 0.10354955273728256}} {"text": "# MIT License\n#\n# Copyright (C) IBM Corporation 2019\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThe Wishart mechanism in differential privacy, for producing positive semi-definite perturbed second-moment matrices\n\"\"\"\nfrom numbers import Real\nimport warnings\n\nimport numpy as np\n\nfrom diffprivlib.mechanisms.base import DPMechanism\nfrom diffprivlib.utils import copy_docstring\n\n\nclass Wishart(DPMechanism):\n r\"\"\"\n The Wishart mechanism in differential privacy.\n\n Used to achieve differential privacy on 2nd moment matrices.\n\n Paper link: https://ieeexplore.ieee.org/abstract/document/7472095/\n\n .. deprecated:: 0.4\n `Wishart` is deprecated and will be removed in version 0.5. The Wishart mechanism has been shown not to satisfy\n differential privacy, and its continued use is not recommended.\n\n Parameters\n ----------\n epsilon : float\n The value of epsilon for achieving :math:`(\\epsilon,\\delta)`-differential privacy with the mechanism. Must be\n > 0.\n\n sensitivity : float\n The maximum l2-norm of the data. Must be >= 0.\n\n \"\"\"\n def __init__(self, epsilon, sensitivity):\n warnings.warn(\"The Wishart mechanism has been shown not to satisfy differential privacy as originally \"\n \"proposed. As a result, the Wishart mechanism is deprecated as of version 0.4, and will be \"\n \"removed in version 0.5. To get a differentially private estimate of a covariance matrix, it is \"\n \"recommended to use `models.utils.covariance_eig` instead.\", DeprecationWarning)\n\n super().__init__(epsilon=epsilon, delta=0.0)\n self.sensitivity = self._check_sensitivity(sensitivity)\n\n self._rng = np.random.default_rng()\n\n @classmethod\n def _check_epsilon_delta(cls, epsilon, delta):\n if not delta == 0:\n raise ValueError(\"Delta must be zero\")\n\n return super()._check_epsilon_delta(epsilon, delta)\n\n @classmethod\n def _check_sensitivity(cls, sensitivity):\n if not isinstance(sensitivity, Real):\n raise TypeError(\"Sensitivity must be numeric\")\n\n if sensitivity < 0:\n raise ValueError(\"Sensitivity must be non-negative\")\n\n return float(sensitivity)\n\n def _check_all(self, value):\n super()._check_all(value)\n self._check_sensitivity(self.sensitivity)\n\n if not isinstance(value, np.ndarray):\n raise TypeError(\"Value to be randomised must be a numpy array, got %s\" % type(value))\n if value.ndim != 2:\n raise ValueError(\"Array must be 2-dimensional, got %d dimensions\" % value.ndim)\n if value.shape[0] != value.shape[1]:\n raise ValueError(\"Array must be square, got %d x %d\" % (value.shape[0], value.shape[1]))\n\n return True\n\n @copy_docstring(DPMechanism.bias)\n def bias(self, value):\n raise NotImplementedError\n\n @copy_docstring(DPMechanism.variance)\n def variance(self, value):\n raise NotImplementedError\n\n def randomise(self, value):\n \"\"\"Randomise `value` with the mechanism.\n\n Parameters\n ----------\n value : numpy array\n The data to be randomised.\n\n Returns\n -------\n numpy array\n The randomised array.\n\n \"\"\"\n self._check_all(value)\n\n scale = 1 / 2 / self.epsilon\n n_features = value.shape[0]\n\n noise_array = self._rng.standard_normal((n_features, n_features + 1)) * scale * self.sensitivity\n noise_array = np.dot(noise_array, noise_array.T)\n\n return value + noise_array\n", "meta": {"hexsha": "0134ada64dcabdb210b9d858b98b3ab4f4e5708e", "size": 4621, "ext": "py", "lang": "Python", "max_stars_repo_path": "diffprivlib/mechanisms/wishart.py", "max_stars_repo_name": "Originofamonia/differential-privacy-library", "max_stars_repo_head_hexsha": "11759216bd418f764ff5c4a2349975b14f6e7ffb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-26T06:15:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-26T06:15:13.000Z", "max_issues_repo_path": "diffprivlib/mechanisms/wishart.py", "max_issues_repo_name": "SHIHUA110/differential-privacy-library", "max_issues_repo_head_hexsha": "a889ba0f8d19c77e2b0369451ebc392969fac685", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "diffprivlib/mechanisms/wishart.py", "max_forks_repo_name": "SHIHUA110/differential-privacy-library", "max_forks_repo_head_hexsha": "a889ba0f8d19c77e2b0369451ebc392969fac685", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-07T10:40:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-07T10:40:49.000Z", "avg_line_length": 37.2661290323, "max_line_length": 120, "alphanum_fraction": 0.6831854577, "include": true, "reason": "import numpy", "num_tokens": 1013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.19193278875832634, "lm_q1q2_score": 0.10344855264053164}} {"text": "import math\nimport torch.nn.functional as F\nimport collections\nimport torch\nimport numpy\nfrom collections import defaultdict\nfrom dataclasses import dataclass\nfrom fairseq import metrics\n# \n# from fairseq.sequence_generator import SequenceGenerator\n# from sequence_generator import \nfrom fairseq import utils #, bleu\nfrom fairseq.dataclass import FairseqDataclass\nfrom fairseq.criterions import FairseqCriterion, register_criterion\nfrom omegaconf import II\nfrom fairseq.models import FairseqMultiModel\nfrom fairseq.sequence_generator import SequenceGenerator\n\n\n@register_criterion('v2')\nclass V2Criterion(FairseqCriterion):\n\n def __init__(self, task, sentence_avg): #(self, args, task):\n super().__init__(task)\n self.cnt=0\n\n # def forward(self, model, sample, reduce=True):\n # \"\"\"Compute the loss for the given sample.\n #\n # Returns a tuple with three elements:\n # 1) the loss\n # 2) the sample size, which is used as the denominator for the gradient\n # 3) logging outputs to display while training\n # \"\"\"\n # net_output = model(**sample['net_input'])\n # lprobs = model.get_normalized_probs(net_output, log_probs=True)\n # lprobs = lprobs.view(-1, lprobs.size(-1))\n # target = model.get_targets(sample, net_output).view(-1)\n # loss = F.nll_loss(lprobs, target, size_average=False,\n # ignore_index=self.padding_idx,\n # reduce=reduce)\n # sample_size = sample['target'].size(0) if self.args.sentence_avg else sample['ntokens']\n # logging_output = {\n # 'loss': utils.item(loss.data) if reduce else loss.data,\n # 'ntokens': sample['ntokens'],\n # 'sample_size': sample_size,\n # }\n # return loss, sample_size, logging_output\n\n def forward(self, model, sample, reduce=True):\n # sample mode\n #print('!!!RL loss.')\n model.eval()\n # src_dict = self.task.source_dictionary\n tgt_dict = self.task.target_dictionary\n eos_idx = self.task.target_dictionary.eos()\n sample_beam = 4 #self.args.sample_beam\n\n translator = SequenceGenerator([model], tgt_dict=tgt_dict,beam_size=sample_beam)\n\n translator.cuda()\n ct = 0\n translations = []\n\n s = utils.move_to_cuda(sample)\n input = s['net_input']\n max_len = 200\n with torch.no_grad():\n hypos = translator.generate([model],s)\n for i, id in enumerate(s['id'].data):\n src = input['src_tokens'].data[i, :]\n # remove padding from ref\n ref = utils.strip_pad(s['target'].data[i, :], tgt_dict.pad()) if s['target'] is not None else None\n translations.append((id, src, ref, hypos[i]))\n\n ct += 1\n # print(\"sample batch size:\", ct)\n\n model.train()\n\n # MLE loss\n mle_net_output = model(**sample['net_input'])\n mle_lprobs = model.get_normalized_probs(mle_net_output, log_probs=True)\n mle_lprobs = mle_lprobs.view(-1, mle_lprobs.size(-1))\n mle_target = model.get_targets(sample, mle_net_output).view(-1)\n mle_loss = F.nll_loss(mle_lprobs, mle_target, size_average=False,\n ignore_index=self.padding_idx, reduce=reduce)\n mle_tokens = sample['ntokens']\n avg_mle_loss = mle_loss / mle_tokens\n self.cnt += 1\n if self.cnt % 4 !=0 : \n total_loss = avg_mle_loss\n total_tokens = sample[\"ntokens\"]\n logging_output = {\n 'loss': utils.item(total_loss.data),\n 'ntokens': total_tokens,\n 'sample_size': total_tokens,\n }\n # print('total: ',total_loss)\n return total_loss, total_tokens, logging_output\n\n \n print('avg_mle_loss:', avg_mle_loss)\n # RL loss\n batch_rl_loss = 0\n batch_tokens = 0\n sample_ind = 0\n for sample_id, src_tokens, tgt_tokens, hypos in translations:\n # calculate bleu\n sample_ind += 1\n rewards = torch.Tensor(sample_beam).float().cuda()\n logprobs = torch.Tensor(sample_beam).float().cuda()\n for i in range(sample_beam):\n hypo = hypos[i]\n trans_tokens = hypo['tokens']\n rewards[i] = self.compute_gleu(tgt_tokens.cpu(), trans_tokens.cpu(), max_order=4, gram=0).cuda()\n # one_sample loss calculation\n tgt_input_tokens = trans_tokens.new(trans_tokens.shape).fill_(0)\n assert trans_tokens[-1] == eos_idx\n tgt_input_tokens[0] = eos_idx\n tgt_input_tokens[1:] = trans_tokens[:-1]\n train_sample = {\n 'net_input': {\n 'src_tokens': src_tokens.view(1, -1),\n 'src_lengths': torch.LongTensor(src_tokens.numel()).view(1, -1),\n 'prev_output_tokens': tgt_input_tokens.view(1, -1),\n },\n 'target': trans_tokens.view(1, -1)\n }\n train_sample = utils.move_to_cuda(train_sample)\n net_output = model(**train_sample['net_input'])\n lprobs = model.get_normalized_probs(net_output, log_probs=True)\n lprobs = lprobs.view(-1, lprobs.size(-1))\n target = model.get_targets(train_sample, net_output).view(-1, 1)\n non_pad_mask = target.ne(tgt_dict.pad())\n lprob = -lprobs.gather(dim=-1, index=target)[non_pad_mask]\n logprobs[i] = torch.sum(lprob)\n ntokens = len(train_sample['target'])\n batch_tokens += ntokens\n rl_loss = torch.sum(logprobs * (rewards - rewards.mean())) # one sample loss \n batch_rl_loss += rl_loss\n \n avg_rl_loss = batch_rl_loss / batch_tokens\n print('avg_rl_loss:', avg_rl_loss)\n if True:\n total_loss = avg_mle_loss + avg_rl_loss\n total_tokens = batch_tokens + mle_tokens\n else:\n total_loss = avg_rl_loss\n total_tokens = batch_tokens\n logging_output = {\n 'loss': utils.item(total_loss.data),\n 'ntokens': total_tokens,\n 'sample_size': total_tokens,\n }\n print('total: ',total_loss)\n return total_loss, total_tokens, logging_output\n\n\n def _get_ngrams(self, segment, max_order):\n ngram_counts = collections.Counter()\n for order in range(1, max_order + 1):\n for i in range(0, len(segment) - order + 1):\n ngram = tuple(segment[i:i + order])\n ngram_counts[ngram] += 1\n return ngram_counts\n\n def compute_gleu(self, reference_corpus, translation_corpus, max_order=4, gram=0, smooth=False):\n scores = torch.zeros(max_order)\n reference_array = numpy.array(reference_corpus)\n translation_array = numpy.array(translation_corpus)\n matches_by_order = [0] * max_order\n possible_matches_by_order_ref = [0] * max_order\n possible_matches_by_order_trans = [0] * max_order\n reference_length = 0\n translation_length = 0\n reference_length += reference_array.shape[0]\n translation_length += translation_array.shape[0]\n merged_ref_ngram_counts = collections.Counter()\n merged_ref_ngram_counts |= self._get_ngrams(reference_array, max_order)\n translation_ngram_counts = self._get_ngrams(translation_array, max_order)\n overlap = translation_ngram_counts & merged_ref_ngram_counts\n for ngram in overlap:\n matches_by_order[len(ngram)-1] += overlap[ngram]\n for order in range(1, max_order+1):\n possible_matches_trans = translation_length - order + 1\n if possible_matches_trans > 0:\n possible_matches_by_order_trans[order-1] += possible_matches_trans\n possible_matches_ref = reference_length - order + 1\n if possible_matches_ref > 0:\n possible_matches_by_order_ref[order-1] += possible_matches_ref\n precisions = [0] * max_order\n recalls = [0] * max_order\n\n for i in range(0, max_order):\n if smooth:\n precisions[i] = ((matches_by_order[i] + 1.) / (possible_matches_by_order_trans[i] + 1.))\n recalls[i] = ((matches_by_order[i] + 1.) / (possible_matches_by_order_ref[i] + 1.))\n else:\n if possible_matches_by_order_trans[i] > 0:\n precisions[i] = (float(matches_by_order[i]) / possible_matches_by_order_trans[i])\n else:\n precisions[i] = 0.0\n \n if possible_matches_by_order_ref[i] > 0:\n recalls[i] = (float(matches_by_order[i]) / possible_matches_by_order_ref[i])\n else:\n recalls[i] = 0.0\n for i in range(max_order):\n scores[i] = min(precisions[i],recalls[i])\n\n if False :#self.args.modgleu:\n if reference_length < max_order and translation_length < max_order:\n order = max(reference_length, translation_length)\n scores = scores[0:order]\n else:\n order = max_order\n else:\n order = max_order\n if gram == 0:\n if min(scores) > 0:\n log_scores = torch.log(scores)\n p_log_sum = torch.sum((1. / order) * log_scores)\n geo_mean = torch.exp(p_log_sum)\n return geo_mean\n else:\n return torch.tensor(0.0)\n else:\n if scores[gram] > 0:\n return scores[gram]\n else:\n return torch.tensor(0.0)\n \n @staticmethod\n def aggregate_logging_outputs(logging_outputs):\n \"\"\"Aggregate logging outputs from data parallel training.\"\"\"\n loss_sum = sum(log.get('loss', 0) for log in logging_outputs)\n ntokens = sum(log.get('ntokens', 0) for log in logging_outputs)\n sample_size = sum(log.get('sample_size', 0) for log in logging_outputs)\n agg_output = {\n 'loss': loss_sum / sample_size / math.log(2),\n 'sample_size': sample_size,\n }\n if sample_size != ntokens:\n agg_output['nll_loss'] = loss_sum / ntokens / math.log(2)\n return agg_output\n\n @staticmethod\n def reduce_metrics(logging_outputs) -> None:\n \"\"\"Aggregate logging outputs from data parallel training.\"\"\"\n loss_sum = sum(log.get(\"loss\", 0) for log in logging_outputs)\n ntokens = sum(log.get(\"ntokens\", 0) for log in logging_outputs)\n sample_size = sum(log.get(\"sample_size\", 0) for log in logging_outputs)\n\n # we divide by log(2) to convert the loss from base e to base 2\n metrics.log_scalar(\n \"loss\", loss_sum / sample_size / math.log(2), sample_size, round=3\n )\n if sample_size != ntokens:\n metrics.log_scalar(\n \"nll_loss\", loss_sum / ntokens / math.log(2), ntokens, round=3\n )\n metrics.log_derived(\n \"ppl\", lambda meters: utils.get_perplexity(meters[\"nll_loss\"].avg)\n )\n else:\n metrics.log_derived(\n \"ppl\", lambda meters: utils.get_perplexity(meters[\"loss\"].avg)\n )\n\n @staticmethod\n def logging_outputs_can_be_summed() -> bool:\n \"\"\"\n Whether the logging outputs returned by `forward` can be summed\n across workers prior to calling `reduce_metrics`. Setting this\n to True will improves distributed training speed.\n \"\"\"\n return True\n", "meta": {"hexsha": "f25db81a7e4ec08ee88d1238b2398837c5211fa6", "size": 11744, "ext": "py", "lang": "Python", "max_stars_repo_path": "fairseq/criterions/v2.py", "max_stars_repo_name": "guangyliu/EISL-fairseq", "max_stars_repo_head_hexsha": "28d203622cd29b81269c53e359cf418c1bc41242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fairseq/criterions/v2.py", "max_issues_repo_name": "guangyliu/EISL-fairseq", "max_issues_repo_head_hexsha": "28d203622cd29b81269c53e359cf418c1bc41242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fairseq/criterions/v2.py", "max_forks_repo_name": "guangyliu/EISL-fairseq", "max_forks_repo_head_hexsha": "28d203622cd29b81269c53e359cf418c1bc41242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.0931899642, "max_line_length": 112, "alphanum_fraction": 0.5903440054, "include": true, "reason": "import numpy", "num_tokens": 2687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.2043418902459481, "lm_q1q2_score": 0.10296913939250937}} {"text": "# Introduction\n\nClassical mechanics is a topic which has been taught intensively over\nseveral centuries. It is, with its many variants and ways of\npresenting the educational material, normally the first **real** physics\ncourse many of us meet and it lays the foundation for further physics\nstudies. Many of the equations and ways of reasoning about the\nunderlying laws of motion and pertinent forces, shape our approaches and understanding\nof the scientific method and discourse, as well as the way we develop our insights\nand deeper understanding about physical systems. \n\nThere is a wealth of\nwell-tested (from both a physics point of view and a pedagogical\nstandpoint) exercises and problems which can be solved\nanalytically. However, many of these problems represent idealized and\nless realistic situations. The large majority of these problems are\nsolved by paper and pencil and are traditionally aimed\nat what we normally refer to as continuous models from which we may find an analytical solution. As a consequence,\nwhen teaching mechanics, it implies that we can seldomly venture beyond an idealized case\nin order to develop our understandings and insights about the\nunderlying forces and laws of motion.\n\n\nOn the other hand, numerical algorithms call for approximate discrete\nmodels and much of the development of methods for continuous models\nare nowadays being replaced by methods for discrete models in science and\nindustry, simply because **much larger classes of problems can be addressed** with discrete models, often by simpler and more\ngeneric methodologies.\n\nAs we will see below, when properly scaling the equations at hand,\ndiscrete models open up for more advanced abstractions and the possibility to\nstudy real life systems, with the added bonus that we can explore and\ndeepen our basic understanding of various physical systems\n\nAnalytical solutions are as important as before. In addition, such\nsolutions provide us with invaluable benchmarks and tests for our\ndiscrete models. Such benchmarks, as we will see below, allow us \nto discuss possible sources of errors and their behaviors. And\nfinally, since most of our models are based on various algorithms from\nnumerical mathematics, we have a unique oppotunity to gain a deeper\nunderstanding of the mathematical approaches we are using.\n\n\n\nWith computing and data science as important elements in essentially\nall aspects of a modern society, we could then try to define Computing as\n**solving scientific problems using all possible tools, including\nsymbolic computing, computers and numerical algorithms, and analytical\npaper and pencil solutions**. \nComputing provides us with the tools to develope our own understanding of the scientific method by enhancing algorithmic thinking.\n\n\nThe way we will teach this course reflects\nthis definition of computing. The course contains both classical paper\nand pencil exercises as well as computational projects and exercises. The\nhope is that this will allow you to explore the physics of systems\ngoverned by the degrees of freedom of classical mechanics at a deeper\nlevel, and that these insights about the scientific method will help\nyou to develop a better understanding of how the underlying forces and\nequations of motion and how they impact a given system. Furthermore, by introducing various numerical methods\nvia computational projects and exercises, we aim at developing your competences and skills about these topics.\n\n\nThese competences will enable you to\n\n* understand how algorithms are used to solve mathematical problems,\n\n* derive, verify, and implement algorithms,\n\n* understand what can go wrong with algorithms,\n\n* use these algorithms to construct reproducible scientific outcomes and to engage in science in ethical ways, and\n\n* think algorithmically for the purposes of gaining deeper insights about scientific problems.\n\nAll these elements are central for maturing and gaining a better understanding of the modern scientific process *per se*.\n\nThe power of the scientific method lies in identifying a given problem\nas a special case of an abstract class of problems, identifying\ngeneral solution methods for this class of problems, and applying a\ngeneral method to the specific problem (applying means, in the case of\ncomputing, calculations by pen and paper, symbolic computing, or\nnumerical computing by ready-made and/or self-written software). This\ngeneric view on problems and methods is particularly important for\nunderstanding how to apply available, generic software to solve a\nparticular problem.\n\n*However, verification of algorithms and understanding their limitations requires much of the classical knowledge about continuous models.*\n\n\n\n## A well-known examples to illustrate many of the above concepts\n\nBefore we venture into a reminder on Python and mechanics relevant applications, let us briefly outline some of the\nabovementioned topics using an example many of you may have seen before in for example CMSE201. \nA simple algorithm for integration is the Trapezoidal rule. \nIntegration of a function $f(x)$ by the Trapezoidal Rule is given by following algorithm for an interval $x \\in [a,b]$\n\n$$\n\\int_a^b(f(x) dx = \\frac{1}{2}\\left [f(a)+2f(a+h)+\\dots+2f(b-h)+f(b)\\right] +O(h^2),\n$$\n\nwhere $h$ is the so-called stepsize defined by the number of integration points $N$ as $h=(b-a)/(n)$.\nPython offers an extremely versatile programming environment, allowing for\nthe inclusion of analytical studies in a numerical program. Here we show an\nexample code with the **trapezoidal rule**. We use also **SymPy** to evaluate the exact value of the integral and compute the absolute error\nwith respect to the numerically evaluated one of the integral\n$\\int_0^1 dx x^2 = 1/3$.\nThe following code for the trapezoidal rule allows you to plot the relative error by comparing with the exact result. By increasing to $10^8$ points one arrives at a region where numerical errors start to accumulate.\n\n%matplotlib inline\n\nfrom math import log10\nimport numpy as np\nfrom sympy import Symbol, integrate\nimport matplotlib.pyplot as plt\n# function for the trapezoidal rule\ndef Trapez(a,b,f,n):\n h = (b-a)/float(n)\n s = 0\n x = a\n for i in range(1,n,1):\n x = x+h\n s = s+ f(x)\n s = 0.5*(f(a)+f(b)) +s\n return h*s\n# function to compute pi\ndef function(x):\n return x*x\n# define integration limits\na = 0.0; b = 1.0;\n# find result from sympy\n# define x as a symbol to be used by sympy\nx = Symbol('x')\nexact = integrate(function(x), (x, a, b))\n# set up the arrays for plotting the relative error\nn = np.zeros(9); y = np.zeros(9);\n# find the relative error as function of integration points\nfor i in range(1, 8, 1):\n npts = 10**i\n result = Trapez(a,b,function,npts)\n RelativeError = abs((exact-result)/exact)\n n[i] = log10(npts); y[i] = log10(RelativeError);\nplt.plot(n,y, 'ro')\nplt.xlabel('n')\nplt.ylabel('Relative error')\nplt.show()\n\nThis example shows the potential of combining numerical algorithms with symbolic calculations, allowing us to \n\n* Validate and verify their algorithms. \n\n* Including concepts like unit testing, one has the possibility to test and test several or all parts of the code.\n\n* Validation and verification are then included *naturally* and one can develop a better attitude to what is meant with an ethically sound scientific approach.\n\n* The above example allows the student to also test the mathematical error of the algorithm for the trapezoidal rule by changing the number of integration points. The students get **trained from day one to think error analysis**. \n\n* With a Jupyter notebook you can keep exploring similar examples and turn them in as your own notebooks. \n\nIn this process we can easily bake in\n1. How to structure a code in terms of functions\n\n2. How to make a module\n\n3. How to read input data flexibly from the command line\n\n4. How to create graphical/web user interfaces\n\n5. How to write unit tests (test functions or doctests)\n\n6. How to refactor code in terms of classes (instead of functions only)\n\n7. How to conduct and automate large-scale numerical experiments\n\n8. How to write scientific reports in various formats (LaTeX, HTML)\n\nThe conventions and techniques outlined here will save you a lot of time when you incrementally extend software over time from simpler to more complicated problems. In particular, you will benefit from many good habits:\n1. New code is added in a modular fashion to a library (modules)\n\n2. Programs are run through convenient user interfaces\n\n3. It takes one quick command to let all your code undergo heavy testing \n\n4. Tedious manual work with running programs is automated,\n\n5. Your scientific investigations are reproducible, scientific reports with top quality typesetting are produced both for paper and electronic devices.", "meta": {"hexsha": "8dbc695442246ca6e800feff4e36d3c29eba8367", "size": 8800, "ext": "py", "lang": "Python", "max_stars_repo_path": "doc/src/LectureNotes/testbook/_build/jupyter_execute/chapter1.py", "max_stars_repo_name": "anacost/MachineLearning", "max_stars_repo_head_hexsha": "89e1c3637fe302c2b15b96bf89c8a01d2d693f29", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/src/LectureNotes/testbook/_build/jupyter_execute/chapter1.py", "max_issues_repo_name": "anacost/MachineLearning", "max_issues_repo_head_hexsha": "89e1c3637fe302c2b15b96bf89c8a01d2d693f29", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/src/LectureNotes/testbook/_build/jupyter_execute/chapter1.py", "max_forks_repo_name": "anacost/MachineLearning", "max_forks_repo_head_hexsha": "89e1c3637fe302c2b15b96bf89c8a01d2d693f29", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-04T16:21:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-04T16:21:16.000Z", "avg_line_length": 47.0588235294, "max_line_length": 230, "alphanum_fraction": 0.7879545455, "include": true, "reason": "import numpy,from sympy", "num_tokens": 1909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807711081161995, "lm_q2_score": 0.3040416686603661, "lm_q1q2_score": 0.10278952890704042}} {"text": "import torch\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd.function import Function\nfrom torch.autograd import Variable\n\n\nclass CenterTripletLoss(nn.Module):\n \"\"\" Hetero-center-triplet-loss-for-VT-Re-ID\n \"Parameters Sharing Exploration and Hetero-Center Triplet Loss for Visible-Thermal Person Re-Identification\"\n [(arxiv)](https://arxiv.org/abs/2008.06223).\n \n Args:\n - margin (float): margin for triplet.\n \"\"\"\n \n def __init__(self, batch_size, margin=0.3):\n super(CenterTripletLoss, self).__init__()\n self.margin = margin\n self.ranking_loss = nn.MarginRankingLoss(margin=margin)\n\n def forward(self, feats, labels):\n \"\"\"\n Args:\n - inputs: feature matrix with shape (batch_size, feat_dim)\n - targets: ground truth labels with shape (num_classes)\n \"\"\"\n label_uni = labels.unique()\n targets = torch.cat([label_uni,label_uni])\n label_num = len(label_uni)\n feat = feats.chunk(label_num*2, 0)\n center = []\n for i in range(label_num*2):\n center.append(torch.mean(feat[i], dim=0, keepdim=True))\n inputs = torch.cat(center)\n\n n = inputs.size(0)\n \n # Compute pairwise distance, replace by the official when merged\n dist = torch.pow(inputs, 2).sum(dim=1, keepdim=True).expand(n, n)\n dist = dist + dist.t()\n dist.addmm_(1, -2, inputs, inputs.t())\n dist = dist.clamp(min=1e-12).sqrt() # for numerical stability\n \n # For each anchor, find the hardest positive and negative\n mask = targets.expand(n, n).eq(targets.expand(n, n).t())\n dist_ap, dist_an = [], []\n for i in range(n):\n dist_ap.append(dist[i][mask[i]].max().unsqueeze(0))\n dist_an.append(dist[i][mask[i] == 0].min().unsqueeze(0))\n dist_ap = torch.cat(dist_ap)\n dist_an = torch.cat(dist_an)\n \n # Compute ranking hinge loss\n y = torch.ones_like(dist_an)\n loss = self.ranking_loss(dist_an, dist_ap, y)\n \n # compute accuracy\n correct = torch.ge(dist_an, dist_ap).sum().item()\n return loss, correct\n\n\n\n\n\nclass CrossEntropyLabelSmooth(nn.Module):\n \"\"\"Cross entropy loss with label smoothing regularizer.\n Reference:\n Szegedy et al. Rethinking the Inception Architecture for Computer Vision. CVPR 2016.\n Equation: y = (1 - epsilon) * y + epsilon / K.\n Args:\n num_classes (int): number of classes.\n epsilon (float): weight.\n \"\"\"\n def __init__(self, num_classes, epsilon=0.1, use_gpu=True):\n super(CrossEntropyLabelSmooth, self).__init__()\n self.num_classes = num_classes\n self.epsilon = epsilon\n self.use_gpu = use_gpu\n self.logsoftmax = nn.LogSoftmax(dim=1)\n\n def forward(self, inputs, targets):\n \"\"\"\n Args:\n inputs: prediction matrix (before softmax) with shape (batch_size, num_classes)\n targets: ground truth labels with shape (num_classes)\n \"\"\"\n log_probs = self.logsoftmax(inputs)\n targets = torch.zeros(log_probs.size()).scatter_(1, targets.unsqueeze(1).data.cpu(), 1)\n if self.use_gpu: targets = targets.cuda()\n targets = (1 - self.epsilon) * targets + self.epsilon / self.num_classes\n loss = (- targets * log_probs).mean(0).sum()\n return loss\n\n\nclass OriTripletLoss(nn.Module):\n \"\"\"Triplet loss with hard positive/negative mining.\n \n Reference:\n Hermans et al. In Defense of the Triplet Loss for Person Re-Identification. arXiv:1703.07737.\n Code imported from https://github.com/Cysu/open-reid/blob/master/reid/loss/triplet.py.\n \n Args:\n - margin (float): margin for triplet.\n \"\"\"\n \n def __init__(self, batch_size, margin=0.3):\n super(OriTripletLoss, self).__init__()\n self.margin = margin\n self.ranking_loss = nn.MarginRankingLoss(margin=margin)\n\n def forward(self, inputs, targets):\n \"\"\"\n Args:\n - inputs: feature matrix with shape (batch_size, feat_dim)\n - targets: ground truth labels with shape (num_classes)\n \"\"\"\n n = inputs.size(0)\n \n # Compute pairwise distance, replace by the official when merged\n dist = torch.pow(inputs, 2).sum(dim=1, keepdim=True).expand(n, n)\n dist = dist + dist.t()\n dist.addmm_(1, -2, inputs, inputs.t())\n dist = dist.clamp(min=1e-12).sqrt() # for numerical stability\n \n # For each anchor, find the hardest positive and negative\n mask = targets.expand(n, n).eq(targets.expand(n, n).t())\n dist_ap, dist_an = [], []\n for i in range(n):\n dist_ap.append(dist[i][mask[i]].max().unsqueeze(0))\n dist_an.append(dist[i][mask[i] == 0].min().unsqueeze(0))\n dist_ap = torch.cat(dist_ap)\n dist_an = torch.cat(dist_an)\n \n # Compute ranking hinge loss\n y = torch.ones_like(dist_an)\n loss = self.ranking_loss(dist_an, dist_ap, y)\n \n # compute accuracy\n correct = torch.ge(dist_an, dist_ap).sum().item()\n return loss, correct\n\n\n\n \n# Adaptive weights\ndef softmax_weights(dist, mask):\n max_v = torch.max(dist * mask, dim=1, keepdim=True)[0]\n diff = dist - max_v\n Z = torch.sum(torch.exp(diff) * mask, dim=1, keepdim=True) + 1e-6 # avoid division by zero\n W = torch.exp(diff) * mask / Z\n return W\n\ndef normalize(x, axis=-1):\n \"\"\"Normalizing to unit length along the specified dimension.\n Args:\n x: pytorch Variable\n Returns:\n x: pytorch Variable, same shape as input\n \"\"\"\n x = 1. * x / (torch.norm(x, 2, axis, keepdim=True).expand_as(x) + 1e-12)\n return x\n\nclass TripletLoss_WRT(nn.Module):\n \"\"\"Weighted Regularized Triplet'.\"\"\"\n\n def __init__(self):\n super(TripletLoss_WRT, self).__init__()\n self.ranking_loss = nn.SoftMarginLoss()\n\n def forward(self, inputs, targets, normalize_feature=False):\n if normalize_feature:\n inputs = normalize(inputs, axis=-1)\n dist_mat = pdist_torch(inputs, inputs)\n\n N = dist_mat.size(0)\n # shape [N, N]\n is_pos = targets.expand(N, N).eq(targets.expand(N, N).t()).float()\n is_neg = targets.expand(N, N).ne(targets.expand(N, N).t()).float()\n\n # `dist_ap` means distance(anchor, positive)\n # both `dist_ap` and `relative_p_inds` with shape [N, 1]\n dist_ap = dist_mat * is_pos\n dist_an = dist_mat * is_neg\n\n weights_ap = softmax_weights(dist_ap, is_pos)\n weights_an = softmax_weights(-dist_an, is_neg)\n furthest_positive = torch.sum(dist_ap * weights_ap, dim=1)\n closest_negative = torch.sum(dist_an * weights_an, dim=1)\n\n y = furthest_positive.new().resize_as_(furthest_positive).fill_(1)\n loss = self.ranking_loss(closest_negative - furthest_positive, y)\n\n\n # compute accuracy\n correct = torch.ge(closest_negative, furthest_positive).sum().item()\n return loss, correct\n \ndef pdist_torch(emb1, emb2):\n '''\n compute the eucilidean distance matrix between embeddings1 and embeddings2\n using gpu\n '''\n m, n = emb1.shape[0], emb2.shape[0]\n emb1_pow = torch.pow(emb1, 2).sum(dim = 1, keepdim = True).expand(m, n)\n emb2_pow = torch.pow(emb2, 2).sum(dim = 1, keepdim = True).expand(n, m).t()\n dist_mtx = emb1_pow + emb2_pow\n dist_mtx = dist_mtx.addmm_(1, -2, emb1, emb2.t())\n # dist_mtx = dist_mtx.clamp(min = 1e-12)\n dist_mtx = dist_mtx.clamp(min = 1e-12).sqrt()\n return dist_mtx \n\n\ndef pdist_np(emb1, emb2):\n '''\n compute the eucilidean distance matrix between embeddings1 and embeddings2\n using cpu\n '''\n m, n = emb1.shape[0], emb2.shape[0]\n emb1_pow = np.square(emb1).sum(axis = 1)[..., np.newaxis]\n emb2_pow = np.square(emb2).sum(axis = 1)[np.newaxis, ...]\n dist_mtx = -2 * np.matmul(emb1, emb2.T) + emb1_pow + emb2_pow\n # dist_mtx = np.sqrt(dist_mtx.clip(min = 1e-12))\n return dist_mtx\n", "meta": {"hexsha": "7cf5988ff7b60571c122145c1753e3be5446867a", "size": 8066, "ext": "py", "lang": "Python", "max_stars_repo_path": "loss.py", "max_stars_repo_name": "hijune6/Hetero-center-triplet-loss-for-VT-Re-ID", "max_stars_repo_head_hexsha": "5a695325d68e9c701338eda3bd54ad63f5d05f9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2020-11-06T12:56:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T08:19:26.000Z", "max_issues_repo_path": "loss.py", "max_issues_repo_name": "mtjmtj7/Hetero-center-triplet-loss-for-VT-Re-ID", "max_issues_repo_head_hexsha": "5a695325d68e9c701338eda3bd54ad63f5d05f9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-11-23T12:11:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-22T00:17:01.000Z", "max_forks_repo_path": "loss.py", "max_forks_repo_name": "mtjmtj7/Hetero-center-triplet-loss-for-VT-Re-ID", "max_forks_repo_head_hexsha": "5a695325d68e9c701338eda3bd54ad63f5d05f9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-12-14T07:04:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-26T03:10:54.000Z", "avg_line_length": 35.6902654867, "max_line_length": 111, "alphanum_fraction": 0.6214976444, "include": true, "reason": "import numpy", "num_tokens": 2096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.1993079883920791, "lm_q1q2_score": 0.10198920711041193}} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Naive Bayes\n# Welcome to week two of this specialization. You will learn about Naive Bayes. Concretely, you will be using Naive Bayes for sentiment analysis on tweets. Given a tweet, you will decide if it has a positive sentiment or a negative one. Specifically you will: \n# \n# * Train a naive bayes model on a sentiment analysis task\n# * Test using your model\n# * Compute ratios of positive words to negative words\n# * Do some error analysis\n# * Predict on your own tweet\n# \n# You may already be familiar with Naive Bayes and its justification in terms of conditional probabilities and independence.\n# * In this week's lectures and assignments we used the ratio of probabilities between positive and negative sentiments.\n# * This approach gives us simpler formulas for these 2-way classification tasks.\n# \n# Load the cell below to import some packages.\n# You may want to browse the documentation of unfamiliar libraries and functions.\n\n# In[2]:\n\n\nfrom utils import process_tweet, lookup\nimport pdb\nfrom nltk.corpus import stopwords, twitter_samples\nimport numpy as np\nimport pandas as pd\nimport nltk\nimport string\nfrom nltk.tokenize import TweetTokenizer\nfrom os import getcwd\n\n\n# If you are running this notebook in your local computer,\n# don't forget to download the twitter samples and stopwords from nltk.\n# \n# ```\n# nltk.download('stopwords')\n# nltk.download('twitter_samples')\n# ```\n\n# In[3]:\n\n\n# add folder, tmp2, from our local workspace containing pre-downloaded corpora files to nltk's data path\nfilePath = f\"{getcwd()}/../tmp2/\"\nnltk.data.path.append(filePath)\n\n\n# In[4]:\n\n\n# get the sets of positive and negative tweets\nall_positive_tweets = twitter_samples.strings('positive_tweets.json')\nall_negative_tweets = twitter_samples.strings('negative_tweets.json')\n\n# split the data into two pieces, one for training and one for testing (validation set)\ntest_pos = all_positive_tweets[4000:]\ntrain_pos = all_positive_tweets[:4000]\ntest_neg = all_negative_tweets[4000:]\ntrain_neg = all_negative_tweets[:4000]\n\ntrain_x = train_pos + train_neg\ntest_x = test_pos + test_neg\n\n# avoid assumptions about the length of all_positive_tweets\ntrain_y = np.append(np.ones(len(train_pos)), np.zeros(len(train_neg)))\ntest_y = np.append(np.ones(len(test_pos)), np.zeros(len(test_neg)))\n\n\n# # Part 1: Process the Data\n# \n# For any machine learning project, once you've gathered the data, the first step is to process it to make useful inputs to your model.\n# - **Remove noise**: You will first want to remove noise from your data -- that is, remove words that don't tell you much about the content. These include all common words like 'I, you, are, is, etc...' that would not give us enough information on the sentiment.\n# - We'll also remove stock market tickers, retweet symbols, hyperlinks, and hashtags because they can not tell you a lot of information on the sentiment.\n# - You also want to remove all the punctuation from a tweet. The reason for doing this is because we want to treat words with or without the punctuation as the same word, instead of treating \"happy\", \"happy?\", \"happy!\", \"happy,\" and \"happy.\" as different words.\n# - Finally you want to use stemming to only keep track of one variation of each word. In other words, we'll treat \"motivation\", \"motivated\", and \"motivate\" similarly by grouping them within the same stem of \"motiv-\".\n# \n# We have given you the function `process_tweet()` that does this for you.\n\n# In[5]:\n\n\ncustom_tweet = \"RT @Twitter @chapagain Hello There! Have a great day. :) #good #morning http://chapagain.com.np\"\n\n# print cleaned tweet\nprint(process_tweet(custom_tweet))\n\n\n# ## Part 1.1 Implementing your helper functions\n# \n# To help train your naive bayes model, you will need to build a dictionary where the keys are a (word, label) tuple and the values are the corresponding frequency. Note that the labels we'll use here are 1 for positive and 0 for negative.\n# \n# You will also implement a `lookup()` helper function that takes in the `freqs` dictionary, a word, and a label (1 or 0) and returns the number of times that word and label tuple appears in the collection of tweets.\n# \n# For example: given a list of tweets `[\"i am rather excited\", \"you are rather happy\"]` and the label 1, the function will return a dictionary that contains the following key-value pairs:\n# \n# {\n# (\"rather\", 1): 2\n# (\"happi\", 1) : 1\n# (\"excit\", 1) : 1\n# }\n# \n# - Notice how for each word in the given string, the same label 1 is assigned to each word.\n# - Notice how the words \"i\" and \"am\" are not saved, since it was removed by process_tweet because it is a stopword.\n# - Notice how the word \"rather\" appears twice in the list of tweets, and so its count value is 2.\n# \n# #### Instructions\n# Create a function `count_tweets()` that takes a list of tweets as input, cleans all of them, and returns a dictionary.\n# - The key in the dictionary is a tuple containing the stemmed word and its class label, e.g. (\"happi\",1).\n# - The value the number of times this word appears in the given collection of tweets (an integer).\n\n#
\n# \n# Hints\n# \n#

\n#

    \n#
  • Please use the `process_tweet` function that was imported above, and then store the words in their respective dictionaries and sets.
  • \n#
  • You may find it useful to use the `zip` function to match each element in `tweets` with each element in `ys`.
  • \n#
  • Remember to check if the key in the dictionary exists before adding that key to the dictionary, or incrementing its value.
  • \n#
  • Assume that the `result` dictionary that is input will contain clean key-value pairs (you can assume that the values will be integers that can be incremented). It is good practice to check the datatype before incrementing the value, but it's not required here.
  • \n#
\n#

\n\n# In[6]:\n\n\n# UNQ_C1 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\ndef count_tweets(result, tweets, ys):\n '''\n Input:\n result: a dictionary that will be used to map each pair to its frequency\n tweets: a list of tweets\n ys: a list corresponding to the sentiment of each tweet (either 0 or 1)\n Output:\n result: a dictionary mapping each pair to its frequency\n '''\n\n ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###\n for y, tweet in zip(ys, tweets):\n for word in process_tweet(tweet):\n # define the key, which is the word and label tuple\n pair = (word, y)\n\n # if the key exists in the dictionary, increment the count\n if pair in result:\n result[pair] += 1\n\n # else, if the key is new, add it to the dictionary and set the count to 1\n else:\n result[pair] = 1\n ### END CODE HERE ###\n\n return result\n\n\n# In[7]:\n\n\n# Testing your function\n\n\nresult = {}\ntweets = ['i am happy', 'i am tricked', 'i am sad', 'i am tired', 'i am tired']\nys = [1, 0, 0, 0, 0]\ncount_tweets(result, tweets, ys)\n\n\n# **Expected Output**: {('happi', 1): 1, ('trick', 0): 1, ('sad', 0): 1, ('tire', 0): 2}\n\n# # Part 2: Train your model using Naive Bayes\n# \n# Naive bayes is an algorithm that could be used for sentiment analysis. It takes a short time to train and also has a short prediction time.\n# \n# #### So how do you train a Naive Bayes classifier?\n# - The first part of training a naive bayes classifier is to identify the number of classes that you have.\n# - You will create a probability for each class.\n# $P(D_{pos})$ is the probability that the document is positive.\n# $P(D_{neg})$ is the probability that the document is negative.\n# Use the formulas as follows and store the values in a dictionary:\n# \n# $$P(D_{pos}) = \\frac{D_{pos}}{D}\\tag{1}$$\n# \n# $$P(D_{neg}) = \\frac{D_{neg}}{D}\\tag{2}$$\n# \n# Where $D$ is the total number of documents, or tweets in this case, $D_{pos}$ is the total number of positive tweets and $D_{neg}$ is the total number of negative tweets.\n\n# #### Prior and Logprior\n# \n# The prior probability represents the underlying probability in the target population that a tweet is positive versus negative. In other words, if we had no specific information and blindly picked a tweet out of the population set, what is the probability that it will be positive versus that it will be negative? That is the \"prior\".\n# \n# The prior is the ratio of the probabilities $\\frac{P(D_{pos})}{P(D_{neg})}$.\n# We can take the log of the prior to rescale it, and we'll call this the logprior\n# \n# $$\\text{logprior} = log \\left( \\frac{P(D_{pos})}{P(D_{neg})} \\right) = log \\left( \\frac{D_{pos}}{D_{neg}} \\right)$$.\n# \n# Note that $log(\\frac{A}{B})$ is the same as $log(A) - log(B)$. So the logprior can also be calculated as the difference between two logs:\n# \n# $$\\text{logprior} = \\log (P(D_{pos})) - \\log (P(D_{neg})) = \\log (D_{pos}) - \\log (D_{neg})\\tag{3}$$\n\n# #### Positive and Negative Probability of a Word\n# To compute the positive probability and the negative probability for a specific word in the vocabulary, we'll use the following inputs:\n# \n# - $freq_{pos}$ and $freq_{neg}$ are the frequencies of that specific word in the positive or negative class. In other words, the positive frequency of a word is the number of times the word is counted with the label of 1.\n# - $N_{pos}$ and $N_{neg}$ are the total number of positive and negative words for all documents (for all tweets), respectively.\n# - $V$ is the number of unique words in the entire set of documents, for all classes, whether positive or negative.\n# \n# We'll use these to compute the positive and negative probability for a specific word using this formula:\n# \n# $$ P(W_{pos}) = \\frac{freq_{pos} + 1}{N_{pos} + V}\\tag{4} $$\n# $$ P(W_{neg}) = \\frac{freq_{neg} + 1}{N_{neg} + V}\\tag{5} $$\n# \n# Notice that we add the \"+1\" in the numerator for additive smoothing. This [wiki article](https://en.wikipedia.org/wiki/Additive_smoothing) explains more about additive smoothing.\n\n# #### Log likelihood\n# To compute the loglikelihood of that very same word, we can implement the following equations:\n# \n# $$\\text{loglikelihood} = \\log \\left(\\frac{P(W_{pos})}{P(W_{neg})} \\right)\\tag{6}$$\n\n# ##### Create `freqs` dictionary\n# - Given your `count_tweets()` function, you can compute a dictionary called `freqs` that contains all the frequencies.\n# - In this `freqs` dictionary, the key is the tuple (word, label)\n# - The value is the number of times it has appeared.\n# \n# We will use this dictionary in several parts of this assignment.\n\n# In[8]:\n\n\n# Build the freqs dictionary for later uses\n\nfreqs = count_tweets({}, train_x, train_y)\n\n\n# #### Instructions\n# Given a freqs dictionary, `train_x` (a list of tweets) and a `train_y` (a list of labels for each tweet), implement a naive bayes classifier.\n# \n# ##### Calculate $V$\n# - You can then compute the number of unique words that appear in the `freqs` dictionary to get your $V$ (you can use the `set` function).\n# \n# ##### Calculate $freq_{pos}$ and $freq_{neg}$\n# - Using your `freqs` dictionary, you can compute the positive and negative frequency of each word $freq_{pos}$ and $freq_{neg}$.\n# \n# ##### Calculate $N_{pos}$ and $N_{neg}$\n# - Using `freqs` dictionary, you can also compute the total number of positive words and total number of negative words $N_{pos}$ and $N_{neg}$.\n# \n# ##### Calculate $D$, $D_{pos}$, $D_{neg}$\n# - Using the `train_y` input list of labels, calculate the number of documents (tweets) $D$, as well as the number of positive documents (tweets) $D_{pos}$ and number of negative documents (tweets) $D_{neg}$.\n# - Calculate the probability that a document (tweet) is positive $P(D_{pos})$, and the probability that a document (tweet) is negative $P(D_{neg})$\n# \n# ##### Calculate the logprior\n# - the logprior is $log(D_{pos}) - log(D_{neg})$\n# \n# ##### Calculate log likelihood\n# - Finally, you can iterate over each word in the vocabulary, use your `lookup` function to get the positive frequencies, $freq_{pos}$, and the negative frequencies, $freq_{neg}$, for that specific word.\n# - Compute the positive probability of each word $P(W_{pos})$, negative probability of each word $P(W_{neg})$ using equations 4 & 5.\n# \n# $$ P(W_{pos}) = \\frac{freq_{pos} + 1}{N_{pos} + V}\\tag{4} $$\n# $$ P(W_{neg}) = \\frac{freq_{neg} + 1}{N_{neg} + V}\\tag{5} $$\n# \n# **Note:** We'll use a dictionary to store the log likelihoods for each word. The key is the word, the value is the log likelihood of that word).\n# \n# - You can then compute the loglikelihood: $log \\left( \\frac{P(W_{pos})}{P(W_{neg})} \\right)\\tag{6}$.\n\n# In[24]:\n\n\n# UNQ_C2 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\ndef train_naive_bayes(freqs, train_x, train_y):\n '''\n Input:\n freqs: dictionary from (word, label) to how often the word appears\n train_x: a list of tweets\n train_y: a list of labels correponding to the tweets (0,1)\n Output:\n logprior: the log prior. (equation 3 above)\n loglikelihood: the log likelihood of you Naive bayes equation. (equation 6 above)\n '''\n loglikelihood = {}\n logprior = 0\n\n ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###\n\n # calculate V, the number of unique words in the vocabulary\n vocab = set([pair[0] for pair in freqs.keys()])\n V = len(vocab)\n\n # calculate N_pos and N_neg\n N_pos = N_neg = 0\n \n for pair in freqs.keys():\n # if the label is positive (greater than zero)\n if pair[1] > 0:\n\n # Increment the number of positive words by the count for this (word, label) pair\n N_pos += freqs[pair]\n\n # else, the label is negative\n else:\n\n # increment the number of negative words by the count for this (word,label) pair\n N_neg += freqs[pair]\n\n # Calculate D, the number of documents\n D = len(train_y)\n\n # Calculate D_pos, the number of positive documents (*hint: use sum())\n D_pos = (train_y == 1).sum()\n \n # Calculate D_neg, the number of negative documents (*hint: compute using D and D_pos)\n D_neg = (train_y == 0).sum()\n\n # Calculate logprior\n logprior = np.log(D_pos) - np.log(D_neg)\n\n # For each word in the vocabulary...\n for word in vocab:\n # get the positive and negative frequency of the word\n if (word, 1) in freqs:\n freq_pos = freqs[(word, 1)]\n else:\n freq_pos = 0\n \n if (word, 0) in freqs:\n freq_neg = freqs[(word, 0)]\n else:\n freq_neg = 0\n\n # calculate the probability that each word is positive, and negative\n p_w_pos = (freq_pos + 1)/ (V + N_pos)\n p_w_neg = (freq_neg + 1)/ (V + N_neg)\n\n # calculate the log likelihood of the word\n loglikelihood[word] = np.log(p_w_pos) - np.log(p_w_neg)\n\n ### END CODE HERE ###\n\n return logprior, loglikelihood\n\n\n# In[25]:\n\n\n# UNQ_C3 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# You do not have to input any code in this cell, but it is relevant to grading, so please do not change anything\nlogprior, loglikelihood = train_naive_bayes(freqs, train_x, train_y)\nprint(logprior)\nprint(len(loglikelihood))\n\n\n# **Expected Output**:\n# \n# 0.0\n# \n# 9089\n\n# # Part 3: Test your naive bayes\n# \n# Now that we have the `logprior` and `loglikelihood`, we can test the naive bayes function by making predicting on some tweets!\n# \n# #### Implement `naive_bayes_predict`\n# **Instructions**:\n# Implement the `naive_bayes_predict` function to make predictions on tweets.\n# * The function takes in the `tweet`, `logprior`, `loglikelihood`.\n# * It returns the probability that the tweet belongs to the positive or negative class.\n# * For each tweet, sum up loglikelihoods of each word in the tweet.\n# * Also add the logprior to this sum to get the predicted sentiment of that tweet.\n# \n# $$ p = logprior + \\sum_i^N (loglikelihood_i)$$\n# \n# #### Note\n# Note we calculate the prior from the training data, and that the training data is evenly split between positive and negative labels (4000 positive and 4000 negative tweets). This means that the ratio of positive to negative 1, and the logprior is 0.\n# \n# The value of 0.0 means that when we add the logprior to the log likelihood, we're just adding zero to the log likelihood. However, please remember to include the logprior, because whenever the data is not perfectly balanced, the logprior will be a non-zero value.\n\n# In[19]:\n\n\n# UNQ_C4 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\ndef naive_bayes_predict(tweet, logprior, loglikelihood):\n '''\n Input:\n tweet: a string\n logprior: a number\n loglikelihood: a dictionary of words mapping to numbers\n Output:\n p: the sum of all the logliklihoods of each word in the tweet (if found in the dictionary) + logprior (a number)\n\n '''\n ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###\n # process the tweet to get a list of words\n word_l = process_tweet(tweet)\n\n # initialize probability to zero\n p = 0\n\n # add the logprior\n p += logprior\n\n for word in word_l:\n\n # check if the word exists in the loglikelihood dictionary\n if word in loglikelihood:\n # add the log likelihood of that word to the probability\n p += loglikelihood[word]\n\n ### END CODE HERE ###\n\n return p\n\n\n# In[26]:\n\n\n# UNQ_C5 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# You do not have to input any code in this cell, but it is relevant to grading, so please do not change anything\n\n# Experiment with your own tweet.\nmy_tweet = 'She smiled.'\np = naive_bayes_predict(my_tweet, logprior, loglikelihood)\nprint('The expected output is', p)\n\n\n# **Expected Output**:\n# - The expected output is around 1.57\n# - The sentiment is positive.\n\n# #### Implement test_naive_bayes\n# **Instructions**:\n# * Implement `test_naive_bayes` to check the accuracy of your predictions.\n# * The function takes in your `test_x`, `test_y`, log_prior, and loglikelihood\n# * It returns the accuracy of your model.\n# * First, use `naive_bayes_predict` function to make predictions for each tweet in text_x.\n\n# In[27]:\n\n\n# UNQ_C6 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\ndef test_naive_bayes(test_x, test_y, logprior, loglikelihood):\n \"\"\"\n Input:\n test_x: A list of tweets\n test_y: the corresponding labels for the list of tweets\n logprior: the logprior\n loglikelihood: a dictionary with the loglikelihoods for each word\n Output:\n accuracy: (# of tweets classified correctly)/(total # of tweets)\n \"\"\"\n accuracy = 0 # return this properly\n\n ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###\n y_hats = []\n for tweet in test_x:\n # if the prediction is > 0\n if naive_bayes_predict(tweet, logprior, loglikelihood) > 0:\n # the predicted class is 1\n y_hat_i = 1\n else:\n # otherwise the predicted class is 0\n y_hat_i = 0\n\n # append the predicted class to the list y_hats\n y_hats.append(y_hat_i)\n\n # error is the average of the absolute values of the differences between y_hats and test_y\n error = (1/len(test_y))*(test_y != y_hats).sum()\n\n # Accuracy is 1 minus the error\n accuracy = 1- error\n\n ### END CODE HERE ###\n\n return accuracy\n\n\n# In[28]:\n\n\nprint(\"Naive Bayes accuracy = %0.4f\" %\n (test_naive_bayes(test_x, test_y, logprior, loglikelihood)))\n\n\n# **Expected Accuracy**:\n# \n# 0.9940\n\n# In[29]:\n\n\n# UNQ_C7 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# You do not have to input any code in this cell, but it is relevant to grading, so please do not change anything\n\n# Run this cell to test your function\nfor tweet in ['I am happy', 'I am bad', 'this movie should have been great.', 'great', 'great great', 'great great great', 'great great great great']:\n # print( '%s -> %f' % (tweet, naive_bayes_predict(tweet, logprior, loglikelihood)))\n p = naive_bayes_predict(tweet, logprior, loglikelihood)\n# print(f'{tweet} -> {p:.2f} ({p_category})')\n print(f'{tweet} -> {p:.2f}')\n\n\n# **Expected Output**:\n# - I am happy -> 2.15\n# - I am bad -> -1.29\n# - this movie should have been great. -> 2.14\n# - great -> 2.14\n# - great great -> 4.28\n# - great great great -> 6.41\n# - great great great great -> 8.55\n\n# In[30]:\n\n\n# Feel free to check the sentiment of your own tweet below\nmy_tweet = 'you are bad :('\nnaive_bayes_predict(my_tweet, logprior, loglikelihood)\n\n\n# # Part 4: Filter words by Ratio of positive to negative counts\n# \n# - Some words have more positive counts than others, and can be considered \"more positive\". Likewise, some words can be considered more negative than others.\n# - One way for us to define the level of positiveness or negativeness, without calculating the log likelihood, is to compare the positive to negative frequency of the word.\n# - Note that we can also use the log likelihood calculations to compare relative positivity or negativity of words.\n# - We can calculate the ratio of positive to negative frequencies of a word.\n# - Once we're able to calculate these ratios, we can also filter a subset of words that have a minimum ratio of positivity / negativity or higher.\n# - Similarly, we can also filter a subset of words that have a maximum ratio of positivity / negativity or lower (words that are at least as negative, or even more negative than a given threshold).\n# \n# #### Implement `get_ratio()`\n# - Given the `freqs` dictionary of words and a particular word, use `lookup(freqs,word,1)` to get the positive count of the word.\n# - Similarly, use the `lookup()` function to get the negative count of that word.\n# - Calculate the ratio of positive divided by negative counts\n# \n# $$ ratio = \\frac{\\text{pos_words} + 1}{\\text{neg_words} + 1} $$\n# \n# Where pos_words and neg_words correspond to the frequency of the words in their respective classes. \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n#
\n# Words\n# \n# Positive word count\n# \n# Negative Word Count\n#
\n# glad\n# \n# 41\n# \n# 2\n#
\n# arriv\n# \n# 57\n# \n# 4\n#
\n# :(\n# \n# 1\n# \n# 3663\n#
\n# :-(\n# \n# 0\n# \n# 378\n#
\n\n# In[31]:\n\n\n# UNQ_C8 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\ndef get_ratio(freqs, word):\n '''\n Input:\n freqs: dictionary containing the words\n word: string to lookup\n\n Output: a dictionary with keys 'positive', 'negative', and 'ratio'.\n Example: {'positive': 10, 'negative': 20, 'ratio': 0.5}\n '''\n pos_neg_ratio = {'positive': 0, 'negative': 0, 'ratio': 0.0}\n ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###\n # use lookup() to find positive counts for the word (denoted by the integer 1)\n pos_neg_ratio['positive'] = lookup(freqs, word, 1)\n\n # use lookup() to find negative counts for the word (denoted by integer 0)\n pos_neg_ratio['negative'] = lookup(freqs, word, 0)\n\n # calculate the ratio of positive to negative counts for the word\n pos_neg_ratio['ratio'] = (pos_neg_ratio['positive'] + 1)/( pos_neg_ratio['negative'] + 1)\n ### END CODE HERE ###\n return pos_neg_ratio\n\n\n# In[32]:\n\n\nget_ratio(freqs, 'happi')\n\n\n# #### Implement `get_words_by_threshold(freqs,label,threshold)`\n# \n# * If we set the label to 1, then we'll look for all words whose threshold of positive/negative is at least as high as that threshold, or higher.\n# * If we set the label to 0, then we'll look for all words whose threshold of positive/negative is at most as low as the given threshold, or lower.\n# * Use the `get_ratio()` function to get a dictionary containing the positive count, negative count, and the ratio of positive to negative counts.\n# * Append a dictionary to a list, where the key is the word, and the dictionary is the dictionary `pos_neg_ratio` that is returned by the `get_ratio()` function.\n# An example key-value pair would have this structure:\n# ```\n# {'happi':\n# {'positive': 10, 'negative': 20, 'ratio': 0.5}\n# }\n# ```\n\n# In[35]:\n\n\n# UNQ_C9 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\ndef get_words_by_threshold(freqs, label, threshold):\n '''\n Input:\n freqs: dictionary of words\n label: 1 for positive, 0 for negative\n threshold: ratio that will be used as the cutoff for including a word in the returned dictionary\n Output:\n word_set: dictionary containing the word and information on its positive count, negative count, and ratio of positive to negative counts.\n example of a key value pair:\n {'happi':\n {'positive': 10, 'negative': 20, 'ratio': 0.5}\n }\n '''\n word_list = {}\n\n ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###\n for key in freqs.keys():\n word, _ = key\n\n # get the positive/negative ratio for a word\n pos_neg_ratio = get_ratio(freqs, word)['ratio']\n\n # if the label is 1 and the ratio is greater than or equal to the threshold...\n if label == 1 and pos_neg_ratio >= threshold:\n\n # Add the pos_neg_ratio to the dictionary\n word_list[word] = pos_neg_ratio\n\n # If the label is 0 and the pos_neg_ratio is less than or equal to the threshold...\n elif label == 0 and pos_neg_ratio <= threshold:\n\n # Add the pos_neg_ratio to the dictionary\n word_list[word] = pos_neg_ratio\n\n # otherwise, do not include this word in the list (do nothing)\n\n ### END CODE HERE ###\n return word_list\n\n\n# In[36]:\n\n\n# Test your function: find negative words at or below a threshold\nget_words_by_threshold(freqs, label=0, threshold=0.05)\n\n\n# In[37]:\n\n\n# Test your function; find positive words at or above a threshold\nget_words_by_threshold(freqs, label=1, threshold=10)\n\n\n# Notice the difference between the positive and negative ratios. Emojis like :( and words like 'me' tend to have a negative connotation. Other words like 'glad', 'community', and 'arrives' tend to be found in the positive tweets.\n\n# # Part 5: Error Analysis\n# \n# In this part you will see some tweets that your model missclassified. Why do you think the misclassifications happened? Were there any assumptions made by the naive bayes model?\n\n# In[38]:\n\n\n# Some error analysis done for you\nprint('Truth Predicted Tweet')\nfor x, y in zip(test_x, test_y):\n y_hat = naive_bayes_predict(x, logprior, loglikelihood)\n if y != (np.sign(y_hat) > 0):\n print('%d\\t%0.2f\\t%s' % (y, np.sign(y_hat) > 0, ' '.join(\n process_tweet(x)).encode('ascii', 'ignore')))\n\n\n# # Part 6: Predict with your own tweet\n# \n# In this part you can predict the sentiment of your own tweet.\n\n# In[39]:\n\n\n# Test with your own tweet - feel free to modify `my_tweet`\nmy_tweet = 'I am happy because I am learning :)'\n\np = naive_bayes_predict(my_tweet, logprior, loglikelihood)\nprint(p)\n\n\n# Congratulations on completing this assignment. See you next week!\n", "meta": {"hexsha": "4f7d285fa17434b0a22b28431fc16e10e7e07616", "size": 27416, "ext": "py", "lang": "Python", "max_stars_repo_path": "Naive_Bayes_Sentiment_Analysis.py", "max_stars_repo_name": "escha2019/AI", "max_stars_repo_head_hexsha": "c7e918f7f076e15ba3a41c037476f1f1bc925046", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Naive_Bayes_Sentiment_Analysis.py", "max_issues_repo_name": "escha2019/AI", "max_issues_repo_head_hexsha": "c7e918f7f076e15ba3a41c037476f1f1bc925046", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Naive_Bayes_Sentiment_Analysis.py", "max_forks_repo_name": "escha2019/AI", "max_forks_repo_head_hexsha": "c7e918f7f076e15ba3a41c037476f1f1bc925046", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5047879617, "max_line_length": 336, "alphanum_fraction": 0.6725634666, "include": true, "reason": "import numpy", "num_tokens": 7220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.2043418950913969, "lm_q1q2_score": 0.10137275325723598}} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Classical Mechanics, Mathematics and Numerical background\n# \n# ## Introduction\n# \n# Classical mechanics is a topic which has been taught intensively over\n# several centuries. It is, with its many variants and ways of\n# presenting the educational material, normally the first **real** physics\n# course many of us meet and it lays the foundation for further physics\n# studies. Many of the equations and ways of reasoning about the\n# underlying laws of motion and pertinent forces, shape our approaches and understanding\n# of the scientific method and discourse, as well as the way we develop our insights\n# and deeper understanding about physical systems. \n# \n# \n# There is a wealth of\n# well-tested (from both a physics point of view and a pedagogical\n# standpoint) exercises and problems which can be solved\n# analytically. However, many of these problems represent idealized and\n# less realistic situations. The large majority of these problems are\n# solved by paper and pencil and are traditionally aimed\n# at what we normally refer to as continuous models from which we may find an analytical solution. As a consequence,\n# when teaching mechanics, it implies that we can seldomly venture beyond an idealized case\n# in order to develop our understandings and insights about the\n# underlying forces and laws of motion.\n# \n# We aim at changing this here by introducing throughout the course what\n# we will call a **computational path**, where with computations we mean\n# solving scientific problems with all possible tools and means, from\n# plain paper an pencil exercises, via symbolic calculations to writing\n# a code and running a program to solve a specific\n# problem. Mathematically this normally means that we move from a\n# continuous problem to a discretized one. This appproach enables us to\n# solve a much broader class of problems.\n# In mechanics this means, since we often rephrase the physical problems in terms of differential equations, that we can in most settings reuse the same program with some minimal changes. \n# \n# \n# ## Reminder on vectors and other mathematical quantities\n# \n# Our studies will start with the motion of different types of objects\n# such as a falling ball, a runner, a bicycle etc etc. It means that an\n# object's position in space varies with time.\n# In order to study such systems we need to define\n# \n# * choice of origin\n# \n# * choice of the direction of the axes\n# \n# * choice of positive direction (left-handed or right-handed system of reference)\n# \n# * choice of units and dimensions\n# \n# These choices lead to some important questions such as\n# \n# * is the physics of a system independent of the origin of the axes?\n# \n# * is the physics independent of the directions of the axes, that is are there privileged axes?\n# \n# * is the physics independent of the orientation of system?\n# \n# * is the physics independent of the scale of the length?\n# \n# Throughout this course we will use the standardized SI units. The standard unit for length is thus one meter 1m, for mass\n# one kilogram 1kg, for time one second 1s, for force one Newton 1kgm/s$^2$ and for energy 1 Joule 1kgm$^2$s$^{-2}$.\n# \n# We will use the following notations for various variables (vectors are always boldfaced in these lecture notes):\n# * position $\\boldsymbol{r}$, in one dimention we will normally just use $x$,\n# \n# * mass $m$,\n# \n# * time $t$,\n# \n# * velocity $\\boldsymbol{v}$ or just $v$ in one dimension,\n# \n# * acceleration $\\boldsymbol{a}$ or just $a$ in one dimension,\n# \n# * momentum $\\boldsymbol{p}$ or just $p$ in one dimension,\n# \n# * kinetic energy $K$,\n# \n# * potential energy $V$ and\n# \n# * frequency $\\omega$.\n# \n# More variables will be defined as we need them.\n# \n# \n# It is also important to keep track of dimensionalities. Don't mix this\n# up with a chosen unit for a given variable. We mark the dimensionality\n# in these lectures as $[a]$, where $a$ is the quantity we are\n# interested in. Thus\n# \n# * $[\\boldsymbol{r}]=$ length\n# \n# * $[m]=$ mass\n# \n# * $[K]=$ energy\n# \n# * $[t]=$ time\n# \n# * $[\\boldsymbol{v}]=$ length over time\n# \n# * $[\\boldsymbol{a}]=$ length over time squared\n# \n# * $[\\boldsymbol{p}]=$ mass times length over time\n# \n# * $[\\omega]=$ 1/time\n# \n# ## Scalars, Vectors and Matrices\n# \n# A scalar is something with a value that is independent of coordinate\n# system. Examples are mass, or the relative time between events. A\n# vector has magnitude and direction. Under rotation, the magnitude\n# stays the same but the direction changes. Scalars have no spatial\n# index, whereas a three-dimensional vector has 3 indices, e.g. the\n# position $\\boldsymbol{r}$ has components $r_1,r_2,r_3$, which are often\n# referred to as $x,y,z$.\n# \n# There are several categories of changes of coordinate system. The\n# observer can translate the origin, might move with a different\n# velocity, or might rotate her/his coordinate axes. For instance, a\n# particle's position vector changes when the origin is translated, but\n# its velocity does not. When you study relativity you will find that\n# quantities you thought of as scalars, such as time or an electric\n# potential, are actually parts of four-dimensional vectors and that\n# changes of the velocity of the reference frame act in a similar way to\n# rotations.\n# \n# In addition to vectors and scalars, there are matrices, which have two\n# indices. One also has objects with 3 or four indices. These are called\n# tensors of rank $n$, where $n$ is the number of indices. A matrix is a\n# rank-two tensor. The Levi-Civita symbol, $\\epsilon_{ijk}$ used for\n# cross products of vectors, is a tensor of rank three.\n# \n# \n# \n# \n# In these lectures we will use boldfaced lower-case letters to label a\n# vector. A vector $\\boldsymbol{a}$ in three dimensions is thus defined as\n\n# $$\n# \\boldsymbol{a} =(a_x,a_y, a_z),\n# $$\n\n# and using the unit vectors (see below) in a cartesian system we have\n\n# $$\n# \\boldsymbol{a} = a_x\\boldsymbol{e}_1+a_y\\boldsymbol{e}_2+a_z\\boldsymbol{e}_3,\n# $$\n\n# where the unit vectors have magnitude $\\vert\\boldsymbol{e}_i\\vert = 1$ with\n# $i=1=x$, $i=2=y$ and $i=3=z$. Some authors use letters\n# $\\boldsymbol{i}=\\boldsymbol{e}_1$, $\\boldsymbol{j}=\\boldsymbol{e}_2$ and $\\boldsymbol{k}=\\boldsymbol{e}_3$.\n# \n# \n# \n# Alternatively, you may also encounter the above vector as\n\n# $$\n# \\boldsymbol{a} = a_1\\boldsymbol{e}_1+a_2\\boldsymbol{e}_2+a_3\\boldsymbol{e}_3.\n# $$\n\n# Here we have used that $a_1=a_x$, $a_2=a_y$ and $a_3=a_z$. Such a\n# notation is sometimes more convenient if we wish to represent vector\n# operations in a mathematically more compact way, see below here. We may also find this useful if we want the different\n# components to represent other coordinate systems that the Cartesian one. A typical example would be going from a Cartesian representation to a spherical basis. We will encounter such cases many times in this course. \n# \n# We use lower-case letters for vectors and upper-case letters for matrices. Vectors and matrices are always boldfaced.\n# \n# \n# \n# ### Polar Coordinates\n# \n# As an example, consider a two-dimensional Cartesian system with a vector $\\boldsymbol{r}=(x,y)$.\n# Our vector is then written as\n\n# $$\n# \\boldsymbol{r} = x\\boldsymbol{e}_1+y\\boldsymbol{e}_2.\n# $$\n\n# Transforming to polar coordinates with the radius $\\rho\\in [0,\\infty)$\n# and the angle $\\phi \\in [0,2\\pi]$ we have the familiar transformations\n\n# $$\n# x = \\rho \\cos{\\phi} \\hspace{0.5cm} y = \\rho \\sin{\\phi},\n# $$\n\n# and the inverse relations\n\n# $$\n# \\rho =\\sqrt{x^2+y^2} \\hspace{0.5cm} \\phi = \\mathrm{arctan}(\\frac{y}{x}).\n# $$\n\n# We can rewrite the vector $\\boldsymbol{a}$ in terms of $\\rho$ and $\\phi$ as\n\n# $$\n# \\boldsymbol{a} = \\rho \\cos{\\phi}\\boldsymbol{e}_1+\\rho \\sin{\\phi}\\boldsymbol{e}_2,\n# $$\n\n# and we define the new unit vectors as $\\boldsymbol{e}'_1=\\cos{\\phi}\\boldsymbol{e}_1$ and $\\boldsymbol{e}'_2=\\sin{\\phi}\\boldsymbol{e}_2$, we have\n\n# $$\n# \\boldsymbol{a}' = \\rho\\boldsymbol{e}'_1+\\rho \\boldsymbol{e}'_2.\n# $$\n\n# Below we will show that the norms of this vector in a Cartesian basis and a Polar basis are equal.\n# \n# \n# ### Unit Vectors\n# \n# Also known as basis vectors, unit vectors point in the direction of\n# the coordinate axes, have unit norm, and are orthogonal to one\n# another. Sometimes this is referred to as an orthonormal basis,\n\n# \n#
\n# \n# $$\n# \\begin{equation}\n# \\boldsymbol{e}_i\\cdot\\boldsymbol{e}_j=\\delta_{ij}=\\begin{bmatrix}\n# 1 & 0 & 0\\\\\n# 0& 1 & 0\\\\\n# 0 & 0 & 1\n# \\end{bmatrix}.\n# \\label{_auto1} \\tag{1}\n# \\end{equation}\n# $$\n\n# Here, $\\delta_{ij}$ is unity when $i=j$ and is zero otherwise. This is\n# called the unit matrix, because you can multiply it with any other\n# matrix and not change the matrix. The **dot** denotes the dot product,\n# $\\boldsymbol{a}\\cdot\\boldsymbol{b}=a_1b_1+a_2b_2+a_3b_3=|a||b|\\cos\\theta_{ab}$. Sometimes\n# the unit vectors are called $\\hat{x}$, $\\hat{y}$ and\n# $\\hat{z}$.\n# \n# \n# \n# Vectors can be decomposed in terms of unit vectors,\n\n# \n#
\n# \n# $$\n# \\begin{equation}\n# \\boldsymbol{r}=r_1\\hat{e}_1+r_2\\hat{e}_2+r_3\\hat{e}_3.\n# \\label{_auto2} \\tag{2}\n# \\end{equation}\n# $$\n\n# The vector components $r_1$, $r_2$ and $r_3$ might be\n# called $x$, $y$ and $z$ for a displacement. Another way to write this is to define the vector $\\boldsymbol{r}=(x,y,z)$.\n# \n# Similarly, for the velocity we will use in this course the components $\\boldsymbol{v}=(v_x, v_y,v_z$. The accelaration is then given by $\\boldsymbol{a}=(a_x,a_y,a_z)$.\n# \n# \n# \n# As mentioned above, repeated indices infer sums.\n# This means that when you encounter an expression like the one on the left-hand side here, it stands actually for a sum (right-hand side)\n\n# $$\n# x_iy_i=\\sum_i x_iy_i=\\boldsymbol{x}\\cdot\\boldsymbol{y}.\n# $$\n\n# We will in our lectures seldom use this notation and rather spell out the summations. This inferred summation over indices is normally called [Einstein summation convention](https://en.wikipedia.org/wiki/Einstein_notation).\n# \n# \n# ## Vector Operations, Scalar Product (or dot product)\n# \n# For two vectors $\\boldsymbol{a}$ and $\\boldsymbol{b}$ we have\n\n# $$\n# \\begin{eqnarray*}\n# \\boldsymbol{a}\\cdot\\boldsymbol{b}&=&\\sum_ia_ib_i=|a||b|\\cos\\theta_{ab},\\\\\n# |a|&\\equiv& \\sqrt{\\boldsymbol{a}\\cdot\\boldsymbol{a}},\n# \\end{eqnarray*}\n# $$\n\n# or with a norm-2 notation\n\n# $$\n# |a|\\equiv \\vert\\vert \\boldsymbol{a}\\vert\\vert_2=\\sqrt{\\sum_i a_i^2}.\n# $$\n\n# Not of all of you are familiar with linear algebra. Numerically we will always deal with arrays and the dot product vector is given by the product of the transposed vector multiplied with the other vector, that is we have\n\n# $$\n# \\boldsymbol{a}^T\\boldsymbol{b}=\\sum_i a_ib_i=|a||b|\\cos\\theta_{ab}.\n# $$\n\n# The superscript $T$ represents the transposition operations. \n# \n# \n# \n# ## Digression, Linear Algebra Notation for Vectors\n# \n# As an example, consider a three-dimensional velocity defined by a vector $\\boldsymbol{v}=(v_x,v_y,v_z)$. For those of you familiar with linear algebra, we would write this quantity as\n\n# $$\n# \\boldsymbol{v}=\\begin{bmatrix} v_x\\\\ v_y \\\\ v_z \\end{bmatrix},\n# $$\n\n# and the transpose as\n\n# $$\n# \\boldsymbol{v}^T=\\begin{bmatrix} v_x & v_y &v_z \\end{bmatrix}.\n# $$\n\n# The norm is\n\n# $$\n# \\boldsymbol{v}^T\\boldsymbol{v}=v_x^2+v_y^2+v_z^2,\n# $$\n\n# as it should.\n# \n# Since we will use Python as a programming language throughout this course, the above vector, using the package **numpy** (see discussions below), can be written as\n\n# In[1]:\n\n\nimport numpy as np\n# Define the values of vx, vy and vz\nvx = 0.0\nvy = 1.0\nvz = 0.0\nv = np.array([vx, vy, vz])\nprint(v)\n# The print the transpose of v\nprint(v.T)\n\n\n# Try to figure out how to calculate the norm with **numpy**.\n# We will come back to **numpy** in the examples below.\n# \n# \n# \n# \n# As an example, consider our transformation of a two-dimensional Cartesian vector $\\boldsymbol{r}$ to polar coordinates.\n# We had\n\n# $$\n# \\boldsymbol{r} = x\\boldsymbol{e}_1+y\\boldsymbol{e}_2.\n# $$\n\n# Transforming to polar coordinates with the radius $\\rho\\in [0,\\infty)$\n# and the angle $\\phi \\in [0,2\\pi]$ we have\n\n# $$\n# x = \\rho \\cos{\\phi} \\hspace{0.5cm} y = \\rho \\sin{\\phi}.\n# $$\n\n# We can write this\n\n# $$\n# \\boldsymbol{r} = \\begin{bmatrix} x \\\\ y \\end{bmatrix}= \\begin{bmatrix} \\rho \\cos{\\phi} \\\\ \\rho \\sin{\\phi} \\end{bmatrix}.\n# $$\n\n# The norm in Cartesian coordinates is $\\boldsymbol{r}\\cdot\\boldsymbol{r}=x^2+y^2$ and\n# using Polar coordinates we have\n# $\\rho^2(\\cos{\\phi})^2+\\rho^2(\\cos{\\phi})^2=\\rho^2$, which shows that\n# the norm is conserved since we have $\\rho = \\sqrt{x^2+y^2}$. A\n# transformation to a new basis should not change the norm.\n# \n# \n# \n# ## Vector Product (or cross product) of vectors $\\boldsymbol{a}$ and $\\boldsymbol{b}$\n\n# $$\n# \\begin{eqnarray*}\n# \\boldsymbol{c}&=&\\boldsymbol{a}\\times\\boldsymbol{b},\\\\\n# c_i&=&\\epsilon_{ijk}a_jb_k.\n# \\end{eqnarray*}\n# $$\n\n# Here $\\epsilon$ is the third-rank anti-symmetric tensor, also known as\n# the Levi-Civita symbol. It is $\\pm 1$ only if all three indices are\n# different, and is zero otherwise. The choice of $\\pm 1$ depends on\n# whether the indices are an even or odd permutation of the original\n# symbols. The permutation $xyz$ or $123$ is considered to be $+1$. Its elements are\n\n# $$\n# \\begin{eqnarray}\n# \\epsilon_{ijk}&=&-\\epsilon_{ikj}=-\\epsilon_{jik}=-\\epsilon_{kji}\\\\\n# \\nonumber\n# \\epsilon_{123}&=&\\epsilon_{231}=\\epsilon_{312}=1,\\\\\n# \\nonumber\n# \\epsilon_{213}&=&\\epsilon_{132}=\\epsilon_{321}=-1,\\\\\n# \\nonumber\n# \\epsilon_{iij}&=&\\epsilon_{iji}=\\epsilon_{jii}=0.\n# \\end{eqnarray}\n# $$\n\n# You may have met cross-products when studying magnetic\n# fields. Because the matrix is anti-symmetric, switching the $x$ and\n# $y$ axes (or any two axes) flips the sign. If the coordinate system is\n# right-handed, meaning the $xyz$ axes satisfy\n# $\\hat{x}\\times\\hat{y}=\\hat{z}$, where you can point along the $x$ axis\n# with your extended right index finger, the $y$ axis with your\n# contracted middle finger and the $z$ axis with your extended\n# thumb. Switching to a left-handed system flips the sign of the vector\n# $\\boldsymbol{c}=\\boldsymbol{a}\\times\\boldsymbol{b}$.\n# \n# Note that\n# $\\boldsymbol{a}\\times\\boldsymbol{b}=-\\boldsymbol{b}\\times\\boldsymbol{a}$. The vector $\\boldsymbol{c}$ is\n# perpendicular to both $\\boldsymbol{a}$ and $\\boldsymbol{b}$ and the magnitude of\n# $\\boldsymbol{c}$ is given by\n\n# $$\n# |c|=|a||b|\\sin{\\theta_{ab}}.\n# $$\n\n# ### Pseudo-vectors\n# \n# Vectors obtained by the cross product of two real vectors are called\n# pseudo-vectors because the assignment of their direction can be\n# arbitrarily flipped by defining the Levi-Civita symbol to be based on\n# left-handed rules. Examples are the magnetic field and angular\n# momentum. If the direction of a real vector prefers the right-handed\n# over the left-handed direction, that constitutes a violation of\n# parity. For instance, one can polarize the spins (angular momentum) of\n# nuclei with a magnetic field so that the spins preferentially point\n# along the direction of the magnetic field. This does not violate\n# parity because both are pseudo-vectors. Now assume these polarized\n# nuclei decay and that electrons are one of the products. If these\n# electrons prefer to exit the decay parallel vs. antiparallel to the\n# polarizing magnetic field, this constitutes parity violation because\n# the direction of the outgoing electron momenta are a real vector. This\n# is precisely what is observed in weak decays.\n# \n# \n# ## Differentiation of a vector with respect to a scalar\n# \n# As an example, consider the\n# acceleration $\\boldsymbol{a}$, which is given by the change in velocity per unit time, $\\boldsymbol{a}=d\\boldsymbol{v}/dt$\n# with components\n\n# $$\n# a_i = (d\\boldsymbol{v}/dt)_i=\\frac{dv_i}{dt}.\n# $$\n\n# Here $i=x,y,z$ or $i=1,2,3$ if we are in three dimensions.\n# \n# \n# ### Gradient operator $\\nabla$\n# \n# This represents the derivatives $\\partial/\\partial\n# x$, $\\partial/\\partial y$ and $\\partial/\\partial z$. An often used shorthand is $\\partial_x=\\partial/\\partial_x$.\n# \n# The gradient of a scalar function of position and time\n# $\\Phi(x,y,z)=\\Phi(\\boldsymbol{r},t)$ is given by\n\n# $$\n# \\boldsymbol{\\nabla}~\\Phi,\n# $$\n\n# with components $i$\n\n# $$\n# (\\nabla\\Phi(x,y,z,t))_i=\\partial/\\partial r_i\\Phi(\\boldsymbol{r},t)=\\partial_i\\Phi(\\boldsymbol{r},t).\n# $$\n\n# Note that the gradient is a vector.\n# \n# Taking the dot product of the gradient with a vector, normally called the divergence,\n# we have\n\n# $$\n# \\mathrm{div} \\boldsymbol{a}, \\nabla\\cdot\\boldsymbol{a}=\\sum_i \\partial_i a_i.\n# $$\n\n# Note that the divergence is a scalar. \n# \n# \n# ### The curl\n# \n# The **curl** of a vector is defined as\n# $\\nabla\\times\\boldsymbol{a}$,\n\n# $$\n# {\\rm\\bf curl}~\\boldsymbol{a},\n# $$\n\n# with components\n\n# $$\n# (\\boldsymbol{\\nabla}\\times\\boldsymbol{a})_i=\\epsilon_{ijk}\\partial_j a_k(\\boldsymbol{r},t).\n# $$\n\n# ### The Laplacian\n# \n# The Laplacian is referred to as $\\nabla^2$ and is defined as\n\n# $$\n# \\boldsymbol{\\nabla}^2=\\boldsymbol{\\nabla}\\cdot\\boldsymbol{\\nabla}=\\frac{\\partial^2}{\\partial x^2}+\\frac{\\partial^2}{\\partial y^2}+\\frac{\\partial^2}{\\partial z^2}.\n# $$\n\n# Question: is the Laplacian a scalar or a vector?\n# \n# ### Some identities\n# \n# Here we simply state these, but you may wish to prove a few. They are useful for this class and will be essential when you study electromagnetism.\n\n# $$\n# \\begin{eqnarray}\n# \\boldsymbol{a}\\cdot(\\boldsymbol{b}\\times\\boldsymbol{c})&=&\\boldsymbol{b}\\cdot(\\boldsymbol{c}\\times\\boldsymbol{a})=\\boldsymbol{c}\\cdot(\\boldsymbol{a}\\times\\boldsymbol{b})\\\\\n# \\nonumber\n# \\boldsymbol{a}\\times(\\boldsymbol{b}\\times\\boldsymbol{c})&=&(\\boldsymbol{a}\\cdot\\boldsymbol{c})\\boldsymbol{b}-(\\boldsymbol{a}\\cdot\\boldsymbol{b})\\boldsymbol{c}\\\\\n# \\nonumber\n# (\\boldsymbol{a}\\times\\boldsymbol{b})\\cdot(\\boldsymbol{c}\\times\\boldsymbol{d})&=&(\\boldsymbol{a}\\cdot\\boldsymbol{c})(\\boldsymbol{b}\\cdot\\boldsymbol{d})\n# -(\\boldsymbol{a}\\cdot\\boldsymbol{d})(\\boldsymbol{b}\\cdot\\boldsymbol{c})\n# \\end{eqnarray}\n# $$\n\n# ### More useful relations\n# \n# Using the fact that multiplication of reals is distributive we can show that\n\n# $$\n# \\boldsymbol{a}(\\boldsymbol{b}+\\boldsymbol{c})=\\boldsymbol{a}\\boldsymbol{b}+\\boldsymbol{a}\\boldsymbol{c},\n# $$\n\n# Similarly we can also show that (using product rule for differentiating reals)\n\n# $$\n# \\frac{d}{dt}(\\boldsymbol{a}\\boldsymbol{b})=\\boldsymbol{a}\\frac{d\\boldsymbol{b}}{dt}+\\boldsymbol{b}\\frac{d\\boldsymbol{a}}{dt}.\n# $$\n\n# We can repeat these operations for the cross products and show that they are distribuitive\n\n# $$\n# \\boldsymbol{a}\\times(\\boldsymbol{b}+\\boldsymbol{c})=\\boldsymbol{a}\\times\\boldsymbol{b}+\\boldsymbol{a}\\times\\boldsymbol{c}.\n# $$\n\n# We have also that\n\n# $$\n# \\frac{d}{dt}(\\boldsymbol{a}\\times\\boldsymbol{b})=\\boldsymbol{a}\\times\\frac{d\\boldsymbol{b}}{dt}+\\boldsymbol{b}\\times\\frac{d\\boldsymbol{a}}{dt}.\n# $$\n\n# ### Gauss's Theorem\n# \n# For an integral over a volume $V$ confined by a surface $S$, Gauss's theorem gives\n\n# $$\n# \\int_V dv~\\nabla\\cdot\\boldsymbol{A}=\\int_Sd\\boldsymbol{S}\\cdot\\boldsymbol{A}.\n# $$\n\n# For a closed path $C$ which carves out some area $S$,\n\n# $$\n# \\int_C d\\boldsymbol{\\ell}\\cdot\\boldsymbol{A}=\\int_Sd\\boldsymbol{s} \\cdot(\\nabla\\times\\boldsymbol{A})\n# $$\n\n# ### and Stokes's Theorem\n# \n# Stoke's law can be understood by considering a small rectangle,\n# $-\\Delta x\n# \n# Relations Name matrix elements \n# \n# \n# $A = A^{T}$ symmetric $a_{ij} = a_{ji}$ \n# $A = \\left (A^{T} \\right )^{-1}$ real orthogonal $\\sum_k a_{ik} a_{jk} = \\sum_k a_{ki} a_{kj} = \\delta_{ij}$ \n# $A = A^{ * }$ real matrix $a_{ij} = a_{ij}^{ * }$ \n# $A = A^{\\dagger}$ hermitian $a_{ij} = a_{ji}^{ * }$ \n# $A = \\left (A^{\\dagger} \\right )^{-1}$ unitary $\\sum_k a_{ik} a_{jk}^{ * } = \\sum_k a_{ki}^{ * } a_{kj} = \\delta_{ij}$ \n# \n# \n# \n# \n# ### Some famous Matrices\n# \n# * Diagonal if $a_{ij}=0$ for $i\\ne j$\n# \n# * Upper triangular if $a_{ij}=0$ for $i > j$\n# \n# * Lower triangular if $a_{ij}=0$ for $i < j$\n# \n# * Upper Hessenberg if $a_{ij}=0$ for $i > j+1$\n# \n# * Lower Hessenberg if $a_{ij}=0$ for $i < j+1$\n# \n# * Tridiagonal if $a_{ij}=0$ for $|i -j| > 1$\n# \n# * Lower banded with bandwidth $p$: $a_{ij}=0$ for $i > j+p$\n# \n# * Upper banded with bandwidth $p$: $a_{ij}=0$ for $i < j+p$\n# \n# * Banded, block upper triangular, block lower triangular....\n# \n# For an $N\\times N$ matrix $\\mathbf{A}$ the following properties are all equivalent\n# \n# * If the inverse of $\\mathbf{A}$ exists, $\\mathbf{A}$ is nonsingular.\n# \n# * The equation $\\mathbf{Ax}=0$ implies $\\mathbf{x}=0$.\n# \n# * The rows of $\\mathbf{A}$ form a basis of $R^N$.\n# \n# * The columns of $\\mathbf{A}$ form a basis of $R^N$.\n# \n# * $\\mathbf{A}$ is a product of elementary matrices.\n# \n# * $0$ is not eigenvalue of $\\mathbf{A}$.\n# \n# ## Rotations\n# \n# \n# Here, we use rotations as an example of matrices and their operations. One can consider a different orthonormal basis $\\hat{e}'_1$, $\\hat{e}'_2$ and $\\hat{e}'_3$. The same vector $\\boldsymbol{r}$ mentioned above can also be expressed in the new basis,\n\n# \n#
\n# \n# $$\n# \\begin{equation}\n# \\boldsymbol{r}=r'_1\\hat{e}'_1+r'_2\\hat{e}'_2+r'_3\\hat{e}'_3.\n# \\label{_auto3} \\tag{3}\n# \\end{equation}\n# $$\n\n# Even though it is the same vector, the components have changed. Each\n# new unit vector $\\hat{e}'_i$ can be expressed as a linear sum of the\n# previous vectors,\n\n# \n#
\n# \n# $$\n# \\begin{equation}\n# \\hat{e}'_i=\\sum_j U_{ij}\\hat{e}_j,\n# \\label{_auto4} \\tag{4}\n# \\end{equation}\n# $$\n\n# and the matrix $U$ can be found by taking the dot product of both sides with $\\hat{e}_k$,\n\n# \n#
\n# \n# $$\n# \\begin{eqnarray}\n# \\nonumber\n# \\hat{e}_k\\cdot\\hat{e}'_i&=&\\sum_jU_{ij}\\hat{e}_k\\cdot\\hat{e}_j\\\\\n# \\label{eq:lambda_angles} \\tag{5}\n# \\hat{e}_k\\cdot\\hat{e}'_i&=&\\sum_jU_{ij}\\delta_{jk}=U_{ik}.\n# \\end{eqnarray}\n# $$\n\n# Thus, the matrix lambda has components $U_{ij}$ that are equal to the\n# cosine of the angle between new unit vector $\\hat{e}'_i$ and the old\n# unit vector $\\hat{e}_j$.\n\n# \n#
\n# \n# $$\n# \\begin{equation}\n# U = \\begin{bmatrix}\n# \\hat{e}'_1\\cdot\\hat{e}_1& \\hat{e}'_1\\cdot\\hat{e}_2& \\hat{e}'_1\\cdot\\hat{e}_3\\\\\n# \\hat{e}'_2\\cdot\\hat{e}_1& \\hat{e}'_2\\cdot\\hat{e}_2& \\hat{e}'_2\\cdot\\hat{e}_3\\\\\n# \\hat{e}'_3\\cdot\\hat{e}_1& \\hat{e}'_3\\cdot\\hat{e}_2& \\hat{e}'_3\\cdot\\hat{e}_3\n# \\end{bmatrix},~~~~~U_{ij}=\\hat{e}'_i\\cdot\\hat{e}_j=\\cos\\theta_{ij}.\n# \\label{_auto5} \\tag{6}\n# \\end{equation}\n# $$\n\n# Note that the matrix is not symmetric, $U_{ij}\\ne U_{ji}$. One can also look at the inverse transformation, by switching the primed and unprimed coordinates,\n\n# \n#
\n# \n# $$\n# \\begin{eqnarray}\n# \\label{eq:inverseU} \\tag{7}\n# \\hat{e}_i&=&\\sum_jU^{-1}_{ij}\\hat{e}'_j,\\\\\n# \\nonumber\n# U^{-1}_{ij}&=&\\hat{e}_i\\cdot\\hat{e}'_j=U_{ji}.\n# \\end{eqnarray}\n# $$\n\n# The definition of transpose of a matrix, $M^{t}_{ij}=M_{ji}$, allows one to state this as\n\n# \n#
\n# \n# $$\n# \\begin{eqnarray}\n# \\label{eq:transposedef} \\tag{8}\n# U^{-1}&=&U^{t}.\n# \\end{eqnarray}\n# $$\n\n# ### Tensors\n# \n# A tensor obeying Eq. ([8](#eq:transposedef)) defines what is known as\n# a unitary, or orthogonal, transformation.\n# \n# The matrix $U$ can be used to transform any vector to the new basis. Consider a vector\n\n# $$\n# \\begin{eqnarray}\n# \\boldsymbol{r}&=&r_1\\hat{e}_1+r_2\\hat{e}_2+r_3\\hat{e}_3\\\\\n# \\nonumber\n# &=&r'_1\\hat{e}'_1+r'_2\\hat{e}'_2+r'_3\\hat{e}'_3.\n# \\end{eqnarray}\n# $$\n\n# This is the same vector expressed as a sum over two different sets of\n# basis vectors. The coefficients $r_i$ and $r'_i$ represent components\n# of the same vector. The relation between them can be found by taking\n# the dot product of each side with one of the unit vectors,\n# $\\hat{e}_i$, which gives\n\n# $$\n# \\begin{eqnarray}\n# r_i&=&\\sum_j \\hat{e}_i\\cdot\\hat{e}'_j~r'_j.\n# \\end{eqnarray}\n# $$\n\n# Using Eq. ([7](#eq:inverseU)) one can see that the transformation of $r$ can be also written in terms of $U$,\n\n# \n#
\n# \n# $$\n# \\begin{eqnarray}\n# \\label{eq:rotateR} \\tag{9}\n# r_i&=&\\sum_jU^{-1}_{ij}~r'_j.\n# \\end{eqnarray}\n# $$\n\n# Thus, the matrix that transforms the coordinates of the unit vectors,\n# Eq. ([7](#eq:inverseU)) is the same one that transforms the\n# coordinates of a vector, Eq. ([9](#eq:rotateR)).\n# \n# \n# \n# As a small exercise, find the rotation matrix $U$ for finding the\n# components in the primed coordinate system given from those in the\n# unprimed system, given that the unit vectors in the new system are\n# found by rotating the coordinate system by and angle $\\phi$ about the\n# $z$ axis.\n# \n# In this case\n\n# $$\n# \\begin{eqnarray*}\n# \\hat{e}'_1&=&\\cos\\phi \\hat{e}_1-\\sin\\phi\\hat{e}_2,\\\\\n# \\hat{e}'_2&=&\\sin\\phi\\hat{e}_1+\\cos\\phi\\hat{e}_2,\\\\\n# \\hat{e}'_3&=&\\hat{e}_3.\n# \\end{eqnarray*}\n# $$\n\n# By inspecting Eq. ([5](#eq:lambda_angles)), we get\n\n# $$\n# U=\\left(\\begin{array}{ccc}\n# \\cos\\phi&-\\sin\\phi&0\\\\\n# \\sin\\phi&\\cos\\phi&0\\\\\n# 0&0&1\\end{array}\\right).\n# $$\n\n# Under a unitary transformation $U$ (or basis transformation) scalars\n# are unchanged, whereas vectors $\\boldsymbol{r}$ and matrices $M$ change as\n\n# $$\n# \\begin{eqnarray}\n# r'_i&=&U_{ij}~ r_j, ~~({\\rm sum~inferred})\\\\\n# \\nonumber\n# M'_{ij}&=&U_{ik}M_{km}U^{-1}_{mj}.\n# \\end{eqnarray}\n# $$\n\n# Physical quantities with no spatial indices are scalars (or\n# pseudoscalars if they depend on right-handed vs. left-handed\n# coordinate systems), and are unchanged by unitary\n# transformations. This includes quantities like the trace of a matrix,\n# the matrix itself had indices but none remain after performing the\n# trace.\n\n# $$\n# \\begin{eqnarray}\n# {\\rm Tr} M&\\equiv& M_{ii}.\n# \\end{eqnarray}\n# $$\n\n# Because there are no remaining indices, one expects it to be a scalar. Indeed one can see this,\n\n# $$\n# \\begin{eqnarray}\n# {\\rm Tr} M'&=&U_{ij}M_{jm}U^{-1}_{mi}\\\\\n# \\nonumber\n# &=&M_{jm}U^{-1}_{mi}U_{ij}\\\\\n# \\nonumber\n# &=&M_{jm}\\delta_{mj}\\\\\n# \\nonumber\n# &=&M_{jj}={\\rm Tr} M.\n# \\end{eqnarray}\n# $$\n\n# A similar example is the determinant of a matrix, which is also a scalar.\n# \n# \n# \n# \n# ## Numerical Elements\n# \n# Numerical algorithms call for approximate discrete models and much of\n# the development of methods for continuous models are nowadays being\n# replaced by methods for discrete models in science and industry,\n# simply because **much larger classes of problems can be addressed** with\n# discrete models, often by simpler and more generic methodologies.\n# \n# As we will see throughout this course, when properly scaling the equations at hand,\n# discrete models open up for more advanced abstractions and the possibility to\n# study real life systems, with the added bonus that we can explore and\n# deepen our basic understanding of various physical systems\n# \n# Analytical solutions are as important as before. In addition, such\n# solutions provide us with invaluable benchmarks and tests for our\n# discrete models. Such benchmarks, as we will see below, allow us \n# to discuss possible sources of errors and their behaviors. And\n# finally, since most of our models are based on various algorithms from\n# numerical mathematics, we have a unique oppotunity to gain a deeper\n# understanding of the mathematical approaches we are using.\n# \n# \n# \n# With computing and data science as important elements in essentially\n# all aspects of a modern society, we could then try to define Computing as\n# **solving scientific problems using all possible tools, including\n# symbolic computing, computers and numerical algorithms, and analytical\n# paper and pencil solutions**. \n# Computing provides us with the tools to develope our own understanding of the scientific method by enhancing algorithmic thinking.\n# \n# \n# \n# The way we will teach this course reflects this definition of\n# computing. The course contains both classical paper and pencil\n# exercises as well as computational projects and exercises. The hope is\n# that this will allow you to explore the physics of systems governed by\n# the degrees of freedom of classical mechanics at a deeper level, and\n# that these insights about the scientific method will help you to\n# develop a better understanding of how the underlying forces and\n# equations of motion and how they impact a given system.\n# \n# Furthermore,\n# by introducing various numerical methods via computational projects\n# and exercises, we aim at developing your competences and skills about\n# these topics.\n# \n# \n# \n# \n# These competences will enable you to\n# \n# * understand how algorithms are used to solve mathematical problems,\n# \n# * derive, verify, and implement algorithms,\n# \n# * understand what can go wrong with algorithms,\n# \n# * use these algorithms to construct reproducible scientific outcomes and to engage in science in ethical ways, and\n# \n# * think algorithmically for the purposes of gaining deeper insights about scientific problems.\n# \n# All these elements are central for maturing and gaining a better understanding of the modern scientific process *per se*.\n# \n# The power of the scientific method lies in identifying a given problem\n# as a special case of an abstract class of problems, identifying\n# general solution methods for this class of problems, and applying a\n# general method to the specific problem (applying means, in the case of\n# computing, calculations by pen and paper, symbolic computing, or\n# numerical computing by ready-made and/or self-written software). This\n# generic view on problems and methods is particularly important for\n# understanding how to apply available, generic software to solve a\n# particular problem.\n# \n# *However, verification of algorithms and understanding their limitations requires much of the classical knowledge about continuous models.*\n# \n# \n# \n# ## A well-known example to illustrate many of the above concepts\n# \n# Before we venture into a reminder on Python and mechanics relevant applications, let us briefly outline some of the\n# abovementioned topics using an example many of you may have seen before in for example CMSE201. \n# A simple algorithm for integration is the Trapezoidal rule. \n# Integration of a function $f(x)$ by the Trapezoidal Rule is given by following algorithm for an interval $x \\in [a,b]$\n\n# $$\n# \\int_a^b(f(x) dx = \\frac{1}{2}\\left [f(a)+2f(a+h)+\\dots+2f(b-h)+f(b)\\right] +O(h^2),\n# $$\n\n# where $h$ is the so-called stepsize defined by the number of integration points $N$ as $h=(b-a)/(n)$.\n# Python offers an extremely versatile programming environment, allowing for\n# the inclusion of analytical studies in a numerical program. Here we show an\n# example code with the **trapezoidal rule**. We use also **SymPy** to evaluate the exact value of the integral and compute the absolute error\n# with respect to the numerically evaluated one of the integral\n# $\\int_0^1 dx x^2 = 1/3$.\n# The following code for the trapezoidal rule allows you to plot the relative error by comparing with the exact result. By increasing to $10^8$ points one arrives at a region where numerical errors start to accumulate.\n\n# In[2]:\n\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n\nfrom math import log10\nimport numpy as np\nfrom sympy import Symbol, integrate\nimport matplotlib.pyplot as plt\n# function for the trapezoidal rule\ndef Trapez(a,b,f,n):\n h = (b-a)/float(n)\n s = 0\n x = a\n for i in range(1,n,1):\n x = x+h\n s = s+ f(x)\n s = 0.5*(f(a)+f(b)) +s\n return h*s\n# function to compute pi\ndef function(x):\n return x*x\n# define integration limits\na = 0.0; b = 1.0;\n# find result from sympy\n# define x as a symbol to be used by sympy\nx = Symbol('x')\nexact = integrate(function(x), (x, a, b))\n# set up the arrays for plotting the relative error\nn = np.zeros(9); y = np.zeros(9);\n# find the relative error as function of integration points\nfor i in range(1, 8, 1):\n npts = 10**i\n result = Trapez(a,b,function,npts)\n RelativeError = abs((exact-result)/exact)\n n[i] = log10(npts); y[i] = log10(RelativeError);\nplt.plot(n,y, 'ro')\nplt.xlabel('n')\nplt.ylabel('Relative error')\nplt.show()\n\n\n# ### Analyzing the above example\n# \n# This example shows the potential of combining numerical algorithms\n# with symbolic calculations, allowing us to\n# \n# * Validate and verify their algorithms. \n# \n# * Including concepts like unit testing, one has the possibility to test and test several or all parts of the code.\n# \n# * Validation and verification are then included *naturally* and one can develop a better attitude to what is meant with an ethically sound scientific approach.\n# \n# * The above example allows the student to also test the mathematical error of the algorithm for the trapezoidal rule by changing the number of integration points. The students get **trained from day one to think error analysis**. \n# \n# * With a Jupyter notebook you can keep exploring similar examples and turn them in as your own notebooks. \n# \n# ## Python practicalities, Software and needed installations\n# \n# We will make extensive use of Python as programming language and its\n# myriad of available libraries. You will find\n# Jupyter notebooks invaluable in your work. \n# \n# If you have Python installed (we strongly recommend Python3) and you feel\n# pretty familiar with installing different packages, we recommend that\n# you install the following Python packages via **pip** as \n# \n# 1. pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow \n# \n# For Python3, replace **pip** with **pip3**.\n# \n# For OSX users we recommend, after having installed Xcode, to\n# install **brew**. Brew allows for a seamless installation of additional\n# software via for example \n# \n# 1. brew install python3\n# \n# For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,\n# you can use **pip** as well and simply install Python as \n# \n# 1. sudo apt-get install python3 (or python for pyhton2.7)\n# \n# etc etc. \n# \n# \n# \n# ### Python installers\n# \n# If you don't want to perform these operations separately and venture\n# into the hassle of exploring how to set up dependencies and paths, we\n# recommend two widely used distrubutions which set up all relevant\n# dependencies for Python, namely \n# \n# * [Anaconda](https://docs.anaconda.com/), \n# \n# which is an open source\n# distribution of the Python and R programming languages for large-scale\n# data processing, predictive analytics, and scientific computing, that\n# aims to simplify package management and deployment. Package versions\n# are managed by the package management system **conda**. \n# \n# * [Enthought canopy](https://www.enthought.com/product/canopy/) \n# \n# is a Python\n# distribution for scientific and analytic computing distribution and\n# analysis environment, available for free and under a commercial\n# license.\n# \n# Furthermore, [Google's Colab](https://colab.research.google.com/notebooks/welcome.ipynb) is a free Jupyter notebook environment that requires \n# no setup and runs entirely in the cloud. Try it out!\n# \n# \n# ## Useful Python libraries\n# \n# Here we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there)\n# \n# * [NumPy](https://www.numpy.org/) is a highly popular library for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays\n# \n# * [The pandas](https://pandas.pydata.org/) library provides high-performance, easy-to-use data structures and data analysis tools \n# \n# * [Xarray](http://xarray.pydata.org/en/stable/) is a Python package that makes working with labelled multi-dimensional arrays simple, efficient, and fun!\n# \n# * [Scipy](https://www.scipy.org/) (pronounced “Sigh Pie”) is a Python-based ecosystem of open-source software for mathematics, science, and engineering. \n# \n# * [Matplotlib](https://matplotlib.org/) is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.\n# \n# * [Autograd](https://github.com/HIPS/autograd) can automatically differentiate native Python and Numpy code. It can handle a large subset of Python's features, including loops, ifs, recursion and closures, and it can even take derivatives of derivatives of derivatives\n# \n# * [SymPy](https://www.sympy.org/en/index.html) is a Python library for symbolic mathematics. \n# \n# * [scikit-learn](https://scikit-learn.org/stable/) has simple and efficient tools for machine learning, data mining and data analysis\n# \n# * [TensorFlow](https://www.tensorflow.org/) is a Python library for fast numerical computing created and released by Google\n# \n# * [Keras](https://keras.io/) is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano\n# \n# * And many more such as [pytorch](https://pytorch.org/), [Theano](https://pypi.org/project/Theano/) etc \n# \n# Your jupyter notebook can easily be\n# converted into a nicely rendered **PDF** file or a Latex file for\n# further processing. For example, convert to latex as\n\n# pycod jupyter nbconvert filename.ipynb --to latex \n# \n\n# And to add more versatility, the Python package [SymPy](http://www.sympy.org/en/index.html) is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python. \n# \n# \n# \n# ## Numpy examples and Important Matrix and vector handling packages\n# \n# There are several central software libraries for linear algebra and eigenvalue problems. Several of the more\n# popular ones have been wrapped into ofter software packages like those from the widely used text **Numerical Recipes**. The original source codes in many of the available packages are often taken from the widely used\n# software package LAPACK, which follows two other popular packages\n# developed in the 1970s, namely EISPACK and LINPACK. We describe them shortly here.\n# \n# * LINPACK: package for linear equations and least square problems.\n# \n# * LAPACK:package for solving symmetric, unsymmetric and generalized eigenvalue problems. From LAPACK's website it is possible to download for free all source codes from this library. Both C/C++ and Fortran versions are available.\n# \n# * BLAS (I, II and III): (Basic Linear Algebra Subprograms) are routines that provide standard building blocks for performing basic vector and matrix operations. Blas I is vector operations, II vector-matrix operations and III matrix-matrix operations. Highly parallelized and efficient codes, all available for download from .\n# \n# [Numpy](http://www.numpy.org/) provides an easy way to handle arrays in Python. The standard way to import this library is as\n\n# In[ ]:\n\n\nimport numpy as np\n\n\n# Here follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution,\n\n# In[ ]:\n\n\nn = 10\nx = np.random.normal(size=n)\nprint(x)\n\n\n# We defined a vector $x$ with $n=10$ elements with its values given by the Normal distribution $N(0,1)$.\n# Another alternative is to declare a vector as follows\n\n# In[ ]:\n\n\nimport numpy as np\nx = np.array([1, 2, 3])\nprint(x)\n\n\n# Here we have defined a vector with three elements, with $x_0=1$, $x_1=2$ and $x_2=3$. Note that both Python and C++\n# start numbering array elements from $0$ and on. This means that a vector with $n$ elements has a sequence of entities $x_0, x_1, x_2, \\dots, x_{n-1}$. We could also let (recommended) Numpy to compute the logarithms of a specific array as\n\n# In[ ]:\n\n\nimport numpy as np\nx = np.log(np.array([4, 7, 8]))\nprint(x)\n\n\n# In the last example we used Numpy's unary function $np.log$. This function is\n# highly tuned to compute array elements since the code is vectorized\n# and does not require looping. We normaly recommend that you use the\n# Numpy intrinsic functions instead of the corresponding **log** function\n# from Python's **math** module. The looping is done explicitely by the\n# **np.log** function. The alternative, and slower way to compute the\n# logarithms of a vector would be to write\n\n# In[ ]:\n\n\nimport numpy as np\nfrom math import log\nx = np.array([4, 7, 8])\nfor i in range(0, len(x)):\n x[i] = log(x[i])\nprint(x)\n\n\n# We note that our code is much longer already and we need to import the **log** function from the **math** module. \n# The attentive reader will also notice that the output is $[1, 1, 2]$. Python interprets automagically our numbers as integers (like the **automatic** keyword in C++). To change this we could define our array elements to be double precision numbers as\n\n# In[ ]:\n\n\nimport numpy as np\nx = np.log(np.array([4, 7, 8], dtype = np.float64))\nprint(x)\n\n\n# or simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is\n\n# In[ ]:\n\n\nimport numpy as np\nx = np.log(np.array([4.0, 7.0, 8.0])\nprint(x)\n\n\n# To check the number of bytes (remember that one byte contains eight bits for double precision variables), you can use simple use the **itemsize** functionality (the array $x$ is actually an object which inherits the functionalities defined in Numpy) as\n\n# In[ ]:\n\n\nimport numpy as np\nx = np.log(np.array([4.0, 7.0, 8.0])\nprint(x.itemsize)\n\n\n# ### Matrices in Python\n# \n# Having defined vectors, we are now ready to try out matrices. We can\n# define a $3 \\times 3 $ real matrix $\\hat{A}$ as (recall that we user\n# lowercase letters for vectors and uppercase letters for matrices)\n\n# In[ ]:\n\n\nimport numpy as np\nA = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\nprint(A)\n\n\n# If we use the **shape** function we would get $(3, 3)$ as output, that is verifying that our matrix is a $3\\times 3$ matrix. We can slice the matrix and print for example the first column (Python organized matrix elements in a row-major order, see below) as\n\n# In[ ]:\n\n\nimport numpy as np\nA = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n# print the first column, row-major order and elements start with 0\nprint(A[:,0])\n\n\n# We can continue this was by printing out other columns or rows. The example here prints out the second column\n\n# In[ ]:\n\n\nimport numpy as np\nA = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n# print the first column, row-major order and elements start with 0\nprint(A[1,:])\n\n\n# Numpy contains many other functionalities that allow us to slice, subdivide etc etc arrays. We strongly recommend that you look up the [Numpy website for more details](http://www.numpy.org/). Useful functions when defining a matrix are the **np.zeros** function which declares a matrix of a given dimension and sets all elements to zero\n\n# In[ ]:\n\n\nimport numpy as np\nn = 10\n# define a matrix of dimension 10 x 10 and set all elements to zero\nA = np.zeros( (n, n) )\nprint(A)\n\n\n# or initializing all elements to\n\n# In[ ]:\n\n\nimport numpy as np\nn = 10\n# define a matrix of dimension 10 x 10 and set all elements to one\nA = np.ones( (n, n) )\nprint(A)\n\n\n# or as unitarily distributed random numbers (see the material on random number generators in the statistics part)\n\n# In[ ]:\n\n\nimport numpy as np\nn = 10\n# define a matrix of dimension 10 x 10 and set all elements to random numbers with x \\in [0, 1]\nA = np.random.rand(n, n)\nprint(A)\n\n\n# ### Meet the Pandas\n# \n# Another useful Python package is\n# [pandas](https://pandas.pydata.org/), which is an open source library\n# providing high-performance, easy-to-use data structures and data\n# analysis tools for Python. **pandas** stands for panel data, a term borrowed from econometrics and is an efficient library for data analysis with an emphasis on tabular data.\n# \n# **pandas** has two major classes, the **DataFrame** class with\n# two-dimensional data objects and tabular data organized in columns and\n# the class **Series** with a focus on one-dimensional data objects. Both\n# classes allow you to index data easily as we will see in the examples\n# below. **pandas** allows you also to perform mathematical operations on\n# the data, spanning from simple reshapings of vectors and matrices to\n# statistical operations.\n# \n# The following simple example shows how we can, in an easy way make\n# tables of our data. Here we define a data set which includes names,\n# place of birth and date of birth, and displays the data in an easy to\n# read way. We will see repeated use of **pandas**, in particular in\n# connection with classification of data.\n\n# In[ ]:\n\n\nimport pandas as pd\nfrom IPython.display import display\ndata = {'First Name': [\"Frodo\", \"Bilbo\", \"Aragorn II\", \"Samwise\"],\n 'Last Name': [\"Baggins\", \"Baggins\",\"Elessar\",\"Gamgee\"],\n 'Place of birth': [\"Shire\", \"Shire\", \"Eriador\", \"Shire\"],\n 'Date of Birth T.A.': [2968, 2890, 2931, 2980]\n }\ndata_pandas = pd.DataFrame(data)\ndisplay(data_pandas)\n\n\n# In the above we have imported **pandas** with the shorthand **pd**, the latter has become the standard way we import **pandas**. We make then a list of various variables\n# and reorganize the above lists into a **DataFrame** and then print out a neat table with specific column labels as *Name*, *place of birth* and *date of birth*.\n# Displaying these results, we see that the indices are given by the default numbers from zero to three.\n# **pandas** is extremely flexible and we can easily change the above indices by defining a new type of indexing as\n\n# In[ ]:\n\n\ndata_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])\ndisplay(data_pandas)\n\n\n# Thereafter we display the content of the row which begins with the index **Aragorn**\n\n# In[ ]:\n\n\ndisplay(data_pandas.loc['Aragorn'])\n\n\n# We can easily append data to this, for example\n\n# In[ ]:\n\n\nnew_hobbit = {'First Name': [\"Peregrin\"],\n 'Last Name': [\"Took\"],\n 'Place of birth': [\"Shire\"],\n 'Date of Birth T.A.': [2990]\n }\ndata_pandas=data_pandas.append(pd.DataFrame(new_hobbit, index=['Pippin']))\ndisplay(data_pandas)\n\n\n# Here are other examples where we use the **DataFrame** functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix \n# of dimensionality $10\\times 5$ and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations.\n\n# In[ ]:\n\n\nimport numpy as np\nimport pandas as pd\nfrom IPython.display import display\nnp.random.seed(100)\n# setting up a 10 x 5 matrix\nrows = 10\ncols = 5\na = np.random.randn(rows,cols)\ndf = pd.DataFrame(a)\ndisplay(df)\nprint(df.mean())\nprint(df.std())\ndisplay(df**2)\n\n\n# Thereafter we can select specific columns only and plot final results\n\n# In[ ]:\n\n\ndf.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']\ndf.index = np.arange(10)\n\ndisplay(df)\nprint(df['Second'].mean() )\nprint(df.info())\nprint(df.describe())\n\nfrom pylab import plt, mpl\nplt.style.use('seaborn')\nmpl.rcParams['font.family'] = 'serif'\n\ndf.cumsum().plot(lw=2.0, figsize=(10,6))\nplt.show()\n\n\ndf.plot.bar(figsize=(10,6), rot=15)\nplt.show()\n\n\n# We can produce a $4\\times 4$ matrix\n\n# In[ ]:\n\n\nb = np.arange(16).reshape((4,4))\nprint(b)\ndf1 = pd.DataFrame(b)\nprint(df1)\n\n\n# and many other operations. \n# \n# \n# The **Series** class is another important class included in\n# **pandas**. You can view it as a specialization of **DataFrame** but where\n# we have just a single column of data. It shares many of the same\n# features as **DataFrame**. As with **DataFrame**, most operations are\n# vectorized, achieving thereby a high performance when dealing with\n# computations of arrays, in particular labeled arrays. As we will see\n# below it leads also to a very concice code close to the mathematical\n# operations we may be interested in. For multidimensional arrays, we\n# recommend strongly\n# [xarray](http://xarray.pydata.org/en/stable/). **xarray** has much of\n# the same flexibility as **pandas**, but allows for the extension to\n# higher dimensions than two.\n# \n# \n# \n# \n# \n# ## Introduction to Git and GitHub/GitLab and similar\n# \n# [Git](https://git-scm.com/) is a distributed version-control system\n# for tracking changes in any set of files, originally designed for\n# coordinating work among programmers cooperating on source code during\n# software development.\n# \n# The [reference document and videos here](https://git-scm.com/doc)\n# give you an excellent introduction to the **git**.\n# \n# We believe you will find version-control software very useful in your work. \n# \n# \n# \n# \n# All teaching material related to this course is open and freely\n# available via the GitHub site of the course. The video here gives a\n# short intro to\n# [GitHub](https://www.youtube.com/watch/w3jLJU7DT5E?reload=9).\n# \n# See also the [overview video on Git and GitHub](https://mediaspace.msu.edu/media/t/1_8mgx3cyf).\n# \n# \n# \n# ### Useful Git and GitHub links\n# \n# These are a couple references that we have found useful (git commands, markdown, GitPages):\n# * \n# \n# * \n# \n# * \n# \n# When dealing with homeworks, at some point you would need to use an\n# editor, or an integrated development envinroment (IDE). As an IDE, we\n# would like to recommend **anaconda** since we end up using\n# jupyter-notebooks. **anaconda** runs on all known operating systems.\n# \n# \n# If you prefer editing **Python** codes, there are several excellent cross-platform editors.\n# If you are in a Windows environment, **word** is the classical text editor.\n# \n# There is however a wealth of text editors and/ord IDEs that run on all operating\n# systems and functions well with Python. Some of the more popular ones are\n# \n# * [Atom](https://atom.io/)\n# \n# * [Sublime](https://www.sublimetext.com/)\n", "meta": {"hexsha": "e48379ca0accfca4fd548e274b84dc67ef733b4d", "size": 52934, "ext": "py", "lang": "Python", "max_stars_repo_path": "doc/LectureNotes/_build/jupyter_execute/chapter2.py", "max_stars_repo_name": "Shield94/Physics321", "max_stars_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/LectureNotes/_build/jupyter_execute/chapter2.py", "max_issues_repo_name": "Shield94/Physics321", "max_issues_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/LectureNotes/_build/jupyter_execute/chapter2.py", "max_forks_repo_name": "Shield94/Physics321", "max_forks_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0340367597, "max_line_length": 353, "alphanum_fraction": 0.6925227642, "include": true, "reason": "import numpy,from sympy", "num_tokens": 15329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416729909662417, "lm_q2_score": 0.22815649691270326, "lm_q1q2_score": 0.10077056239981373}} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Residual Networks\n# \n# Welcome to the first assignment of this week! You'll be building a very deep convolutional network, using Residual Networks (ResNets). In theory, very deep networks can represent very complex functions; but in practice, they are hard to train. Residual Networks, introduced by [He et al.](https://arxiv.org/pdf/1512.03385.pdf), allow you to train much deeper networks than were previously feasible.\n# \n# **By the end of this assignment, you'll be able to:**\n# \n# - Implement the basic building blocks of ResNets in a deep neural network using Keras\n# - Put together these building blocks to implement and train a state-of-the-art neural network for image classification\n# - Implement a skip connection in your network\n# \n# For this assignment, you'll use Keras. \n# \n# Before jumping into the problem, run the cell below to load the required packages.\n\n# ## Table of Content\n# \n# - [1 - Packages](#1)\n# - [2 - The Problem of Very Deep Neural Networks](#2)\n# - [3 - Building a Residual Network](#3)\n# - [3.1 - The Identity Block](#3-1)\n# - [Exercise 1 - identity_block](#ex-1)\n# - [3.2 - The Convolutional Block](#3-2)\n# - [Exercise 2 - convolutional_block](#ex-2)\n# - [4 - Building Your First ResNet Model (50 layers)](#4)\n# - [Exercise 3 - ResNet50](#ex-3)\n# - [5 - Test on Your Own Image (Optional/Ungraded)](#5)\n# - [6 - Bibliography](#6)\n\n#
\n# ## 1 - Packages\n\n# In[1]:\n\n\nimport tensorflow as tf\nimport numpy as np\nimport scipy.misc\nfrom tensorflow.keras.applications.resnet_v2 import ResNet50V2\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.applications.resnet_v2 import preprocess_input, decode_predictions\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, AveragePooling2D, MaxPooling2D, GlobalMaxPooling2D\nfrom tensorflow.keras.models import Model, load_model\nfrom resnets_utils import *\nfrom tensorflow.keras.initializers import random_uniform, glorot_uniform, constant, identity\nfrom tensorflow.python.framework.ops import EagerTensor\nfrom matplotlib.pyplot import imshow\n\nfrom test_utils import summary, comparator\nimport public_tests\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# \n# ## 2 - The Problem of Very Deep Neural Networks\n# \n# Last week, you built your first convolutional neural networks: first manually with numpy, then using Tensorflow and Keras. \n# \n# In recent years, neural networks have become much deeper, with state-of-the-art networks evolving from having just a few layers (e.g., AlexNet) to over a hundred layers.\n# \n# * The main benefit of a very deep network is that it can represent very complex functions. It can also learn features at many different levels of abstraction, from edges (at the shallower layers, closer to the input) to very complex features (at the deeper layers, closer to the output). \n# \n# * However, using a deeper network doesn't always help. A huge barrier to training them is vanishing gradients: very deep networks often have a gradient signal that goes to zero quickly, thus making gradient descent prohibitively slow.\n# \n# * More specifically, during gradient descent, as you backpropagate from the final layer back to the first layer, you are multiplying by the weight matrix on each step, and thus the gradient can decrease exponentially quickly to zero (or, in rare cases, grow exponentially quickly and \"explode,\" from gaining very large values). \n# \n# * During training, you might therefore see the magnitude (or norm) of the gradient for the shallower layers decrease to zero very rapidly as training proceeds, as shown below: \n\n# \n#
Figure 1 : Vanishing gradient
The speed of learning decreases very rapidly for the shallower layers as the network trains
\n# \n# Not to worry! You are now going to solve this problem by building a Residual Network!\n\n# \n# ## 3 - Building a Residual Network\n# \n# In ResNets, a \"shortcut\" or a \"skip connection\" allows the model to skip layers: \n# \n# \n#
Figure 2 : A ResNet block showing a skip-connection
\n# \n# The image on the left shows the \"main path\" through the network. The image on the right adds a shortcut to the main path. By stacking these ResNet blocks on top of each other, you can form a very deep network. \n# \n# The lecture mentioned that having ResNet blocks with the shortcut also makes it very easy for one of the blocks to learn an identity function. This means that you can stack on additional ResNet blocks with little risk of harming training set performance. \n# \n# On that note, there is also some evidence that the ease of learning an identity function accounts for ResNets' remarkable performance even more than skip connections help with vanishing gradients.\n# \n# Two main types of blocks are used in a ResNet, depending mainly on whether the input/output dimensions are the same or different. You are going to implement both of them: the \"identity block\" and the \"convolutional block.\"\n\n# \n# ### 3.1 - The Identity Block\n# \n# The identity block is the standard block used in ResNets, and corresponds to the case where the input activation (say $a^{[l]}$) has the same dimension as the output activation (say $a^{[l+2]}$). To flesh out the different steps of what happens in a ResNet's identity block, here is an alternative diagram showing the individual steps:\n# \n# \n#
Figure 3 : Identity block. Skip connection \"skips over\" 2 layers.
\n# \n# The upper path is the \"shortcut path.\" The lower path is the \"main path.\" In this diagram, notice the CONV2D and ReLU steps in each layer. To speed up training, a BatchNorm step has been added. Don't worry about this being complicated to implement--you'll see that BatchNorm is just one line of code in Keras! \n# \n# In this exercise, you'll actually implement a slightly more powerful version of this identity block, in which the skip connection \"skips over\" 3 hidden layers rather than 2 layers. It looks like this: \n# \n# \n#
Figure 4 : Identity block. Skip connection \"skips over\" 3 layers.
\n\n# These are the individual steps:\n# \n# First component of main path: \n# - The first CONV2D has $F_1$ filters of shape (1,1) and a stride of (1,1). Its padding is \"valid\". Use 0 as the seed for the random uniform initialization: `kernel_initializer = initializer(seed=0)`. \n# - The first BatchNorm is normalizing the 'channels' axis.\n# - Then apply the ReLU activation function. This has no hyperparameters. \n# \n# Second component of main path:\n# - The second CONV2D has $F_2$ filters of shape $(f,f)$ and a stride of (1,1). Its padding is \"same\". Use 0 as the seed for the random uniform initialization: `kernel_initializer = initializer(seed=0)`.\n# - The second BatchNorm is normalizing the 'channels' axis.\n# - Then apply the ReLU activation function. This has no hyperparameters.\n# \n# Third component of main path:\n# - The third CONV2D has $F_3$ filters of shape (1,1) and a stride of (1,1). Its padding is \"valid\". Use 0 as the seed for the random uniform initialization: `kernel_initializer = initializer(seed=0)`. \n# - The third BatchNorm is normalizing the 'channels' axis.\n# - Note that there is **no** ReLU activation function in this component. \n# \n# Final step: \n# - The `X_shortcut` and the output from the 3rd layer `X` are added together.\n# - **Hint**: The syntax will look something like `Add()([var1,var2])`\n# - Then apply the ReLU activation function. This has no hyperparameters. \n# \n# \n# ### Exercise 1 - identity_block\n# \n# Implement the ResNet identity block. The first component of the main path has been implemented for you already! First, you should read these docs carefully to make sure you understand what's happening. Then, implement the rest. \n# - To implement the Conv2D step: [Conv2D](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2D)\n# - To implement BatchNorm: [BatchNormalization](https://www.tensorflow.org/api_docs/python/tf/keras/layers/BatchNormalization) `BatchNormalization(axis = 3)(X, training = training)`. If training is set to False, its weights are not updated with the new examples. I.e when the model is used in prediction mode.\n# - For the activation, use: `Activation('relu')(X)`\n# - To add the value passed forward by the shortcut: [Add](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Add)\n# \n# We have added the initializer argument to our functions. This parameter receives an initializer function like the ones included in the package [tensorflow.keras.initializers](https://www.tensorflow.org/api_docs/python/tf/keras/initializers) or any other custom initializer. By default it will be set to [random_uniform](https://www.tensorflow.org/api_docs/python/tf/keras/initializers/RandomUniform)\n# \n# Remember that these functions accept a `seed` argument that can be any value you want, but that in this notebook must set to 0 for **grading purposes**.\n\n# Here is where you're actually using the power of the Functional API to create a shortcut path: \n\n# In[2]:\n\n\n# UNQ_C1\n# GRADED FUNCTION: identity_block\n\ndef identity_block(X, f, filters, training=True, initializer=random_uniform):\n \"\"\"\n Implementation of the identity block as defined in Figure 4\n \n Arguments:\n X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)\n f -- integer, specifying the shape of the middle CONV's window for the main path\n filters -- python list of integers, defining the number of filters in the CONV layers of the main path\n training -- True: Behave in training mode\n False: Behave in inference mode\n initializer -- to set up the initial weights of a layer. Equals to random uniform initializer\n \n Returns:\n X -- output of the identity block, tensor of shape (m, n_H, n_W, n_C)\n \"\"\"\n \n \n # Retrieve Filters\n F1, F2, F3 = filters\n \n # Save the input value. You'll need this later to add back to the main path. \n X_shortcut = X\n \n # First component of main path\n X = Conv2D(filters = F1, kernel_size = 1, strides = (1,1), padding = 'valid', kernel_initializer = initializer(seed=0))(X)\n X = BatchNormalization(axis = 3)(X, training = training) # Default axis\n X = Activation('relu')(X)\n \n ### START CODE HERE\n ## Second component of main path (≈3 lines)\n X = Conv2D(filters = F2, kernel_size = (f, f), strides = (1,1), padding = 'same', kernel_initializer = initializer(seed=0))(X)\n X = BatchNormalization(axis = 3)(X, training = training)\n X = Activation('relu')(X) \n\n ## Third component of main path (≈2 lines)\n X = Conv2D(filters = F3, kernel_size = (1, 1), strides = (1,1), padding = 'valid', kernel_initializer = initializer(seed=0))(X)\n X = BatchNormalization(axis = 3)(X, training = training)\n \n ## Final step: Add shortcut value to main path, and pass it through a RELU activation (≈2 lines)\n X = Add()([X, X_shortcut])\n X = Activation('relu')(X) \n ### END CODE HERE\n\n return X\n\n\n# In[3]:\n\n\nnp.random.seed(1)\nX1 = np.ones((1, 4, 4, 3)) * -1\nX2 = np.ones((1, 4, 4, 3)) * 1\nX3 = np.ones((1, 4, 4, 3)) * 3\n\nX = np.concatenate((X1, X2, X3), axis = 0).astype(np.float32)\n\nA3 = identity_block(X, f=2, filters=[4, 4, 3],\n initializer=lambda seed=0:constant(value=1),\n training=False)\nprint('\\033[1mWith training=False\\033[0m\\n')\nA3np = A3.numpy()\nprint(np.around(A3.numpy()[:,(0,-1),:,:].mean(axis = 3), 5))\nresume = A3np[:,(0,-1),:,:].mean(axis = 3)\nprint(resume[1, 1, 0])\n\nprint('\\n\\033[1mWith training=True\\033[0m\\n')\nnp.random.seed(1)\nA4 = identity_block(X, f=2, filters=[3, 3, 3],\n initializer=lambda seed=0:constant(value=1),\n training=True)\nprint(np.around(A4.numpy()[:,(0,-1),:,:].mean(axis = 3), 5))\n\npublic_tests.identity_block_test(identity_block)\n\n\n# **Expected value**\n# \n# ```\n# With training=False\n# \n# [[[ 0. 0. 0. 0. ]\n# [ 0. 0. 0. 0. ]]\n# \n# [[192.71234 192.71234 192.71234 96.85617]\n# [ 96.85617 96.85617 96.85617 48.92808]]\n# \n# [[578.1371 578.1371 578.1371 290.5685 ]\n# [290.5685 290.5685 290.5685 146.78426]]]\n# 96.85617\n# \n# With training=True\n# \n# [[[0. 0. 0. 0. ]\n# [0. 0. 0. 0. ]]\n# \n# [[0.40739 0.40739 0.40739 0.40739]\n# [0.40739 0.40739 0.40739 0.40739]]\n# \n# [[4.99991 4.99991 4.99991 3.25948]\n# [3.25948 3.25948 3.25948 2.40739]]]\n# ```\n\n# \n# ### 3.2 - The Convolutional Block\n# \n# The ResNet \"convolutional block\" is the second block type. You can use this type of block when the input and output dimensions don't match up. The difference with the identity block is that there is a CONV2D layer in the shortcut path: \n# \n# \n#
Figure 4 : Convolutional block
\n# \n# * The CONV2D layer in the shortcut path is used to resize the input $x$ to a different dimension, so that the dimensions match up in the final addition needed to add the shortcut value back to the main path. (This plays a similar role as the matrix $W_s$ discussed in lecture.) \n# * For example, to reduce the activation dimensions's height and width by a factor of 2, you can use a 1x1 convolution with a stride of 2. \n# * The CONV2D layer on the shortcut path does not use any non-linear activation function. Its main role is to just apply a (learned) linear function that reduces the dimension of the input, so that the dimensions match up for the later addition step. \n# * As for the previous exercise, the additional `initializer` argument is required for grading purposes, and it has been set by default to [glorot_uniform](https://www.tensorflow.org/api_docs/python/tf/keras/initializers/GlorotUniform)\n# \n# The details of the convolutional block are as follows. \n# \n# First component of main path:\n# - The first CONV2D has $F_1$ filters of shape (1,1) and a stride of (s,s). Its padding is \"valid\". Use 0 as the `glorot_uniform` seed `kernel_initializer = initializer(seed=0)`.\n# - The first BatchNorm is normalizing the 'channels' axis.\n# - Then apply the ReLU activation function. This has no hyperparameters. \n# \n# Second component of main path:\n# - The second CONV2D has $F_2$ filters of shape (f,f) and a stride of (1,1). Its padding is \"same\". Use 0 as the `glorot_uniform` seed `kernel_initializer = initializer(seed=0)`.\n# - The second BatchNorm is normalizing the 'channels' axis.\n# - Then apply the ReLU activation function. This has no hyperparameters. \n# \n# Third component of main path:\n# - The third CONV2D has $F_3$ filters of shape (1,1) and a stride of (1,1). Its padding is \"valid\". Use 0 as the `glorot_uniform` seed `kernel_initializer = initializer(seed=0)`.\n# - The third BatchNorm is normalizing the 'channels' axis. Note that there is no ReLU activation function in this component. \n# \n# Shortcut path:\n# - The CONV2D has $F_3$ filters of shape (1,1) and a stride of (s,s). Its padding is \"valid\". Use 0 as the `glorot_uniform` seed `kernel_initializer = initializer(seed=0)`.\n# - The BatchNorm is normalizing the 'channels' axis. \n# \n# Final step: \n# - The shortcut and the main path values are added together.\n# - Then apply the ReLU activation function. This has no hyperparameters. \n# \n# \n# ### Exercise 2 - convolutional_block\n# \n# Implement the convolutional block. The first component of the main path is already implemented; then it's your turn to implement the rest! As before, always use 0 as the seed for the random initialization, to ensure consistency with the grader.\n# - [Conv2D](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2D)\n# - [BatchNormalization](https://www.tensorflow.org/api_docs/python/tf/keras/layers/BatchNormalization) (axis: Integer, the axis that should be normalized (typically the features axis)) `BatchNormalization(axis = 3)(X, training = training)`. If training is set to False, its weights are not updated with the new examples. I.e when the model is used in prediction mode.\n# - For the activation, use: `Activation('relu')(X)`\n# - [Add](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Add)\n# \n# We have added the initializer argument to our functions. This parameter receives an initializer function like the ones included in the package [tensorflow.keras.initializers](https://www.tensorflow.org/api_docs/python/tf/keras/initializers) or any other custom initializer. By default it will be set to [random_uniform](https://www.tensorflow.org/api_docs/python/tf/keras/initializers/RandomUniform)\n# \n# Remember that these functions accept a `seed` argument that can be any value you want, but that in this notebook must set to 0 for **grading purposes**.\n\n# In[4]:\n\n\n# UNQ_C2\n# GRADED FUNCTION: convolutional_block\n\ndef convolutional_block(X, f, filters, s = 2, training=True, initializer=glorot_uniform):\n \"\"\"\n Implementation of the convolutional block as defined in Figure 4\n \n Arguments:\n X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)\n f -- integer, specifying the shape of the middle CONV's window for the main path\n filters -- python list of integers, defining the number of filters in the CONV layers of the main path\n s -- Integer, specifying the stride to be used\n training -- True: Behave in training mode\n False: Behave in inference mode\n initializer -- to set up the initial weights of a layer. Equals to Glorot uniform initializer, \n also called Xavier uniform initializer.\n \n Returns:\n X -- output of the convolutional block, tensor of shape (n_H, n_W, n_C)\n \"\"\"\n \n # Retrieve Filters\n F1, F2, F3 = filters\n \n # Save the input value\n X_shortcut = X\n\n\n ##### MAIN PATH #####\n \n # First component of main path glorot_uniform(seed=0)\n X = Conv2D(filters = F1, kernel_size = 1, strides = (s, s), padding='valid', kernel_initializer = initializer(seed=0))(X)\n X = BatchNormalization(axis = 3)(X, training=training)\n X = Activation('relu')(X)\n\n ### START CODE HERE\n \n ## Second component of main path (≈3 lines)\n X = Conv2D(filters = F2, kernel_size = (f,f), strides = (1, 1), padding='same', kernel_initializer = initializer(seed=0))(X) \n X = BatchNormalization(axis = 3)(X, training=training) \n X = Activation('relu')(X) \n\n ## Third component of main path (≈2 lines)\n X = Conv2D(filters = F3, kernel_size = (1,1), strides = (1, 1), padding='valid', kernel_initializer = initializer(seed=0))(X) \n X = BatchNormalization(axis = 3)(X, training=training) \n \n ##### SHORTCUT PATH ##### (≈2 lines)\n X_shortcut = Conv2D(filters = F3, kernel_size = (1,1), strides = (s, s), padding='valid', kernel_initializer = initializer(seed=0))(X_shortcut)\n X_shortcut = BatchNormalization(axis = 3)(X_shortcut, training=training) \n \n ### END CODE HERE\n\n # Final step: Add shortcut value to main path (Use this order [X, X_shortcut]), and pass it through a RELU activation\n X = Add()([X, X_shortcut])\n X = Activation('relu')(X)\n \n return X\n\n\n# In[5]:\n\n\nfrom outputs import convolutional_block_output1, convolutional_block_output2\nnp.random.seed(1)\n#X = np.random.randn(3, 4, 4, 6).astype(np.float32)\nX1 = np.ones((1, 4, 4, 3)) * -1\nX2 = np.ones((1, 4, 4, 3)) * 1\nX3 = np.ones((1, 4, 4, 3)) * 3\n\nX = np.concatenate((X1, X2, X3), axis = 0).astype(np.float32)\n\nA = convolutional_block(X, f = 2, filters = [2, 4, 6], training=False)\n\nassert type(A) == EagerTensor, \"Use only tensorflow and keras functions\"\nassert tuple(tf.shape(A).numpy()) == (3, 2, 2, 6), \"Wrong shape.\"\nassert np.allclose(A.numpy(), convolutional_block_output1), \"Wrong values when training=False.\"\nprint(A[0])\n\nB = convolutional_block(X, f = 2, filters = [2, 4, 6], training=True)\nassert np.allclose(B.numpy(), convolutional_block_output2), \"Wrong values when training=True.\"\n\nprint('\\033[92mAll tests passed!')\n\n\n# **Expected value**\n# \n# ```\n# tf.Tensor(\n# [[[0. 0.66683817 0. 0. 0.88853896 0.5274254 ]\n# [0. 0.65053666 0. 0. 0.89592844 0.49965227]]\n# \n# [[0. 0.6312079 0. 0. 0.8636247 0.47643146]\n# [0. 0.5688321 0. 0. 0.85534114 0.41709304]]], shape=(2, 2, 6), dtype=float32)\n# ```\n\n# \n# ## 4 - Building Your First ResNet Model (50 layers)\n# \n# You now have the necessary blocks to build a very deep ResNet. The following figure describes in detail the architecture of this neural network. \"ID BLOCK\" in the diagram stands for \"Identity block,\" and \"ID BLOCK x3\" means you should stack 3 identity blocks together.\n# \n# \n#
Figure 5 : ResNet-50 model
\n# \n# The details of this ResNet-50 model are:\n# - Zero-padding pads the input with a pad of (3,3)\n# - Stage 1:\n# - The 2D Convolution has 64 filters of shape (7,7) and uses a stride of (2,2). \n# - BatchNorm is applied to the 'channels' axis of the input.\n# - ReLU activation is applied.\n# - MaxPooling uses a (3,3) window and a (2,2) stride.\n# - Stage 2:\n# - The convolutional block uses three sets of filters of size [64,64,256], \"f\" is 3, and \"s\" is 1.\n# - The 2 identity blocks use three sets of filters of size [64,64,256], and \"f\" is 3.\n# - Stage 3:\n# - The convolutional block uses three sets of filters of size [128,128,512], \"f\" is 3 and \"s\" is 2.\n# - The 3 identity blocks use three sets of filters of size [128,128,512] and \"f\" is 3.\n# - Stage 4:\n# - The convolutional block uses three sets of filters of size [256, 256, 1024], \"f\" is 3 and \"s\" is 2.\n# - The 5 identity blocks use three sets of filters of size [256, 256, 1024] and \"f\" is 3.\n# - Stage 5:\n# - The convolutional block uses three sets of filters of size [512, 512, 2048], \"f\" is 3 and \"s\" is 2.\n# - The 2 identity blocks use three sets of filters of size [512, 512, 2048] and \"f\" is 3.\n# - The 2D Average Pooling uses a window of shape (2,2).\n# - The 'flatten' layer doesn't have any hyperparameters.\n# - The Fully Connected (Dense) layer reduces its input to the number of classes using a softmax activation.\n# \n# \n# \n# ### Exercise 3 - ResNet50 \n# \n# Implement the ResNet with 50 layers described in the figure above. We have implemented Stages 1 and 2. Please implement the rest. (The syntax for implementing Stages 3-5 should be quite similar to that of Stage 2) Make sure you follow the naming convention in the text above. \n# \n# You'll need to use this function: \n# - Average pooling [see reference](https://www.tensorflow.org/api_docs/python/tf/keras/layers/AveragePooling2D)\n# \n# Here are some other functions we used in the code below:\n# - Conv2D: [See reference](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2D)\n# - BatchNorm: [See reference](https://www.tensorflow.org/api_docs/python/tf/keras/layers/BatchNormalization) (axis: Integer, the axis that should be normalized (typically the features axis))\n# - Zero padding: [See reference](https://www.tensorflow.org/api_docs/python/tf/keras/layers/ZeroPadding2D)\n# - Max pooling: [See reference](https://www.tensorflow.org/api_docs/python/tf/keras/layers/MaxPool2D)\n# - Fully connected layer: [See reference](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense)\n# - Addition: [See reference](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Add)\n\n# In[9]:\n\n\n# UNQ_C3\n# GRADED FUNCTION: ResNet50\n\ndef ResNet50(input_shape = (64, 64, 3), classes = 6):\n \"\"\"\n Stage-wise implementation of the architecture of the popular ResNet50:\n CONV2D -> BATCHNORM -> RELU -> MAXPOOL -> CONVBLOCK -> IDBLOCK*2 -> CONVBLOCK -> IDBLOCK*3\n -> CONVBLOCK -> IDBLOCK*5 -> CONVBLOCK -> IDBLOCK*2 -> AVGPOOL -> FLATTEN -> DENSE \n\n Arguments:\n input_shape -- shape of the images of the dataset\n classes -- integer, number of classes\n\n Returns:\n model -- a Model() instance in Keras\n \"\"\"\n \n # Define the input as a tensor with shape input_shape\n X_input = Input(input_shape)\n\n \n # Zero-Padding\n X = ZeroPadding2D((3, 3))(X_input)\n \n # Stage 1\n X = Conv2D(64, (7, 7), strides = (2, 2), kernel_initializer = glorot_uniform(seed=0))(X)\n X = BatchNormalization(axis = 3)(X)\n X = Activation('relu')(X)\n X = MaxPooling2D((3, 3), strides=(2, 2))(X)\n\n # Stage 2\n X = convolutional_block(X, f = 3, filters = [64, 64, 256], s = 1)\n X = identity_block(X, 3, [64, 64, 256])\n X = identity_block(X, 3, [64, 64, 256])\n\n ### START CODE HERE\n \n ## Stage 3 (≈4 lines)\n X = convolutional_block(X, f = 3, filters = [128,128,512], s = 2)\n X = identity_block(X, 3, [128,128,512]) \n X = identity_block(X, 3, [128,128,512])\n X = identity_block(X, 3, [128,128,512]) \n \n ## Stage 4 (≈6 lines)\n X = convolutional_block(X, f = 3, filters = [256,256,1024], s = 2) \n X = identity_block(X, 3, [256, 256, 1024]) \n X = identity_block(X, 3, [256, 256, 1024]) \n X = identity_block(X, 3, [256, 256, 1024]) \n X = identity_block(X, 3, [256, 256, 1024]) \n X = identity_block(X, 3, [256, 256, 1024]) \n\n ## Stage 5 (≈3 lines)\n X = convolutional_block(X, f = 3, filters = [512, 512, 2048], s = 2) \n X = identity_block(X, 3, [512, 512, 2048]) \n X = identity_block(X, 3, [512, 512, 2048]) \n\n ## AVGPOOL (≈1 line). Use \"X = AveragePooling2D(...)(X)\"\n X = X = AveragePooling2D((2,2))(X) \n \n ### END CODE HERE\n\n # output layer\n X = Flatten()(X)\n X = Dense(classes, activation='softmax', kernel_initializer = glorot_uniform(seed=0))(X)\n \n \n # Create model\n model = Model(inputs = X_input, outputs = X)\n\n return model\n\n\n# Run the following code to build the model's graph. If your implementation is incorrect, you'll know it by checking your accuracy when running `model.fit(...)` below.\n\n# In[10]:\n\n\nmodel = ResNet50(input_shape = (64, 64, 3), classes = 6)\nprint(model.summary())\n\n\n# In[11]:\n\n\nfrom outputs import ResNet50_summary\n\nmodel = ResNet50(input_shape = (64, 64, 3), classes = 6)\n\ncomparator(summary(model), ResNet50_summary)\n\n\n# As shown in the Keras Tutorial Notebook, prior to training a model, you need to configure the learning process by compiling the model.\n\n# In[12]:\n\n\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n\n# The model is now ready to be trained. The only thing you need now is a dataset!\n\n# Let's load your old friend, the SIGNS dataset.\n# \n# \n#
Figure 6 : SIGNS dataset
\n# \n\n# In[13]:\n\n\nX_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()\n\n# Normalize image vectors\nX_train = X_train_orig / 255.\nX_test = X_test_orig / 255.\n\n# Convert training and test labels to one hot matrices\nY_train = convert_to_one_hot(Y_train_orig, 6).T\nY_test = convert_to_one_hot(Y_test_orig, 6).T\n\nprint (\"number of training examples = \" + str(X_train.shape[0]))\nprint (\"number of test examples = \" + str(X_test.shape[0]))\nprint (\"X_train shape: \" + str(X_train.shape))\nprint (\"Y_train shape: \" + str(Y_train.shape))\nprint (\"X_test shape: \" + str(X_test.shape))\nprint (\"Y_test shape: \" + str(Y_test.shape))\n\n\n# Run the following cell to train your model on 10 epochs with a batch size of 32. On a GPU, it should take less than 2 minutes. \n\n# In[14]:\n\n\nmodel.fit(X_train, Y_train, epochs = 10, batch_size = 32)\n\n\n# **Expected Output**:\n# \n# ```\n# Epoch 1/10\n# 34/34 [==============================] - 1s 34ms/step - loss: 1.9241 - accuracy: 0.4620\n# Epoch 2/10\n# 34/34 [==============================] - 2s 57ms/step - loss: 0.6403 - accuracy: 0.7898\n# Epoch 3/10\n# 34/34 [==============================] - 1s 24ms/step - loss: 0.3744 - accuracy: 0.8731\n# Epoch 4/10\n# 34/34 [==============================] - 2s 44ms/step - loss: 0.2220 - accuracy: 0.9231\n# Epoch 5/10\n# 34/34 [==============================] - 2s 57ms/step - loss: 0.1333 - accuracy: 0.9583\n# Epoch 6/10\n# 34/34 [==============================] - 2s 52ms/step - loss: 0.2243 - accuracy: 0.9444\n# Epoch 7/10\n# 34/34 [==============================] - 2s 48ms/step - loss: 0.2913 - accuracy: 0.9102\n# Epoch 8/10\n# 34/34 [==============================] - 1s 30ms/step - loss: 0.2269 - accuracy: 0.9306\n# Epoch 9/10\n# 34/34 [==============================] - 2s 46ms/step - loss: 0.1113 - accuracy: 0.9630\n# Epoch 10/10\n# 34/34 [==============================] - 2s 57ms/step - loss: 0.0709 - accuracy: 0.9778\n# ```\n# \n# The exact values could not match, but don't worry about that. The important thing that you must see is that the loss value decreases, and the accuracy increases for the firsts 5 epochs.\n\n# Let's see how this model (trained on only two epochs) performs on the test set.\n\n# In[15]:\n\n\npreds = model.evaluate(X_test, Y_test)\nprint (\"Loss = \" + str(preds[0]))\nprint (\"Test Accuracy = \" + str(preds[1]))\n\n\n# **Expected Output**:\n# \n# \n# \n# \n# \n# \n# \n#
\n# Test Accuracy\n# \n# >0.80\n#
\n\n# For the purposes of this assignment, you've been asked to train the model for ten epochs. You can see that it performs well. The online grader will only run your code for a small number of epochs as well. Please go ahead and submit your assignment. \n\n# After you have finished this official (graded) part of this assignment, you can also optionally train the ResNet for more iterations, if you want. It tends to get much better performance when trained for ~20 epochs, but this does take more than an hour when training on a CPU. \n# \n# Using a GPU, this ResNet50 model's weights were trained on the SIGNS dataset. You can load and run the trained model on the test set in the cells below. It may take ≈1min to load the model. Have fun! \n\n# In[16]:\n\n\npre_trained_model = tf.keras.models.load_model('resnet50.h5')\n\n\n# In[17]:\n\n\npreds = pre_trained_model.evaluate(X_test, Y_test)\nprint (\"Loss = \" + str(preds[0]))\nprint (\"Test Accuracy = \" + str(preds[1]))\n\n\n# **Congratulations** on finishing this assignment! You've now implemented a state-of-the-art image classification system! Woo hoo! \n# \n# ResNet50 is a powerful model for image classification when it's trained for an adequate number of iterations. Hopefully, from this point, you can use what you've learned and apply it to your own classification problem to perform state-of-the-art accuracy.\n\n# \n# \n# **What you should remember**:\n# \n# - Very deep \"plain\" networks don't work in practice because vanishing gradients make them hard to train. \n# - Skip connections help address the Vanishing Gradient problem. They also make it easy for a ResNet block to learn an identity function. \n# - There are two main types of blocks: The **identity block** and the **convolutional block**. \n# - Very deep Residual Networks are built by stacking these blocks together.\n\n# \n# ## 5 - Test on Your Own Image (Optional/Ungraded)\n\n# If you wish, you can also take a picture of your own hand and see the output of the model. To do this:\n# 1. Click on \"File\" in the upper bar of this notebook, then click \"Open\" to go on your Coursera Hub.\n# 2. Add your image to this Jupyter Notebook's directory, in the \"images\" folder\n# 3. Write your image's name in the following code\n# 4. Run the code and check if the algorithm is right! \n\n# In[ ]:\n\n\nimg_path = 'images/my_image.jpg'\nimg = image.load_img(img_path, target_size=(64, 64))\nx = image.img_to_array(img)\nx = np.expand_dims(x, axis=0)\nx = x/255.0\nprint('Input image shape:', x.shape)\nimshow(img)\nprediction = pre_trained_model.predict(x)\nprint(\"Class prediction vector [p(0), p(1), p(2), p(3), p(4), p(5)] = \", prediction)\nprint(\"Class:\", np.argmax(prediction))\n\n\n# Even though the model has high accuracy, it might be performing poorly on your own set of images. Notice that, the shape of the pictures, the lighting where the photos were taken, and all of the preprocessing steps can have an impact on the performance of the model. Considering everything you have learned in this specialization so far, what do you think might be the cause here?\n# \n# *Hint*: It might be related to some distributions. Can you come up with a potential solution ?\n\n# You can also print a summary of your model by running the following code.\n\n# In[ ]:\n\n\npre_trained_model.summary()\n\n\n# \n# ## 6 - Bibliography\n# \n# This notebook presents the ResNet algorithm from He et al. (2015). The implementation here also took significant inspiration and follows the structure given in the GitHub repository of Francois Chollet: \n# \n# - Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun - [Deep Residual Learning for Image Recognition (2015)](https://arxiv.org/abs/1512.03385)\n# - Francois Chollet's GitHub repository: https://github.com/fchollet/deep-learning-models/blob/master/resnet50.py\n# \n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "4c62bdd805802b6fc332936b33fe4d2b04208d62", "size": 34144, "ext": "py", "lang": "Python", "max_stars_repo_path": "4 - Convolutional Neural Networks/Residual_Networks.py", "max_stars_repo_name": "pouyalj/DeepLearningCoursera", "max_stars_repo_head_hexsha": "4c0d79a53bbdd24fbb77503fed35e73d24949be2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-01T00:14:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-01T00:14:18.000Z", "max_issues_repo_path": "4 - Convolutional Neural Networks/Residual_Networks.py", "max_issues_repo_name": "pouyalj/DeepLearningCoursera", "max_issues_repo_head_hexsha": "4c0d79a53bbdd24fbb77503fed35e73d24949be2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4 - Convolutional Neural Networks/Residual_Networks.py", "max_forks_repo_name": "pouyalj/DeepLearningCoursera", "max_forks_repo_head_hexsha": "4c0d79a53bbdd24fbb77503fed35e73d24949be2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.2254495159, "max_line_length": 401, "alphanum_fraction": 0.6871192596, "include": true, "reason": "import numpy,import scipy", "num_tokens": 9730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.396068180531364, "lm_q2_score": 0.25386101825929835, "lm_q1q2_score": 0.10054627160979968}}