Exemple #1
0
def solveTrajectoryCAMS(meteor_list, output_dir, solver='original', **kwargs):
    """ Feed the list of meteors in the trajectory solver. """


    # Normalize the observations to the same reference Julian date and precess them from J2000 to the 
    # epoch of date
    jdt_ref, meteor_list = prepareObservations(meteor_list)


    if meteor_list is not None:

        for meteor in meteor_list:
            print(meteor)


        # Init the trajectory solver
        if solver == 'original':
            traj = Trajectory(jdt_ref, output_dir=output_dir, meastype=1, **kwargs)

        elif solver.lower().startswith('gural'):
            velmodel = solver.lower().strip('gural')
            if len(velmodel) == 1:
                velmodel = int(velmodel)
            else:
                velmodel = 0

            traj = GuralTrajectory(len(meteor_list), jdt_ref, velmodel=velmodel, meastype=1, verbose=1, 
                output_dir=output_dir)

        else:
            print('No such solver:', solver)
            return 


        # Add meteor observations to the solver
        for meteor in meteor_list:

            if solver == 'original':

                traj.infillTrajectory(meteor.ra_data, meteor.dec_data, meteor.time_data, meteor.latitude, 
                    meteor.longitude, meteor.height, station_id=meteor.station_id, \
                    magnitudes=meteor.mag_data)

                # traj.infillTrajectory(meteor.azim_data, meteor.elev_data, meteor.time_data, meteor.latitude, 
                #      meteor.longitude, meteor.height, station_id=meteor.station_id, \
                #      magnitudes=meteor.mag_data)

            elif solver == 'gural':

                traj.infillTrajectory(meteor.ra_data, meteor.dec_data, meteor.time_data, meteor.latitude, 
                    meteor.longitude, meteor.height)

                # traj.infillTrajectory(meteor.azim_data, meteor.elev_data, meteor.time_data, meteor.latitude, 
                #     meteor.longitude, meteor.height)


        # Solve the trajectory
        traj.run()

        return traj
Exemple #2
0
def solveTrajectoryMet(met, solver='original', velmodel=3, **kwargs):
        """ Runs the trajectory solver on points of the given type. 

        Keyword arguments:
            solver: [str] Trajectory solver to use:
                - 'original' (default) - "in-house" trajectory solver implemented in Python
                - 'gural' - Pete Gural's PSO solver
            velmodel: [int] Velocity propagation model for the Gural solver
                0 = constant   v(t) = vinf
                1 = linear     v(t) = vinf - |acc1| * t
                2 = quadratic  v(t) = vinf - |acc1| * t + acc2 * t^2
                3 = exponent   v(t) = vinf - |acc1| * |acc2| * exp( |acc2| * t ) (default)
        """


        # Check that there are at least two stations present
        if len(met.sites) < 2:
            print('ERROR! The .met file does not contain multistation data!')

            return False



        time_data = {}
        theta_data = {}
        phi_data = {}
        mag_data = {}

        # Go through all sites
        for site in met.sites:

            time_picks = []
            theta_picks = []
            phi_picks = []
            mag_picks = []

            # Go through all picks
            for pick in met.picks_objs[site]:

                # Add the pick to the picks list
                theta_picks.append(pick.theta)
                phi_picks.append(pick.phi)

                # Add the time of the pick to a list
                time_picks.append(pick.unix_time)

                # Add magnitude
                mag_picks.append(pick.mag)


            # Add the picks to the list of picks of both sites
            time_data[site] = np.array(time_picks).ravel()
            theta_data[site] = np.array(theta_picks).ravel()
            phi_data[site] = np.array(phi_picks).ravel()
            mag_data[site] = np.array(mag_picks).ravel()


        # Take the earliest time of all sites as the reference time
        ref_unix_time = min([time_data[key][0] for key in time_data.keys()])

        # Normalize all times with respect to the reference times
        for site in met.sites:
            time_data[site] = time_data[site] - ref_unix_time


        # Convert the reference Unix time to Julian date
        ts = int(ref_unix_time)
        tu = (ref_unix_time - ts)*1e6
        ref_JD = unixTime2JD(ts, tu)


        if solver == 'original':

            # Init the new trajectory solver object
            traj = Trajectory(ref_JD, output_dir=met.dir_path, **kwargs)

        elif solver == 'gural':

            # Select extra keyword arguments that are present only for the gural solver
            gural_keys = ['max_toffset', 'nummonte', 'meastype', 'verbose', 'show_plots']
            gural_kwargs = {key: kwargs[key] for key in gural_keys if key in kwargs}

            # Init the new Gural trajectory solver object
            traj = GuralTrajectory(len(met.sites), ref_JD, velmodel, verbose=1, output_dir=met.dir_path, 
                **gural_kwargs)


        # Infill trajectories from each site
        for site in met.sites:

            theta_picks = theta_data[site]
            phi_picks = phi_data[site]
            time_picks = time_data[site]
            mag_picks = mag_data[site]

            if not np.any(mag_picks):
                mag_picks = None

            lat = met.lat[site]
            lon = met.lon[site]
            elev = met.elev[site]


            # MC solver
            if solver == 'original':

                traj.infillTrajectory(phi_picks, theta_picks, time_picks, lat, lon, elev, \
                    station_id=str(site), magnitudes=mag_picks)
            
            # Gural solver
            else:
                traj.infillTrajectory(phi_picks, theta_picks, time_picks, lat, lon, elev)


        print('Filling done!')


        # # Dump measurements to a file
        # traj.dumpMeasurements(self.met.dir_path.split(os.sep)[-1] + '_dump.txt')


        # Solve the trajectory
        traj = traj.run()

        return traj
