PK\NC,ZZradiotools/__init__.py """A tool package for cosmic-ray and neutrino radio detectors.""" __version__ = '0.1.0'PK[Nىt**radiotools/coordinatesystems.py#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import math from numpy.linalg import linalg import copy from radiotools import helper as hp class cstrafo(): """ class to performe coordinate transformations typically used in air shower radio detection the following transformations are implemented: From the cartesian ground coordinate system (x: East, y: North, z: up) to * to the vxB-vx(vxB) system * to the on-sky coordinate system (spherical coordinates eR, eTheta, ePhi) * to a ground coordinate system where the y-axis is oriented to magnetic North (instead of geographic North) and vice versa. """ def __init__(self, zenith, azimuth, magnetic_field_vector=None, site=None): """ Initialization with signal/air-shower direction and magnetic field configuration. All parameters should be specified according to the default coordinate system of the radiotools package (the Auger coordinate system). Parameters ---------- zenith : float zenith angle of the incoming signal/air-shower direction (0 deg is pointing to the zenith) azimuth : float azimuth angle of the incoming signal/air-shower direction (0 deg is North, 90 deg is South) magnetic_field_vector (optional): 3-vector, default None the magnetic field vector in the cartesian ground coordinate system, if no magnetic field vector is specified, the default value for the site specified in the 'site' function argument is used. site (optional): string, default 'Auger' this argument has only effect it 'magnetic_field_vector' is None the site for which the magnetic field vector should be used. Currently, default values for for the sites 'auger' and 'arianna' are available """ showeraxis = -1 * hp.spherical_to_cartesian(zenith, azimuth) # -1 is because shower is propagating towards us if(magnetic_field_vector is None): magnetic_field_vector = hp.get_magnetic_field_vector(site=site) magnetic_field_normalized = magnetic_field_vector / linalg.norm(magnetic_field_vector) vxB = np.cross(showeraxis, magnetic_field_normalized) e1 = vxB e2 = np.cross(showeraxis, vxB) e3 = np.cross(e1, e2) e1 /= linalg.norm(e1) e2 /= linalg.norm(e2) e3 /= linalg.norm(e3) self.__transformation_matrix_vBvvB = copy.copy(np.matrix([e1, e2, e3])) self.__inverse_transformation_matrix_vBvvB = np.linalg.inv(self.__transformation_matrix_vBvvB) # initilize transformation matrix to on-sky coordinate system (er, etheta, ephi) ct = np.cos(zenith) st = np.sin(zenith) cp = np.cos(azimuth) sp = np.sin(azimuth) e1 = np.array([st * cp, st * sp, ct]) e2 = np.array([ct * cp, ct * sp, -st]) e3 = np.array([-sp, cp, 0]) self.__transformation_matrix_onsky = copy.copy(np.matrix([e1, e2, e3])) self.__inverse_transformation_matrix_onsky = np.linalg.inv(self.__transformation_matrix_onsky) # initilize transformation matrix from magnetic north to geographic north coordinate system declination = hp.get_declination(magnetic_field_vector) c = np.cos(-1 * declination) s = np.sin(-1 * declination) e1 = np.array([c, -s, 0]) e2 = np.array([s, c, 0]) e3 = np.array([0, 0, 1]) self.__transformation_matrix_magnetic = copy.copy(np.matrix([e1, e2, e3])) self.__inverse_transformation_matrix_magnetic = np.linalg.inv(self.__transformation_matrix_magnetic) # initilize transformation matrix from ground (geographic) cs to ground cs where x axis points into shower direction projected on ground c = np.cos(-1 * azimuth) s = np.sin(-1 * azimuth) e1 = np.array([c, -s, 0]) e2 = np.array([s, c, 0]) e3 = np.array([0, 0, 1]) self.__transformation_matrix_azimuth = copy.copy(np.matrix([e1, e2, e3])) self.__inverse_transformation_matrix_azimuth = np.linalg.inv(self.__transformation_matrix_azimuth) # def __transform(self, positions, matrix): # if(len(positions.shape) == 1): # temp = np.squeeze(np.asarray(np.dot(matrix, positions.T).T)) # return temp # else: # result = np.zeros_like(positions) # for i, pos in enumerate(positions): # temp = np.squeeze(np.asarray(np.dot(matrix, pos))) # result[i] = temp # return result def __transform(self, positions, matrix): return np.squeeze(np.asarray(np.dot(matrix, positions))) def transform_from_ground_to_onsky(self, positions): """ on sky coordinates are eR, eTheta, ePhi """ return self.__transform(positions, self.__transformation_matrix_onsky) def transform_from_onsky_to_ground(self, positions): """ on sky coordinates are eR, eTheta, ePhi """ return self.__transform(positions, self.__inverse_transformation_matrix_onsky) def transform_from_magnetic_to_geographic(self, positions): return self.__transform(positions, self.__transformation_matrix_magnetic) def transform_from_geographic_to_magnetic(self, positions): return self.__transform(positions, self.__inverse_transformation_matrix_magnetic) def transform_from_azimuth_to_geographic(self, positions): return self.__transform(positions, self.__transformation_matrix_azimuth) def transform_from_geographic_to_azimuth(self, positions): return self.__transform(positions, self.__inverse_transformation_matrix_azimuth) def transform_to_vxB_vxvxB(self, station_position, core=None): """ transform a single station position or a list of multiple station positions into vxB, vxvxB shower plane This function is supposed to transform time traces with the shape (number of polarizations, length of trace) and a list of station positions with the shape of (length of list, 3). The function automatically differentiates between the two cases by checking the length of the second dimension. If this dimension is '3', a list of station positions is assumed to be the input. Note: this logic will fail if a trace will have a shape of (3, 3), which is however unlikely to happen. """ # to keep station_position constant (for the outside) if(core is not None): station_position = np.array(copy.deepcopy(station_position)) # if a single station position is transformed: (3,) -> (1, 3) if station_position.ndim == 1: station_position = np.expand_dims(station_position, axis=0) nX, nY = station_position.shape if(nY != 3): return self.__transform(station_position, self.__transformation_matrix_vBvvB) else: result = [] for pos in station_position: if(core is not None): pos -= core result.append(np.squeeze(np.asarray(np.dot(self.__transformation_matrix_vBvvB, pos)))) return np.squeeze(np.array(result)) def transform_from_vxB_vxvxB(self, station_position, core=None): """ transform a single station position or a list of multiple station positions back to x,y,z CS This function is supposed to transform time traces with the shape (number of polarizations, length of trace) and a list of station positions with the shape of (length of list, 3). The function automatically differentiates between the two cases by checking the length of the second dimension. If this dimension is '3', a list of station positions is assumed to be the input. Note: this logic will fail if a trace will have a shape of (3, 3), which is however unlikely to happen. """ # to keep station_position constant (for the outside) if(core is not None): station_position = np.array(copy.deepcopy(station_position)) # if a single station position is transformed: (3,) -> (1, 3) if station_position.ndim == 1: station_position = np.expand_dims(station_position, axis=0) nX, nY = station_position.shape if(nY != 3): return self.__transform(station_position, self.__inverse_transformation_matrix_vBvvB) else: result = [] for pos in station_position: temp = np.squeeze(np.asarray(np.dot(self.__inverse_transformation_matrix_vBvvB, pos))) if(core is not None): result.append(temp + core) else: result.append(temp) return np.squeeze(np.array(result)) def transform_from_vxB_vxvxB_2D(self, station_position, core=None): """ transform a single station position or a list of multiple station positions back to x,y,z CS """ # to keep station_position constant (for the outside) if(core is not None): station_position = np.array(copy.deepcopy(station_position)) # if a single station position is transformed: (3,) -> (1, 3) if station_position.ndim == 1: station_position = np.expand_dims(station_position, axis=0) result = [] for pos in station_position: position = np.array([pos[0], pos[1], self.get_height_in_showerplane(pos[0], pos[1])]) pos_transformed = np.squeeze(np.asarray(np.dot(self.__inverse_transformation_matrix_vBvvB, position))) if(core is not None): pos_transformed += core result.append(pos_transformed) return np.squeeze(np.array(result)) def get_height_in_showerplane(self, x, y): return -1. * (self.__transformation_matrix_vBvvB[0, 2] * x + self.__transformation_matrix_vBvvB[1, 2] * y) / self.__transformation_matrix_vBvvB[2, 2] def get_euler_angles(self): R = self.__transformation_matrix_vBvvB if(abs(R[2, 0]) != 1): theta_1 = -math.asin(R[2, 0]) theta_2 = math.pi - theta_1 psi_1 = math.atan2(R[2, 1] / math.cos(theta_1), R[2, 2] / math.cos(theta_1)) psi_2 = math.atan2(R[2, 1] / math.cos(theta_2), R[2, 2] / math.cos(theta_2)) phi_1 = math.atan2(R[1, 0] / math.cos(theta_1), R[0, 0] / math.cos(theta_1)) phi_2 = math.atan2(R[1, 0] / math.cos(theta_2), R[0, 0] / math.cos(theta_2)) else: phi_1 = 0. if(R[2, 0] == -1): theta_1 = math.pi * 0.5 psi_1 = phi_1 + math.atan2(R[0, 1], R[0, 2]) else: theta_1 = -1. * math.pi * 0.5 psi_1 = -phi_1 + math.atan2(-R[0, 1], -R[0, 2]) return psi_1, theta_1, phi_1 PK[N 8fnfnradiotools/helper.py#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function # , unicode_literals import numpy as np def linear_to_dB(linear): """ conversion to decibel scale Parameters ------------ linear : float quantity in linear units Returns -------- dB : float quantity in dB units """ return 10 * np.log10(linear) def dB_to_linear(dB): """ conversion from decibel scale to linear scale Parameters ------------ dB : float quantity in dB units Returns -------- linear : float quantity in linear units """ return 10 ** (dB / 10.) def gps_to_datetime(gps): """ conversion between GPS seconds and a python datetime object (taking into account leap seconds) """ from radiotools import leapseconds from datetime import datetime, timedelta return leapseconds.gps_to_utc(datetime(1980, 1, 6) + timedelta(seconds=gps)) def datetime_to_gps(date): from radiotools import leapseconds from datetime import datetime return (leapseconds.utc_to_gps(date) - datetime(1980, 1, 6)).total_seconds() def GPS_to_UTC(gps): offset = 315964800 + 16 return gps + offset def UTC_to_GPS(utc): return utc - GPS_to_UTC(0) def datetime_to_UTC(dt): import calendar return calendar.timegm(dt.timetuple()) def spherical_to_cartesian(zenith, azimuth): sinZenith = np.sin(zenith) x = sinZenith * np.cos(azimuth) y = sinZenith * np.sin(azimuth) z = np.cos(zenith) if hasattr(zenith, '__len__') and hasattr(azimuth, '__len__'): return np.array(zip(x, y, z)) else: return np.array([x, y, z]) def cartesian_to_spherical(x, y, z): # normlize vector norm = (x ** 2 + y ** 2 + z ** 2) ** 0.5 x2 = x / norm y2 = y / norm z2 = z / norm theta = 0 if hasattr(x, '__len__') and hasattr(y, '__len__')and hasattr(z, '__len__'): theta = np.zeros_like(x) theta[z2 < 1] = np.arccos(z2[z2 < 1]) phi = np.arctan2(y2, x2) return theta, phi else: if (z2 < 1): theta = np.arccos(z2) phi = np.arctan2(y2, x2) return theta, phi def get_angle(v1, v2): arccos = np.dot(v1, v2) / (np.linalg.norm(v1.T, axis=0) * np.linalg.norm(v2.T, axis=0)) # catch numerical overlow mask1 = arccos > 1 mask2 = arccos < -1 mask = np.logical_or(mask1, mask2) if (type(mask) != np.bool_): arccos[mask] = 1 arccos[mask] = -1 else: if (mask): arccos = 1 return np.arccos(arccos) def get_rotation(v1, v2): """ calculates the rotation matrix to transform vector 1 to vector 2 """ v = np.cross(v1, v2) phi = get_angle(v1, v2) v_x = np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]]) vx2 = np.matmul(v_x, v_x) return np.identity(3) + v_x + vx2 * 1. / (1 + np.cos(phi)) def get_normalized_angle(angle, degree=False, interval=np.deg2rad([0, 360])): import collections if degree: interval = np.rad2deg(interval) delta = interval[1] - interval[0] if(isinstance(angle, (collections.Sequence, np.ndarray))): angle[angle >= interval[1]] -= delta angle[angle < interval[0]] += delta else: while (angle >= interval[1]): angle -= delta while (angle < interval[0]): angle += delta return angle def get_declination(magnetic_field_vector): declination = np.arccos(np.dot(np.array([0, 1]), magnetic_field_vector[:2] / np.linalg.norm(magnetic_field_vector[:2]))) return declination def get_magnetic_field_vector(site=None): """ get the geomagnetic field vector in Gauss. x points to geographic East and y towards geographic North """ magnetic_fields = {'auger': np.array([0.00871198, 0.19693423, 0.1413841]), 'mooresbay': np.array([0.058457, -0.09042, 0.61439]), 'southpole': np.array([-0.14390398, 0.08590658, 0.52081228])} # position of SP arianna station if site is None: site = 'auger' return magnetic_fields[site] # # Magnetic Field Vector in Argentina # Bzenith = np.deg2rad(54.351) # Bazimuth = np.deg2rad(87.467) # vec = spherical_to_cartesian(Bzenith, Bazimuth) # vec *= 0.242587 def get_angle_to_magnetic_field_vector(zenith, azimuth, site=None): """ returns the angle between shower axis and magnetic field """ magnetic_field = get_magnetic_field_vector(site=site) v = spherical_to_cartesian(zenith, azimuth) return get_angle(magnetic_field, v) def get_magneticfield_azimuth(magnetic_field_declination): return magnetic_field_declination + np.deg2rad(90) def get_inclination(magnetic_field_vector): zenith, azimuth = cartesian_to_spherical(*magnetic_field_vector) return np.deg2rad(90) - zenith def get_magneticfield_zenith(magnetic_field_inclination): if (magnetic_field_inclination < 0): return magnetic_field_inclination + np.deg2rad(90) else: return np.deg2rad(90) - magnetic_field_inclination def get_magnetic_field_vector_from_inc(inclination, declination): return spherical_to_cartesian(get_magneticfield_zenith(inclination), get_magneticfield_azimuth(declination)) def get_lorentzforce_vector(zenith, azimuth, magnetic_field_vector=None): if (magnetic_field_vector is None): magnetic_field_vector = get_magnetic_field_vector() showerAxis = spherical_to_cartesian(zenith, azimuth) magnetic_field_vector_normalized = magnetic_field_vector / \ np.linalg.norm(magnetic_field_vector.T, axis=0, keepdims=True).T return np.cross(showerAxis, magnetic_field_vector_normalized) def get_sine_angle_to_lorentzforce(zenith, azimuth, magnetic_field_vector=None): # we use the tanspose of the vector or matrix to be able to always use # axis=0 return np.linalg.norm(get_lorentzforce_vector(zenith, azimuth, magnetic_field_vector).T, axis=0) def get_chargeexcess_vector(core, zenith, azimuth, stationPosition): showerAxis = spherical_to_cartesian(zenith, azimuth) magnitues = np.dot((stationPosition - core), showerAxis) showerAxis = np.outer(magnitues, showerAxis) chargeExcessVector = core - stationPosition + showerAxis norm = np.linalg.norm(chargeExcessVector.T, axis=0) chargeExcessVector = (chargeExcessVector.T / norm).T return np.squeeze(chargeExcessVector) def get_chargeexcess_correction_factor(core, zenithSd, azimuthSd, stationPositions, a=0.14, magnetic_field_vector=None): chargeExcessVector = get_chargeexcess_vector(core, zenithSd, azimuthSd, stationPositions) LorentzVector = get_lorentzforce_vector(zenithSd, azimuthSd, magnetic_field_vector) correctionFactor = np.linalg.norm((LorentzVector + a * chargeExcessVector).T, axis=0) return correctionFactor def get_polarization_vector_max(trace): """ calculates polarization vector of efield trace (vector at maximum pulse position) """ from scipy.signal import hilbert h = np.sqrt(np.sum(np.abs(hilbert(trace)) ** 2, axis=0)) max_pos = h.argmax() pol = trace[:, max_pos] return pol def get_interval(trace, scale=0.5): h = np.abs(trace) max_pos = h.argmax() n_samples = trace.T.shape[0] h_max = h.max() up_pos = max_pos low_pos = max_pos for i in xrange(max_pos, n_samples): if (h[i] < h_max * scale): up_pos = i break for i in range(0, max_pos)[::-1]: if (h[i] < h_max * scale): low_pos = i break return low_pos, up_pos def get_interval_hilbert(trace, scale=0.5): from scipy.signal import hilbert d = len(trace.shape) if (d == 1): h = np.abs(hilbert(trace)) elif (d == 2): h = np.sqrt(np.sum(np.abs(hilbert(trace)) ** 2, axis=0)) else: print("ERROR, trace has not the correct dimension") raise return get_interval(h, scale) def get_FWHM_hilbert(trace): return get_interval_hilbert(trace, scale=0.5) def get_polarization_vector_FWHM(trace): """ calculates polarization vector of efield trace, all vectors in the FWHM interval are averaged, the amplitude is set to the maximum of the hilbert envelope """ from scipy.signal import hilbert h = np.sqrt(np.sum(np.abs(hilbert(trace)) ** 2, axis=0)) max_pos = h.argmax() h_max = h.max() low_pos, up_pos = get_FWHM_hilbert(trace) sign = np.expand_dims(np.sign(trace[:, max_pos]), axis=1) * np.ones(up_pos - low_pos) pol = np.mean(sign * np.abs(trace[:, low_pos: up_pos]), axis=-1) pol /= np.linalg.norm(pol) * h_max return pol def get_expected_efield_vector(core, zenith, azimuth, stationPositions, a=0.14, magnetic_field_vector=None): chargeExcessVector = get_chargeexcess_vector(core, zenith, azimuth, stationPositions) LorentzVector = get_lorentzforce_vector(zenith, azimuth, magnetic_field_vector) return LorentzVector + a * chargeExcessVector def get_expected_efield_vector_vxB_vxvxB(station_positions, zenith, azimuth, a=.14): """ also returns the expected electric field vector, but station positions and the returned field vectors are in the vxB-vxvxB coordinate system """ alpha = get_angle_to_magnetic_field_vector(zenith, azimuth) e_geomagnetic = np.array([-np.sin(alpha), 0, 0]) e_charge_excess = -a * station_positions / np.linalg.norm(station_positions) return e_charge_excess + e_geomagnetic def get_angle_to_efieldexpectation_in_showerplane(efield, core, zenith, azimuth, stationPositions, a=0.14, magnetic_field_vector=None): """ calculated the angle between a measured efield vector and the expectation from the geomagnetic and chargeexcess emission model. Thereby, the angular difference is evaluated in the showerfront, components not perpendicular to the shower axis are thus neglected. """ if (efield.shape != stationPositions.shape): print("ERROR: shape of efield and station positions is not the same.") raise from CSTransformation import CSTransformation cs = CSTransformation(zenith, azimuth) efield_transformed = cs.transform_to_vxB_vxvxB(efield) # print "efieldtransformed ", efield_transformed if (len(stationPositions.shape) == 1): if (efield_transformed[0] > 0): efield_transformed *= -1. else: for i in xrange(len(efield_transformed)): if (efield_transformed[i][0] > 0): efield_transformed[i] *= -1. efield_expectations = get_expected_efield_vector(core, zenith, azimuth, stationPositions, a=a, magnetic_field_vector=magnetic_field_vector) exp_efields_transformed = cs.transform_to_vxB_vxvxB(efield_expectations) # print exp_efields_transformed # print exp_efields_transformed[..., 1] exp_phi = np.arctan2(exp_efields_transformed[..., 1], exp_efields_transformed[..., 0]) # print exp_phi phi = np.arctan2(efield_transformed[..., 1], efield_transformed[..., 0]) # print phi diff = exp_phi - phi if (len(stationPositions.shape) == 1): while (diff > np.pi): diff -= 2 * np.pi while (diff < -np.pi): diff += 2 * np.pi else: for i in xrange(len(diff)): while (diff[i] > np.pi): diff[i] -= 2 * np.pi while (diff[i] < -np.pi): diff[i] += 2 * np.pi return diff def get_distance_to_showeraxis(core, zenith, azimuth, antennaPosition): showerAxis = spherical_to_cartesian(zenith, azimuth) showerAxis = core + showerAxis num = np.linalg.norm(np.cross( antennaPosition - core, antennaPosition - showerAxis).T, axis=0) den = np.linalg.norm((showerAxis - core).T, axis=0) return num / den def get_position_at_height(pos, height, zenith, azimuth): ez = np.array([0, 0, 1.]) # t = pos * ez - np.outer(ez, height) # print t # t = np.array([0, 0, pos[2] - height]) n = spherical_to_cartesian(zenith, azimuth) # print n # print "(ez * t)", np.inner(ez, t) # print "(ez * n)", np.inner(ez, n) scaling = (pos[2] - height) / n[2] # print "np.outer(scaling, n)", np.outer(scaling, n) pos = pos - np.outer(scaling, n) # print pos return pos def get_2d_probability(x, y, xx, yy, xx_error, yy_error, xy_correlation, sigma=False): from scipy.stats import multivariate_normal cov = np.array( [[xx_error ** 2, xx_error * yy_error * xy_correlation], [xx_error * yy_error * xy_correlation, yy_error ** 2]]) p = multivariate_normal.pdf([x, y], mean=[xx, yy], cov=cov) denom = (2 * np.pi * xx_error * yy_error * np.sqrt(1 - xy_correlation ** 2)) nom = np.exp(-1. / (2 * (1 - xy_correlation ** 2)) * ((x - xx) ** 2 / xx_error ** 2 + (y - yy) ** 2 / yy_error ** 2 - 2 * xy_correlation * (x - xx) * ( y - yy) / (xx_error * yy_error))) if sigma: from scipy.stats import chi2, norm # p = norm.cdf(i) - norm.cdf(-i) print("p = ", nom, denom, nom / denom, "sigma =", chi2.ppf(nom / denom, 1)) print("p = ", p) print(norm.ppf(nom / denom)) return chi2.ppf(nom / denom, 1) else: return nom / denom def is_equal(a, b, rel_precision=1e-5): if (a + b) != 0: if ((0.5 * abs(a - b) / (abs(a + b))) < rel_precision): return True else: return False else: if a == 0: return True else: if ((0.5 * abs(a - b) / (abs(a) + abs(b))) < rel_precision): return True else: return False def has_same_direction(zenith1, azimuth1, zenith2, azimuth2, distancecut=20): distancecut = np.deg2rad(distancecut) axis1 = spherical_to_cartesian(zenith1, azimuth1) axis2 = spherical_to_cartesian(zenith2, azimuth2) diff = get_angle(axis1, axis2) if (diff < distancecut): return True else: return False def get_cherenkov_angle(h, model=1): """ returns the cherenkov angle for the density at height above ground assuming that the particle speed is the speed of light """ from radiotools.atmosphere import models as atm return np.arccos(1. / (atm.get_n(h, model=model))) def get_cherenkov_ellipse(zenith, xmax, model=1): """ returns the major and minor axis of the cherenkov cone projected on the ground plane reference: 10.1016/j.astropartphys.2014.04.004 """ from radiotools.atmosphere import models as atm h = atm.get_vertical_height(xmax, model=model) / np.cos(zenith) cherenkov = get_cherenkov_angle(h, model=model) ra = (np.tan(zenith + cherenkov) - np.tan(zenith)) * h rb = np.tan(cherenkov) / np.cos(zenith) * h return ra, rb def gaisser_hillas1_parametric(x, xmax, nmax=1): """ return one parametric form of Gaisser-Hillers function Reference: http://en.wikipedia.org/wiki/Gaisser%E2%80%93Hillas_function and Darko Veberic (2012). "Lambert W Function for Applications in Physics". Computer Physics Communications 183 (12): 2622–2628. arXiv:1209.0735. doi:10.1016/j.cpc.2012.07.008. """ return nmax * (x / xmax) ** xmax * np.exp(xmax - x) def gaisser_hillas(X, xmax, X0, lam, nmax=1): """ returns the Gaisser-Hillers function Reference: http://en.wikipedia.org/wiki/Gaisser%E2%80%93Hillas_function """ return nmax * ((X - X0) / (xmax - X0)) ** ((xmax - X0) / lam) * np.exp((xmax - X) / lam) def is_confined(x, y, station_positions, delta_confinement=0): """ returns True if core (x, y coordinate) is confined within stations given by 'station_positions'. If the 'delta_confinement' parameter is given, the stations need this minimum distance to the core for the core to be confined. """ is_confined = ( np.bool(np.sum([((x - delta_confinement) > sp_x and (y - delta_confinement) > sp_y) for (sp_x, sp_y, sp_z) in station_positions])) and np.bool(np.sum([((x - delta_confinement) > sp_x and (y + delta_confinement) < sp_y) for (sp_x, sp_y, sp_z) in station_positions])) and np.bool(np.sum([((x + delta_confinement) < sp_x and (y - delta_confinement) > sp_y) for (sp_x, sp_y, sp_z) in station_positions])) and np.bool(np.sum([((x + delta_confinement) < sp_x and (y + delta_confinement) < sp_y) for (sp_x, sp_y, sp_z) in station_positions]))) return is_confined def is_confined_weak(x, y, station_positions, delta_confinement=0): """ returns True if core (x, y coordinate) is confined within stations given by 'station_positions'. If the 'delta_confinement' parameter is given, the stations need this minimum distance to the core for the core to be confined. The criterion is weaker than in isConfined(). Here, at least one station has to be above, below, left or right the core position.""" is_confined = ( np.bool(np.sum([((x - delta_confinement) > sp_x) for (sp_x, sp_y, sp_z) in station_positions])) and np.bool(np.sum([((x + delta_confinement) < sp_x) for (sp_x, sp_y, sp_z) in station_positions])) and np.bool(np.sum([((y - delta_confinement) > sp_y) for (sp_x, sp_y, sp_z) in station_positions])) and np.bool(np.sum([((y + delta_confinement) < sp_y) for (sp_x, sp_y, sp_z) in station_positions]))) return is_confined def in_hull(p, hull): # """ # Test if points in `p` are in `hull` # # `p` should be a `NxK` coordinates of `N` points in `K` dimensions # `hull` is either a scipy.spatial.Delaunay object or the `MxK` array of the # coordinates of `M` points in `K`dimensions for which Delaunay triangulation # will be computed # """ from scipy.spatial import Delaunay if not isinstance(hull, Delaunay): hull = Delaunay(hull) return hull.find_simplex(p) >= 0 def is_confined2(x, y, station_positions, delta_confinement=0): from scipy.spatial import Delaunay s1 = station_positions + np.array([delta_confinement, 0, 0]) s2 = station_positions + np.array([-1. * delta_confinement, 0, 0]) s3 = station_positions + np.array([0, delta_confinement, 0]) s4 = station_positions + np.array([0, -1. * delta_confinement, 0]) positions = np.append(np.append(s1, s2, axis=0), np.append(s3, s4, axis=0), axis=0) hull = Delaunay(positions[..., 0:2]) points = np.array([x, y]).T return np.array([in_hull(p, hull) for p in points], dtype=np.bool) def get_efield_in_shower_plane(ex, ey, ez, zenith, azimuth): e_theta = np.cos(zenith) * np.cos(azimuth) * ex + np.cos(zenith) * np.sin(azimuth) * ey - np.sin(zenith) * ez e_phi = -np.sin(azimuth) * ex + np.cos(azimuth) * ey e_r = np.sin(zenith) * np.cos(azimuth) * ex + np.sin(zenith) * np.sin(azimuth) * ey + np.cos(zenith) * ez return e_theta, e_phi, e_r def get_dirac_pulse(samples, binning=1., low_freq=30., up_freq=80.): """ generate dirac pulse """ from numpy import fft ff = fft.rfftfreq(samples, binning * 1e-9) * 1e-6 # frequencies in MHz dirac = np.zeros(samples) dirac[samples / 2] = 1 diracfft = fft.rfft(dirac) mask = (ff >= low_freq) & (ff <= up_freq) diracfft[~mask] = 0 dirac = fft.irfft(diracfft) dirac = dirac / abs(dirac).max() return dirac def rotate_vector_in_2d(v, angle): # rotate a 2d vector counter-clockwise rotation_matrix = np.array([[np.cos(angle), -np.sin(angle), 0], [np.sin(angle), np.cos(angle), 0], [0, 0, 1]]) v_rotated = np.dot(rotation_matrix, v) return v_rotated def get_sd_core_error_ellipse(easting_error, northing_error, error_correlation, p): """ returns semi major and semi minor axis of the confidence region with p-value p """ import scipy.stats cov = np.array([[easting_error ** 2, easting_error * northing_error * error_correlation], [easting_error * northing_error * error_correlation, northing_error ** 2]]) chi_2 = scipy.stats.chi2.isf(1 - p, 2) eigen_values, eigen_vectors = np.linalg.eig(cov) eigen_vector_1 = np.array([eigen_vectors[0][0], eigen_vectors[1][0], 0]) eigen_vector_2 = np.array([eigen_vectors[0][1], eigen_vectors[1][1], 0]) axis_1 = eigen_vector_1 * np.sqrt(chi_2 * eigen_values[0]) axis_2 = eigen_vector_2 * np.sqrt(chi_2 * eigen_values[1]) if eigen_values[0] >= eigen_values[1]: return [axis_1, axis_2] else: return [axis_2, axis_1] def transform_error_ellipse_into_vxB_vxvxB(semi_major_axis, semi_minor_axis, zenith, azimuth): """ accepts semi major and semi minor axis of an ellipse in standard auger coordinates. transforms the ellipse into vxB-vxvxB system and projects it onto the vxB-vxvxB_plane. returns the semi major and semi minor axis of the result. """ import coordinatesystems cs = coordinatesystems.cstrafo(zenith, azimuth) axis_1_vxB_vxvxB = cs.transform_to_vxB_vxvxB(semi_major_axis) axis_2_vxB_vxvxB = cs.transform_to_vxB_vxvxB(semi_minor_axis) a_dot_b = axis_1_vxB_vxvxB[0] * axis_2_vxB_vxvxB[0] + axis_1_vxB_vxvxB[1] * axis_2_vxB_vxvxB[1] if a_dot_b == 0: return [[axis_1_vxB_vxvxB[0], axis_1_vxB_vxvxB[1]], [axis_2_vxB_vxvxB[0], axis_2_vxB_vxvxB[1]]] abs_a_squared = axis_1_vxB_vxvxB[0] ** 2 + axis_1_vxB_vxvxB[1] ** 2 abs_b_squared = axis_2_vxB_vxvxB[0] ** 2 + axis_2_vxB_vxvxB[1] ** 2 tan_phi_1 = -.5 * (abs_a_squared - abs_b_squared) / a_dot_b + np.sqrt( .25 * ((abs_a_squared - abs_b_squared) / a_dot_b) ** 2 + 1) tan_phi_2 = -.5 * (abs_a_squared - abs_b_squared) / a_dot_b - np.sqrt( .25 * ((abs_a_squared - abs_b_squared) / a_dot_b) ** 2 + 1) phi_1 = np.arctan(tan_phi_1) phi_2 = np.arctan(tan_phi_2) axis_1 = [axis_1_vxB_vxvxB[0] * np.cos(phi_1) + axis_2_vxB_vxvxB[0] * np.sin(phi_1), axis_1_vxB_vxvxB[1] * np.cos(phi_1) + axis_2_vxB_vxvxB[1] * np.sin(phi_1)] axis_2 = [axis_1_vxB_vxvxB[0] * np.cos(phi_2) + axis_2_vxB_vxvxB[0] * np.sin(phi_2), axis_1_vxB_vxvxB[1] * np.cos(phi_2) + axis_2_vxB_vxvxB[1] * np.sin(phi_2)] if axis_1[0] ** 2 + axis_1[1] ** 2 >= axis_2[0] ** 2 + axis_2[1] ** 2: return [axis_1, axis_2] else: return [axis_2, axis_1] def is_in_quantile(center, station_position, easting_error, northing_error, error_correlation, p): """ returns true if station_position is within the p-quantile around center, false otherwise """ import scipy.stats cov = np.array([[easting_error ** 2, easting_error * northing_error * error_correlation], [easting_error * northing_error * error_correlation, northing_error ** 2]]) cov_inv = np.linalg.inv(cov) diff = [center[0] - station_position[0], center[1] - station_position[1]] c = diff[0] * (cov_inv[0][0] * diff[0] + cov_inv[0][1] * diff[1]) + diff[1] * ( cov_inv[1][0] * diff[0] + cov_inv[1][1] * diff[1]) if c <= scipy.stats.chi2.isf(1 - p, 2): return True else: return False def get_ellipse_tangents_through_point(point, semi_major_axis, semi_minor_axis): """ determines the points where the tangents to an ellipse with given semi major and semi minor axis that go through point touch the ellipse. returns none if point is inside the ellipse """ theta = np.arctan2(semi_major_axis[1], semi_major_axis[0]) point_r = rotate_vector_in_2d([point[0], point[1], 0], -theta) r_major = np.sqrt(semi_major_axis[0] ** 2 + semi_major_axis[1] ** 2) r_minor = np.sqrt(semi_minor_axis[0] ** 2 + semi_minor_axis[1] ** 2) divisor = point_r[1] ** 2 * r_major ** 2 + r_minor ** 2 * point_r[0] ** 2 if (point_r[0] / r_major) ** 2 + (point_r[1] / r_minor) ** 2 <= 1: return None square_root_term = (r_minor ** 2 * point_r[0] * r_major ** 2 / divisor) ** 2 + \ (point_r[1] ** 2 * r_major ** 4 - r_minor ** 2 * r_major ** 4) / divisor tan_1_x = r_minor ** 2 * point_r[0] / divisor + np.sqrt(square_root_term) tan_2_x = r_minor ** 2 * point_r[0] / divisor - np.sqrt(square_root_term) tan_1_y = r_minor ** 2 / point_r[1] - (r_minor / r_major) ** 2 * tan_1_x * point_r[0] / point_r[1] tan_2_y = r_minor ** 2 / point_r[1] - (r_minor / r_major) ** 2 * tan_2_x * point_r[0] / point_r[1] tan_1_r = np.array([tan_1_x, tan_1_y, 0]) tan_2_r = np.array([tan_2_x, tan_2_y, 0]) tan_1 = rotate_vector_in_2d(tan_1_r, theta) tan_2 = rotate_vector_in_2d(tan_2_r, theta) return [[tan_1[0], tan_1[1], 0], [tan_2[0], tan_2[1], 0]] def covariance_to_correlation(M): """ converts covariance matrix into correlation matrix """ D = np.diagflat(np.diag(M)) ** 0.5 Dinv = np.linalg.inv(D) return np.dot(Dinv, np.dot(M, Dinv)) def get_normalized_xcorr(trace1, trace2, mode='full'): from scipy.signal import correlate return correlate(trace1, trace2, mode=mode, method='auto') / (np.sum(trace1 ** 2) * np.sum(trace2 ** 2)) ** 0.5 def linreg(x, y): ''' Linear regression: returns the offset a and slope b for the function y_lin(x) = a + b*x that approximates the distribtion y(x) the best (sum of squares of residuals is minimized). input: x: array-like, values where y-values are valid y: array-like, must have same length as x, values y(x) output: a = offset of linear function resulting from regression b = slope of linear function resulting from regression ''' # number of observations/points n = np.size(x) # mean of x and y vector m_x, m_y = np.mean(x), np.mean(y) # calculating cross-deviation and deviation about x SS_xy = np.sum(y * x) - n * m_y * m_x SS_xx = np.sum(x * x) - n * m_x * m_x # calculating regression coefficients b = SS_xy / SS_xx # slope a = m_y - b * m_x # zero-offset return(a, b) # Test Code: if __name__ == "__main__": import radiotools.HelperFunctions as hp n = 10000 from radiotools.AERA import coordinates, signal_prediction stations = coordinates.get_stations_CRS() positions = np.array(stations.values()) positions_names = np.array(stations.keys()) de_mask = ~np.array([(x in coordinates.get_NL_stations()) for x in positions_names], dtype=np.bool) AERA24_mask = np.zeros(len(positions), dtype=np.bool) AERA24_mask[:23] = np.ones(23, dtype=np.bool) positions = positions[de_mask & AERA24_mask] positions_names = positions_names[de_mask & AERA24_mask] delta = 500. cores = np.array([np.random.uniform(positions[..., 0].min() - delta, positions[..., 0].max() + delta, n), np.random.uniform(positions[..., 1].min() - delta, positions[..., 1].max() + delta, n), np.zeros(n)]).T # distances = np.array([np.min(np.linalg.norm(c - positions, axis=-1)) for c in cores]) near_AERA_mask = hp.is_confined2(cores[..., 0], cores[..., 1], positions, delta_confinement=150) c = hp.is_confined2(cores[near_AERA_mask][..., 0], cores[near_AERA_mask][..., 1], positions, delta_confinement=0) print(100. * np.sum(c) / len(c)) import matplotlib.pyplot as plt plt.scatter(cores[near_AERA_mask][..., 0], cores[near_AERA_mask][..., 1]) plt.scatter(cores[near_AERA_mask][c][..., 0], cores[near_AERA_mask][c][..., 1]) plt.plot(positions[..., 0], positions[..., 1], "ok") positions2 = np.array(stations.values())[~(de_mask & AERA24_mask)] plt.plot(positions2[..., 0], positions2[..., 1], "ob") positions2 = np.array(stations.values())[~(de_mask)] plt.plot(positions2[..., 0], positions2[..., 1], "or") plt.xlim(-1e3, 100) plt.ylim(-1e3, 200) plt.show() pass PKpyyI8R((radiotools/leapseconds.py#!/usr/bin/env python """Get TAI-UTC difference in seconds for a given time using tzdata. i.e., find the number of seconds that must be added to UTC to compute TAI for any timestamp at or after the given time[1]. >>> from datetime import datetime >>> import leapseconds >>> leapseconds.dTAI_UTC_from_utc(datetime(2005, 1, 1)) datetime.timedelta(0, 32) >>> leapseconds.utc_to_tai(datetime(2015, 7, 1)) datetime.datetime(2015, 7, 1, 0, 0, 36) >>> leapseconds.tai_to_utc(datetime(2015, 7, 1, 0, 0, 36)) datetime.datetime(2015, 7, 1, 0, 0) >>> leapseconds.tai_to_utc(datetime(2015, 7, 1, 0, 0, 35)) # leap second datetime.datetime(2015, 7, 1, 0, 0) >>> leapseconds.tai_to_utc(datetime(2015, 7, 1, 0, 0, 34)) datetime.datetime(2015, 6, 30, 23, 59, 59) Python 2.6+, Python 3, Jython, Pypy support. [1]: https://github.com/eggert/tz/blob/master/leap-seconds.list [2]: https://github.com/eggert/tz/blob/master/tzfile.h [3]: https://github.com/eggert/tz/blob/master/zic.c [4]: http://datacenter.iers.org/eop/-/somos/5Rgv/latest/16 """ from __future__ import with_statement from collections import namedtuple from datetime import datetime, timedelta from struct import Struct from warnings import warn __all__ = ['leapseconds', 'LeapSecond', 'dTAI_UTC_from_utc', 'dTAI_UTC_from_tai', 'tai_to_utc', 'utc_to_tai', 'gps_to_utc', 'utc_to_gps', 'tai_to_gps', 'gps_to_tai'] __version__ = "0.1.0" # from timezone/tzfile.h [2] (the file is in public domain) """ struct tzhead { char tzh_magic[4]; /* TZ_MAGIC */ char tzh_version[1]; /* '\0' or '2' or '3' as of 2013 */ char tzh_reserved[15]; /* reserved--must be zero */ char tzh_ttisgmtcnt[4]; /* coded number of trans. time flags */ char tzh_ttisstdcnt[4]; /* coded number of trans. time flags */ char tzh_leapcnt[4]; /* coded number of leap seconds */ char tzh_timecnt[4]; /* coded number of transition times */ char tzh_typecnt[4]; /* coded number of local time types */ char tzh_charcnt[4]; /* coded number of abbr. chars */ }; # from zic.c[3] (the file is in public domain) convert(const int_fast32_t val, char *const buf) { register int i; register int shift; unsigned char *const b = (unsigned char *) buf; for (i = 0, shift = 24; i < 4; ++i, shift -= 8) b[i] = val >> shift; } # val = 0x12345678 # (val >> 24) & 0xff, (val >> 16) & 0xff, (val >> 8) & 0xff, val & 0xff # 0x12 0x34 0x56 0x78 # therefore "coded number" means big-endian 32-bit integer """ dTAI_GPS = timedelta(seconds=19) # constant offset LeapSecond = namedtuple('LeapSecond', 'utc dTAI_UTC') # tai = utc + dTAI_UTC sentinel = LeapSecond(utc=datetime.max, dTAI_UTC=timedelta(0)) def leapseconds(tzfiles=['/usr/share/zoneinfo/right/UTC', '/usr/lib/zoneinfo/right/UTC'], use_fallback=False): """Extract leap seconds from *tzfiles*.""" for filename in tzfiles: try: file = open(filename, 'rb') except IOError: continue else: break else: # no break if not use_fallback: raise ValueError('Unable to open any tzfile: %s' % (tzfiles,)) else: return _fallback() with file: header = Struct('>4s c 15x 6i') # see struct tzhead above (magic, version, _, _, leapcnt, timecnt, typecnt, charcnt) = header.unpack_from(file.read(header.size)) if magic != "TZif".encode(): raise ValueError('Wrong magic %r in tzfile: %s' % ( magic, file.name)) if version not in '\x0023'.encode(): warn('Unsupported version %r in tzfile: %s' % ( version, file.name), RuntimeWarning) if leapcnt == 0: raise ValueError("No leap seconds in tzfile: %s" % ( file.name)) """# from tzfile.h[2] (the file is in public domain) . . .header followed by. . . tzh_timecnt (char [4])s coded transition times a la time(2) tzh_timecnt (unsigned char)s types of local time starting at above tzh_typecnt repetitions of one (char [4]) coded UT offset in seconds one (unsigned char) used to set tm_isdst one (unsigned char) that's an abbreviation list index tzh_charcnt (char)s '\0'-terminated zone abbreviations tzh_leapcnt repetitions of one (char [4]) coded leap second transition times one (char [4]) total correction after above """ file.read(timecnt * 5 + typecnt * 6 + charcnt) # skip result = [LeapSecond(datetime(1972, 1, 1), timedelta(seconds=10))] nleap_seconds = 10 tai_epoch_as_tai = datetime(1970, 1, 1, 0, 0, 10) buf = Struct(">2i") for _ in range(leapcnt): # read leap seconds t, cnt = buf.unpack_from(file.read(buf.size)) dTAI_UTC = nleap_seconds + cnt utc = tai_epoch_as_tai + timedelta(seconds=t - dTAI_UTC + 1) assert utc - datetime(utc.year, utc.month, utc.day) == timedelta(0) result.append(LeapSecond(utc, timedelta(seconds=dTAI_UTC))) result.append(sentinel) return result def _fallback(): """Leap seconds list if no tzfiles are available.""" return [ LeapSecond(utc=datetime(1972, 1, 1, 0, 0), dTAI_UTC=timedelta(0, 10)), LeapSecond(utc=datetime(1972, 7, 1, 0, 0), dTAI_UTC=timedelta(0, 11)), LeapSecond(utc=datetime(1973, 1, 1, 0, 0), dTAI_UTC=timedelta(0, 12)), LeapSecond(utc=datetime(1974, 1, 1, 0, 0), dTAI_UTC=timedelta(0, 13)), LeapSecond(utc=datetime(1975, 1, 1, 0, 0), dTAI_UTC=timedelta(0, 14)), LeapSecond(utc=datetime(1976, 1, 1, 0, 0), dTAI_UTC=timedelta(0, 15)), LeapSecond(utc=datetime(1977, 1, 1, 0, 0), dTAI_UTC=timedelta(0, 16)), LeapSecond(utc=datetime(1978, 1, 1, 0, 0), dTAI_UTC=timedelta(0, 17)), LeapSecond(utc=datetime(1979, 1, 1, 0, 0), dTAI_UTC=timedelta(0, 18)), LeapSecond(utc=datetime(1980, 1, 1, 0, 0), dTAI_UTC=timedelta(0, 19)), LeapSecond(utc=datetime(1981, 7, 1, 0, 0), dTAI_UTC=timedelta(0, 20)), LeapSecond(utc=datetime(1982, 7, 1, 0, 0), dTAI_UTC=timedelta(0, 21)), LeapSecond(utc=datetime(1983, 7, 1, 0, 0), dTAI_UTC=timedelta(0, 22)), LeapSecond(utc=datetime(1985, 7, 1, 0, 0), dTAI_UTC=timedelta(0, 23)), LeapSecond(utc=datetime(1988, 1, 1, 0, 0), dTAI_UTC=timedelta(0, 24)), LeapSecond(utc=datetime(1990, 1, 1, 0, 0), dTAI_UTC=timedelta(0, 25)), LeapSecond(utc=datetime(1991, 1, 1, 0, 0), dTAI_UTC=timedelta(0, 26)), LeapSecond(utc=datetime(1992, 7, 1, 0, 0), dTAI_UTC=timedelta(0, 27)), LeapSecond(utc=datetime(1993, 7, 1, 0, 0), dTAI_UTC=timedelta(0, 28)), LeapSecond(utc=datetime(1994, 7, 1, 0, 0), dTAI_UTC=timedelta(0, 29)), LeapSecond(utc=datetime(1996, 1, 1, 0, 0), dTAI_UTC=timedelta(0, 30)), LeapSecond(utc=datetime(1997, 7, 1, 0, 0), dTAI_UTC=timedelta(0, 31)), LeapSecond(utc=datetime(1999, 1, 1, 0, 0), dTAI_UTC=timedelta(0, 32)), LeapSecond(utc=datetime(2006, 1, 1, 0, 0), dTAI_UTC=timedelta(0, 33)), LeapSecond(utc=datetime(2009, 1, 1, 0, 0), dTAI_UTC=timedelta(0, 34)), LeapSecond(utc=datetime(2012, 7, 1, 0, 0), dTAI_UTC=timedelta(0, 35)), LeapSecond(utc=datetime(2015, 7, 1, 0, 0), dTAI_UTC=timedelta(0, 36)), LeapSecond(utc=datetime(2017, 1, 1, 0, 0), dTAI_UTC=timedelta(0, 37)), sentinel] def dTAI_UTC_from_utc(utc_time): """TAI time = utc_time + dTAI_UTC_from_utc(utc_time).""" return _dTAI_UTC(utc_time, lambda ls: ls.utc) def dTAI_UTC_from_tai(tai_time): """UTC time = tai_time - dTAI_UTC_from_tai(tai_time).""" return _dTAI_UTC(tai_time, lambda ls: ls.utc + ls.dTAI_UTC) def _dTAI_UTC(time, leapsecond_to_time, leapseconds=leapseconds): """Get TAI-UTC difference in seconds for a given time. >>> from datetime import datetime, timedelta >>> _dTAI_UTC(datetime(1972, 1, 1), lambda ls: ls.utc) datetime.timedelta(0, 10) >>> tai = lambda ls: ls.utc + ls.dTAI_UTC >>> _dTAI_UTC(datetime(2015, 7, 1, 0, 0, 34), tai) datetime.timedelta(0, 35) >>> _dTAI_UTC(datetime(2015, 7, 1, 0, 0, 35), tai) # leap second datetime.timedelta(0, 35) >>> _dTAI_UTC(datetime(2015, 7, 1, 0, 0, 36), tai) datetime.timedelta(0, 36) Bulletin C 51 says "NO leap second will be introduced at the end of June 2016."[4] and therefore UTC-TAI is still 36 at 27 June 2016: >>> _dTAI_UTC(datetime(2016, 6, 27), lambda ls: ls.utc) datetime.timedelta(0, 36) """ leapseconds_list = leapseconds() transition_times = list(map(leapsecond_to_time, leapseconds_list)) if time < transition_times[0]: raise ValueError("Dates before %s are not supported, got %r" % ( transition_times[0], time)) for i, (start, end) in enumerate(zip(transition_times, transition_times[1:])): if start <= time < end: return leapseconds_list[i].dTAI_UTC assert 0 def tai_to_utc(tai_time): """Convert TAI time given as datetime object to UTC time.""" return tai_time - dTAI_UTC_from_tai(tai_time) def utc_to_tai(utc_time): """Convert UTC time given as datetime object to TAI time.""" return utc_time + dTAI_UTC_from_utc(utc_time) def gps_to_utc(gps_time): """Convert GPS time given as datetime object to UTC time.""" return tai_to_utc(gps_to_tai(gps_time)) def utc_to_gps(utc_time): """Convert UTC time given as datetime object to GPS time.""" return tai_to_gps(utc_to_tai(utc_time)) def tai_to_gps(tai_time): """Convert TAI time given as datetime object to GPS time.""" return tai_time - dTAI_GPS def gps_to_tai(gps_time): """Convert GPS time given as datetime object to TAI time.""" return gps_time + dTAI_GPS if __name__ == "__main__": import doctest doctest.testmod() import json assert all(ls.dTAI_UTC == timedelta(seconds=ls.dTAI_UTC.seconds) for ls in leapseconds()) # ~+200 leap second until 2100 print(json.dumps([dict(utc=t.utc, tai=t.utc + t.dTAI_UTC, dTAI_UTC=t.dTAI_UTC.seconds) for t in leapseconds()], default=str, indent=4, sort_keys=True)) PK[N5ܸCCradiotools/plthelpers.pyimport inspect, re import math import os from matplotlib import colors as mcolors from scipy import optimize import matplotlib.pyplot as plt import numpy as np def get_discrete_cmap(N, base_cmap='viridis'): cmap = plt.get_cmap(base_cmap, N) colors = [] N = np.int(N) for i in range(N): if(i % 2 == 0): colors.append(cmap.colors[i // 2]) else: colors.append(cmap.colors[-i // 2]) return mcolors.ListedColormap(colors) # base = plt.cm.get_cmap(base_cmap) # color_list = base(np.linspace(0, 1, N)) # cmap_name = base.name + str(N) # return base.from_list(cmap_name, color_list, N) def fit_chi2(func, datax, datay, datayerror, p_init=None): datayerror[datayerror == 0] = 1 popt, cov = optimize.curve_fit(func, datax, datay, sigma=datayerror, p0=p_init) # print optimize.curve_fit(func, datax, datay, sigma=datayerror, # p0=p_init, full_output=True) y_fit = func(datax, *popt) chi2 = np.sum((y_fit - datay) ** 2 / datayerror ** 2) if(len(datax) != len(popt)): chi2ndf = 1. * chi2 / (len(datax) - len(popt)) else: chi2ndf = np.NAN func2 = lambda x: func(x, *popt) print("result of chi2 fit:") print("\tchi2/ndf = %0.2g/%i = %0.2g" % (chi2, len(datax) - len(popt), chi2ndf)) print("\tpopt = ", popt) print("\tcov = ", cov) return popt, cov, chi2ndf, func2 def fit_line(datax, datay, datayerror=None, p_init=None): if datayerror is None: datayerror = np.ones_like(datay) func = lambda x, p0, p1: x * p1 + p0 return fit_chi2(func, datax, datay, datayerror, p_init=p_init) def fit_pol2(datax, datay, datayerror=None, p_init=None): if datayerror is None: datayerror = np.ones_like(datay) func = lambda x, p0, p1, p2: x ** 2 * p2 + x * p1 + p0 return fit_chi2(func, datax, datay, datayerror, p_init=p_init) # popt, cov = optimize.curve_fit(lambda x, p0, p1: x * p1 + p0, datax, datay, # sigma=datayerror) # y_fit = popt[1] * datax + popt[0] # chi2 = np.sum((y_fit - datay) ** 2 / datayerror ** 2) # chi2ndf = 1. * chi2 / (len(datax) - 2) # func = lambda x: popt[1] * x + popt[0] # return popt, cov, chi2ndf, func def fit_gaus(datax, datay, datayerror, p_init=None): func = lambda x, p0, p1, p2: p0 * (2 * np.pi * p2) ** -0.5 * np.exp(-0.5 * (x - p1) ** 2 * p2 ** -2) # if(p_init == None): # p_init = [datay.max()*(2 * np.pi * datay.std())**0.5, datay.mean(), datay.std()] return fit_chi2(func, datax, datay, datayerror, p_init=p_init) def plot_fit_stats(ax, popt, cov, chi2ndf, posx=0.95, posy=0.95, ha='right', significant_figure=False, color='k', funcstring='', parnames=None): textstr = '' if(funcstring != ''): textstr += funcstring + "\n" textstr += "$\chi^2/ndf=%.2g$" % chi2ndf if(len(popt) == 1): parname = "p0" if(parnames): parname = parnames[0] textstr += "\n$%s = %.2g \pm %.2g$" % (parname, popt[0], np.squeeze(cov) ** 0.5) elif(len(cov) == 1): for i, p in enumerate(popt): parname = "p%i" % i if(parnames): parname = parnames[i] textstr += "\n$%s = %.2g \pm %s$" % (parname, p, 'nan') else: for i, p in enumerate(popt): parname = "p%i" % i if(parnames): parname = parnames[i] if(significant_figure): import SignificantFigures as serror textstr += "\n$%s = %s \pm %s$" % ((parname,) + (serror.formatError(p, cov[i, i] ** 0.5))) else: textstr += "\n$%s = %.2g \pm %.2g$" % (parname, p, cov[i, i] ** 0.5) props = dict(boxstyle='square', facecolor='wheat', alpha=0.5) ax.text(posx, posy, textstr, transform=ax.transAxes, fontsize=14, verticalalignment='top', horizontalalignment=ha, multialignment='left', bbox=props, color=color) def plot_fit_stats2(ax, popt, cov, chi2ndf, posx=0.95, posy=0.95): from MatplotlibTools import Figures plt.rc('text', usetex=True) table = Figures.Table() table.addValue("$\chi^2/ndf$", chi2ndf) if(len(cov) == 1): for i, p in enumerate(popt): table.addValue("p%i" % i, p) else: for i, p in enumerate(popt): table.addValue("p%i" % i, p, cov[i, i] ** 0.5) props = dict(boxstyle='square', facecolor='wheat', alpha=0.5) # print(table.getTable()) ax.text(posx, posy, r'$%s$' % table.getTable(), transform=ax.transAxes, fontsize=14, verticalalignment='top', horizontalalignment='right', multialignment='left', bbox=props) def plot_hist_stats(ax, data, weights=None, posx=0.05, posy=0.95, overflow=None, underflow=None, rel=False, additional_text="", additional_text_pre="", fontsize=12, color="k", va="top", ha="left", median=True, quantiles=True, mean=True, std=True, N=True, single_sided=False): data = np.array(data) textstr = additional_text_pre if (textstr != ""): textstr += "\n" if N: textstr += "$N=%i$\n" % data.size if not single_sided: tmean = data.mean() tstd = data.std() if weights is not None: def weighted_avg_and_std(values, weights): """ Return the weighted average and standard deviation. values, weights -- Numpy ndarrays with the same shape. """ average = np.average(values, weights=weights) variance = np.average((values - average) ** 2, weights=weights) # Fast and numerically precise return (average, variance ** 0.5) tmean, tstd = weighted_avg_and_std(data, weights) # import SignificantFigures as serror if mean: if weights is None: # textstr += "$\mu = %s \pm %s$\n" % serror.formatError(tmean, # tstd / math.sqrt(data.size)) textstr += "$\mu = {:.3g}$\n".format(tmean) else: textstr += "$\mu = {:.3g}$\n".format(tmean) if median: tweights = np.ones_like(data) if weights is not None: tweights = weights import stats if quantiles: q1 = stats.quantile_1d(data, tweights, 0.16) q2 = stats.quantile_1d(data, tweights, 0.84) median = stats.median(data, tweights) # median_str = serror.formatError(median, 0.05 * (np.abs(median - q2) + np.abs(median - q1)))[0] textstr += "$\mathrm{median} = %.3g^{+%.2g}_{-%.2g}$\n" % (median, np.abs(median - q2), np.abs(median - q1)) else: textstr += "$\mathrm{median} = %.3g $\n" % stats.median(data, tweights) if std: if rel: textstr += "$\sigma = %.2g$ (%.1f\%%)\n" % (tstd, tstd / tmean * 100.) else: textstr += "$\sigma = %.2g$\n" % (tstd) else: import stat if(weights is None): w = np.ones_like(data) else: w = weights q68 = stats.quantile_1d(data, weights=w, quant=.68) q95 = stats.quantile_1d(data, weights=w, quant=.95) textstr += "$\sigma_\mathrm{{68}}$ = {:.1f}$^\circ$\n".format(q68) textstr += "$\sigma_\mathrm{{95}}$ = {:.1f}$^\circ$\n".format(q95) if(overflow): textstr += "$\mathrm{overflows} = %i$\n" % overflow if(underflow): textstr += "$\mathrm{underflows} = %i$\n" % underflow textstr += additional_text textstr = textstr[:-1] props = dict(boxstyle='square', facecolor='w', alpha=0.5) ax.text(posx, posy, textstr, transform=ax.transAxes, fontsize=fontsize, verticalalignment=va, ha=ha, multialignment='left', bbox=props, color=color) def get_graph(x_data, y_data, filename=None, show=False, xerr=None, yerr=None, funcs=None, xlabel="", ylabel="", title="", fmt='bo', fit_stats=None, xmin=None, xmax=None, ymin=None, ymax=None, hlines=None, **kwargs): fig, ax1 = plt.subplots(1, 1) ax1.set_xlabel(xlabel) ax1.set_ylabel(ylabel) ax1.set_title(title) ax1.errorbar(x_data, y_data, xerr=xerr, yerr=yerr, fmt='bo', **kwargs) if(not xmin is None): ax1.set_xlim(left=xmin) if(not xmax is None): ax1.set_xlim(right=xmax) if(not ymin is None): ax1.set_ylim(bottom=ymin) if(not ymax is None): ax1.set_ylim(top=ymax) if(funcs): for func in funcs: xlim = np.array(ax1.get_xlim()) xx = np.linspace(xlim[0], xlim[1], 100) if('args' in func): ax1.plot(xx, func['func'](xx), *func['args']) if('kwargs' in func): ax1.plot(xx, func['func'](xx), *func['args'], **func['kwargs']) else: ax1.plot(xx, func['func'](xx)) if(hlines): for hline in hlines: xlim = np.array(ax1.get_xlim()) ax1.hlines(hline['y'], *xlim, **hline['kwargs']) if(fit_stats): plot_fit_stats(ax1, *fit_stats) plt.tight_layout() if(show): plt.show() return fig, ax1 def save_graph(filename=None, **kwargs): fig, ax1 = get_graph(**kwargs) if(filename and filename != ""): fig.savefig(filename) plt.close(fig) def get_histograms(histograms, bins=None, xlabels=None, ylabels=None, stats=True, fig=None, axes=None, histtype=u'bar', titles=None, weights=None, figsize=4, stat_kwargs=None, kwargs={'facecolor': '0.7', 'alpha': 1, 'edgecolor': "k"}): N = len(histograms) if((fig is None) or (axes is None)): if(N == 1): fig, axes = get_histogram(histograms, bins=bins, xlabel=xlabels, ylabel=ylabels, title=titles, stats=stats, weights=weights) return fig, axes elif(N <= 3): fig, axes = plt.subplots(1, N, figsize=(figsize * N, figsize)) elif(N == 4): fig, axes = plt.subplots(2, 2, figsize=(figsize * 2, figsize * 2)) elif(N <= 6): fig, axes = plt.subplots(2, 3, figsize=(figsize * 3, figsize * 2)) elif(N <= 8): fig, axes = plt.subplots(2, 4, figsize=(figsize * 4, figsize * 2)) elif(N <= 9): fig, axes = plt.subplots(3, 3, figsize=(figsize * 3, figsize * 3)) elif(N <= 12): fig, axes = plt.subplots(3, 4, figsize=(figsize * 4, figsize * 3)) elif(N <= 16): fig, axes = plt.subplots(4, 4, figsize=(figsize * 4, figsize * 4)) elif(N <= 20): fig, axes = plt.subplots(4, 5, figsize=(figsize * 5, figsize * 4)) elif(N <= 25): fig, axes = plt.subplots(5, 5, figsize=(figsize * 5, figsize * 5)) elif(N <= 30): fig, axes = plt.subplots(5, 5, figsize=(figsize * 6, figsize * 5)) elif(N <= 35): fig, axes = plt.subplots(5, 7, figsize=(figsize * 7, figsize * 5)) else: print("WARNING: more than 35 pads are not implemented") raise "WARNING: more than 35 pads are not implemented" shape = np.array(np.array(axes).shape) n1 = shape[0] n2 = 1 if(len(shape) == 2): n2 = shape[1] axes = np.reshape(axes, n1 * n2) for i in xrange(N): xlabel = "" if xlabels: if(type(xlabels) != np.str): xlabel = xlabels[i] else: xlabel = xlabels ylabel = "entries" if ylabels: if(len(ylabels) > 1): ylabel = ylabels[i] else: ylabel = ylabels tbin = 10 title = "" if titles: title = titles[i] if bins is not None: if(type(bins) == np.int): tbin = bins else: if (isinstance(bins[0], float) or isinstance(bins[0], int)): tbin = bins else: tbin = bins[i] if(len(histograms[i])): tweights = None if weights is not None: if (isinstance(weights[0], float) or isinstance(weights[0], int)): tweights = weights else: tweights = weights[i] n, binst, patches = axes[i].hist(histograms[i], bins=tbin, histtype=histtype, weights=tweights, **kwargs) axes[i].set_xlabel(xlabel) axes[i].set_ylabel(ylabel) ymax = max(axes[i].get_ylim()[1], 1.2 * n.max()) axes[i].set_ylim(0, ymax) axes[i].set_xlim(binst[0], binst[-1]) axes[i].set_title(title) underflow = np.sum(histograms[i] < binst[0]) overflow = np.sum(histograms[i] > binst[-1]) if isinstance(stats, bool): if stats: if(stat_kwargs is None): plot_hist_stats(axes[i], histograms[i], weights=tweights, overflow=overflow, underflow=underflow) else: plot_hist_stats(axes[i], histograms[i], weights=tweights, overflow=overflow, underflow=underflow, **stat_kwargs) else: if(stats[i]): if(stat_kwargs is None): plot_hist_stats(axes[i], histograms[i], weights=tweights, overflow=overflow, underflow=underflow) else: plot_hist_stats(axes[i], histograms[i], weights=tweights, overflow=overflow, underflow=underflow, **stat_kwargs) fig.tight_layout() return fig, axes def get_histogram(data, bins=10, xlabel="", ylabel="entries", weights=None, title="", stats=True, show=False, stat_kwargs=None, funcs=None, overflow=True, ax=None, kwargs={'facecolor':'0.7', 'alpha':1, 'edgecolor':"k"}, figsize=None): """ creates a histogram using matplotlib from array """ if(ax is None): if figsize is None: fig, ax1 = plt.subplots(1, 1) else: fig, ax1 = plt.subplots(1, 1, figsize=figsize) else: ax1 = ax ax1.set_xlabel(xlabel) ax1.set_ylabel(ylabel) ax1.set_title(title) n, bins, patches = ax1.hist(data, bins, density=0, weights=weights, **kwargs) if(funcs): for func in funcs: xlim = np.array(ax1.get_xlim()) xx = np.linspace(xlim[0], xlim[1], 100) if('args' in func): ax1.plot(xx, func['func'](xx), *func['args']) if('kwargs' in func): ax1.plot(xx, func['func'](xx), *func['args'], **func['kwargs']) else: ax1.plot(xx, func['func'](xx)) ax1.set_ylim(0, n.max() * 1.2) ax1.set_xlim(bins[0], bins[-1]) if stats: if overflow: underflow = np.sum(data < bins[0]) overflow = np.sum(data > bins[-1]) else: underflow = None underflow = None if(stat_kwargs is None): plot_hist_stats(ax1, data, overflow=overflow, underflow=underflow, weights=weights) else: plot_hist_stats(ax1, data, overflow=overflow, underflow=underflow, weights=weights, **stat_kwargs) if(show): plt.show() if(ax is None): return fig, ax1 def save_histogram(filename, *args, **kwargs): fig, ax = get_histogram(*args, **kwargs) fig.savefig(filename) plt.close(fig) def varname(p): for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]: m = re.search(r'\bvarname\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line) if m: return m.group(1) def make_dir(path): if(not os.path.isdir(path)): os.makedirs(path) def get_marker(i): colors = ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7"] markers = ["o", "D", "^", "s", ">"] return colors[i % len(colors)] + markers[i / len(colors)] def get_marker_only(i): markers = ["o", "D", "^", "s", ">"] return markers[i % len(markers)] def get_marker2(i): colors = ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7"] markers = ["o", "D", "^", "s", ">"] return colors[i % len(colors)] + markers[i % len(markers)] def get_color(i): colors = ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7"] return colors[i % len(colors)] def get_color_linestyle(i): colors = ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7"] markers = ["-", "--", ":", "-."] return markers[i % len(markers)] + colors[i % len(colors)] PKAM$9PPradiotools/stats.py""" Statistic functions """ import numpy as np def mid(x): """ Midpoints of a given array """ return (x[:-1] + x[1:]) / 2. def mean_and_variance(y, weights): """ Weighted mean and variance """ w_sum = sum(weights) m = np.dot(y, weights) / w_sum v = np.dot((y - m)**2, weights) / w_sum return m, v def quantile_1d(data, weights, quant): # from https://github.com/nudomarinero/wquantiles/blob/master/weighted.py """ Compute the weighted quantile of a 1D numpy array. Parameters ---------- data : ndarray Input array (one dimension). weights : ndarray Array with the weights of the same size of `data`. quant : float Quantile to compute. It must have a value between 0 and 1. Returns ------- quantile_1d : float The output value. """ # Check the data if not isinstance(data, np.matrix): data = np.asarray(data) if not isinstance(weights, np.matrix): weights = np.asarray(weights) nd = data.ndim if nd != 1: raise TypeError("data must be a one dimensional array") ndw = weights.ndim if ndw != 1: raise TypeError("weights must be a one dimensional array") if data.shape != weights.shape: raise TypeError("the length of data and weights must be the same") if (quant > 1.) or (quant < 0.): raise ValueError("quantile must have a value between 0. and 1.") # Sort the data ind_sorted = np.argsort(data) sorted_data = data[ind_sorted] sorted_weights = weights[ind_sorted] # Compute the auxiliary arrays sn = np.cumsum(sorted_weights) # TODO: Check that the weights do not sum zero # assert Sn != 0, "The sum of the weights must not be zero" pn = (sn - 0.5 * sorted_weights) / np.sum(sorted_weights) # Get the value of the weighted median # noinspection PyTypeChecker return np.interp(quant, pn, sorted_data) def quantile(data, weights, quant): # pylint: disable=R1710 # from https://github.com/nudomarinero/wquantiles/blob/master/weighted.py """ Weighted quantile of an array with respect to the last axis. Parameters ---------- data : ndarray Input array. weights : ndarray Array with the weights. It must have the same size of the last axis of `data`. quant : float Quantile to compute. It must have a value between 0 and 1. Returns ------- quantile : float The output value. """ # TODO: Allow to specify the axis nd = data.ndim if nd == 0: TypeError("data must have at least one dimension") elif nd == 1: return quantile_1d(data, weights, quant) elif nd > 1: n = data.shape imr = data.reshape((np.prod(n[:-1]), n[-1])) result = np.apply_along_axis(quantile_1d, -1, imr, weights, quant) return result.reshape(n[:-1]) def median(data, weights): # from https://github.com/nudomarinero/wquantiles/blob/master/weighted.py """ Weighted median of an array with respect to the last axis. Alias for `quantile(data, weights, 0.5)`. """ return quantile(data, weights, 0.5) def binned_mean(x, y, bins, weights=None): """ _i : mean of y in bins of x """ dig = np.digitize(x, bins) n = len(bins) - 1 my = np.zeros(n) if weights is None: weights = np.ones(len(x)) # use weights=1 if none given for i in range(n): idx = (dig == i+1) try: my[i] = np.average(y[idx], weights=weights[idx]) except ZeroDivisionError: my[i] = np.nan return my def binned_mean_and_variance(x, y, bins, weights=None): """ _i, sigma(y)_i : mean and variance of y in bins of x This is effectively a ROOT.TProfile """ dig = np.digitize(x, bins) n = len(bins) - 1 my, vy = np.zeros(n), np.zeros(n) for i in range(n): idx = (dig == i+1) if not idx.any(): # check for empty bin my[i] = np.nan vy[i] = np.nan continue if weights is None: my[i] = np.mean(y[idx]) vy[i] = np.std(y[idx])**2 else: my[i], vy[i] = mean_and_variance(y[idx], weights[idx]) return my, vy def sym_interval_around(x, xm, alpha): """ In a distribution represented by a set of samples, find the interval that contains (1-alpha)/2 to each the left and right of xm. If xm is too marginal to allow both sides to contain (1-alpha)/2, add the remaining fraction to the other side. """ xt = x.copy() xt.sort() i = xt.searchsorted(xm) # index of central value n = len(x) # number of samples ns = int((1 - alpha) * n) # number of samples corresponding to 1-alpha i0 = i - ns/2 # index of lower and upper bound of interval i1 = i + ns/2 # if central value doesn't allow for (1-alpha)/2 on left side, add to right if i0 < 0: i1 -= i0 i0 = 0 # if central value doesn't allow for (1-alpha)/2 on right side, add to left if i1 >= n: i0 -= i1-n+1 i1 = n-1 return xt[int(i0)], xt[int(i1)] PKqwKradiotools/analyses/__init__.pyPKҹ+Naa%radiotools/analyses/energy_fluence.pyfrom scipy.signal import hilbert import numpy as np import sys conversion_factor_integrated_signal = 2.65441729e-3 * 6.24150934e18 # to convert V**2/m**2 * s -> J/m**2 -> eV/m**2 def calculate_energy_fluence_vector(traces, times, signal_window=100., remove_noise=True): """ get energy fluence vector Parameters ---------- traces: array time series in V / m array is expected to have 2 (time, channel) or 3 (antenna, time, channel) dimensions times: array corresponding time vector in seconds array is expected to have 1 (time) or 2 (antenna, time) dimensions signal_window (optional): float time window used to calculate the signal power in nano seconds remove_noise (optional): bool if true, subtract energy content in noise window (~signal_window) from content in signal window default: True Returns -------- array: energy fluence per polarisation in eV / m**2 (not a real vector) array has the (3,) or (n_antenna, 3) """ if traces.ndim != 2 and traces.ndim != 3 and traces.ndim != times.ndim: sys.exit("Error: traces does not fullfil reqiuerments") # if traces for only on antenna is given (dim = 2) a dummy dimension is added if traces.ndim == 2: traces = np.expand_dims(traces, axis=0) times = np.expand_dims(times, axis=0) # determine signal position with maximum of hilbert envelope hilbenv = np.abs(hilbert(traces, axis=1)) hilbenv_sum_max_idx = np.argmax(np.sum(hilbenv ** 2, axis=-1) ** 0.5, axis=-1) # produces FutureWarning peak_sum_time = times[range(len(hilbenv_sum_max_idx)), hilbenv_sum_max_idx] # choose signal window # conversion from ns in s signal_window *= 1e-9 mask_signal = (times > (peak_sum_time[..., None] - signal_window / 2.)) & (times < (peak_sum_time[..., None] + signal_window / 2.)) # get tstep tstep = times[0, 1] - times[0, 0] # calculate energy fluence in signal window u_signal = np.array([np.sum(traces[i][mask_signal[i]] ** 2, axis=0) for i in range(len(mask_signal))]) u_signal *= conversion_factor_integrated_signal * tstep if remove_noise: mask_noise = ~mask_signal # calculate energy fluence in noise window u_noise = np.array([np.sum(traces[i][mask_noise[i]] ** 2, axis=0) for i in range(len(mask_noise))]) u_noise *= conversion_factor_integrated_signal * tstep # account for unequal window sizes u_noise *= (np.sum(mask_signal, axis=-1) / np.sum(mask_noise, axis=-1))[..., None] power = u_signal - u_noise else: power = u_signal return np.squeeze(power) def calculate_energy_fluence(traces, times, signal_window=100., remove_noise=True): """ get energy fluence Parameters ---------- traces: array time series in V / m array is expected to have 2 (time, channel) or 3 (antenna, time, channel) dimensions times: array corresponding time vector in seconds array is expected to have 1 (time) or 2 (antenna, time) dimensions signal_window (optional): float time window used to calculate the signal power in nano seconds remove_noise (optional): bool if true, subtract energy content in noise window (~signal_window) from content in signal window default: True Returns -------- float or array: energy fluence in eV / m**2 for a singel station or array of stations """ energy_fluence_vector = calculate_energy_fluence_vector(traces, times, signal_window, remove_noise) return np.sum(energy_fluence_vector, axis=-1) PKK#joW W &radiotools/analyses/radiationenergy.pyimport numpy as np from radiotools.atmosphere import models as atm # see Glaser et al., JCAP 09(2016)024 for the derivation of the formulas average_xmax = 669.40191244545326 # 1 EeV, 50% proton, 50% iron composition average_zenith = np.deg2rad(45) atmc = atm.Atmosphere(model=1) average_density = atmc.get_density(average_zenith, average_xmax) * 1e-3 # in kg/m^3 def get_clipping(dxmax): """ get clipping correction Parameters ---------- dxmax : float distance to shower maximum in g/cm^2 Returns ------- float fraction of radiation energy that is radiated in the atmosphere """ return 1 - np.exp(-8.7 * (dxmax * 1e-3 + 0.29) ** 1.89) def get_a(rho): """ get relative charge excess strength Parameters ---------- rho : float density at shower maximum in kg/m^3 Returns ------- float relative charge excess strength a """ return -0.23604683 + 0.43426141 * np.exp(1.11141046 * (rho - average_density)) def get_a_zenith(zenith): """ get relative charge excess strength wo Xmax information Parameters ---------- zentith : float zenith angle in rad according to radiotools default coordinate system Returns -------- float relative charge excess strength a """ rho = atmc.get_density(zenith, average_xmax) * 1e-3 return -0.24304254 + 0.4511355 * np.exp(1.1380946 * (rho - average_density)) def get_S(Erad, sinalpha, density, p0=0.250524463912, p1=-2.95290494, b_scale=1., b=1.8): """ get corrected radiation energy (S_RD) Parameters ---------- Erad : float radiation energy (in eV) sinalpha: float sine of angle between shower axis and geomagnetic field density : float density at shower maximum in kg/m^3 Returns -------- float: corrected radiation energy (in eV) """ a = get_a(density) * b_scale ** (-0.5 * b) return Erad / (a ** 2 + (1 - a ** 2) * sinalpha ** 2 * b_scale ** b) / \ (1 - p0 + p0 * np.exp(p1 * (density - average_density))) ** 2 def get_S_zenith(erad, sinalpha, zeniths, b_scale=1., p0=0.239, p1=-3.13): """ get corrected radiation energy (S_RD) wo xmax information Parameters ---------- Erad : float radiation energy (in eV) sinalpha: float sine of angle between shower axis and geomagnetic field density : float density at shower maximum in kg/m^3 Returns -------- float: corrected radiation energy wo Xmax information (in eV) """ rho = atmc.get_density(zeniths, average_xmax) * 1e-3 return get_S(erad, sinalpha, rho, p0=p0, p1=p1, b_scale=b_scale) def get_radiation_energy(Srd, sinalpha, density, p0=0.250524463912, p1=-2.95290494, b_scale=1., b=1.8): """ get radiation energy (S_RD) Parameters ---------- Srd : float corrected radiation energy (in eV) sinalpha: float sine of angle between shower axis and geomagnetic field density : float density at shower maximum in kg/m^3 Returns -------- float: radiation energy (in eV) """ a = get_a(density) * b_scale ** (-0.5 * b) return Srd * (a ** 2 + (1 - a ** 2) * sinalpha ** 2 * b_scale ** b) * \ (1 - p0 + p0 * np.exp(p1 * (density - average_density))) ** 2 PKwK!radiotools/atmosphere/__init__.pyPK8Nwwradiotools/atmosphere/models.pyfrom __future__ import absolute_import, division, print_function # , unicode_literals import numpy as np import os import pickle import unittest default_curved = True default_model = 17 r_e = 6.371 * 1e6 # radius of Earth """ All functions use "grams" and "meters", only the functions that receive and return "atmospheric depth" use the unit "g/cm^2" atmospheric density models as used in CORSIKA. The parameters are documented in the CORSIKA manual the parameters for the Auger atmospheres are documented in detail in GAP2011-133 The May and October atmospheres describe the annual average best. """ h_max = 112829.2 # height above sea level where the mass overburden vanishes atm_models = { # US standard after Linsley 1: {'a': 1e4 * np.array([-186.555305, -94.919, 0.61289, 0., 0.01128292]), 'b': 1e4 * np.array([1222.6562, 1144.9069, 1305.5948, 540.1778, 1.]), 'c': 1e-2 * np.array([994186.38, 878153.55, 636143.04, 772170.16, 1.e9]), 'h': 1e3 * np.array([4., 10., 40., 100.]) }, # southpole January after Lipari 15: {'a': 1e4 * np.array([-113.139, -79.0635, -54.3888, 0., 0.00421033]), 'b': 1e4 * np.array([1133.1, 1101.2, 1085., 1098., 1.]), 'c': 1e-2 * np.array([861730., 826340., 790950., 682800., 2.6798156e9]), 'h': 1e3 * np.array([2.67, 5.33, 8., 100.]) }, # US standard after Keilhauer 17: {'a': 1e4 * np.array([-149.801663, -57.932486, 0.63631894, 4.35453690e-4, 0.01128292]), 'b': 1e4 * np.array([1183.6071, 1143.0425, 1322.9748, 655.67307, 1.]), 'c': 1e-2 * np.array([954248.34, 800005.34, 629568.93, 737521.77, 1.e9]), 'h': 1e3 * np.array([7., 11.4, 37., 100.]) }, # Malargue January 18: {'a': 1e4 * np.array([-136.72575606, -31.636643044, 1.8890234035, 3.9201867984e-4, 0.01128292]), 'b': 1e4 * np.array([1174.8298334, 1204.8233453, 1637.7703583, 735.96095023, 1.]), 'c': 1e-2 * np.array([982815.95248, 754029.87759, 594416.83822, 733974.36972, 1e9]), 'h': 1e3 * np.array([9.4, 15.3, 31.6, 100.]) }, # Malargue February 19: {'a': 1e4 * np.array([-137.25655862, -31.793978896, 2.0616227547, 4.1243062289e-4, 0.01128292]), 'b': 1e4 * np.array([1176.0907565, 1197.8951104, 1646.4616955, 755.18728657, 1.]), 'c': 1e-2 * np.array([981369.6125, 756657.65383, 592969.89671, 731345.88332, 1.e9]), 'h': 1e3 * np.array([9.2, 15.4, 31., 100.]) }, # Malargue March 20: {'a': 1e4 * np.array([-132.36885162, -29.077046629, 2.090501509, 4.3534337925e-4, 0.01128292]), 'b': 1e4 * np.array([1172.6227784, 1215.3964677, 1617.0099282, 769.51991638, 1.]), 'c': 1e-2 * np.array([972654.0563, 742769.2171, 595342.19851, 728921.61954, 1.e9]), 'h': 1e3 * np.array([9.6, 15.2, 30.7, 100.]) }, # Malargue April 21: {'a': 1e4 * np.array([-129.9930412, -21.847248438, 1.5211136484, 3.9559055121e-4, 0.01128292]), 'b': 1e4 * np.array([1172.3291878, 1250.2922774, 1542.6248413, 713.1008285, 1.]), 'c': 1e-2 * np.array([962396.5521, 711452.06673, 603480.61835, 735460.83741, 1.e9]), 'h': 1e3 * np.array([10., 14.9, 32.6, 100.]) }, # Malargue May 22: {'a': 1e4 * np.array([-125.11468467, -14.591235621, 0.93641128677, 3.2475590985e-4, 0.01128292]), 'b': 1e4 * np.array([1169.9511302, 1277.6768488, 1493.5303781, 617.9660747, 1.]), 'c': 1e-2 * np.array([947742.88769, 685089.57509, 609640.01932, 747555.95526, 1.e9]), 'h': 1e3 * np.array([10.2, 15.1, 35.9, 100.]) }, # Malargue June 23: {'a': 1e4 * np.array([-126.17178851, -7.7289852811, 0.81676828638, 3.1947676891e-4, 0.01128292]), 'b': 1e4 * np.array([1171.0916276, 1295.3516434, 1455.3009344, 595.11713507, 1.]), 'c': 1e-2 * np.array([940102.98842, 661697.57543, 612702.0632, 749976.26832, 1.e9]), 'h': 1e3 * np.array([10.1, 16., 36.7, 100.]) }, # Malargue July 24: {'a': 1e4 * np.array([-126.17216789, -8.6182537514, 0.74177836911, 2.9350702097e-4, 0.01128292]), 'b': 1e4 * np.array([1172.7340688, 1258.9180079, 1450.0537141, 583.07727715, 1.]), 'c': 1e-2 * np.array([934649.58886, 672975.82513, 614888.52458, 752631.28536, 1.e9]), 'h': 1e3 * np.array([9.6, 16.5, 37.4, 100.]) }, # Malargue August 25: {'a': 1e4 * np.array([-123.27936204, -10.051493041, 0.84187346153, 3.2422546759e-4, 0.01128292]), 'b': 1e4 * np.array([1169.763036, 1251.0219808, 1436.6499372, 627.42169844, 1.]), 'c': 1e-2 * np.array([931569.97625, 678861.75136, 617363.34491, 746739.16141, 1.e9]), 'h': 1e3 * np.array([9.6, 15.9, 36.3, 100.]) }, # Malargue September 26: {'a': 1e4 * np.array([-126.94494665, -9.5556536981, 0.74939405052, 2.9823116961e-4, 0.01128292]), 'b': 1e4 * np.array([1174.8676453, 1251.5588529, 1440.8257549, 606.31473165, 1.]), 'c': 1e-2 * np.array([936953.91919, 678906.60516, 618132.60561, 750154.67709, 1.e9]), 'h': 1e3 * np.array([9.5, 15.9, 36.3, 100.]) }, # Malargue October 27: {'a': 1e4 * np.array([-133.13151125, -13.973209265, 0.8378263431, 3.111742176e-4, 0.01128292]), 'b': 1e4 * np.array([1176.9833473, 1244.234531, 1464.0120855, 622.11207419, 1.]), 'c': 1e-2 * np.array([954151.404, 692708.89816, 615439.43936, 747969.08133, 1.e9]), 'h': 1e3 * np.array([9.5, 15.5, 36.5, 100.]) }, # Malargue November 28: {'a': 1e4 * np.array([-134.72208165, -18.172382908, 1.1159806845, 3.5217025515e-4, 0.01128292]), 'b': 1e4 * np.array([1175.7737972, 1238.9538504, 1505.1614366, 670.64752105, 1.]), 'c': 1e-2 * np.array([964877.07766, 706199.57502, 610242.24564, 741412.74548, 1.e9]), 'h': 1e3 * np.array([9.6, 15.3, 34.6, 100.]) }, # Malargue December 29: {'a': 1e4 * np.array([-135.40825209, -22.830409026, 1.4223453493, 3.7512921774e-4, 0.01128292]), 'b': 1e4 * np.array([1174.644971, 1227.2753683, 1585.7130562, 691.23389637, 1.]), 'c': 1e-2 * np.array([973884.44361, 723759.74682, 600308.13983, 738390.20525, 1.e9]), 'h': 1e3 * np.array([9.6, 15.6, 33.3, 100.]) } } def get_auger_monthly_model(month): """ Helper function to get the correct model number for monthly Auger atmospheres """ return month + 17 def get_height_above_ground(d, zenith, observation_level=0): """ returns the perpendicular height above ground for a distance d from ground at a given zenith angle """ r = r_e + observation_level x = d * np.sin(zenith) y = d * np.cos(zenith) + r h = (x ** 2 + y ** 2) ** 0.5 - r # print "d = %.1f, obs = %.1f, z = %.2f -> h = %.1f" % (d, observation_level, np.rad2deg(zenith), h) return h def get_distance_for_height_above_ground(h, zenith, observation_level=0): """ inverse of get_height_above_ground() """ r = r_e + observation_level return (h ** 2 + 2 * r * h + r ** 2 * np.cos(zenith) ** 2) ** 0.5 - r * np.cos(zenith) def get_vertical_height(at, model=default_model): """ input: atmosphere above in g/cm^2 [e.g. Xmax] output: height in m """ return _get_vertical_height(at * 1e4, model=model) def _get_vertical_height(at, model=default_model): if np.shape(at) == (): T = _get_i_at(at, model=model) else: T = np.zeros(len(at)) for i, at in enumerate(at): T[i] = _get_i_at(at, model=model) return T def _get_i_at(at, model=default_model): a = atm_models[model]['a'] b = atm_models[model]['b'] c = atm_models[model]['c'] layers = atm_models[model]['h'] if at > _get_atmosphere(layers[0], model=model): i = 0 elif at > _get_atmosphere(layers[1], model=model): i = 1 elif at > _get_atmosphere(layers[2], model=model): i = 2 elif at > _get_atmosphere(layers[3], model=model): i = 3 else: i = 4 if i == 4: h = -1. * c[i] * (at - a[i]) / b[i] else: h = -1. * c[i] * np.log((at - a[i]) / b[i]) return h def get_atmosphere(h, model=default_model): """ returns the (vertical) amount of atmosphere above the height h above see level in units of g/cm^2 input: height above sea level in meter""" return _get_atmosphere(h, model=model) * 1e-4 def _get_atmosphere(h, model=default_model): a = atm_models[model]['a'] b = atm_models[model]['b'] c = atm_models[model]['c'] layers = atm_models[model]['h'] y = np.where(h < layers[0], a[0] + b[0] * np.exp(-1 * h / c[0]), a[1] + b[1] * np.exp(-1 * h / c[1])) y = np.where(h < layers[1], y, a[2] + b[2] * np.exp(-1 * h / c[2])) y = np.where(h < layers[2], y, a[3] + b[3] * np.exp(-1 * h / c[3])) y = np.where(h < layers[3], y, a[4] - b[4] * h / c[4]) y = np.where(h < h_max, y, 0) return y def get_density(h, allow_negative_heights=True, model=default_model): """ returns the atmospheric density [g/m^3] for the height h above see level""" b = atm_models[model]['b'] c = atm_models[model]['c'] layers = atm_models[model]['h'] y = np.zeros_like(h, dtype=np.float) if not allow_negative_heights: y *= np.nan # set all requested densities for h < 0 to nan y = np.where(h < 0, y, b[0] * np.exp(-1 * h / c[0]) / c[0]) else: y = b[0] * np.exp(-1 * h / c[0]) / c[0] y = np.where(h < layers[0], y, b[1] * np.exp(-1 * h / c[1]) / c[1]) y = np.where(h < layers[1], y, b[2] * np.exp(-1 * h / c[2]) / c[2]) y = np.where(h < layers[2], y, b[3] * np.exp(-1 * h / c[3]) / c[3]) y = np.where(h < layers[3], y, b[4] / c[4]) y = np.where(h < h_max, y, 0) return y def get_density_from_barometric_formula(hh): """ returns the atmospheric density [g/m^3] for the height h abolve see level according to https://en.wikipedia.org/wiki/Barometric_formula""" if isinstance(hh, float): hh = np.array([hh]) R = 8.31432 # universal gas constant for air: 8.31432 N m/(mol K) g0 = 9.80665 # gravitational acceleration (9.80665 m/s2) M = 0.0289644 # molar mass of Earth's air (0.0289644 kg/mol) rhob = [1.2250, 0.36391, 0.08803, 0.01322, 0.00143, 0.00086, 0.000064] Tb = [288.15, 216.65, 216.65, 228.65, 270.65, 270.65, 214.65] Lb = [-0.0065, 0, 0.001, 0.0028, 0, -0.0028, -0.002] hb = [0, 11000, 20000, 32000, 47000, 51000, 71000] def rho1(h, i): # for Lb != 0 return rhob[i] * (Tb[i] / (Tb[i] + Lb[i] * (h - hb[i]))) ** (1 + (g0 * M) / (R * Lb[i])) def rho2(h, i): # for Lb == 0 return rhob[i] * np.exp(-g0 * M * (h - hb[i]) / (R * Tb[i])) densities = np.zeros_like(hh) for i, h in enumerate(hh): if (h < 0): densities[i] = np.nan elif(h > 86000): densities[i] = 0 else: t = h - hb # print "t = ", t, "h = ", h index = np.argmin(t[t >= 0]) if Lb[index] == 0: densities[i] = rho2(h, index) else: densities[i] = rho1(h, index) # print "h = ", h, " index = ", index, " density = ", densities[i] return densities * 1e3 def get_atmosphere_upper_limit(model=default_model): """ returns the altitude where the mass overburden vanishes """ from scipy import optimize from functools import partial return optimize.newton(partial(_get_atmosphere, model=model), x0=112.8e3) def get_n(h, n0=(1 + 2.92e-4), allow_negative_heights=False, model=1): return (n0 - 1) * get_density(h, allow_negative_heights=allow_negative_heights, model=model) / get_density(0, model=model) + 1 class Atmosphere(): def __init__(self, model=17, n_taylor=5, curved=True, zenith_numeric=np.deg2rad(83)): import sys print("model is ", model) self.model = model self.curved = curved self.n_taylor = n_taylor self.__zenith_numeric = zenith_numeric self.b = atm_models[model]['b'] self.c = atm_models[model]['c'] self.number_of_zeniths = 201 hh = atm_models[model]['h'] self.h = np.append([0], hh) if curved: folder = os.path.dirname(os.path.abspath(__file__)) filename = os.path.join(folder, "constants_%02i_%i.picke" % (self.model, n_taylor)) print("searching constants at ", filename) if os.path.exists(filename): print("reading constants from ", filename) fin = open(filename, "rb") self.a, self.d = pickle.load(fin) fin.close() if(len(self.a) != self.number_of_zeniths): os.remove(filename) print("constants outdated, please rerun to calculate new constants") sys.exit(0) self.a_funcs = [] zeniths = np.arccos(np.linspace(0, 1, self.number_of_zeniths)) from scipy.interpolate import interp1d mask = zeniths < np.deg2rad(90) for i in xrange(5): self.a_funcs.append(interp1d(zeniths[mask], self.a[..., i][mask], kind='cubic')) else: # self.d = self.__calculate_d() self.d = np.zeros(self.number_of_zeniths) self.a = self.__calculate_a() fin = open(filename, "w") pickle.dump([self.a, self.d], fin) fin.close() print("all constants calculated, exiting now... please rerun your analysis") sys.exit(0) def __calculate_a(self,): zeniths = np.arccos(np.linspace(0, 1, self.number_of_zeniths)) a = np.zeros((self.number_of_zeniths, 5)) self.curved = True self.__zenith_numeric = 0 for iZ, z in enumerate(zeniths): print("calculating constants for %.02f deg zenith angle (iZ = %i, nT = %i)..." % (np.rad2deg(z), iZ, self.n_taylor)) a[iZ] = self.__get_a(z) print("\t... a = ", a[iZ], " iZ = ", iZ) return a def __get_a(self, zenith): a = np.zeros(5) b = self.b c = self.c h = self.h a[0] = self._get_atmosphere_numeric([zenith], h_low=h[0]) - b[0] * self._get_dldh(h[0], zenith, 0) a[1] = self._get_atmosphere_numeric([zenith], h_low=h[1]) - b[1] * np.exp(-h[1] / c[1]) * self._get_dldh(h[1], zenith, 1) a[2] = self._get_atmosphere_numeric([zenith], h_low=h[2]) - b[2] * np.exp(-h[2] / c[2]) * self._get_dldh(h[2], zenith, 2) a[3] = self._get_atmosphere_numeric([zenith], h_low=h[3]) - b[3] * np.exp(-h[3] / c[3]) * self._get_dldh(h[3], zenith, 3) a[4] = self._get_atmosphere_numeric([zenith], h_low=h[4]) + b[4] * h[4] / c[4] * self._get_dldh(h[4], zenith, 4) return a def _get_dldh(self, h, zenith, iH): if iH < 4: c = self.c[iH] st = np.sin(zenith) ct = np.cos(zenith) dldh = np.ones_like(zenith) / ct if self.n_taylor >= 1: dldh += -(st ** 2 / ct ** 3 * (c + h) / r_e) if self.n_taylor >= 2: tmp = 3. / 2. * st ** 2 * (2 * c ** 2 + 2 * c * h + h ** 2) / (r_e ** 2 * ct ** 5) dldh += tmp if self.n_taylor >= 3: t1 = 6 * c ** 3 + 6 * c ** 2 * h + 3 * c * h ** 2 + h ** 3 tmp = st ** 2 / (2 * r_e ** 3 * ct ** 7) * (ct ** 2 - 5) * t1 dldh += tmp if self.n_taylor >= 4: t1 = 24 * c ** 4 + 24 * c ** 3 * h + 12 * c ** 2 * h ** 2 + 4 * c * h ** 3 + h ** 4 tmp = -1. * st ** 2 * 5. / (8. * r_e ** 4 * ct ** 9) * (3 * ct ** 2 - 7) * t1 dldh += tmp if self.n_taylor >= 5: t1 = 120 * c ** 5 + 120 * c ** 4 * h + 60 * c ** 3 * h ** 2 + 20 * c ** 2 * h ** 3 + 5 * c * h ** 4 + h ** 5 tmp = st ** 2 * (ct ** 4 - 14. * ct ** 2 + 21.) * (-3. / 8.) / (r_e ** 5 * ct ** 11) * t1 dldh += tmp elif(iH == 4): c = self.c[iH] st = np.sin(zenith) ct = np.cos(zenith) dldh = np.ones_like(zenith) / ct if self.n_taylor >= 1: dldh += (-0.5 * st ** 2 / ct ** 3 * h / r_e) if self.n_taylor >= 2: dldh += 0.5 * st ** 2 / ct ** 5 * (h / r_e) ** 2 if self.n_taylor >= 3: dldh += 1. / 8. * (st ** 2 * (ct ** 2 - 5) * h ** 3) / (r_e ** 3 * ct ** 7) if self.n_taylor >= 4: tmp2 = -1. / 8. * st ** 2 * (3 * ct ** 2 - 7) * (h / r_e) ** 4 / ct ** 9 dldh += tmp2 if self.n_taylor >= 5: tmp2 = -1. / 16. * st ** 2 * (ct ** 4 - 14 * ct ** 2 + 21) * (h / r_e) ** 5 / ct ** 11 dldh += tmp2 else: print("ERROR, height index our of bounds") import sys sys.exit(-1) # print "get dldh for h= %.8g, z = %.8g, iH=%i -> %.7f" % (h, np.rad2deg(zenith), iH, dldh) return dldh def __get_method_mask(self, zenith): if not self.curved: return np.ones_like(zenith, dtype=np.bool), np.zeros_like(zenith, dtype=np.bool), np.zeros_like(zenith, dtype=np.bool) mask_flat = np.zeros_like(zenith, dtype=np.bool) mask_taylor = zenith < self.__zenith_numeric mask_numeric = zenith >= self.__zenith_numeric return mask_flat, mask_taylor, mask_numeric def __get_height_masks(self, hh): # mask0 = (hh >= 0) & (hh < atm_models[self.model]['h'][0]) mask0 = (hh < atm_models[self.model]['h'][0]) mask1 = (hh >= atm_models[self.model]['h'][0]) & (hh < atm_models[self.model]['h'][1]) mask2 = (hh >= atm_models[self.model]['h'][1]) & (hh < atm_models[self.model]['h'][2]) mask3 = (hh >= atm_models[self.model]['h'][2]) & (hh < atm_models[self.model]['h'][3]) mask4 = (hh >= atm_models[self.model]['h'][3]) & (hh < h_max) mask5 = hh >= h_max return np.array([mask0, mask1, mask2, mask3, mask4, mask5]) def __get_X_masks(self, X, zenith): mask0 = X > self._get_atmosphere(zenith, atm_models[self.model]['h'][0]) mask1 = (X <= self._get_atmosphere(zenith, atm_models[self.model]['h'][0])) & \ (X > self._get_atmosphere(zenith, atm_models[self.model]['h'][1])) mask2 = (X <= self._get_atmosphere(zenith, atm_models[self.model]['h'][1])) & \ (X > self._get_atmosphere(zenith, atm_models[self.model]['h'][2])) mask3 = (X <= self._get_atmosphere(zenith, atm_models[self.model]['h'][2])) & \ (X > self._get_atmosphere(zenith, atm_models[self.model]['h'][3])) mask4 = (X <= self._get_atmosphere(zenith, atm_models[self.model]['h'][3])) & \ (X > self._get_atmosphere(zenith, h_max)) mask5 = X <= 0 return np.array([mask0, mask1, mask2, mask3, mask4, mask5]) def __get_arguments(self, mask, *args): tmp = [] ones = np.ones(np.array(mask).size) for a in args: if np.shape(a) == (): tmp.append(a * ones) else: tmp.append(a[mask]) return tmp def get_atmosphere(self, zenith, h_low=0., h_up=np.infty): """ returns the atmosphere for an air shower with given zenith angle (in g/cm^2) """ return self._get_atmosphere(zenith, h_low=h_low, h_up=h_up) * 1e-4 def _get_atmosphere(self, zenith, h_low=0., h_up=np.infty): mask_flat, mask_taylor, mask_numeric = self.__get_method_mask(zenith) mask_finite = np.array((h_up * np.ones_like(zenith)) < h_max) is_mask_finite = np.sum(mask_finite) tmp = np.zeros_like(zenith) if np.sum(mask_numeric): # print "getting numeric" tmp[mask_numeric] = self._get_atmosphere_numeric(*self.__get_arguments(mask_numeric, zenith, h_low, h_up)) if np.sum(mask_taylor): # print "getting taylor" tmp[mask_taylor] = self._get_atmosphere_taylor(*self.__get_arguments(mask_taylor, zenith, h_low)) if(is_mask_finite): # print "\t is finite" mask_tmp = np.squeeze(mask_finite[mask_taylor]) tmp2 = self._get_atmosphere_taylor(*self.__get_arguments(mask_taylor, zenith, h_up)) tmp[mask_tmp] = tmp[mask_tmp] - np.array(tmp2) if np.sum(mask_flat): # print "getting flat atm" tmp[mask_flat] = self._get_atmosphere_flat(*self.__get_arguments(mask_flat, zenith, h_low)) if(is_mask_finite): mask_tmp = np.squeeze(mask_finite[mask_flat]) tmp2 = self._get_atmosphere_flat(*self.__get_arguments(mask_flat, zenith, h_up)) tmp[mask_tmp] = tmp[mask_tmp] - np.array(tmp2) return tmp def __get_zenith_a_indices(self, zeniths): n = self.number_of_zeniths - 1 cosz_bins = np.linspace(0, n, self.number_of_zeniths, dtype=np.int) cosz = np.array(np.round(np.cos(zeniths) * n), dtype=np.int) tmp = np.squeeze([np.argwhere(t == cosz_bins) for t in cosz]) return tmp def __get_a_from_cache(self, zeniths): n = self.number_of_zeniths - 1 cosz_bins = np.linspace(0, n, self.number_of_zeniths, dtype=np.int) cosz = np.array(np.round(np.cos(zeniths) * n), dtype=np.int) a_indices = np.squeeze([np.argwhere(t == cosz_bins) for t in cosz]) cosz_bins_num = np.linspace(0, 1, self.number_of_zeniths) # print "correction = ", (cosz_bins_num[a_indices] / np.cos(zeniths)) # print "a = ", self.a[a_indices] a = ((self.a[a_indices]).T * (cosz_bins_num[a_indices] / np.cos(zeniths))).T return a def __get_a_from_interpolation(self, zeniths): a = np.zeros((len(zeniths), 5)) for i in xrange(5): a[..., i] = self.a_funcs[i](zeniths) return a def plot_a(self): import matplotlib.pyplot as plt zeniths = np.arccos(np.linspace(0, 1, self.number_of_zeniths)) mask = zeniths < np.deg2rad(83) fig, ax = plt.subplots(1, 1) x = np.rad2deg(zeniths[mask]) # mask2 = np.array([0, 1] * (np.sum(mask) / 2), dtype=np.bool) ax.plot(x, self.a[..., 0][mask], ".", label="a0") ax.plot(x, self.a[..., 1][mask], ".", label="a1") ax.plot(x, self.a[..., 2][mask], ".", label="a2") ax.plot(x, self.a[..., 3][mask], ".", label="a3") ax.plot(x, self.a[..., 4][mask], ".", label="a4") ax.set_xlim(0, 84) ax.legend() plt.tight_layout() from scipy.interpolate import interp1d for i in xrange(5): y = self.a[..., i][mask] f2 = interp1d(x, y, kind='cubic') xxx = np.linspace(0, 81, 100) ax.plot(xxx, f2(xxx), "-") ax.set_ylim(-1e8, 1e8) plt.show() # tmp = (f2(x[~mask2][1:-1]) - y[~mask2][1:-1]) / y[~mask2][1:-1] # print tmp.mean(), tmp.std() # res = optimize.minimize(obj, x0=(-0.18, 1, 90)) # print res def _get_atmosphere_taylor(self, zenith, h_low=0.): b = self.b c = self.c # a_indices = self.__get_zenith_a_indices(zenith) a = self.__get_a_from_interpolation(zenith) # print "a indices are", a_indices , "-> ", a masks = self.__get_height_masks(h_low) tmp = np.zeros_like(zenith) for iH, mask in enumerate(masks): if(np.sum(mask)): if(np.array(h_low).size == 1): h = h_low else: h = h_low[mask] # print "getting atmosphere taylor for layer ", iH if iH < 4: dldh = self._get_dldh(h, zenith[mask], iH) tmp[mask] = np.array([a[..., iH][mask] + b[iH] * np.exp(-1 * h / c[iH]) * dldh]).squeeze() elif iH == 4: dldh = self._get_dldh(h, zenith[mask], iH) tmp[mask] = np.array([a[..., iH][mask] - b[iH] * h / c[iH] * dldh]) else: tmp[mask] = np.zeros(np.sum(mask)) return tmp def _get_atmosphere_numeric(self, zenith, h_low=0, h_up=np.infty): zenith = np.array(zenith) tmp = np.zeros_like(zenith) for i in xrange(len(tmp)): from scipy import integrate if(np.array(h_up).size == 1): t_h_up = h_up else: t_h_up = h_up[i] if(np.array(h_low).size == 1): t_h_low = h_low else: t_h_low = h_low[i] # if(np.array(zenith).size == 1): # z = zenith # else: # z = zenith[i] z = zenith[i] # t_h_low = h_low[i] # t_h_up = h_up[i] if t_h_up <= t_h_low: print("WARNING _get_atmosphere_numeric(): upper limit less than lower limit") return np.nan if t_h_up == np.infty: t_h_up = h_max b = t_h_up d_low = get_distance_for_height_above_ground(t_h_low, z) d_up = get_distance_for_height_above_ground(b, z) # d_up_1 = d_low + 2.e3 # full_atm = 0 # points = get_distance_for_height_above_ground(atm_models[self.model]['h'], z).tolist() full_atm = integrate.quad(self._get_density4, d_low, d_up, args=(z,), limit=500)[0] # if d_up_1 > d_up: # else: # full_atm = integrate.quad(self._get_density4, # d_low, d_up_1, args=(z,), limit=100, epsabs=1e-4)[0] # full_atm += integrate.quad(self._get_density4, # d_up_1, d_up, args=(z,), limit=100, epsabs=1e-4)[0] # print "getting atmosphere numeric from ", d_low, "to ", d_up, ", = ", full_atm * 1e-4 tmp[i] = full_atm return tmp def _get_atmosphere_flat(self, zenith, h=0): a = atm_models[self.model]['a'] b = atm_models[self.model]['b'] c = atm_models[self.model]['c'] layers = atm_models[self.model]['h'] y = np.where(h < layers[0], a[0] + b[0] * np.exp(-1 * h / c[0]), a[1] + b[1] * np.exp(-1 * h / c[1])) y = np.where(h < layers[1], y, a[2] + b[2] * np.exp(-1 * h / c[2])) y = np.where(h < layers[2], y, a[3] + b[3] * np.exp(-1 * h / c[3])) y = np.where(h < layers[3], y, a[4] - b[4] * h / c[4]) y = np.where(h < h_max, y, 0) # print "getting flat atmosphere from h=%.2f to infinity = %.2f" % (h, y / np.cos(zenith) * 1e-4) return y / np.cos(zenith) # def _get_atmosphere2(self, zenith, h_low=0., h_up=np.infty): # if use_curved(zenith, self.curved): # from scipy import integrate # if h_up <= h_low: # print "WARNING: upper limit less than lower limit" # return np.nan # if h_up == np.infty: # h_up = h_max # b = h_up # d_low = get_distance_for_height_above_ground(h_low, zenith) # d_up = get_distance_for_height_above_ground(b, zenith) # d_up_1 = d_low + 2.e3 # if d_up_1 > d_up: # full_atm = integrate.quad(self._get_density4, # zenith, d_low, d_up, limit=100, epsabs=1e-2)[0] # else: # full_atm = integrate.quad(self._get_density4, # zenith, d_low, d_up_1, limit=100, epsabs=1e-4)[0] # full_atm += integrate.quad(self._get_density4, # zenith, d_up_1, d_up, limit=100, epsabs=1e-2)[0] # return full_atm # else: # return (_get_atmosphere(h_low, model=self.model) - _get_atmosphere(h_up, model=self.model)) / np.cos(zenith) # def get_atmosphere3(self, h_low=0., h_up=np.infty): # return self._get_atmosphere3(h_low=h_low, h_up=h_up) * 1e-4 # # def _get_atmosphere3(self, h_low=0., h_up=np.infty): # a = self.a # b = self.b # c = self.c # h = h_low # layers = atm_models[self.model]['h'] # dldh = self._get_dldh(h) # y = np.where(h < layers[0], a[0] + b[0] * np.exp(-1 * h / c[0]) * dldh[0], a[1] + b[1] * np.exp(-1 * h / c[1]) * dldh[1]) # y = np.where(h < layers[1], y, a[2] + b[2] * np.exp(-1 * h / c[2]) * dldh[2]) # y = np.where(h < layers[2], y, a[3] + b[3] * np.exp(-1 * h / c[3]) * dldh[3]) # y = np.where(h < layers[3], y, a[4] - b[4] * h / c[4] * dldh[4]) # y = np.where(h < h_max, y, 0) # return y def get_vertical_height(self, zenith, xmax): """ returns the (vertical) height above see level [in meters] as a function of zenith angle and Xmax [in g/cm^2] """ return self._get_vertical_height(zenith, xmax * 1e4) def _get_vertical_height(self, zenith, X): mask_flat, mask_taylor, mask_numeric = self.__get_method_mask(zenith) tmp = np.zeros_like(zenith) if np.sum(mask_numeric): print("get vertical height numeric", zenith) tmp[mask_numeric] = self._get_vertical_height_numeric(*self.__get_arguments(mask_numeric, zenith, X)) if np.sum(mask_taylor): tmp[mask_taylor] = self._get_vertical_height_numeric_taylor(*self.__get_arguments(mask_taylor, zenith, X)) if np.sum(mask_flat): print("get vertical height flat") tmp[mask_flat] = self._get_vertical_height_flat(*self.__get_arguments(mask_flat, zenith, X)) return tmp def __calculate_d(self): zeniths = np.arccos(np.linspace(0, 1, self.number_of_zeniths)) d = np.zeros((self.number_of_zeniths, 4)) self.curved = True self.__zenith_numeric = 0 for iZ, z in enumerate(zeniths): z = np.array([z]) print("calculating constants for %.02f deg zenith angle (iZ = %i, nT = %i)..." % (np.rad2deg(z), iZ, self.n_taylor)) d[iZ][0] = 0 X1 = self._get_atmosphere(z, self.h[1]) d[iZ][1] = self._get_vertical_height_numeric(z, X1) - self._get_vertical_height_taylor_wo_constants(z, X1) X2 = self._get_atmosphere(z, self.h[2]) d[iZ][2] = self._get_vertical_height_numeric(z, X2) - self._get_vertical_height_taylor_wo_constants(z, X2) X3 = self._get_atmosphere(z, self.h[3]) d[iZ][3] = self._get_vertical_height_numeric(z, X3) - self._get_vertical_height_taylor_wo_constants(z, X3) print("\t... d = ", d[iZ], " iZ = ", iZ) return d def _get_vertical_height_taylor(self, zenith, X): tmp = self._get_vertical_height_taylor_wo_constants(zenith, X) masks = self.__get_X_masks(X, zenith) d = self.d[self.__get_zenith_a_indices(zenith)] for iX, mask in enumerate(masks): if(np.sum(mask)): if iX < 4: # print mask # print tmp[mask], len(tmp[mask]) # print d[mask][..., iX] tmp[mask] += d[mask][..., iX] return tmp def _get_vertical_height_taylor_wo_constants(self, zenith, X): b = self.b c = self.c ct = np.cos(zenith) T0 = self._get_atmosphere(zenith) masks = self.__get_X_masks(X, zenith) # Xs = [self._get_atmosphere(zenith, h) for h in self.h] # d = np.array([self._get_vertical_height_numeric(zenith, t) for t in Xs]) tmp = np.zeros_like(zenith) for iX, mask in enumerate(masks): if(np.sum(mask)): if iX < 4: xx = X[mask] - T0[mask] # print "iX < 4", iX if self.n_taylor >= 1: tmp[mask] = -c[iX] / b[iX] * ct[mask] * xx if self.n_taylor >= 2: tmp[mask] += -0.5 * c[iX] * (ct[mask] ** 2 * c[iX] - ct[mask] ** 2 * r_e - c[iX]) / (r_e * b[iX] ** 2) * xx ** 2 if self.n_taylor >= 3: tmp[mask] += -1. / 6. * c[iX] * ct[mask] * (3 * ct[mask] ** 2 * c[iX] ** 2 - 4 * ct[mask] ** 2 * r_e * c[iX] + 2 * r_e ** 2 * ct[mask] ** 2 - 3 * c[iX] ** 2 + 4 * r_e * c[iX]) / (r_e ** 2 * b[iX] ** 3) * xx ** 3 if self.n_taylor >= 4: tmp[mask] += -1. / (24. * r_e ** 3 * b[iX] ** 4) * c[iX] * (15 * ct[mask] ** 4 * c[iX] ** 3 - 25 * c[iX] ** 2 * r_e * ct[mask] ** 4 + 18 * c[iX] * r_e ** 2 * ct[mask] ** 4 - 6 * r_e ** 3 * ct[mask] ** 4 - 18 * c[iX] ** 3 * ct[mask] ** 2 + 29 * c[iX] ** 2 * r_e * ct[mask] ** 2 - 18 * c[iX] * r_e ** 2 * ct[mask] ** 2 + 3 * c[iX] ** 3 - 4 * c[iX] ** 2 * r_e) * xx ** 4 if self.n_taylor >= 5: tmp[mask] += -1. / (120. * r_e ** 4 * b[iX] ** 5) * c[iX] * ct[mask] * (ct[mask] ** 4 * (105 * c[iX] ** 4 - 210 * c[iX] ** 3 * r_e + 190 * c[iX] ** 2 * r_e ** 2 - 96 * c[iX] * r_e ** 3 + 24 * r_e ** 4) + ct[mask] ** 2 * (-150 * c[iX] ** 4 + 288 * c[iX] ** 3 * r_e - 242 * c[iX] ** 2 * r_e ** 2 + 96 * c[iX] * r_e ** 3) + 45 * c[iX] ** 4 - 78 * r_e * c[iX] ** 3 + 52 * r_e ** 2 * c[iX] ** 2) * xx ** 5 if self.n_taylor >= 6: tmp[mask] += -1. / (720. * r_e ** 5 * b[iX] ** 6) * c[iX] * (ct[mask] ** 6 * (945 * c[iX] ** 5 - 2205 * c[iX] ** 4 * r_e + 2380 * c[iX] ** 3 * r_e ** 2 - 1526 * c[iX] ** 2 * r_e ** 3 + 600 * c[iX] * r_e ** 4 - 120 * r_e ** 5) + ct[mask] ** 4 * (-1575 * c[iX] ** 5 + 3528 * c[iX] ** 4 * r_e - 3600 * c[iX] ** 3 * r_e ** 2 + 2074 * c[iX] ** 2 * r_e ** 3 - 600 * c[iX] * r_e ** 4) + ct[mask] ** 2 * (675 * c[iX] ** 5 - 1401 * c[iX] ** 4 * r_e - 1272 * c[iX] ** 3 * r_e ** 2 - 548 * c[iX] ** 2 * r_e ** 3) - 45 * c[iX] ** 5 + 78 * c[iX] ** 4 * r_e - 52 * c[iX] ** 3 * r_e ** 2) * xx ** 6 elif iX == 4: print("iX == 4", iX) # numeric fallback tmp[mask] = self._get_vertical_height_numeric(zenith, X) else: print("iX > 4", iX) tmp[mask] = np.ones_like(mask) * h_max return tmp def _get_vertical_height_numeric(self, zenith, X): from scipy import optimize tmp = np.zeros_like(zenith) zenith = np.array(zenith) for i in xrange(len(tmp)): x0 = get_distance_for_height_above_ground(self._get_vertical_height_flat(zenith[i], X[i]), zenith[i]) def ftmp(d, zenith, xmax, observation_level=0): h = get_height_above_ground(d, zenith, observation_level=observation_level) h += observation_level tmp = self._get_atmosphere_numeric([zenith], h_low=h) dtmp = tmp - xmax return dtmp dxmax_geo = optimize.brentq(ftmp, -1e3, x0 + 1e4, xtol=1e-6, args=(zenith[i], X[i])) tmp[i] = get_height_above_ground(dxmax_geo, zenith[i]) return tmp def _get_vertical_height_numeric_taylor(self, zenith, X): from scipy import optimize tmp = np.zeros_like(zenith) zenith = np.array(zenith) for i in xrange(len(tmp)): if(X[i] < 0): X[i] = 0 x0 = get_distance_for_height_above_ground(self._get_vertical_height_flat(zenith[i], X[i]), zenith[i]) def ftmp(d, zenith, xmax, observation_level=0): h = get_height_above_ground(d, zenith, observation_level=observation_level) h += observation_level tmp = self._get_atmosphere_taylor(np.array([zenith]), h_low=np.array([h])) dtmp = tmp - xmax return dtmp # print zenith[i], X[i] dxmax_geo = optimize.brentq(ftmp, -1e3, x0 + 1e4, xtol=1e-6, args=(zenith[i], X[i])) tmp[i] = get_height_above_ground(dxmax_geo, zenith[i]) return tmp def _get_vertical_height_flat(self, zenith, X): return _get_vertical_height(X * np.cos(zenith), model=self.model) def get_density(self, zenith, xmax): """ returns the atmospheric density as a function of zenith angle and shower maximum Xmax (in g/cm^2) """ return self._get_density(zenith, xmax * 1e4) def _get_density(self, zenith, xmax): """ returns the atmospheric density as a function of zenith angle and shower maximum Xmax """ h = self._get_vertical_height(zenith, xmax) rho = get_density(h, model=self.model) return rho # def __get_density2_curved(self, xmax): # dxmax_geo = self._get_distance_xmax_geometric(xmax, observation_level=0) # return self._get_density4(dxmax_geo) # def _get_density4(self, d, zenith): h = get_height_above_ground(d, zenith) return get_density(h, model=self.model) def get_distance_xmax(self, zenith, xmax, observation_level=1564.): """ input: - xmax in g/cm^2 - zenith in radians output: distance to xmax in g/cm^2 """ dxmax = self._get_distance_xmax(zenith, xmax * 1e4, observation_level=observation_level) return dxmax * 1e-4 def _get_distance_xmax(self, zenith, xmax, observation_level=1564.): return self._get_atmosphere(zenith, h_low=observation_level) - xmax def get_distance_xmax_geometric(self, zenith, xmax, observation_level=1564.): """ input: - xmax in g/cm^2 - zenith in radians output: distance to xmax in m """ return self._get_distance_xmax_geometric(zenith, xmax * 1e4, observation_level=observation_level) def _get_distance_xmax_geometric(self, zenith, xmax, observation_level=1564.): h = self._get_vertical_height(zenith, xmax) - observation_level return get_distance_for_height_above_ground(h, zenith, observation_level) # def __get_distance_xmax_geometric_flat(self, xmax, observation_level=1564.): # # _get_vertical_height(xmax, self.model) # # dxmax = self._get_distance_xmax(xmax, observation_level=observation_level) # # txmax = _get_atmosphere(observation_level, model=self.model) - dxmax * np.cos(self.zenith) # # height = _get_vertical_height(txmax) # # return (height - observation_level) / np.cos(self.zenith) # # # height = _get_vertical_height(xmax * np.cos(self.zenith)) - observation_level # return height / np.cos(self.zenith) # full = _get_atmosphere(observation_level, model=self.model) / np.cos(self.zenith) # dxmax = full - xmax # height = _get_vertical_height(_get_atmosphere(0, model=self.model) - dxmax * np.cos(self.zenith)) # return height / np.cos(self.zenith) # def get_distance_xmax_geometric2(xmax, zenith, observation_level=1564., # model=1, curved=False): # """ input: # - xmax in g/cm^2 # - zenith in radians # output: distance to xmax in m # """ # return _get_distance_xmax_geometric2(zenith, xmax * 1e4, # observation_level=observation_level, # model=model, curved=curved) # def _get_distance_xmax_geometric2(zenith, xmax, observation_level=1564., # model=default_model, # curved=default_curved): # if curved: # from scipy import optimize # x0 = _get_distance_xmax_geometric(zenith, xmax, # observation_level=observation_level, # model=model, curved=False) # # def ftmp(d, dxmax, zenith, observation_level): # h = get_height_above_ground(d, zenith, observation_level=observation_level) # h += observation_level # dtmp = _get_atmosphere2(zenith, h_low=observation_level, h_up=h, model=model) - dxmax # print "d = %.5g, h = %.5g, dtmp = %.5g" % (d, h, dtmp) # return dtmp # # dxmax = _get_distance_xmax(xmax, zenith, observation_level=observation_level, curved=True) # print "distance to xmax = ", dxmax # tolerance = max(1e-3, x0 * 1.e-6) # dxmax_geo = optimize.newton(ftmp, x0=x0, maxiter=100, tol=tolerance, # args=(dxmax, zenith, observation_level)) # # print "x0 = %.7g, dxmax_geo = %.7g" % (x0, dxmax_geo) # return dxmax_geo # else: # dxmax = _get_distance_xmax(xmax, zenith, observation_level=observation_level, # model=model, curved=False) # xmax = _get_atmosphere(observation_level, model=model) - dxmax * np.cos(zenith) # height = _get_vertical_height(xmax) # return (height - observation_level) / np.cos(zenith) # ============================================================================= # setting up test suite # ============================================================================= class TestAtmosphericFunctions(unittest.TestCase): def test_height_above_ground_to_distance_transformation(self): zeniths = np.deg2rad(np.linspace(0, 90, 10)) for zenith in zeniths: heights = np.linspace(0, 1e5, 20) for h in heights: obs_levels = np.linspace(0, 2e3, 4) for obs in obs_levels: d = get_distance_for_height_above_ground(h, zenith, observation_level=obs) h2 = get_height_above_ground(d, zenith, observation_level=obs) self.assertAlmostEqual(h, h2) def test_flat_atmosphere(self): atm = Atmosphere(curved=False) zeniths = np.deg2rad(np.linspace(0, 89, 10)) heights = np.linspace(0, 1e4, 10) atm1 = atm.get_atmosphere(zeniths, heights) atm2 = atm.get_atmosphere(np.zeros(10), heights) / np.cos(zeniths) for i in xrange(len(atm1)): self.assertAlmostEqual(atm1[i], atm2[i]) heights2 = np.linspace(1e4, 1e5, 10) atm1 = atm.get_atmosphere(zeniths, heights, heights2) atm2 = atm.get_atmosphere(np.zeros(10), heights, heights2) / np.cos(zeniths) for i in xrange(len(atm1)): self.assertAlmostEqual(atm1[i], atm2[i]) z = np.deg2rad(50) atm1 = atm.get_atmosphere(z, 0) atm2 = atm.get_atmosphere(0, 0) / np.cos(z) self.assertAlmostEqual(atm1, atm2, delta=1e-3) atm1 = atm.get_atmosphere(z, 10, 1e4) atm2 = atm.get_atmosphere(0, 10, 1e4) / np.cos(z) self.assertAlmostEqual(atm1, atm2, delta=1e-3) def test_numeric_atmosphere(self): atm_flat = Atmosphere(curved=False) atm_num = Atmosphere(curved=True, zenith_numeric=0) zeniths = np.deg2rad(np.linspace(0, 20, 3)) atm1 = atm_flat.get_atmosphere(zeniths, 0) atm2 = atm_num.get_atmosphere(zeniths, 0) for i in xrange(len(atm1)): delta = 1e-3 + np.rad2deg(zeniths[i]) * 1e-2 self.assertAlmostEqual(atm1[i], atm2[i], delta=delta) atm1 = atm_flat.get_atmosphere(zeniths, 1e3) atm2 = atm_num.get_atmosphere(zeniths, 1e3) for i in xrange(len(atm1)): delta = 1e-3 + np.rad2deg(zeniths[i]) * 1e-2 self.assertAlmostEqual(atm1[i], atm2[i], delta=delta) atm1 = atm_flat.get_atmosphere(zeniths, 1e3, 1e4) atm2 = atm_num.get_atmosphere(zeniths, 1e3, 1e4) for i in xrange(len(atm1)): delta = 1e-3 + np.rad2deg(zeniths[i]) * 1e-2 self.assertAlmostEqual(atm1[i], atm2[i], delta=delta) z = np.deg2rad(0) atm1 = atm_flat.get_atmosphere(z, 0) atm2 = atm_num.get_atmosphere(z, 0) self.assertAlmostEqual(atm1, atm2, delta=1e-3) atm1 = atm_flat.get_atmosphere(z, 10, 1e4) atm2 = atm_num.get_atmosphere(z, 10, 1e4) self.assertAlmostEqual(atm1, atm2, delta=1e-2) def test_taylor_atmosphere(self): atm_taylor = Atmosphere(curved=True) atm_num = Atmosphere(curved=True, zenith_numeric=0) for h in np.linspace(0, 1e4, 10): atm1 = atm_taylor.get_atmosphere(0, h_low=h) atm2 = atm_num.get_atmosphere(0, h_low=h) self.assertAlmostEqual(atm1, atm2, delta=1e-3) zeniths = np.deg2rad([0, 11.478341, 30.683417]) for i in xrange(len(zeniths)): delta = 1e-6 atm1 = atm_taylor.get_atmosphere(zeniths[i], 0) atm2 = atm_num.get_atmosphere(zeniths[i], 0) self.assertAlmostEqual(atm1, atm2, delta=delta) atm1 = atm_taylor.get_atmosphere(zeniths, 1e3) atm2 = atm_num.get_atmosphere(zeniths, 1e3) for i in xrange(len(atm1)): delta = 1e-5 self.assertAlmostEqual(atm1[i], atm2[i], delta=delta) atm1 = atm_taylor.get_atmosphere(zeniths, 1e3, 1e4) atm2 = atm_num.get_atmosphere(zeniths, 1e3, 1e4) for i in xrange(len(atm1)): delta = 1e-5 self.assertAlmostEqual(atm1[i], atm2[i], delta=delta) z = np.deg2rad(0) atm1 = atm_taylor.get_atmosphere(z, 0) atm2 = atm_num.get_atmosphere(z, 0) self.assertAlmostEqual(atm1, atm2, delta=1e-3) atm1 = atm_taylor.get_atmosphere(z, 10, 1e4) atm2 = atm_num.get_atmosphere(z, 10, 1e4) self.assertAlmostEqual(atm1, atm2, delta=1e-2) def test_taylor_atmosphere2(self): atm_taylor = Atmosphere(curved=True) atm_num = Atmosphere(curved=True, zenith_numeric=0) zeniths = np.deg2rad(np.linspace(0, 83, 20)) for i in xrange(len(zeniths)): delta = 1e-3 # print "checking z = %.1f" % np.rad2deg(zeniths[i]) atm1 = atm_taylor.get_atmosphere(zeniths[i], 0) atm2 = atm_num.get_atmosphere(zeniths[i], 0) delta = max(delta, 1.e-5 * atm1) self.assertAlmostEqual(atm1, atm2, delta=delta) zeniths = np.deg2rad(np.linspace(0, 83, 20)) for i in xrange(len(zeniths)): delta = 1e-2 # print "checking z = %.1f" % np.rad2deg(zeniths[i]) atm1 = atm_taylor.get_atmosphere(zeniths[i], 1e3) atm2 = atm_num.get_atmosphere(zeniths[i], 1e3) self.assertAlmostEqual(atm1, atm2, delta=delta) zeniths = np.deg2rad(np.linspace(0, 83, 20)) for i in xrange(len(zeniths)): delta = 1e-2 # print "checking z = %.1f" % np.rad2deg(zeniths[i]) atm1 = atm_taylor.get_atmosphere(zeniths[i], 0, 1e4) atm2 = atm_num.get_atmosphere(zeniths[i], 0, 1e4) self.assertAlmostEqual(atm1, atm2, delta=delta) def test_vertical_height_flat_numeric(self): atm_flat = Atmosphere(curved=False) atm_num = Atmosphere(curved=True, zenith_numeric=0) zenith = 0 xmax = np.linspace(300, 900, 20) atm1 = atm_flat.get_vertical_height(zenith * np.ones_like(xmax), xmax) atm2 = atm_num.get_vertical_height(zenith * np.ones_like(xmax), xmax) for i in xrange(len(xmax)): self.assertAlmostEqual(atm1[i], atm2[i], delta=1e-2) zeniths = np.deg2rad(np.linspace(0, 30, 4)) xmax = 600 atm1 = atm_flat.get_vertical_height(zeniths, xmax) atm2 = atm_num.get_vertical_height(zeniths, xmax) for i in xrange(len(zeniths)): self.assertAlmostEqual(atm1[i], atm2[i], delta=1e-3 * atm1[i]) def test_vertical_height_taylor_numeric(self): atm_taylor = Atmosphere(curved=True) atm_num = Atmosphere(curved=True, zenith_numeric=0) zeniths = np.deg2rad(np.linspace(0, 85, 30)) xmax = 600 atm1 = atm_taylor.get_vertical_height(zeniths, xmax) atm2 = atm_num.get_vertical_height(zeniths, xmax) for i in xrange(len(zeniths)): # print "zenith = ", np.rad2deg(zeniths[i]) self.assertAlmostEqual(atm1[i], atm2[i], delta=2e-5 * atm1[i]) # # def test_atmosphere_above_height_for_flat_atm(self): # curved = False # zeniths = np.deg2rad(np.linspace(0, 70, 8)) # for zenith in zeniths: # catm = Atmosphere(zenith, curved=curved) # heights = np.linspace(0, 1e5, 20) # for h in heights: # atm = get_atmosphere(h) / np.cos(zenith) # atm2 = catm.get_atmosphere2(h_low=h) # self.assertAlmostEqual(atm, atm2) # # def test_density_for_flat_atm(self): # curved = False # zeniths = np.deg2rad(np.linspace(0, 70, 8)) # for zenith in zeniths: # catm = Atmosphere(zenith, curved=curved) # heights = np.linspace(0, 1e5, 20) # for h in heights: # rho = get_density(h) # xmax = catm.get_atmosphere2(h_low=h) # rho2 = catm.get_density2(xmax) # self.assertAlmostEqual(rho, rho2) # # def test_numerical_density_integration(self): # # def allowed_discrepancy(zenith): # z = np.rad2deg(zenith) # return z ** 2 / 2500 + z / 90. + 1e-2 # # zeniths = np.deg2rad(np.linspace(0, 40, 5)) # for zenith in zeniths: # catm = Atmosphere(zenith) # heights = np.linspace(0, 1e4, 2) # for h in heights: # atm1 = get_atmosphere(h) / np.cos(zenith) # atm2 = catm.get_atmosphere2(h_low=h) # self.assertAlmostEqual(atm1, atm2, delta=allowed_discrepancy(zenith)) # # def test_get_distance_to_xmax_flat_vs_curved(self): # # def allowed_discrepancy(zenith): # z = np.rad2deg(zenith) # return z ** 2 / 2500 + z / 90. + 1e-2 # # zeniths = np.deg2rad(np.linspace(0, 40, 5)) # for zenith in zeniths: # catm = Atmosphere(zenith) # catm_flat = Atmosphere(zenith, curved=False) # xmaxs = np.linspace(0, 1e3, 4) # for xmax in xmaxs: # dxmax1 = catm_flat.get_distance_xmax(xmax, observation_level=0) # dxmax2 = catm.get_distance_xmax(xmax, observation_level=0) # # print "zenith %.0f xmax = %.2g, %.5g, %.5g" % (np.rad2deg(zenith), xmax, dxmax1, dxmax2) # self.assertAlmostEqual(dxmax1, dxmax2, delta=allowed_discrepancy(zenith)) # # def test_get_distance_to_xmax_geometric_flat_self_consitency(self): # # print # # print # # print "test_get_distance_to_xmax_geometric_flat_self_consitency" # zeniths = np.deg2rad(np.linspace(0, 80, 9)) # dxmaxs = np.linspace(0, 4e3, 5) # obs_levels = np.linspace(0, 2e3, 4) # for dxmax1 in dxmaxs: # for zenith in zeniths: # catm = Atmosphere(zenith, curved=False) # for obs in obs_levels: # # print "\tdxmax1 = %.4f, z=%.1f observation level = %.2f" % (dxmax1, np.rad2deg(zenith), obs) # h1 = dxmax1 * np.cos(zenith) + obs # xmax = get_atmosphere(h1) / np.cos(zenith) # dxmax2 = catm.get_distance_xmax_geometric(xmax, observation_level=obs) # self.assertAlmostEqual(dxmax1, dxmax2, delta=1e-5) # # def test_get_distance_to_xmax_geometric_curved_self_consitency(self): # # print # # print # # print "test_get_distance_to_xmax_geometric_curved_self_consitency" # zeniths = np.deg2rad(np.linspace(0, 89, 10)) # dxmaxs = np.linspace(0, 4e3, 5) # obs_levels = np.linspace(0, 2e3, 5) # for dxmax1 in dxmaxs: # # print "checking dxmax = %.2f" % dxmax1 # for zenith in zeniths: # # print "checking zenith angle of %.1f" % (np.rad2deg(zenith)) # catm = Atmosphere(zenith) # delta = 1e-4 # if zenith > np.deg2rad(85): # delta = 1.e-2 # for obs in obs_levels: # # print "\tdxmax1 = %.4f, z=%.1f observation level = %.2f" % (dxmax1, np.rad2deg(zenith), obs) # # print "testing" # h1 = get_height_above_ground(dxmax1, zenith, observation_level=obs) + obs # xmax = catm.get_atmosphere2(h_low=h1) # # print "zenith %.0f dmax = %.2g, obslevel = %.3g -> h1 = %.3g, xmax = %.3g" % (np.rad2deg(zenith), dxmax1, obs, h1, xmax) # dxmax2 = catm.get_distance_xmax_geometric(xmax, observation_level=obs) # self.assertAlmostEqual(dxmax1, dxmax2, delta=delta) # # def test_get_distance_to_xmax_geometric_flat_vs_curved(self): # # print # # print # # print "test_get_distance_to_xmax_geometric_flat_vs_curved" # # def allowed_discrepancy(zenith): # z = np.rad2deg(zenith) # return z ** 2 / 20.**2 * 1e-3 + 1e-3 # # zeniths = np.deg2rad(np.linspace(0, 60, 7)) # xmaxs = np.linspace(100, 900, 4) # obs_levels = np.linspace(0, 1.5e3, 4) # for zenith in zeniths: # catm = Atmosphere(zenith) # catm_flat = Atmosphere(zenith, curved=False) # for xmax in xmaxs: # for obs in obs_levels: # dxmax1 = catm_flat.get_distance_xmax_geometric(xmax, observation_level=obs) # dxmax2 = catm.get_distance_xmax_geometric(xmax, observation_level=obs) # # print "zenith %.0f xmax = %.2g, obslevel = %.3g, %.5g, %.5g %.2g" % (np.rad2deg(zenith), xmax, obs, dxmax1, dxmax2, 3 + np.abs(dxmax1 * allowed_discrepancy(zenith))) # self.assertAlmostEqual(dxmax1, dxmax2, delta=3. + np.abs(dxmax1 * allowed_discrepancy(zenith))) # def test_get_distance_to_xmax_geometric_flat_vs_curved2(self): # # def allowed_discrepancy(zenith): # z = np.rad2deg(zenith) # return z ** 2 / 20.**2 * 1e-3 + 1e-3 # # zeniths = np.deg2rad(np.linspace(0, 60, 7)) # xmaxs = np.linspace(0, 900, 4) # obs_levels = np.linspace(0, 1.5e3, 4) # for zenith in zeniths: # for xmax in xmaxs: # for obs in obs_levels: # print # print "testing " # dxmax1 = get_distance_xmax_geometric2(xmax, zenith, observation_level=obs, curved=False) # if dxmax1 < 0: # print "\t skipping negetive distances" # continue # print "zenith %.0f xmax = %.2g, obslevel = %.3g, %.5g" % (np.rad2deg(zenith), xmax, obs, dxmax1) # dxmax2 = get_distance_xmax_geometric2(xmax, zenith, observation_level=obs, curved=True) # print "zenith %.0f xmax = %.2g, obslevel = %.3g, %.5g, %.5g %.2g" % (np.rad2deg(zenith), xmax, obs, dxmax1, dxmax2, 1e-1 + np.abs(dxmax1 * allowed_discrepancy(zenith))) # self.assertAlmostEqual(dxmax1, dxmax2, delta=3. + np.abs(dxmax1 * allowed_discrepancy(zenith))) if __name__ == "__main__": unittest.main() PKZL! ooradiotools/coreas/GE.py def get_GE_preexecution(jobname=None, rundir=None, mailflags='beas', ncores=1, mpi=False): import StringIO output = StringIO.StringIO() output.write("#!/bin/bash\n") output.write("#$ -N {}\n".format(jobname)) output.write("#$ -j y\n") output.write("#$ -V\n") output.write("#$ -q grb,grb64\n") output.write("#$ -m {}\n".format(mailflags)) output.write("#$ -o {}\n".format(rundir)) if(mpi): output.write("#$ -pe mpi {}\n".format(ncores)) output.write("#$ -R y\n") return output.getvalue() PK\ZLH-'radiotools/coreas/LSF.py def get_LSF_preexecution(jobname=None, outputlog=None, runtime=1, memory=1850., ncores=12, projectid=None, mpi=True, hpcwork=True, email=None): import StringIO import numpy as np import copy output = StringIO.StringIO() output.write("#!/usr/bin/env zsh\n") output.write("### Job name\n") output.write("#BSUB -J %s\n" % jobname) output.write("### File / path where STDOUT & STDERR will be written\n") output.write("### %J is the job ID, %I is the array ID\n") if outputlog is None: output.write("#BSUB -o parcotest.%J.%I\n") else: output.write("#BSUB -o %s\n" % outputlog) if email is not None: output.write("#BSUB -B\n") output.write("#BSUB -N\n") output.write("#BSUB -u %s\n" % email) if projectid is not None: output.write("#BSUB -P %s\n" % projectid) output.write("#BSUB -W %i:%02i\n" % (int(np.floor(runtime)), (runtime % 1) * 60)) output.write("#BSUB -M %.0f\n" % memory) output.write("#BSUB -S 600 # increase stack size\n") output.write("#BSUB -n %i\n" % ncores) output.write("#BSUB -x\n") if mpi: output.write("#BSUB -m mpi-s\n") output.write("#BSUB -a openmpi\n") output.write("#BSUB -R \"span[ptile=12]\"\n") if hpcwork: output.write("#BSUB -R \"select[hpcwork]\"\n") output.write("module load python/2.7.11\n") return output.getvalue() PKYZLradiotools/coreas/__init__.pyPK\L6rJrJ(radiotools/coreas/generate_coreas_sim.pyfrom __future__ import absolute_import, division, print_function # , unicode_literals import os import stat import numpy as np from radiotools import coordinatesystems from radiotools import helper as hp # $_CONDOR_SCRATCH_DIR def write_sh_geninponly(filename, output_dir, run_dir, corsika_executable, seed, particle_type, event_number, energy, zenith, azimuth, tmp_dir="/tmp", geninp_path="", atm=1, conex=False, obs_level=1564., flupro="", flufor="gfortran", pre_executionskript=None, parallel=False, B=[19.71, -14.18], thinning=1e-6, ecuts=[1.000E-01, 5.000E-02, 2.500E-04, 2.500E-04]): scratchdir = '$TMPDIR/glaser/%i/%i/' % (int(event_number), int(particle_type)) fout = open(filename, 'w') if pre_executionskript is not None: fin = open(pre_executionskript, "r") fout.write(fin.read()) fin.close() else: fout.write('#! /bin/bash\n') fout.write('export RUNNR=%06i\n' % int(event_number)) fout.write('{17}geninp_aera.py -r $RUNNR -s {0} -u {1} -a {2} -z {3} -t {4} -d {5} --atm {6} --conex {7} --obslevel {8} --parallel {9} --Bx {10} --Bz {11} --thinning {12} --ecuts {13} {14} {15} {16} > {5}/RUN$RUNNR.inp\n'.format(seed, energy * 1e-9, 180. * azimuth / np.pi, 180 * zenith / np.pi, particle_type, ".", atm, int(conex), obs_level, int(parallel), B[0], B[1], thinning, ecuts[0], ecuts[1], ecuts[2], ecuts[3], geninp_path)) fout.close() os.chmod(filename, stat.S_IXUSR + stat.S_IWUSR + stat.S_IRUSR) def write_sh(filename, output_dir, run_dir, corsika_executable, seed, particle_type, event_number, energy, zenith, azimuth, tmp_dir="/tmp", radiotools_path="", hdf5converter="", atm=1, conex=False, obs_level=1564., flupro="", flufor="gfortran", pre_executionscript_filename=None, pre_executionscript=None, particles=True, parallel=False, parallel_cut=1e-2, B=[19.71, -14.18], thinning=1e-6, ecuts=[1.000E-01, 5.000E-02, 2.500E-04, 2.500E-04], stepfc=1): scratchdir = '$TMPDIR/glaser/%i/%i/' % (int(event_number), int(particle_type)) fout = open(filename, 'w') if pre_executionscript is not None: fout.write(pre_executionscript) elif pre_executionscript_filename is not None: fin = open(pre_executionscript_filename, "r") fout.write(fin.read()) fin.close() else: fout.write('#! /bin/bash\n') fout.write('export FLUFOR=%s\n' % flufor) fout.write('export FLUPRO=%s\n' % flupro) fout.write('export TMPDIR=%s\n' % tmp_dir) fout.write('export RUNNR=%06i\n' % int(event_number)) fout.write('cd ' + run_dir + '/\n') fout.write('rm -rf {0}$RUNNR\n'.format(scratchdir)) fout.write('mkdir -p {0}$RUNNR\n'.format(scratchdir)) executable = os.path.join(radiotools_path, "radiotools", "coreas", "geninp_aera.py") fout.write('{17} -r $RUNNR -s {0} -u {1} -a {2} -z {3} -t {4} -d {5}$RUNNR/ --atm {6} --conex {7} --obslevel {8} --parallel {9} --Bx {10} --Bz {11} --thinning {12} --ecuts {13} {14} {15} {16} --pcut {18} --particles {19} --stepfc {20} > {5}$RUNNR/RUN$RUNNR.inp\n'.format(seed, energy * 1e-9, 180. * azimuth / np.pi, 180 * zenith / np.pi, particle_type, scratchdir, atm, int(conex), obs_level, int(parallel), B[0], B[1], thinning, ecuts[0], ecuts[1], ecuts[2], ecuts[3], executable, parallel_cut, int(particles), stepfc)) fout.write('cp ' + run_dir + '/SIM$RUNNR.reas {1}$RUNNR/SIM$RUNNR.reas\n'.format(event_number, scratchdir)) fout.write('cp ' + run_dir + '/SIM$RUNNR.list {1}$RUNNR/SIM$RUNNR.list\n'.format(event_number, scratchdir)) if (int(particle_type) == 14): fout.write('cp ' + run_dir + '/simprot_$RUNNR.reas {1}$RUNNR/SIM$RUNNR.reas\n'.format(event_number, scratchdir)) fout.write('cp ' + run_dir + '/simprot_$RUNNR.list {1}$RUNNR/SIM$RUNNR.list\n'.format(event_number, scratchdir)) elif (int(particle_type) == 5626): fout.write('cp ' + run_dir + '/simiron_$RUNNR.reas {1}$RUNNR/SIM$RUNNR.reas\n'.format(event_number, scratchdir)) fout.write('cp ' + run_dir + '/simiron_$RUNNR.list {1}$RUNNR/SIM$RUNNR.list\n'.format(event_number, scratchdir)) fout.write('cd ' + os.path.dirname(corsika_executable) + '\n') fout.write('echo "starting CORSIKA simulation at $(date)"\n') if(parallel): fout.write('$MPIEXEC $FLAGS_MPI_BATCH ' + os.path.basename(corsika_executable) + ' {0}$RUNNR/RUN$RUNNR.inp > {0}$RUNNR/RUN$RUNNR.out \n'.format(scratchdir)) else: fout.write('./' + os.path.basename(corsika_executable) + ' < {0}$RUNNR/RUN$RUNNR.inp > {0}$RUNNR/RUN$RUNNR.out \n'.format(scratchdir)) fout.write('echo "CORSIKA simulation finished on $(date)"\n') fout.write('rm -rf {0}/$RUNNR.tar.gz\n'.format(output_dir)) fout.write('mkdir -p {0}\n'.format(output_dir)) fout.write('cd {0}\n'.format(scratchdir)) # fout.write('mv RUN$RUNNR.inp {0}steering/RUN$RUNNR.inp\n'.format(dir)) # fout.write('mv SIM$RUNNR.reas {0}steering/SIM$RUNNR.reas\n'.format(dir)) # fout.write('mv SIM$RUNNR.list {0}steering/SIM$RUNNR.list\n'.format(dir)) fout.write('cwd=${PWD##*/}\n') fout.write('if [ $cwd != "run" ]\n') fout.write('then\n') # fout.write('\trm *flout*\n') # fout.write('\trm *flerr*\n') # fout.write('\ttar --remove-files -cf DAT$RUNNR.tar DAT$RUNNR-*.lst\n') # fout.write('\tmkdir {0}\n'.format(os.path.join(output_dir, "../pickle"))) fout.write('\tmkdir {0}\n'.format(os.path.join(output_dir, "../hdf5"))) fout.write('\texport PYTHONPATH={0}:$PYTHONPATH\n'.format(radiotools_path)) executable = os.path.join(radiotools_path, "radiotools", "coreas", "pickle_sim_to_class.py") particle_identifier = "xx" if (int(particle_type) == 14): particle_identifier = "p" if (int(particle_type) == 5626): particle_identifier = "Fe" # fout.write('\tpython {0} -s -d $RUNNR -o {1} --particle-type {2}\n'.format(executable, os.path.join(output_dir, "../pickle"), particle_identifier)) fout.write('\tpython {} $RUNNR/SIM$RUNNR.reas -o {outputdir} \n'.format(hdf5converter, outputdir=os.path.join(output_dir, "../hdf5"))) if(parallel): # merge particle outputs in case of MPI simulation executable = os.path.join(os.path.dirname(corsika_executable), "..", "coast/CorsikaFileIO", "merge_corsika") fout.write('\tif [ -f %s ]; then\n' % executable) fout.write('\t\techo \"merging particle files\"\n') fout.write('\t\t%s -i \"$RUNNR\"/DAT\"$RUNNR\"-?????? -o \"$RUNNR\"/DAT\"$RUNNR\".part\n' % (executable)) fout.write('\t\tif [ -f \"$RUNNR\"/DAT\"$RUNNR\".part ]; then\n') fout.write('\t\t\trm \"$RUNNR\"/DAT\"$RUNNR\"-??????\n') fout.write('\t\tfi\n') fout.write('\tfi\n') fout.write('\tmv \"$RUNNR\"/DAT\"$RUNNR\"-999999999.long \"$RUNNR\"/DAT\"$RUNNR\".long\n') # fout.write('\ttar -C $RUNNR --remove-files -czf $RUNNR.tar.gz .\n') # fout.write('\tmv $RUNNR.tar.gz {0}/\n'.format(output_dir)) fout.write('\tmv $RUNNR {0}/\n'.format(output_dir)) fout.write('\techo "CoREAS output pickleld and zipped and copied to final destination on $(date)"\n') # fout.write('\tcd {0}\n'.format(output_dir)) fout.write('else\n') fout.write('\techo "ERROR: still in run directory"\n') fout.write('fi\n') fout.close() os.chmod(filename, stat.S_IXUSR + stat.S_IWUSR + stat.S_IRUSR) def write_reas(filename, obs_level=1564., run_number=1, event_number=1, n=1.000292, core_offline=np.array([0, 0, 0]), cs_offline="", magnetic_field_declination=0): fout = open(filename, 'w') fout.write("# CoREAS V1 parameter file\n") fout.write("# parameters setting up the spatial observer configuration:\n") fout.write("CoreCoordinateNorth = 0 ; in cm\n") fout.write("CoreCoordinateWest = 0 ; in cm\n") fout.write("CoreCoordinateVertical = %.2f ; in cm\n" % (obs_level * 100.)) fout.write("# parameters setting up the temporal observer configuration:\n") fout.write("TimeResolution = 2e-10 ; in s\n") fout.write("AutomaticTimeBoundaries = 4e-07 ; 0: off, x: automatic boundaries with width x in s\n") fout.write("TimeLowerBoundary = -1 ; in s, only if AutomaticTimeBoundaries set to 0\n") fout.write("TimeUpperBoundary = 1 ; in s, only if AutomaticTimeBoundaries set to 0\n") fout.write("ResolutionReductionScale = 0 ; 0: off, x: decrease time resolution linearly every x cm in radius\n") fout.write("# parameters setting up the simulation functionality:\n") fout.write("GroundLevelRefractiveIndex = %.8f ; specify refractive index at 0 m asl\n" % n) fout.write("# event information for Offline simulations:\n") fout.write("EventNumber = %i\n" % event_number) fout.write("RunNumber = %i\n" % run_number) fout.write("GPSSecs = 0\n") fout.write("GPSNanoSecs = 0\n") fout.write("CoreEastingOffline = %.4f ; in meters\n" % core_offline[0]) fout.write("CoreNorthingOffline = %.4f ; in meters\n" % core_offline[1]) fout.write("CoreVerticalOffline = %.4f ; in meters\n" % core_offline[2]) fout.write("OfflineCoordinateSystem = %s ; in meters\n" % cs_offline) fout.write("RotationAngleForMagfieldDeclination = %.6f ; in degrees\n" % (np.rad2deg(magnetic_field_declination))) fout.write("Comment =\n") fout.write("CorsikaFilePath = ./\n") fout.write("CorsikaParameterFile = RUN%06i.inp\n" % event_number) fout.close() def write_list(filename, station_positions, station_name=None, append=False): if not append or not os.path.exists(filename): fout = open(filename, 'w') fout.close() fout = open(filename, 'a') for i, position in enumerate(station_positions): if station_name is not None: name = station_name[i] else: name = "station_%i" % (i) fout.write('AntennaPosition = {0} {1} {2} {3}\n'.format(position[1] * 100., -1 * position[0] * 100., position[2] * 100., name)) fout.close() def write_list_star_pattern(filename, zen, az, append=False, obs_level=1564.0, obs_level_corsika=None, inc=np.deg2rad(-35.7324), ground_plane=True, r_min=0., r_max=500., rs=None, slicing_method=None, slices=[], n_rings=20, azimuths=np.deg2rad([0, 45, 90, 135, 180, 225, 270, 315]), gammacut=None): """ if the list file should contain more than one observation level, both the current observation level as well as the CORSIKA observation level needs to be specified as the x, y coordinates are relativ to the core position at the CORSIKA observation level. The coordinates for all observation levels that differ from the CORSIKA observation level need to be shifted along the shower axis accordingly. """ if not append or not os.path.exists(filename): fout = open(filename, 'w') fout.close() if obs_level_corsika is None: obs_level_corsika = obs_level # compute translation in x and y r = np.tan(zen) * (obs_level - obs_level_corsika) deltax = np.cos(az) * r deltay = np.sin(az) * r fout = open(filename, 'a') B = np.array([0, np.cos(inc), -np.sin(inc)]) cs = coordinatesystems.cstrafo(zen, az, magnetic_field_vector=B) observation_plane_string = "gp" if not ground_plane: observation_plane_string = "sp" if rs is None: rs = np.linspace(r_min, r_max, n_rings + 1) else: n_rings = len(rs) rs = np.append(0, rs) for i in np.arange(1, n_rings + 1): for j in np.arange(len(azimuths)): station_position = rs[i] * hp.spherical_to_cartesian(np.pi * 0.5, azimuths[j]) # name = "pos_%i_%i" % (rs[i], np.rad2deg(azimuths[j])) name = "pos_%i_%i_%.0f_%s" % (rs[i], np.rad2deg(azimuths[j]), obs_level, observation_plane_string) if(ground_plane): pos_2d = cs.transform_from_vxB_vxvxB_2D(station_position) # position if height in observer plane should be zero pos_2d[0] += deltax pos_2d[1] += deltay x, y, z = 100 * pos_2d[1], -100 * pos_2d[0], 100 * obs_level else: pos = cs.transform_from_vxB_vxvxB(station_position) pos[0] += deltax pos[1] += deltay x, y, z = 100 * pos[1], -100 * pos[0], 100 * (pos[2] + obs_level) if(slicing_method is None): if gammacut is None: fout.write('AntennaPosition = {0} {1} {2} {3}\n'.format(x, y, z, name)) else: for iG, gcut in enumerate(gammacut): name = "pos_%i_%i_gamma%i" % (rs[i], np.rad2deg(azimuths[j]), iG) fout.write('AntennaPosition = {0} {1} {2} {3} gamma {4} {5}\n'.format(x, y, z, name, gcut[0], gcut[1])) else: if(len(slices) <= 1): print("ERROR: at least one slice must be specified") raise if(not (slicing_method == "distance" or slicing_method == "slantdepth")): print("ERROR: slicing method must be either distance or slantdepth") raise slices = np.array(slices) if(slicing_method == "distance"): slices *= 100 for iSlice in xrange(len(slices) - 1): name = "pos_%i_%i_slice%i" % (rs[i], np.rad2deg(azimuths[j]), iSlice) if gammacut is None: fout.write('AntennaPosition = {0} {1} {2} {3} {4} {5} {6}\n'.format(x, y, z, name, slicing_method, slices[iSlice] * 100., slices[iSlice + 1] * 100.)) else: for iG, gcut in enumerate(gammacut): name_gamma = "%s_gamma%i" % (name, iG) fout.write('AntennaPosition = {0} {1} {2} {3} {4} {5} {6} gamma {7} {8}\n'.format(x, y, z, name_gamma, slicing_method, slices[iSlice] * 100., slices[iSlice + 1] * 100., gcut[0], gcut[1])) fout.close() # def write_list_multiple_heights(filename, zen, az, obs_level=[1564., 0.], # inc=np.deg2rad(-35.7324), zero_height=True, r_min=0., r_max=500., # slicing_method="", slices=[], n_rings=20, # azimuths=np.deg2rad([0, 45, 90, 135, 180, 225, 270, 315]), # atm_model=1): # """ # inc is the inclination of the magnetic field from CoREAS repo (at AERA site) # """ # fout = open(filename, 'w') # B = np.array([0, np.cos(inc), -np.sin(inc)]) # cs = CSTransformation.CSTransformation(zen, az, magnetic_field=B) # # def get_rmax(X): # return 0.37 * X + 2e-5 * X ** 2 # LDF_falloff2.pdf # # for h in obs_level: # # # compute translation in x and y # r = np.tan(zen) * (h - 0) # deltax = np.cos(az) * r # deltay = np.sin(az) * r # # from atmosphere import models as atm # d = h / np.cos(zen) # h2 = atm.get_height_above_ground(d, zen, observation_level=0) # Xst = atm.get_atmosphere2(zen, h_low=h2, model=atm_model) # # Xst = atm.get_atmosphere(h) / np.cos(zen) # rmax = get_rmax(Xst) # rs = np.append(0.005 * rmax, np.append(np.linspace(0.01 * rmax, rmax * 0.15, 12), # np.linspace(rmax * 0.20, rmax, 17))) # # for i, r in enumerate(rs): # for j in np.arange(len(azimuths)): # station_position = rs[i] * hp.SphericalToCartesian(np.pi * 0.5, azimuths[j]) # pos = cs.transform_from_vxB_vxvxB(station_position) # pos_2d = cs.transform_from_vxB_vxvxB_2D(station_position) # position if height in observer plane should be zero # # pos[0] += deltax # pos[1] += deltay # pos_2d[0] += deltax # pos_2d[1] += deltay # # name = "pos_%i_%i_%.0f_%.0f" % (rs[i], np.rad2deg(azimuths[j]), Xst, h) # x, y, z = 100 * pos[1], -100 * pos[0], 100 * (pos[2] + h) # if(zero_height): # x, y, z = 100 * pos_2d[1], -100 * pos_2d[0], 100 * h # if(slicing_method == ""): # fout.write('AntennaPosition = {0} {1} {2} {3}\n'.format(x, y, z, name)) # else: # if(len(slices) <= 1): # print("ERROR: at least one slice must be specified") # raise # if(not (slicing_method == "distance" or slicing_method == "slantdepth")): # print("ERROR: slicing method must be either distance or slantdepth") # raise # slices = np.array(slices) # if(slicing_method == "distance"): # slices *= 100 # for iSlice in xrange(len(slices) - 1): # fout.write('AntennaPosition = {0} {1} {2} {3} {4} {5} {6}\n'.format(x, y, z, name, slicing_method, slices[iSlice] * 100., slices[iSlice + 1] * 100.)) # fout.close() def get_radius(zenith, dxmax, rel=0.01): Amax = LDF2D(0, 0, zenith, dxmax) for x in np.arange(10, 2000, 10): if(LDF2D(x, 0, zenith, dxmax) < (rel * Amax)): return x return 100 def LDF2D(x, y, zenith, dxmax, cx=0, cy=0): c0 = 0.41 c3 = 16.25 c4 = 0.0079 if zenith < np.deg2rad(10): c1 = 8. c2 = -21.2 elif zenith < np.deg2rad(20): c1 = 10. c2 = -23.1 elif zenith < np.deg2rad(30): c1 = 12. c2 = -25.5 elif zenith < np.deg2rad(40): c1 = 20. c2 = -32. elif zenith < np.deg2rad(50): c1 = 25.1 c2 = -34.5 elif zenith < np.deg2rad(55): c1 = 27.3 c2 = -9.8 c0 = 0.46 elif zenith >= np.deg2rad(55): c1 = 27.3 c2 = -9.8 c0 = 0.71 # dxmax = hp.get_distance_xmax(xmax, zenith, observation_level) s1 = 37.7 - 0.006 * dxmax + 5.5e-4 * dxmax ** 2 - 3.7e-7 * dxmax ** 3 s2 = 26.9 - 0.041 * dxmax + 2e-4 * dxmax ** 2 A = 1. # only relative scaling is important p1 = A * np.exp(-((x - cx + c1) ** 2 + (y - cy) ** 2) / s1 ** 2) p2 = A * c0 * np.exp(-((x - cx + c2) ** 2 + (y - cy) ** 2) / (s2) ** 2) return p1 - p2 if __name__ == "__main__": write_list("/tmp/test_write_list.list", np.deg2rad(40), 63. / 12. * np.pi, zero_height=False) PK ZL;d   radiotools/coreas/geninp_aera.py#!/usr/bin/env python2 # -*- coding: utf-8 -*- from optparse import OptionParser # Parse commandline options parser = OptionParser() parser.add_option("-r", "--runnumber", default="0", help="number of run") parser.add_option("-s", "--seed", default="1", help="seed 1") parser.add_option("-u", "--energy", default="1e8", help="cr energy (GeV)") parser.add_option("-t", "--type", default="14", help="particle type ") parser.add_option("-a", "--azimuth", default="0", help="azimuth (degrees; AUGER definition)") parser.add_option("-z", "--zenith", default="0", help="zenith (degrees; AUGER definition) ") parser.add_option("-d", "--dir", default="/tmp", help="output dir") parser.add_option("--atm", default="1", help="atmosphere") parser.add_option("--conex", default=False, help="use conex") parser.add_option("--particles", default=True, help="write particle ouput") parser.add_option("--obslevel", default=1564, help="observation level in m") parser.add_option("-p", "--parallel", default=False, help="use parallel version of CORSIKA") parser.add_option("--Bx", default="19.71", help="magnetic field in x direction in muT") parser.add_option("--Bz", default="-14.18", help="magnetic field in z direction in muT") parser.add_option("--thinning", default="1e-6", help="thinning level") parser.add_option("--ecuts", type="float", nargs=4, default=(1.000E-01, 5.000E-02, 2.500E-04, 2.500E-04), help="energy cuts (hardonns, muons, e+/e-, gamma") parser.add_option("--pcut", type="float", nargs=1, default=1e-2, help="maximal energy for parallel showers as a fraction of cosmic-ray energy.") parser.add_option("--stepfc", default=1., type="float", help="stepfc corsika parameter. Factor by which the multiple scattering length for electrons and positrons in EGS4 simulations is elongated relative to the value given in [17]") (options, args) = parser.parse_args() options.conex = bool(int(options.conex)) options.parallel = bool(int(options.parallel)) options.particles = bool(int(options.particles)) thinning = float(options.thinning) print "RUNNR", int(options.runnumber), " run number" print "EVTNR 1 number of first shower event" if options.parallel: print "PARALLEL %f %f 1 F" % (1000., options.pcut * float(options.energy)) print "SEED", int(options.seed), " 0 0" print "SEED", int(options.seed) + 1, " 0 0" print "SEED", int(options.seed) + 2, " 0 0" if options.parallel: print "SEED", int(options.seed) + 3, " 0 0" print "SEED", int(options.seed) + 4, " 0 0" print "SEED", int(options.seed) + 5, " 0 0" print "NSHOW 1 number of showers to generate" print "PRMPAR", options.type, " primary particle" print "ERANGE", float(options.energy), float(options.energy), " range of energy" print "THETAP", float(options.zenith), float(options.zenith), " range of zenith angle (degree)" print "PHIP", -270 + float(options.azimuth), -270 + float(options.azimuth), " range of azimuth angle (degree)" # print "ECUTS 3.000E-01 3.000E-01 4.010E-04 4.010E-04" # print "ECUTS 1.000E-01 5.000E-02 2.500E-04 2.500E-04" # ecuts from rdobserver print "ECUTS %.4g %.4g %.4g %.4g" % options.ecuts print "ELMFLG T T em. interaction flags (NKG,EGS)" print "THIN ", thinning, " ", thinning * float(options.energy), " 0.000E+00" print "THINH 1.000E+02 1.000E+02" print "STEPFC ", options.stepfc print "OBSLEV %.0f observation level (in cm)" % (float(options.obslevel) * 100) print "ECTMAP 1.E5 cut on gamma factor for printout" print "MUADDI T additional info for muons" print "MUMULT T muon multiple scattering angle" print "MAXPRT 1 max. number of printed events" # print "MAGNET 18.4 -14.0 magnetic field AERA" # print "MAGNET 19.71 -14.18 magnetic field AERA CoREAS Repo" print "MAGNET %s %s Bx and Bz component in micro Tesla " % (options.Bx, options.Bz) if options.conex: print "PAROUT F F" print "CASCADE T T T" else: if options.particles: print "PAROUT T F" else: print "PAROUT F F" # print "CASCADE F F F" print "LONGI T 10. T T longit.distr. & step size & fit & out" print "RADNKG 5.e5 outer radius for NKG lat.dens.distr." print "ATMOD %s" % options.atm print "DIRECT", options.dir, " output directory" print "DATBAS F write .dbase file" print "USER glaser user" print "EXIT terminates input" PKxQMً``radiotools/doc/Makefile# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build SPHINXPROJ = radiotools SOURCEDIR = . BUILDDIR = _build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) PK[Kq{F11radiotools/doc/analyses.rstanalyses ========= A collection of functions and parametrizations of physic analyses. radiation energy ----------------- Implementation of all parametrizations published in Glaser et al., JCAP 09(2016)024. .. automodule:: analyses.radiationenergy :members: :undoc-members: PKK Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {one line to give the program's name and a brief idea of what it does.} Copyright (C) {year} {name of author} This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: {project} Copyright (C) {year} {fullname} This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . PK!HMuSa radiotools-0.1.0.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,szd&Y)r$[)T&UD"PK!H5cM#radiotools-0.1.0.dist-info/METADATAMn0 y 7MiarP&5mDWN҉_af_'%l0"bjd@qtV̋gQ.p0=cKpb;/@9  %%j͞0ihʲu²/C7wY qz]eNU'.&#hz?,7+Rihr` lᑚ^(`|}LHm˳PK!H0Ot!radiotools-0.1.0.dist-info/RECORDIwJ}Hb\܅ l8 (orstrzux.o~^￴b O|/p> c<t+LB B@@~cQtq^=Dajvh{^}\dc=&s|Td(}3\$Bs7g 3&-&MKUM}/QhK6#Z9h $۲YR(j}Z#_w!t<8 "4U~#HRD}/1sz']pbLWmΌJ@;O ꠜv4'J+KrpfEŜ }v'.蜳Ǻb؃!fRa-K?|dg%˓>o,x~ 9- .9<xqWA|u+-zǤ  s^%SJ;9CQ c) ^䅇x^S'pzn5 a<$VBo$i?gL(o2rQE6f]qmaj~s7 ]ʙckrV ߟ׭,f-W3g}h"˨>bӞh^ASI Wa/=u]x 7c O=t GC'u.[fdyg7t<,(8iDea;ɢfE h *ܗŰ <ߦ3I^O@_?Q[o3dģ].KDRt:ʸTyTJow+J&"ٰ/U8<𪮫d붝MH㿴1\g Ag*$S.Rlco>_ Z'3| +gn5Y'u y./Ɖxsy4n#.Y^5ɷzUAAA6; 0$MvIR?dC޶L15;; ASRp@G d#L%s%ՇZBb-8@Zjm/"*7|o!m4CİPK\NC,ZZradiotools/__init__.pyPK[Nىt**radiotools/coordinatesystems.pyPK[N 8fnfn+radiotools/helper.pyPKpyyI8R((radiotools/leapseconds.pyPK[N5ܸCCradiotools/plthelpers.pyPKAM$9PPradiotools/stats.pyPKqwKjradiotools/analyses/__init__.pyPKҹ+Naa%radiotools/analyses/energy_fluence.pyPKK#joW W &K*radiotools/analyses/radiationenergy.pyPKwK!7radiotools/atmosphere/__init__.pyPK8Nww%8radiotools/atmosphere/models.pyPKZL! ooradiotools/coreas/GE.pyPK\ZLH-'}radiotools/coreas/LSF.pyPKYZL}radiotools/coreas/__init__.pyPK\L6rJrJ(radiotools/coreas/generate_coreas_sim.pyPK ZL;d   piradiotools/coreas/geninp_aera.pyPKxQMً``|radiotools/doc/MakefilePK[Kq{F11Nradiotools/doc/analyses.rstPKK