def main(pool, distance=20, filename='output_file.txt', nside=64): #calculate pole centers hp = HEALPix(nside=nside, order='ring', frame=coord.Galactic()) centers = hp.healpix_to_skycoord(np.arange(0, hp.npix)) #only keep poles above equator to not redo calculate with opposite pole centers = centers[centers.b >= 0.0 * u.deg] #pad centers to match to number of processors ncenters = centers.shape[0] nprocs = pool.size if nprocs == 0.: nprocs = 1 ncenters_per_proc = np.ceil(ncenters / float(nprocs)) npads = nprocs * ncenters_per_proc - ncenters skypad = coord.SkyCoord(np.zeros(int(npads)), np.zeros(int(npads)), frame='galactic', unit=u.deg) centers = coord.concatenate((centers, skypad)) #reshape centers so each worker gets a block of them centers = centers.reshape(nprocs, int(ncenters_per_proc)) print('number of workers: ', nprocs) print('number of poles: ', ncenters) print('number of poles per worker: ', ncenters_per_proc) print('number of poles added as padding: ', npads) print('shape of poles array: ', np.shape(centers)) #instantiate worker with filename results will be saved to worker = Worker(filename, args.dist) #you better work ! for r in pool.map(worker, list(centers), callback=worker.callback): pass
def solar_feet(self): """ Coordinates of the solar footpoints. Notes ----- For closed field lines, the footpoint pointing out from the solar surface is returned. """ solar_feet = [fline.solar_footpoint for fline in self.field_lines] if len(solar_feet) == 1: solar_feet = solar_feet[0] else: solar_feet = coord.concatenate(solar_feet) return solar_feet
def source_surface_feet(self): """ Coordinates of the source suface footpoints. Notes ----- For closed field lines, there is no source surface footpoint, but instead the solar footpoint pointing in towards the solar surface is returned. """ source_surface_feet = [fline.source_surface_footpoint for fline in self.field_lines] if len(source_surface_feet) == 1: source_surface_feet = source_surface_feet[0] else: source_surface_feet = coord.concatenate(source_surface_feet) return source_surface_feet
def make_gadget_catalog(frac): firstFile = True for i, fname in enumerate(fname_vec): print i, fname data = readGadgetSnapshot.readGadgetSnapshot(fname, read_pos=True)[1] coords = coordinates.SkyCoord(x=data[:, 0], y=data[:, 1], z=data[:, 2], unit='Mpc', representation='cartesian') coords = coords.transform_to('icrs') coords = coords[coords.distance.value < 2600] coords = coords[(coords.ra.value < 90) & (coords.ra.value > 0)] coords = coords[(coords.ra.value < 60) & (coords.ra.value > 40)] # will invert later #coords = coords[np.random.rand(len(coords)) < frac] if firstFile: fullcat = coords firstFile = False else: newcat = coords fullcat = coordinates.concatenate([fullcat, newcat]) return fullcat
def add_points(self, points, **kwargs): """ Adds multiple points to the CircleCollection. """ self._gen_circles(points, **kwargs) self.points = concatenate((self.points, points))
def from_galpy_orbit( cls, *args, orbit, orbit_bkw=None, frame="galactocentric", method: T.Union[Literal["closest"], Literal["linear"], Literal["cubic"], T.Callable[[T.Sequence], T.Sequence], ] = "closest", time_unit=None, **kwargs, ): """Create an Orbit Offset Frame from a galpy orbit. Parameters ---------- orbit : `~galpy.orbit.Orbit` An integrated single orbit., keyword only the initial 4-vector and conjugate momenta are taken as the origin. orbit_bkw : `~galpy.orbit.Orbit`, optional, keyword only An integrated single orbit in the opposite time direction. This allows for a leading and trailing orbit from the origin point. Must have same origin as `orbit`, but be integrated in reverse. frame : str or BaseCoordinateFrame, optional, keyword only frame in which to represent the orbit. calls ``transform_to(frame)`` on `orbit`'s ICRS SkyCoord output, so be careful about things like Galactocentric defaults method : {"closest", "linear", "cubic"} or Callable, optional, keyword how to construct the affine parameter function mapping time to coordinate The orbit integration is precomputed at discrete time intervals and the path frame needs to be able to match coordinates to the closest point on the orbit. This can be done by treating the orbit as an immutable catalog (option "closest", default), a linearly interpolatable set of points (option "linear") with :class:`~scipy.interpolate.interp1d`, a cubic interpolation (option "cubic") with :class:`~scipy.interpolate.CubicSpline`. .. todo:: allow user-provided functions that take the time and coordinates and return a function that, given a set of coordinates, returns the time of and angular separation from "closest" (for some dfn) point on orbit. time_unit : Quantity or Nont, optional, keyword only preferred time unit. None means no modification. Galpy defaults to Gyr. Raises ------ ValueError if `orbit` is not integrated if `orbit_bkw` is not integrated (and not None) if the potential in `orbit` and `orbit_bkw` do not match. Notes ----- Make sure that the orbit does not wrap and get close to itself. There are currently no checks that this is happening and this can lead to some very strange coordinate projections. .. todo:: allow affine parameter to be arc length """ # ---------------------------------------------------- # Checks # if orbit_bkw is not None, check has potential and matches orbit # check times go in opposite directions try: # check orbit has potential orbit._pot except AttributeError: # it does not raise ValueError("`orbit` must be integrated.") else: # it does # grab the potential, integration time, and origin potential = orbit._pot t_fwd = orbit.time(use_physical=True) origin = orbit.SkyCoord().transform_to(frame) if orbit_bkw is not None: try: orbit._pot except AttributeError: raise ValueError("`orbit_bkw` must be integrated.") if orbit._pot != potential: raise ValueError( ("potential in `orbit` and `orbit_bkw` do not match.")) # check time "directions" are opposite # they "fwd" direction can be back in time. That is permitted # just not allowed to have the "bkw" direction be the same. time_bkw_sgn = np.sign(orbit_bkw.t[1] - orbit_bkw.t[0]) t_fwd_sgn = np.sign(orbit.t[1] - orbit.t[0]) if time_bkw_sgn == t_fwd_sgn: raise ValueError(("`orbit` and `orbit_bkw` must be integrated" "in opposite time directions")) # get back time, converting to correct units t_bkw = orbit_bkw.time(use_physical=True)[::-1] << t_fwd.unit # concatenate fwd and bkw orbits into single orbit catalog orbit_catalog = concatenate([ orbit_bkw.SkyCoord(t_bkw).transform_to(frame).frame, orbit.SkyCoord(t_fwd).transform_to(frame).frame, ]) orbit_time = np.concatenate((t_bkw, t_fwd)) # create time bounds _u = t_fwd.unit if time_unit is None else time_unit if t_fwd[-1] > t_bkw[-1]: t_bnds = [t_bkw[0], t_fwd[-1]] << _u else: t_bnds = [t_fwd[0], t_bkw[-1]] << _u else: # create orbit catalog orbit_catalog = orbit.SkyCoord(t_fwd).transform_to(frame) orbit_time = t_fwd # create time bounds _u = t_fwd.unit if time_unit is None else time_unit if t_fwd[-1] > t_fwd[0]: t_bnds = [t_fwd[0], t_fwd[-1]] << _u else: t_bnds = [t_fwd[-1], t_fwd[0]] << _u # convert orbit time to `time_unit`, if specified if time_unit is not None: orbit_time <<= time_unit # (in-place modification) else: # time unit is not None time_unit = orbit_time.unit # ---------------------------------------------------- # construct affine function track_fn_kw = kwargs.pop("track_fn_kw", {"afn_name": "time"}) inverse_track_fn_kw = kwargs.pop("inverse_track_fn_kw", {}) if isinstance(method, str): # now need to check it's one of the supported strings if method.lower() == "closest": # does a catalog match between the coordinates and the # points on the orbit from the orbit integration # track_fn = ("closest", orbit_catalog, orbit_time) track_fn = catalog_match_track inverse_track_fn = catalog_match_inverse_track track_fn_kw = { "catalog": orbit_catalog, "affine_param": orbit_time, "adj_sep_sgn": True, "afn_name": "time", } inverse_track_fn_kw = { "catalog": orbit_catalog, "affine_param": orbit_time, } _interpolation_flag = False else: # need to handle interpolated functions separately, # because requires a closest point "optimization" if method.lower() == "linear": method = interpolate.interp1d elif method.lower() == "cubic": method = interpolate.CubicSpline else: raise ValueError(f"method {method} not known.") _interpolation_flag = True elif callable(method): _interpolation_flag = True else: raise ValueError(f"method {method} not known.") # /if if _interpolation_flag: # get affine parameter and data interpolation ready affine_param = orbit_time.to_value(time_unit) _data = orbit_catalog.data._values _data = _data.view(np.float64).reshape(_data.shape + (-1, )) # construct interpolation _track_array_fn = method(affine_param, _data.T) # astropy coordinate object reconstruction information _cmpt = [ ( c, orbit_catalog.data._units[c], ) # in right order, but dict for c in orbit_catalog.data.components # tuple = order ] _frame = orbit_catalog.frame.realize_frame(None) _rep = orbit_catalog.frame.get_representation_cls() # interpolation function as astropy, not numpy def _track_fn(affine_param): """_track_array_fn converted back into a coordinate object.""" _oc = _track_array_fn(affine_param) # evaluate interpolation rep = _rep(**{c: _oc[i] * U for i, (c, U) in enumerate(_cmpt)}) catalog = SkyCoord( # make catalog (TODO not SkyCoord) _frame.realize_frame(rep)) return catalog # make actual track and inverse functions def track_fn(coords, tol=None, init_sampler: T.Union[float, int] = 1e4): """Map coordinates to catalog projection. .. todo:: change defualt `tol` to something else Parameters ---------- coords: SkyCoord tol : float or None, optional If None (default), does catalog match but no further minimization. The catalog is the evaluation of the "method" function with affine parameter linearly sampled with `init_sampler` points between "afn_bounds" init_sampler : int or float, optional the number of points in ``np.linspace`` for an inital sampling of the affine parameter. """ _aff = np.linspace( # affine parameter *t_bnds, num=int(init_sampler))[1:-2] catalog = _track_fn(_aff) if tol is None: return catalog_match_track( coords, catalog=catalog, affine_param=_aff, adj_sep_sgn=True, ) else: # TODO actual minimization # initial guess idx, sep2d, _, = match_coordinates_3d(coords, catalog) raise ValueError("Not yet implemented") return idx # /def def inverse_track_fn(coords, **kw): """Map catalog projection to coordinates. .. todo:: this is a very generic function. put somewhere else. Parameters ---------- coords: SkyCoord in orbit projection frame """ # orbit_pos = _track_fn(coords.afn) # need to know offset # d_afn = coords.data._d_afn # Now offset by `d_afn` in direction `that` raise ValueError("TODO") # out = orbit_pos.directional_offset_by( # pa, np.abs(coords.sep) # need abs() b/c `adj_sep_sgn` # ).represent_as("spherical") # return out.x, out.y, coords.z # /def # /if # TODO correct construction with init to get the Attributes self = cls( *args, origin=origin, potential=potential, track_fn=track_fn, inverse_track_fn=inverse_track_fn, track_fn_kw=track_fn_kw, inverse_track_fn_kw=inverse_track_fn_kw, afn_bounds=t_bnds, **kwargs, ) return self
def time_concatenate_scalar(self): concatenate((self.icrs_scalar, self.icrs_scalar))
def spetial_points_calc(x0, y0, sma, eps, pa, n_points, wcs, dist_center, xys_sky_PV): """ Calculates the points for the three interesting points in the elliptical fits from which you can extract important information from. This are where phi is 0, 90 and 180 Parameters ---------- x0, y0, sma, eps, pa: float ellipse parameters wcs: wcs of the image n_points: int number of points of the pv line. The higher the more precises the value of the x_phis are dist_center: float this are the values set to x_phi90, the distances of the centers of the ellipses """ vla4b_sky = SkyCoord(*mf.default_params['vla4b_deg'], unit='deg') ellipse_pixel, ellipse_sky = ellipse_points_calc(x0, y0, sma, eps, pa, n_points, wcs) ellipse_sky_cat = concatenate(ellipse_sky) xys_sky_PV_cat = concatenate(xys_sky_PV) aper = EllipticalAperture((x0, y0), sma, sma * (1. - eps), pa) aper_sky = aper.to_sky(wcs) ell_center_sky = aper_sky.positions sma_arcsec = aper_sky.a.value sminora_arcsec = aper_sky.b.value xys_PV_inrange = np.array([ xys for xys in xys_sky_PV_cat if (xys.separation(ell_center_sky).arcsec <= 1.1 * sma_arcsec) and ( xys.separation(ell_center_sky).arcsec >= 0.5 * sminora_arcsec) ]) xys_180_PV = np.array([ xys for xys in xys_PV_inrange if vla4b_sky.separation(xys).arcsec < vla4b_sky.separation(ell_center_sky).arcsec ]) xys_0_PV = np.array([ xys for xys in xys_PV_inrange if vla4b_sky.separation(xys).arcsec > vla4b_sky.separation(ell_center_sky).arcsec ]) distances_180 = np.array( [[xys.separation(ell).arcsec for ell in ellipse_sky_cat] for xys in xys_180_PV]) distances_0 = np.array( [[xys.separation(ell).arcsec for ell in ellipse_sky_cat] for xys in xys_0_PV]) idx_180 = np.where(distances_180 == np.min(distances_180)) idx_0 = np.where(distances_0 == np.min(distances_0)) p180_sky = ellipse_sky_cat[idx_180[1]] p0_sky = ellipse_sky_cat[idx_0[1]] xp_phi180 = p180_sky.separation(vla4b_sky).arcsec xp_phi90 = dist_center xp_phi0 = p0_sky.separation(vla4b_sky).arcsec return [[ellipse_pixel, ellipse_sky], [p180_sky, p0_sky], [xp_phi180, xp_phi90, xp_phi0]]
def _run_batch( self, n: int = 1, iterations: int = 1, *, representation_type: TH.OptRepresentationLikeType = None, random: RandomLike = None, # extra progress: bool = True, **kwargs, ) -> TH.SkyCoordType: """Sample the potential. Parameters ---------- n : int (optional) Number of sample points. iterations : int (optional) Number of iterations. Must be > 0. representation_type: |Representation| or None (optional, keyword-only) The coordinate representation. random : int or |RandomState| or None (optional, keyword-only) Random state or seed. sequential : bool (optional, keyword-only) Whether to batch sample or yield sequentially. **kwargs Passed to underlying instance Return ------ |SkyCoord| If `sequential` is True. The shape of the SkyCoord is ``(n,)`` Raises ------ ValueError If number if iterations not greater than 0. """ samps = [None] * iterations # premake array mass = [None] * iterations # premake array run_gen = self._run_iter( n=n, iterations=iterations, representation_type=representation_type, random=random, progress=progress, **kwargs, ) for j, samp in enumerate(run_gen): # thru iterations # store samples & mass samps[j] = samp mass[j] = samp.cache["mass"] # Now need to concatenate iterations if j == 0: # 0-dimensional doesn't need concat sample = samps[0] else: # breakpoint() sample = coord.concatenate(samps).reshape((n, iterations)) sample.cache["mass"] = np.vstack(mass).T sample.cache["potential"] = samp.cache["potential"] # all the same return sample
def test_run(self): """Test method ``run``. When Test_MeasurementErrorSampler this calls on the wrapped instance, which is GaussianMeasurementErrorSampler. Subclasses should do real tests on the output. This only tests that we can even call the method. .. todo:: Tests in the subclasses that the results make sense. ie, follow the expected distribution """ if self.obj is not measurement.RVS_Continuous: assert False # should never be here b/c subclasses override # --------------- # c_err = None res = self.inst.run(self.c, random=0, batch=True) res = np.array(res) if isinstance(res, Generator) else res assert res.shape == self.c.shape assert np.allclose(res.ra.value, np.array([1.17640523, 2.44817864])) assert np.allclose(res.dec.value, np.array([2.08003144, 3.5602674])) # TODO! more tests # --------------- # random res2 = self.inst.run(self.c, random=1, batch=True) for c in res2.representation_component_names.keys(): assert not np.allclose(getattr(res, c), getattr(res2, c)) assert np.allclose(res2.ra.value, np.array([1.16243454, 181.78540628])) assert np.allclose(res2.dec.value, np.array([1.87764872, -3.25962229])) # TODO! more tests # --------------- # len(c.shape) == 1 assert len(self.c.shape) == 1 res = self.inst.run(self.c, self.c_err, random=0, batch=True) assert res.shape == self.c.shape assert np.allclose(res.ra.value, np.array([1.17640523, 2.44817864])) assert np.allclose(res.dec.value, np.array([2.08003144, 3.5602674])) # TODO! more tests # --------------- # 2D array, SkyCoord, nerriter = 1 c = concatenate([self.c, self.c]).reshape(len(self.c), -1) res = self.inst.run(c, c_err=self.c_err, random=0, batch=True) assert res.shape == c.shape assert np.allclose( res.ra.value, np.array([[1.17640523, 1.44817864], [2.09500884, 2.0821197]]), ) assert np.allclose( res.dec.value, np.array([[2.08003144, 2.5602674], [2.96972856, 3.04321307]]), ) # --------------- # 2D array, SkyCoord, nerriter != niter c_err = concatenate([self.c_err, self.c_err, self.c_err], ).reshape( len(self.c), -1) with pytest.raises(ValueError, match="c & c_err shape mismatch"): self.inst.run(c, c_err, batch=True) # --------------- # 2D array, SkyCoord, nerriter = niter c_err = concatenate([self.c_err, self.c_err]).reshape( len(self.c), -1, ) res = self.inst.run(c, c_err=c_err, random=0, batch=True) assert res.shape == c.shape assert np.allclose( res.ra.value, np.array([[1.17640523, 1.22408932], [2.19001768, 2.0821197]]), ) assert np.allclose( res.dec.value, np.array([[2.08003144, 2.3735116], [2.95459284, 3.04321307]]), ) # --------------- # 2D array, (Mapping, scalar, callable, %-unit) res = self.inst.run(c, c_err=1 * u.percent, random=0, batch=True) assert res.shape == c.shape assert np.allclose( res.ra.value, np.array([[1.01764052, 1.02240893], [2.01900177, 2.00821197]]), ) assert np.allclose( res.dec.value, np.array([[2.00800314, 2.03735116], [2.99545928, 3.00432131]]), ) # --------------- # 2D array, other with pytest.raises(NotImplementedError, match="not yet supported."): self.inst.run(self.c, NotImplementedError(), batch=True)
def test_run(self): """Test method ``run``. When Test_MeasurementErrorSampler this calls on the wrapped instance, which is GaussianMeasurementErrorSampler. Subclasses should do real tests on the output. This only tests that we can even call the method. .. todo:: Tests in the subclasses that the results make sense. ie, follow the expected distribution """ if self.obj is not measurement.MeasurementErrorSampler: assert False # should never be here b/c subclasses override # --------------- # c_err = None with pytest.raises(NotImplementedError): tuple(self.inst.run(self.c, random=0)) # the tuple is for ``_run_iter`` version # --------------- # random with pytest.raises(NotImplementedError): tuple(self.inst.run(self.c, random=1)) # the tuple is for ``_run_iter`` version # --------------- # len(c.shape) == 1 assert len(self.c.shape) == 1 with pytest.raises(NotImplementedError): tuple(self.inst.run(self.c, self.c_err, random=0)) # the tuple is for ``_run_iter`` version # --------------- # 2D array, SkyCoord, nerriter = 1 c = concatenate([self.c, self.c]).reshape(len(self.c), -1) with pytest.raises(NotImplementedError): tuple(self.inst.run(c, c_err=self.c_err, random=0)) # the tuple is for ``_run_iter`` version # --------------- # 2D array, SkyCoord, nerriter != niter c_err = concatenate([self.c_err, self.c_err, self.c_err], ).reshape( len(self.c), -1) with pytest.raises(ValueError, match="c & c_err shape mismatch"): tuple(self.inst.run(c, c_err)) # the tuple is for ``_run_iter`` version # --------------- # 2D array, SkyCoord, nerriter = niter c_err = concatenate([self.c_err, self.c_err]).reshape(len(self.c), -1) with pytest.raises(NotImplementedError): tuple(self.inst.run(c, c_err=c_err, random=0)) # the tuple is for ``_run_iter`` version # --------------- # 2D array, (Mapping, scalar, callable, %-unit) with pytest.raises(NotImplementedError): tuple(self.inst.run(c, c_err=1 * u.percent, random=0)) # the tuple is for ``_run_iter`` version # --------------- # 2D array, other with pytest.raises(NotImplementedError): tuple(self.inst.run(self.c, NotImplementedError())) # the tuple is for ``_run_iter`` version # --------------- # in different frame assert self.inst.frame != coord.Galactic() with pytest.raises(NotImplementedError): tuple( self.inst.run( c, c_err=10 * u.percent, random=0, frame=coord.Galactic(), ), ) # the tuple is for ``_run_iter`` version # --------------- # & in different representation assert self.inst.frame != coord.Galactic() assert self.inst.representation_type != coord.CylindricalRepresentation with pytest.raises(NotImplementedError): tuple( self.inst.run( c, c_err=10 * u.percent, random=0, frame=coord.Galactic(), representation_type=coord.CylindricalRepresentation, ), )
def time_concatenate_array(self): concatenate((self.icrs_array, self.icrs_array))
def time_concatenate_scalar(self): concatenate((self.icrs_scalar, self.icrs_scalar))
def mk_great_footprint(center, array_rot=0., which_config='LFA', color='green'): r''' Make a DS9 region file of the upGREAT LFA or HFA footprint given some center position. Parameters ---------- center : SkyCoord central RA and Dec passed in as an astropy SkyCoord array_rot : float rotation angle of the array in degrees, default is 0 which_config : string only the LFA and HFA configurations are supported, default is 'LFA' color : string color of regions, default is 'green' Returns ------- None Notes ----- Required modules: astropy, numpy, regions Developed using astropy 4.0.2, numpy 1.19.2, regions 0.5 in iPython 7.19.0 and Python 3.8.5 Author: R. C. Levy ([email protected]) Last Updated: 2022-01-24 Change log: 2022-01-21 : file created 2022-01-24 : generates the footprints in the correct order as numbered in the handbook, https://www-sofia.atlassian.net/wiki/spaces/OHFC1/pages/1147523/6.+GREAT#Figure6-3 Examples -------- >> ipython >> from astropy.coordinates import SkyCoord >> from mkGREATfootprint import mk_great_footprint >> center = SkyCoord('13h05m27.2776s','-49d28m5.556s') #NGC4945 >> mk_great_footprint(center,array_rot=0.,which_config='LFA',color='cyan') >> #output region file has the name SOFIA_upGREAT_[which_config]_Cen[center]_Rot[array_rot].reg ''' import numpy as np from astropy.coordinates import SkyCoord, Angle, concatenate from regions import CircleSkyRegion, Regions #get radius of each pixel, from https://www-sofia.atlassian.net/wiki/spaces/OHFC1/pages/1147523/6.+GREAT#Table6-1 #get linear separation of pixel centers, from #https://www-sofia.atlassian.net/wiki/spaces/OHFC1/pages/1147523/6.+GREAT#Figure6-3 if which_config == 'LFA': radius = Angle(14.1 / 2, 'arcsec') separation = Angle(31.7, 'arcsec') elif which_config == 'HFA': radius = Angle(6.3 / 2, 'arcsec') separation = Angle(13.8, 'arcsec') else: print( "Error: Only LFA and HFA configurations are supported.\nPlease try again with either mk_great_footprint(center,which_config='LFA') or mk_great_footprint(center,which_config='HFA')." ) return #get coordinates of the surrounding pixels #account for any rotation of the array too angles = np.radians(np.arange(0, 360, 60) - 150 + array_rot) other_pixels = center.directional_offset_by(angles, separation) pixel_coords = concatenate((center, other_pixels)) regions = [''] * len(pixel_coords) for i in range(len(pixel_coords)): regions[i] = CircleSkyRegion(pixel_coords[i], radius) regions[i].visual['color'] = color reg = Regions(regions) #write regions to a file fname = 'SOFIA_upGREAT_' + which_config + '_regions_Cen' + center.to_string( 'hmsdms').replace(' ', '') + '_Rot' + str(array_rot) + '.reg' reg.write(fname, format='ds9', overwrite=True) return
def time_concatenate_array(self): concatenate((self.icrs_array, self.icrs_array))
from pywwt.qt import WWTQtClient from astropy import units as u from astropy.coordinates import concatenate, SkyCoord # open widget, render at end of each section wwt = WWTQtClient(size=(600, 400), block_until_ready=True) # big_dipper.png bd = concatenate((SkyCoord.from_name('Alkaid'), SkyCoord.from_name('Mizar'), SkyCoord.from_name('Alioth'), SkyCoord.from_name('Megrez'), SkyCoord.from_name('Phecda'), SkyCoord.from_name('Merak'), SkyCoord.from_name('Dubhe'))) wwt.center_on_coordinates(SkyCoord.from_name('Megrez')) line = wwt.add_line(bd, width=3 * u.pixel) wwt.wait() wwt.render('images/big_dipper.png') # big_dipper2.png line.add_point(SkyCoord.from_name('Megrez')) line.color = 'salmon' wwt.wait() wwt.render('images/big_dipper2.png') # polygons.png wwt.center_on_coordinates(SkyCoord.from_name('eta orion')) wwt.crosshairs = False body = concatenate( (SkyCoord.from_name('zeta orion'), SkyCoord.from_name('betelgeuse'), SkyCoord.from_name('bellatrix'), SkyCoord.from_name('delta orion')))
catalog = read_catalog( max_magnitude=2.5, max_variability=None, ) write_header = True for path in tqdm(sorted(os.listdir(args.inputdir))): img = magic_2018.read(os.path.join(args.inputdir, path)) if img.data.mean() > 0.030: continue stars_altaz = transform_catalog(catalog, img.timestamp, magic_2018) objects = concatenate( [stars_altaz, get_planets(img.timestamp, magic_2018)]) objects = objects[objects.alt.deg > 5] r, c, s = find_stars(img.data, 0.04) found_altaz = magic_2018.pixel2horizontal(r, c, img.timestamp) mask = found_altaz.alt.deg > 5 r, c, s = r[mask], c[mask], s[mask] found_altaz = found_altaz[mask] idx, d2d, d3d = match_coordinates_sky(objects, found_altaz) mask = d2d < 1.0 * u.deg idx = idx[mask] pd.DataFrame( dict(
def SkyCoord( self, t=None, ind=None, *args, frame: Optional[SkyCoord] = None, return_t: bool = False, T: bool = False, **kw, ): """SkyCoord. Parameters ---------- t: array_like time ind: int the index of orbits within each segment to take skycoord .. note:: args and kw do nothing right now Returns ------- SkyCoord ts if return_t is True """ # output frame if frame is None: # inherit current frame frame = self.o.SkyCoord() # astropy bug. not the same galcen_v_sun if hasattr(frame, "galcen_v_sun"): frame_galcen_v_sun = frame.galcen_v_sun else: frame_galcen_v_sun = None # will update later # taking care of index options, slices & lists are naturally supported if ind in (None, Ellipsis): ind = slice(None) scs, ts = [], [] # initializing SkyCoord, time arrays # iterating through orbits for i, time in self.iterator(t): # orbit segment, time w/in segment if not isinstance(i, int): raise ValueError("i not int") try: # getting at times sc = self._orbits[i][ind].SkyCoord(time).transform_to(frame) except ValueError: # not integrated, get initial conditions sc = self._orbits[i][ind].SkyCoord().transform_to(frame) except IndexError: sc = self._orbits[i].SkyCoord(time).transform_to(frame) # astropy bug. not the same, even when should be if hasattr(sc, "galcen_v_sun"): if frame_galcen_v_sun is None: # b/c no provided frame frame_galcen_v_sun = sc.galcen_v_sun sc.galcen_v_sun = frame_galcen_v_sun scs.append(sc.T) ts.append(time) # /for try: scs = concatenate(scs) except ValueError: # only 1 point scs = scs[0] if not T: scs = scs.T if return_t: return scs, astrarray(ts).flatten() else: return scs
import matplotlib.pyplot as plt from all_sky_cloud_detection.cameras import magic_2018 from all_sky_cloud_detection.plotting import ( add_direction_labels, add_zenith_lines, plot_img ) parser = ArgumentParser() parser.add_argument('inputfile') parser.add_argument('-o', '--output') args = parser.parse_args() source_names = ['Mrk 501', 'Mrk 421', '1ES 1959+650'] sources = concatenate([SkyCoord.from_name(n) for n in source_names]) img = magic_2018.read(args.inputfile) altaz = AltAz(location=magic_2018.location, obstime=img.timestamp) sources_altaz = sources.transform_to(altaz) fig, ax, plot = plot_img(img.data) add_direction_labels(magic_2018, ax=ax, color='crimson', weight='bold', size=14) add_zenith_lines(magic_2018, ax=ax) for name, source in zip(source_names, sources_altaz): row, col = magic_2018.horizontal2pixel(source) ax.plot(col, row, color='Gold', marker='o')
def plot_mesh(self): fig = self._figure half_angle = np.radians(self._s_half_angle.val) height = self._s_height.val kappa = self._s_kappa.val lat = np.radians(self._s_lat.val) lon = np.radians(self._s_lon.val) tilt = np.radians(self._s_tilt.val) # calculate and show quantities ra = apex_radius(half_angle, height, kappa) self._l_radius.setText( 'Apex cross-section radius: {:.2f} Rs'.format(ra)) # check if plot should be shown draw_mode = draw_modes[self._cb_mode.currentIndex()] if draw_mode != self._current_draw_mode: for plot in self._mesh_plots: plot.remove() self._mesh_plots = [] fig.canvas.draw() self._current_draw_mode = draw_mode if draw_mode == 'off': return # create GCS mesh mesh = gcs_mesh_sunpy(self._date, half_angle, height, straight_vertices, front_vertices, circle_vertices, kappa, lat, lon, tilt) if draw_mode == 'grid': mesh2 = mesh.reshape((front_vertices + straight_vertices) * 2 - 3, circle_vertices).T.flatten() mesh = concatenate([mesh, mesh2]) for i, (image, ax) in enumerate(zip(self._images, self._axes)): if len(self._mesh_plots) <= i: # new plot style = {'grid': '-', 'point cloud': '.'}[draw_mode] params = { 'grid': dict(lw=0.5), 'point cloud': dict(ms=2) }[draw_mode] p = ax.plot_coord(mesh, style, color='blue', scalex=False, scaley=False, **params)[0] self._mesh_plots.append(p) else: # update plot p = self._mesh_plots[i] frame0 = mesh.frame.transform_to(image.coordinate_frame) xdata = frame0.spherical.lon.to_value(units.deg) ydata = frame0.spherical.lat.to_value(units.deg) p.set_xdata(xdata) p.set_ydata(ydata) ax.draw_artist(p) fig.canvas.draw()