Exemple #3
0
def solveTrajectoryPickle(dir_path,
                          file_name,
                          only_plot=False,
                          solver='original',
                          **kwargs):
    """ Rerun the trajectory solver on the given trajectory pickle file. """

    # Load the pickles trajectory
    traj_p = loadPickle(dir_path, file_name)

    # Run the PyLIG trajectory solver
    if solver == 'original':

        # Given the max time offset from the pickle file and input, use the larger one of the two
        max_toffset = traj_p.max_toffset
        if "max_toffset" in kwargs:

            if (kwargs["max_toffset"] is not None) and (traj_p.max_toffset
                                                        is not None):

                max_toffset = max(traj_p.max_toffset, kwargs["max_toffset"])

            # Remove the max time offset from the list of keyword arguments
            kwargs.pop("max_toffset", None)

        # Preserve the trajectory ID
        if hasattr(traj_p, "traj_id"):
            traj_id = traj_p.traj_id
        else:
            traj_id = None

        # Reinitialize the trajectory solver
        meastype = 2
        traj = Trajectory(traj_p.jdt_ref, output_dir=dir_path, max_toffset=max_toffset, \
            meastype=meastype, traj_id=traj_id, **kwargs)

        # Fill the observations
        for obs in traj_p.observations:
            traj.infillWithObs(obs, meastype=meastype)

    elif solver == 'gural':

        # Init the Gural solver
        traj = GuralTrajectory(len(traj_p.observations), traj_p.jdt_ref, velmodel=3, \
            max_toffset=traj_p.max_toffset, meastype=2, output_dir=dir_path, verbose=True)

        # Fill the observations
        for obs in traj_p.observations:

            traj.infillTrajectory(obs.azim_data, obs.elev_data, obs.time_data,
                                  obs.lat, obs.lon, obs.ele)

    else:
        print('Unrecognized solver:', solver)

    if only_plot:

        # Set saving results
        traj_p.save_results = True

        # Override plotting options with given options
        traj_p.plot_all_spatial_residuals = kwargs[
            "plot_all_spatial_residuals"]
        traj_p.plot_file_type = kwargs["plot_file_type"]

        # Show the plots
        traj_p.savePlots(dir_path,
                         traj_p.file_name,
                         show_plots=kwargs["show_plots"])

    # Recompute the trajectory
    else:

        # Run the trajectory solver
        traj.run()

    return traj
