def insert_beta_plot(fig, ax, prefix, cax): hn = hr(prefix, 'np') para = hn.para n = hn.get_timestep(-1)[-1] try: T = hr(prefix, 'temp_tot').get_timestep(-1)[-1] except NoSuchVariable: T = hr(prefix, 'temp_p').get_timestep(-1)[-1] B = hr(prefix, 'bt').get_timestep(-1)[-1] # Convert units n = n / (1000.0**3) # 1/km^3 -> 1/m^3 T = 1.60218e-19 * T # eV -> J B = 1.6726219e-27 / 1.60217662e-19 * B # proton gyrofrequency -> T # Compute B \cdot B B2 = np.sum(B**2, axis=-1) # Compute plasma beta mu_0 = value('mag. constant') assert unit('mag. constant') == 'N A^-2' data = n * T / (B2 / (2 * mu_0)) m, x, y, s = beta_plot2(ax, data, para, 'xy', mccomas=True) if cax != 'None': fig.colorbar(m, cax=cax, orientation='horizontal')
def test_scenario_2(): # TEST SCENARIO no. 1 # # ^ # * * # |(0,10 anchor1 (10,10) anchor2 # | # | # | * # | (5, 5) mobile # | # | # | (10,0) anchor3 # |------------------------------------*---> # assert (scc.unit('speed of light in vacuum') == 'm s^-1') c = scc.value('speed of light in vacuum') mobile_position = np.asarray((5, 5)) coordinates = np.asarray(( (0, 0), # Anchor 1 (10, 10), # Anchor 2 (10, 0))) # Anchor 3 distances = np.asarray( (np.abs(np.linalg.norm(mobile_position - coordinates[0, :])), np.abs(np.linalg.norm(mobile_position - coordinates[1, :])), np.abs(np.linalg.norm(mobile_position - coordinates[2, :])))) tdoas = distances / c return coordinates, tdoas, mobile_position
def find_constant(name=None) -> dict: """ returns a dictionary of the constant name and it's value: for example: !!! ALL THE CONSTANTS ARE IN SI UNITS !!! :param name: :type name: str :return: dictionary of name and value :rtype: dict """ res = fnd(name) if res is None: print("constant not found") else: ret = {} for key in res: ret.update({key: [con.value(key), con.unit(key)]}) return ret
def doan_vesely(coordinates, distances): """ S. Van Doan and J. Vesely, "The effectivity comparison of TDOA analytical solution methods," 2015 16th International Radar Symposium (IRS), Dresden, 2015, pp. 800-805. """ # TODO propose better way for arguments checking assert (coordinates.shape == (3, 2)) assert (distances.shape == (3,)) assert (scc.unit('speed of light in vacuum') == 'm s^-1') c = scc.value('speed of light in vacuum') c = c * 1e-12 # m/s -> m/ps distances = distances * c L = distances[1] R = distances[2] Xl = coordinates[1, 0] - coordinates[0, 0] Yl = coordinates[1, 1] - coordinates[0, 1] Xr = coordinates[2, 0] - coordinates[0, 0] Yr = coordinates[2, 1] - coordinates[0, 1] A = -2 * np.asanyarray(((Xl, Yl), (Xr, Yr))) B = np.asanyarray(((-2 * L, L ** 2 - Xl ** 2 - Yl ** 2), (2 * R, R ** 2 - Xr ** 2 - Yr ** 2))) tmp, _, _, _ = np.linalg.lstsq(A, B, rcond=None) a = tmp[0, 0] ** 2 + tmp[1, 0] ** 2 - 1 b = 2 * (tmp[0, 0] * tmp[0, 1] + tmp[1, 0] * tmp[1, 1]) c = tmp[0, 1] ** 2 + tmp[1, 1] ** 2 K = np.max(np.real(np.roots((a, b, c)))) X = tmp[0, 0] * K + tmp[0, 1] + coordinates[0, 0] Y = tmp[1, 0] * K + tmp[1, 1] + coordinates[0, 1] return np.asarray((X, Y))
from os.path import join import numpy as np import matplotlib.pyplot as plt import argparse from progress import printProgressBar import FortranFile as ff import HybridParticleReader as hpr from HybridParams import HybridParams from scipy.constants import value, unit kg_per_amu = value('atomic mass constant') assert unit('atomic mass constant') == 'kg' def marginal_outflow(p): part_out = np.zeros(2 * p.para['nt']) mass_out = np.zeros(2 * p.para['nt']) # for each processor for n in range(p.para['num_proc']): f = ff.FortranFile( join(p.particle, "c.outflowing_" + str(n + 1) + ".dat")) # for each half timestep for i in range(2 * p.para['nt']): try: mrat = f.readReals() except ff.NoMoreRecords: break beta_p = f.readReals() tags = f.readReals() # Each of the arrays must have the same length
"""Derivation of variable `toz`.""" import cf_units import iris from scipy import constants from ._baseclass import DerivedVariableBase from ._shared import pressure_level_widths # Constants AVOGADRO_CONST = constants.value('Avogadro constant') AVOGADRO_CONST_UNIT = constants.unit('Avogadro constant') STANDARD_GRAVITY = constants.value('standard acceleration of gravity') STANDARD_GRAVITY_UNIT = constants.unit('standard acceleration of gravity') MW_AIR = 29 MW_AIR_UNIT = cf_units.Unit('g mol^-1') MW_O3 = 48 MW_O3_UNIT = cf_units.Unit('g mol^-1') DOBSON_UNIT = cf_units.Unit('2.69e20 m^-2') class DerivedVariable(DerivedVariableBase): """Derivation of variable `toz`.""" @staticmethod def required(project): """Declare the variables needed for derivation.""" if project == 'CMIP6': required = [{'short_name': 'o3'}, {'short_name': 'ps'}] else: required = [{'short_name': 'tro3'}, {'short_name': 'ps'}] return required
"""Derivation of variable ``loadbc``.""" import warnings import cf_units import iris from scipy import constants from .._regrid import extract_levels, regrid from ._baseclass import DerivedVariableBase from ._shared import pressure_level_widths # Constants STANDARD_GRAVITY = constants.value('standard acceleration of gravity') STANDARD_GRAVITY_UNIT = constants.unit('standard acceleration of gravity') def ensure_correct_lon(mmrbc_cube, ps_cube=None): """Ensure that ``mmrbc`` cube contains ``longitude`` and adapt ``ps`` cube.""" if mmrbc_cube.coords('longitude'): return (mmrbc_cube, ps_cube) # Get zonal mean ps if necessary if ps_cube is not None: ps_cube = ps_cube.collapsed('longitude', iris.analysis.MEAN) ps_cube.remove_coord('longitude') # Add longitude dimension to mmrbc (and ps if necessary) with length 1 cubes = (mmrbc_cube, ps_cube) new_cubes = [] lon_coord = iris.coords.DimCoord([180.0],
"""Derivation of variable `toz`.""" import cf_units import iris import numba import numpy as np from scipy import constants from ._baseclass import DerivedVariableBase # Constants AVOGADRO_CONST = constants.value('Avogadro constant') AVOGADRO_CONST_UNIT = constants.unit('Avogadro constant') STANDARD_GRAVITY = 9.81 STANDARD_GRAVITY_UNIT = cf_units.Unit('m s^-2') MW_AIR = 29 MW_AIR_UNIT = cf_units.Unit('g mol^-1') MW_O3 = 48 MW_O3_UNIT = cf_units.Unit('g mol^-1') DOBSON_UNIT = cf_units.Unit('2.69e20 m^-2') class DerivedVariable(DerivedVariableBase): """Derivation of variable `toz`.""" # Required variables required = [ { 'short_name': 'tro3' }, {
def pressure_pPa(n, t): k = value('Boltzmann constant') assert unit('Boltzmann constant') == 'J K^-1' return k * n * t * (100**3) * (1e12)
def C(s): return Q(constants.value(s), constants.unit(s))
plt.ylabel(r"Anzahl") plt.plot(freqs[(freqs > -15000) & (freqs < 15000)] * 1e-3, np.real(fftdata)[(freqs > -15000) & (freqs < 15000)], "x", label="Fourier-Transformation") #plt.plot(freqs, np.real(fftdata)) #plt.plot(times, real) #plt.plot(times, imag) plt.legend(loc="best") plt.grid() plt.tight_layout() plt.savefig("plots/echo_gradient.pdf") d_f = 6.578947368420178464e+03 + 8.771929824560238558e+03 gamma = const.value("proton gyromag. ratio") gamma_u = const.unit("proton gyromag. ratio") durchmesser = 4.4e-3 # oder 4.2e-3 ? g = 2 * np.pi * d_f / gamma / durchmesser # Gradient, damit dann Diffusionskoeffizient bestimmen Diff = 1 / ufloat(params3[0], err3[0]) * (3 / 2) / gamma**2 / g**2 f = open("plots/results.txt", "w") f.write( f"T_1 =( {params1[0]} +/- {err1[0]}) s, U_0 = ({params1[1]} +/- {err1[1]}) V\n" ) f.write( f"T_2 =( {params2[0]} +/- {err2[0]}) s, U_0 = ({params2[1]} +/- {err2[1]}) V, U_1 = ({params2[2]} +/- {err2[2]}) V\n " ) f.write( f"Konstante =( {params3[0]} +/- {err3[0]}) s, U_0 = ({params3[1]} +/- {err3[1]}) V, U_1 = ({params3[2]} +/- {err3[2]}) V \n" ) f.write(f"d_f = {d_f*1e-3} kHz\n")
from os.path import join import numpy as np from scipy.interpolate import RegularGridInterpolator from scipy.constants import value, unit from HybridReader2 import HybridReader2 as hr from HybridParams import HybridParams import matplotlib.pyplot as plt from matplotlib.figure import figaspect import NH_tools import argparse from argparse import Action # Constants eV2J = value('Boltzmann constant in eV/K') k = value('Boltzmann constant') assert unit('Boltzmann constant') == 'J K^-1' # Command line parsing parser = argparse.ArgumentParser() parser.add_argument('--save', action='store_true') parser.add_argument('--mccomas', action='store_true') group = parser.add_argument_group( 'Select which simulations to include (default --shell)') group_ex = group.add_mutually_exclusive_group() group_ex.add_argument('--all', dest='which', action='store_const', const='all') group_ex.add_argument('--shell', dest='which', action='store_const', const='shell') group_ex.add_argument('--no-shell',
def _localize_mobile(self, mobile_node, anchors, frames): # Assume that all anchors has the same reply delay reply_delay = np.unique(anchors["beacon_reply_delay"]) assert (reply_delay.shape == (1, )) reply_delay = reply_delay[0] assert (scc.unit('speed of light in vacuum') == 'm s^-1') c = scc.value('speed of light in vacuum') c = c * 1e-12 # m/s -> m/ps mobile_frames = frames[frames.node_mac_address == mobile_node["mac_address"], :] #frame_filer = Filter(frames) #frame_filer.equal("node_mac_address", mobile_node["mac_address"]) #mobile_frames = frame_filer.finish() # Filter out all sequence numbers for which mobile node received less than three beacons sequence_numbers, sequence_number_counts = np.unique( mobile_frames["sequence_number"], return_counts=True) sequence_numbers = sequence_numbers[sequence_number_counts >= 3] #result = Results.create_array(sequence_numbers.size, position_dimensions=2) #result["mac_address"] = mobile_node["mac_address"] results = [] for i in range(sequence_numbers.size): sequence_number = sequence_numbers[i] current_positions = [] # Extract beacons with specific sequence number current_beacons = mobile_frames[np.where( mobile_frames["sequence_number"] == sequence_number)] # Set true position #true_begin_position = #true_end_position = result = Result() result.position_dimensions = 2 result.mac_address = mobile_node["mac_address"] result.begin_true_position_x = current_beacons[ 0, "begin_true_position_x"] result.begin_true_position_y = current_beacons[ 0, "begin_true_position_y"] result.begin_true_position_z = current_beacons[ 0, "begin_true_position_z"] result.end_true_position_x = current_beacons[0, "end_true_position_x"] result.end_true_position_y = current_beacons[0, "end_true_position_y"] result.end_true_position_z = current_beacons[0, "end_true_position_z"] # Evaluate different anchors sets anchor_groups = [(0, 1, 2)] for anchor_indices in anchor_groups: # Compute distances between consecutive pairs of anchors (first, second), (second, third) etc. anchors_gaps = [] for anchor_index in itertools.islice(anchor_indices, len(anchor_indices) - 1): gap = np.linalg.norm(anchors[(anchor_index + 1), "position_2d"] - anchors[anchor_index, "position_2d"]) anchors_gaps.append(gap) # Compute ToF between anchor pairs anchors_gaps = np.asarray(anchors_gaps) anchors_gaps = (anchors_gaps / c) + reply_delay # Follow algorithm steps anchor_coordinates = np.zeros((3, 2)) anchor_coordinates[0] = anchors[anchor_indices[0], "position_2d"] anchor_coordinates[1] = anchors[anchor_indices[1], "position_2d"] anchor_coordinates[2] = anchors[anchor_indices[2], "position_2d"] timestamps = np.zeros(3) timestamps[0] = current_beacons[anchor_indices[0], "begin_clock_timestamp"] timestamps[1] = current_beacons[anchor_indices[1], "begin_clock_timestamp"] timestamps[2] = current_beacons[anchor_indices[2], "begin_clock_timestamp"] timestamps[1] -= anchors_gaps[0] timestamps[2] -= (anchors_gaps[0] + anchors_gaps[1]) sorted_anchors_coordinates, sorted_timestamps = common.sort_measurements( anchor_coordinates, timestamps) # Compute TDoA values sorted_tdoa_distances = (sorted_timestamps - sorted_timestamps[0]) * c # Compute position try: solver = self._Solver(sorted_anchors_coordinates, sorted_tdoa_distances, self.solver_configuration) positions = solver.localize() # Choose better position positions = [ position for position in positions if self._area.contains(position) ] if positions: current_positions += positions else: current_positions.append((np.nan, np.nan)) except ValueError: current_positions.append((np.nan, np.nan)) result.position_x, result.position_y = current_positions[0] result.position_z = 0 results.append(result) return results
import os import numpy as np from pint import UnitRegistry import scipy.constants as const import parameters as param ureg = param.ureg Q_ = param.Q_ n = param.n # ====================================================================== # Speed of light in vacuum. c = Q_(const.value('speed of light in vacuum'), const.unit('speed of light in vacuum')) # Metric tensor. #metric = np.asarray( # [[-1., 0., 0., 0.], # [ 0., 1., 0., 0.], # [ 0., 0., 1., 0.], # [ 0., 0., 0., 1.]]) # ====================================================================== # Printing units. # ====================================================================== printing_units_time = 's' printing_units_length = 'm'
n = int(1e3) # ---------------------------------------------------------------------- # Loopped parameters. # ---------------------------------------------------------------------- # Initial time. t0 = Q_(np.asarray([0.]), 'second') # Initial position. r0 = Q_(np.asarray([[0., 0., 0.]]), 'meter') # Initial velocity unit vector. vhat0 = np.asarray([[0., 0., 1.]]) # Charge. q = Q_(np.asarray([1.]), 'e') # Mass. m = [Q_(const.value('proton mass'), const.unit('proton mass'))] # Initial kinetic energy. T0 = Q_(np.asarray([6.]), 'MeV') # Y-component of magnetic field. By = Q_(np.asarray([5.]), 'mT') # Step size. h = Q_(np.asarray([1e0, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15, 1e-18, 1e-21]), 'second')
#!/usr/bin/env python from scipy import constants as K print("pi: {0}".format(K.pi)) print("Planck: {0}".format(K.Planck)) print("c (speed of light): {0}".format(K.c)) print("natural unit of energy: {0}".format(K.value('natural unit of energy'))) print("natural unit of energy (Unit): {0}".format( K.unit('natural unit of energy')))
#!/usr/bin/env python from scipy import constants as K # <1> print("pi: {0}".format(K.pi)) # <2> print("Planck: {0}".format(K.Planck)) # <2> print("c (speed of light): {0}".format(K.c)) # <2> print("natural unit of energy: {0}".format(K.value('natural unit of energy'))) print("natural unit of energy (Unit): {0}".format(K.unit('natural unit of energy')))
import uncertainties.unumpy as unp from uncertainties.unumpy import nominal_values as noms from uncertainties.unumpy import std_devs as stds from uncertainties import ufloat from scipy.optimize import curve_fit import scipy.constants as const import imageio from scipy.signal import find_peaks import pint from tab2tex import make_table ureg = pint.UnitRegistry(auto_reduce_dimensions=True) Q_ = ureg.Quantity tugreen = '#80BA26' c = Q_(const.value('speed of light in vacuum'), const.unit('speed of light in vacuum')) h = Q_(const.value('Planck constant'), const.unit('Planck constant')) def linear(x, a, b): '''Linear Regression''' return a * x + b def test(): # Import data from text files with numpy # x, y = np.genfromtxt('rohdaten/filename.txt', unpack=True) # test data U = np.array(range(20)) I = np.linspace(1, 10, 20) * 2 + np.pi
def localize_mobile(mobile_node, anchors, frames): # Assume that all anchors has the same reply delay reply_delay = np.unique(anchors["beacon_reply_delay"]) assert (reply_delay.shape == (1, )) reply_delay = reply_delay[0] assert (scc.unit('speed of light in vacuum') == 'm s^-1') c = scc.value('speed of light in vacuum') c = c * 1e-12 # m/s -> m/ps frame_filer = Filter() frame_filer.equal("node_mac_address", mobile_node["mac_address"]) mobile_frames = frame_filer.execute(frames) # Filter out all sequence numbers for which mobile node received less than three beacons sequence_numbers, sequence_number_counts = np.unique( mobile_frames["sequence_number"], return_counts=True) sequence_numbers = sequence_numbers[sequence_number_counts > 3] result = Results.create_array(sequence_numbers.size, position_dimensions=2) result["mac_address"] = mobile_node["mac_address"] anchor_triples = ((0, 1, 2), (1, 2, 3)) for i in range(sequence_numbers.size): sequence_number = sequence_numbers[i] # Extract beacons with specific sequence number current_beacons = mobile_frames[np.where( mobile_frames["sequence_number"] == sequence_number)] positions = [] # Evaluate different anchors sets for anchor_triple in anchor_triples: # Compute distances between anchor pairs (first, second) and (second, third) anchor_distances = np.zeros(2) anchor_distances[0] = np.abs( np.linalg.norm(anchors[anchor_triple[1], "position_2d"] - anchors[anchor_triple[0], "position_2d"])) anchor_distances[1] = np.abs( np.linalg.norm(anchors[anchor_triple[2], "position_2d"] - anchors[anchor_triple[1], "position_2d"])) # Compute ToF between anchor pairs anchor_tx_delays = anchor_distances / c + reply_delay # Follow algorithm steps anchor_coordinates = np.zeros((3, 2)) anchor_coordinates[0] = anchors[anchor_triple[1], "position_2d"] anchor_coordinates[1] = anchors[anchor_triple[0], "position_2d"] anchor_coordinates[2] = anchors[anchor_triple[2], "position_2d"] timestamp_differences = np.full(3, float('nan')) timestamp_differences[1] = current_beacons[anchor_triple[1], "begin_clock_timestamp"] - \ current_beacons[anchor_triple[0], "begin_clock_timestamp"] - anchor_tx_delays[0] timestamp_differences[2] = current_beacons[anchor_triple[2], "begin_clock_timestamp"] - \ current_beacons[anchor_triple[1], "begin_clock_timestamp"] - anchor_tx_delays[1] # Compute position position = tdoa.doan_vesely(anchor_coordinates, timestamp_differences) positions.append(position) result[i, "begin_true_position_3d"] = current_beacons[ 0, "begin_true_position_3d"] result[i, "end_true_position_3d"] = current_beacons[ 2, "end_true_position_3d"] # Choose better position # TODO Propose better solution, for now just choose position being closer to (0, 0) if np.abs(np.linalg.norm((0, 0) - positions[0])) < np.abs( np.linalg.norm((0, 0) - positions[1])): result[i, "position_2d"] = positions[0] else: result[i, "position_2d"] = positions[1] return result
def get_units(something: str): return con.unit(something)