Exemple #4
0
def solveTrajectoryEv(ev_file_list, solver='original', velmodel=3, **kwargs):
        """ Runs the trajectory solver on UWO style ev file. 
    
        Arguments:
            ev_file_list: [list] A list of paths to ev files.


        Keyword arguments:
            solver: [str] Trajectory solver to use:
                - 'original' (default) - "in-house" trajectory solver implemented in Python
                - 'gural' - Pete Gural's PSO solver
            velmodel: [int] Velocity propagation model for the Gural solver
                0 = constant   v(t) = vinf
                1 = linear     v(t) = vinf - |acc1| * t
                2 = quadratic  v(t) = vinf - |acc1| * t + acc2 * t^2
                3 = exponent   v(t) = vinf - |acc1| * |acc2| * exp( |acc2| * t ) (default)


        Return:
            traj: [Trajectory instance] Solved trajectory
        """


        # Check that there are at least two stations present
        if len(ev_file_list) < 2:
            print('ERROR! The list of ev files does not contain multistation data!')

            return False


        # Load the ev file
        station_data_list = []
        for ev_file_path in ev_file_list:
            
            # Store the ev file contants into a StationData object
            sd = readEvFile(*os.path.split(ev_file_path))

            # Skip bad ev files
            if sd is None:
                print("Skipping {:s}, bad ev file!".format(ev_file_path))
                continue

            station_data_list.append(sd)


        # Check that there are at least two good stations present
        if len(station_data_list) < 2:
            print('ERROR! The list of ev files does not contain at least 2 good ev files!')

            return False


        # Normalize all times to earliest reference Julian date
        jdt_ref = min([sd_temp.jd_ref for sd_temp in station_data_list])
        for sd in station_data_list:
            for i in range(len(sd.time_data)):
                sd.time_data[i] += (sd.jd_ref - jdt_ref)*86400
            
            sd.jd_ref = jdt_ref


        for sd in station_data_list:
            print(sd)


        # Get the base path of these ev files
        root_path = os.path.dirname(ev_file_list[0])

        # Create a new output directory
        dir_path = os.path.join(root_path, jd2Date(jdt_ref, dt_obj=True).strftime("traj_%Y%m%d_%H%M%S.%f"))
        mkdirP(dir_path)


        if solver == 'original':

            # Init the new trajectory solver object
            traj = Trajectory(jdt_ref, output_dir=dir_path, meastype=4, **kwargs)

        elif solver.startswith('gural'):

            # Extract velocity model is given
            try:
                velmodel = int(solver[-1])

            except: 
                # Default to the exponential model
                velmodel = 3

            # Select extra keyword arguments that are present only for the gural solver
            gural_keys = ['max_toffset', 'nummonte', 'meastype', 'verbose', 'show_plots']
            gural_kwargs = {key: kwargs[key] for key in gural_keys if key in kwargs}

            # Init the new Gural trajectory solver object
            traj = GuralTrajectory(len(station_data_list), jdt_ref, velmodel, verbose=1, \
                output_dir=dir_path, meastype=4, **gural_kwargs)


        # Infill trajectories from each site
        for sd in station_data_list:

            # MC solver
            if solver == 'original':

                traj.infillTrajectory(sd.phi_data, sd.theta_data, sd.time_data, sd.lat, sd.lon, sd.height, \
                    station_id=sd.station_id, magnitudes=sd.mag_data)
            
            # Gural solver
            else:
                traj.infillTrajectory(sd.phi_data, sd.theta_data, sd.time_data, sd.lat, sd.lon, sd.height)


        print('Filling done!')


        # Solve the trajectory
        traj = traj.run()


        # Copy the ev files into the output directory
        for ev_file_path in ev_file_list:
            shutil.copy2(ev_file_path, os.path.join(dir_path, os.path.basename(ev_file_path)))



        return traj
def solveTrajectoryUWOEvent(station_data_dict, solver='original', velmodel=3, **kwargs):
        """ Runs the trajectory solver on points of the given type. 

        Keyword arguments:
            solver: [str] Trajectory solver to use:
                - 'original' (default) - "in-house" trajectory solver implemented in Python
                - 'gural' - Pete Gural's PSO solver
            velmodel: [int] Velocity propagation model for the Gural solver
                0 = constant   v(t) = vinf
                1 = linear     v(t) = vinf - |acc1| * t
                2 = quadratic  v(t) = vinf - |acc1| * t + acc2 * t^2
                3 = exponent   v(t) = vinf - |acc1| * |acc2| * exp( |acc2| * t ) (default)
        """


        # Check that there are at least two stations present
        if len(station_data_dict["station_data"]) < 2:
            print('ERROR! The event.txt file does not contain multistation data!')

            return False



        if solver == 'original':

            # Init the new trajectory solver object
            traj = Trajectory(station_data_dict["jd_ref"], output_dir=station_data_dict["dir_path"], \
                meastype=4, **kwargs)

        elif solver.startswith('gural'):

            # Extract velocity model is given
            try:
                velmodel = int(solver[-1])

            except: 
                # Default to the exponential model
                velmodel = 3

            # Select extra keyword arguments that are present only for the gural solver
            gural_keys = ['max_toffset', 'nummonte', 'meastype', 'verbose', 'show_plots']
            gural_kwargs = {key: kwargs[key] for key in gural_keys if key in kwargs}

            # Init the new Gural trajectory solver object
            traj = GuralTrajectory(len(station_data_dict["station_data"]), station_data_dict["jd_ref"], \
                velmodel, verbose=1, output_dir=station_data_dict["dir_path"], meastype=4, \
                **gural_kwargs)


        # Infill trajectories from each site
        for stat_data in station_data_dict["station_data"]:

            # MC solver
            if solver == 'original':

                traj.infillTrajectory(stat_data.phi_data, stat_data.theta_data, stat_data.time_data, \
                    stat_data.lat, stat_data.lon, stat_data.height, \
                    station_id=stat_data.station_id, magnitudes=stat_data.mag_data)
            
            # Gural solver
            else:
                traj.infillTrajectory(stat_data.phi_data, stat_data.theta_data, stat_data.time_data, \
                    stat_data.lat, stat_data.lon, stat_data.height)


        print('Filling done!')


        # Solve the trajectory
        traj.run()

        return traj
Exemple #6
0
    def solveTrajectory(self,
                        pick_type='original',
                        velmodel=3,
                        solver='original',
                        **kwargs):
        """ Runs the trajectory solver on points of the given type. 

        Keyword arguments:
            pick_type: [str] Can be:
                - 'original' (default) original manual picks
                - 'gc' original picks projected onto a great circle
                - 'draw' picks drawn from a probability distribution
            velmodel: [int] Velocity propagation model
                0 = constant   v(t) = vinf
                1 = linear     v(t) = vinf - |acc1| * t
                2 = quadratic  v(t) = vinf - |acc1| * t + acc2 * t^2
                3 = exponent   v(t) = vinf - |acc1| * |acc2| * exp( |acc2| * t ) (default)
            solver: [str] Trajectory solver to use:
                - 'original' (default) - "in-house" trajectory solver implemented in Python
                - 'gural' - Pete Gural's PSO solver
        """

        time_data = {}
        theta_data = {}
        phi_data = {}

        # Go through all sites
        for site in self.met.sites:

            # Extract picks of the given type
            time_picks, theta_picks, phi_picks = self.extractPicks(
                site, pick_type=pick_type)

            # Add the picks to the list of picks of both sites
            time_data[site] = np.array(time_picks).ravel()
            theta_data[site] = np.array(theta_picks).ravel()
            phi_data[site] = np.array(phi_picks).ravel()

        # Take the earliest time of all sites as the reference time
        ref_unix_time = min([time_data[key][0] for key in time_data.keys()])

        # Normalize all times with respect to the reference times
        for site in self.met.sites:
            time_data[site] = time_data[site] - ref_unix_time

        # Convert the reference Unix time to Julian date
        ts = int(ref_unix_time)
        tu = (ref_unix_time - ts) * 1e6
        ref_JD = unixTime2JD(ts, tu)

        if solver == 'original':

            # Init the new trajectory solver object
            traj_solve = Trajectory(ref_JD,
                                    show_plots=True,
                                    output_dir=self.met.dir_path,
                                    **kwargs)

        elif solver == 'gural':

            # Init the new Gural trajectory solver object
            traj_solve = GuralTrajectory(len(self.met.sites),
                                         ref_JD,
                                         velmodel,
                                         verbose=1)

        # Infill trajectories from each site
        for site in self.met.sites:

            theta_picks = theta_data[site]
            phi_picks = phi_data[site]
            time_picks = time_data[site]

            lat = self.met.exact_plates[site].lat
            lon = self.met.exact_plates[site].lon
            elev = self.met.exact_plates[site].elev

            traj_solve.infillTrajectory(phi_picks, theta_picks, time_picks,
                                        lat, lon, elev)

        print('Filling done!')

        # # Dump measurements to a file
        # traj_solve.dumpMeasurements(self.met.dir_path.split(os.sep)[-1] + '_dump.txt')

        # Solve the trajectory
        traj_solve.run()

        return traj_solve
Exemple #7
0
def solveTrajectoryGeneric(jdt_ref, meteor_list, dir_path, solver='original', **kwargs):
    """ Feed the list of meteors in the trajectory solver and run it. 
    
    Arguments:
        jdt_ref: [float] Reference Julian date for all objects in meteor_list.
        meteor_list: [list] A list of MeteorObservation objects.
        dir_path: [str] Path to the data directory.

    Keyword arguments:
        solver: [str] Solver choice:
            - "original" is the Monte Carlo solver
            - "gural" is the Gural solver (through C++ bindings)
        **kwargs: Keyword arguments for the trajectory solver.

    """

    # Create name of output directory
    output_dir = os.path.join(dir_path, jd2Date(jdt_ref, dt_obj=True).strftime("%Y%m%d-%H%M%S.%f"))


    # Init the trajectory solver
    if solver == 'original':
        traj = Trajectory(jdt_ref, output_dir=output_dir, meastype=1, **kwargs)

    elif solver.lower().startswith('gural'):
        velmodel = solver.lower().strip('gural')
        if len(velmodel) == 1:
            velmodel = int(velmodel)
        else:
            velmodel = 0

        traj = GuralTrajectory(len(meteor_list), jdt_ref, velmodel=velmodel, meastype=1, verbose=1, 
            output_dir=output_dir)

    else:
        print('No such solver:', solver)
        return 


    # Add meteor observations to the solver
    for meteor in meteor_list:

        if solver == 'original':

            comment = ''
            if hasattr(meteor, "ff_name"):
                comment = meteor.ff_name

            traj.infillTrajectory(meteor.ra_data, meteor.dec_data, meteor.time_data, meteor.latitude, 
                meteor.longitude, meteor.height, station_id=meteor.station_id, \
                magnitudes=meteor.mag_data, comment=comment)

        elif solver.lower().startswith('gural'):

            # Extract velocity model is given
            try:
                velmodel = int(solver[-1])

            except: 
                # Default to the exponential model
                velmodel = 3

            traj.infillTrajectory(meteor.ra_data, meteor.dec_data, meteor.time_data, meteor.latitude, 
                meteor.longitude, meteor.height)


    # Solve the trajectory
    traj = traj.run()

    return traj
Exemple #8
0
def solveTrajectoryRMS(json_list, dir_path, solver='original', **kwargs):
    """ Feed the list of meteors in the trajectory solver. """

    # Normalize the observations to the same reference Julian date and precess them from J2000 to the
    # epoch of date
    jdt_ref, meteor_list = initMeteorObjects(json_list)

    # Create name of output directory
    output_dir = os.path.join(
        dir_path,
        jd2Date(jdt_ref, dt_obj=True).strftime("%Y%m%d-%H%M%S.%f"))

    # Init the trajectory solver
    if solver == 'original':
        traj = Trajectory(jdt_ref, output_dir=output_dir, meastype=1, **kwargs)

    elif solver.lower().startswith('gural'):
        velmodel = solver.lower().strip('gural')
        if len(velmodel) == 1:
            velmodel = int(velmodel)
        else:
            velmodel = 0

        traj = GuralTrajectory(len(meteor_list),
                               jdt_ref,
                               velmodel=velmodel,
                               meastype=1,
                               verbose=1,
                               output_dir=output_dir)

    else:
        print('No such solver:', solver)
        return

    # Add meteor observations to the solver
    for meteor in meteor_list:

        if solver == 'original':

            traj.infillTrajectory(meteor.ra_data, meteor.dec_data, meteor.time_data, meteor.latitude,
                meteor.longitude, meteor.height, station_id=meteor.station_id, \
                magnitudes=meteor.mag_data)

        elif solver.lower().startswith('gural'):

            # Extract velocity model is given
            try:
                velmodel = int(solver[-1])

            except:
                # Default to the exponential model
                velmodel = 3

            traj.infillTrajectory(meteor.ra_data, meteor.dec_data,
                                  meteor.time_data, meteor.latitude,
                                  meteor.longitude, meteor.height)

    # Solve the trajectory
    traj.run()

    return traj
Exemple #9
0
def solveTrajectoryMILIG(dir_path, file_name, solver='original', **kwargs):
    """ Run the trajectory solver on data provided in the MILIG format input file. 

    Arguments:
        dir_path: [str] Directory where the MILIG input file is located.
        file_name: [str] Name of the MILIG input file.

    Keyword arguments:
        **kwargs: [dict] Additional keyword arguments will be directly passed to the trajectory solver.


    Return:
        None

    """

    # Load data from the MILIG input file
    jdt_ref, stations = loadMiligInput(os.path.join(dir_path, file_name))

    print('JD', jdt_ref)

    # Init the trajectory solver
    if solver == 'original':
        traj = Trajectory(jdt_ref, output_dir=dir_path, meastype=3, **kwargs)

    elif solver.startswith('gural'):

        # Extract velocity model is given
        try:
            velmodel = int(solver[-1])

        except:
            # Default to the exponential model
            velmodel = 3

        traj = GuralTrajectory(len(stations),
                               jdt_ref,
                               velmodel=velmodel,
                               meastype=3,
                               verbose=1,
                               output_dir=dir_path)

    # Infill data from each station to the solver
    for station in stations:

        print(station)

        if solver == 'original':

            excluded_time = None

            # ### ADD A TIME OF EXCLUSION ###
            # # Add a time range for the given station for which there are not measurements (possibly due to
            # # saturation). This way the calculation of length residuals will not be affected.

            # if station.station_id == "1":
            #     print('EXCLUDED POINTS')
            #     #excluded_time = [0.580001, 0.859983]
            #     #excluded_time = [1.7, 3.2]

            ###############################

            traj.infillTrajectory(station.azim_data, station.zangle_data, station.time_data, station.lat,
                station.lon, station.height, station_id=station.station_id, excluded_time=excluded_time, \
                ignore_list=station.ignore_picks)

        elif 'gural' in solver:

            traj.infillTrajectory(np.array(station.azim_data),
                                  np.array(station.zangle_data),
                                  np.array(station.time_data), station.lat,
                                  station.lon, station.height)

        else:
            print('Solver: {:s} is not a valid solver!'.format(solver))

    # for obs in traj.observations:
    #     print(np.degrees(obs.lat), np.degrees(obs.lon))

    # Run the trajectory solver
    traj.run()

    return traj
                elif 'gural' in traj_solver:

                    # Extract the velocity model
                    try:
                        velmodel = traj_solver.replace('gural', '')

                    except:

                        # Velocity model ID
                        print('Unknown velocity model:', velmodel)
                        sys.exit()

                    # Init the new Gural trajectory solver object
                    traj = GuralTrajectory(len(sim_met.observations), sim_met.jdt_ref, output_dir=output_dir, \
                        max_toffset=t_max_offset, meastype=2, velmodel=velmodel, verbose=1, \
                        show_plots=False, traj_id=unique_id)

                else:
                    print(traj_solver, '- unknown trajectory solver!')
                    sys.exit()

                # Fill in observations
                for obs in sim_met.observations:

                    traj.infillTrajectory(obs.meas1, obs.meas2, obs.time_data, obs.lat, obs.lon, obs.ele, \
                        station_id=obs.station_id)

                # Solve trajectory
                traj = traj.run()