def animate(problem, filename, num_trucks):
    with open(path + filename + ".txt") as f:
        customers = import_customers(problem + ".txt", False)
        Distances.calculate_matrix(customers)
        lines = f.readlines()

        ids = []
        for line in lines[5:]:
            ids.append(line.split()[3:])

    routes = []
    for line in ids:
        route = []
        for cust_number in line:
            route.append((customers[int(cust_number) - 1]))
        routes.append(route)

    truck_lists = []
    for i in range(len(routes)):
        if i % num_trucks == 0:
            truck_lists.append([])
        truck_lists[-1].append(
            Truck(i % num_trucks, 0, 0, len(routes), Path(routes[i])))

    for trucks in truck_lists:
        State(trucks).plot()
        time.sleep(.3)
def animate(problem, filename, num_trucks):
    with open(path + filename + ".txt") as f:
        customers = import_customers(problem + ".txt", False)
        Distances.calculate_matrix(customers)
        lines = f.readlines()

        ids = []
        for line in lines[5:]:
            ids.append(line.split()[3:])

    routes = []
    for line in ids:
        route = []
        for cust_number in line:
            route.append((customers[int(cust_number)-1]))
        routes.append(route)

    truck_lists = []
    for i in range(len(routes)):
        if i % num_trucks == 0:
            truck_lists.append([])
        truck_lists[-1].append(Truck(i % num_trucks, 0, 0, len(routes), Path(routes[i])))

    for trucks in truck_lists:
        State(trucks).plot()
        time.sleep(.3)
Example #3
0
    def get_arrival_time_of_customer(self, cust):
        """Returns the time at which the truck on this path arrives at this customer
        given the order of customers prior to the given customer and their windows"""

        prev_customer = self.route[0]
        time = Distances.get_distance(prev_customer.number, 0)

        if time < prev_customer.open_time:
            time = prev_customer.open_time

        if prev_customer == cust:
            return time

        time += prev_customer.service_time

        for c in self.route[1:]:

            time += Distances.get_distance(prev_customer.number, c.number)
            prev_customer = c

            # if truck arrives before customer is open, assume truck waits
            if time < c.open_time:
                time = c.open_time

            if (c == cust):
                return time

            time += c.service_time

        return -1
Example #4
0
def main(size, rank):
    Ntot = np.zeros(len(dat['z_cgal']))
    sample_i = np.array_split(np.arange(len(dat['z_cgal'])),size)[rank]
    #print(rank, len(sample_i))
    for i in sample_i:
        if rank == 0:
            print(i)
        #print("rank{}:  {}".format(rank, i))
        d = Distances()
        zlens = np.array(dat['z_cgal'])[i]
        Mh_lens = np.array(dat['lmhalo'])[i]
        Mstar_lens = np.array(dat['lmstellar'])[i]
        ind = np.where(redshift[mask]>zlens+.02)[0]
        Nsum = []
        for j in range(len(ind)):
            try:
                z2 = redshift[mask][ind[j]]
                csection = cross_section(z1=zlens,z2=z2,M200=10**Mh_lens,Mstar=10**Mstar_lens)
                beta_caus = csection.get_loc()[1]
                cross_sec = pi*beta_caus**2
                P = cross_sec/tot_area 
                dDa = d.angular_diameter_distance(redshift[mask][ind[j]-1],redshift[mask][ind[j]])
                Nsource = dNdz[mask][ind[j]] * dDa
                Nsum.append(Nsource * P)
            except ValueError:
                print(zlens,z2)
            
            
        Ntot[i] = np.sum(Nsum)
    np.savetxt('ntot_{}.txt'.format(rank),Ntot)
Example #5
0
    def get_excessive_wait_custs(self):
        waits = []

        if len(self) == 0:
            return None

        wait_time = 0
        prev_customer = self.route[0]
        time = Distances.get_distance(prev_customer.number, 0)

        if time < prev_customer.open_time:
            wait_time = prev_customer.open_time - time
            time = prev_customer.open_time

        if wait_time > 20:
            waits.append(prev_customer)

        time += prev_customer.service_time

        for c in self.route[1:]:

            time += Distances.get_distance(prev_customer.number, c.number)
            prev_customer = c

            if time < c.open_time:
                wait_time = prev_customer.open_time - time
                time = c.open_time
            ######## THE WAIT TIME VALUE IS ARBITRARILY PICKED, CAN CHANGE IF NECESSARY
            if wait_time > 20:
                waits.append(c)

            time += c.service_time

        return waits
Example #6
0
    def get_last_customer_visited(self, current_time):
        """Gets the customer the truck was last at"""
        prev_customer = self.route[0]

        time = Distances.get_distance(prev_customer.number, 0)
        if (time > current_time):
            return None

        # if truck arrives before customer is open, assume truck waits
        if time < prev_customer.open_time:
            time = prev_customer.open_time
        time += prev_customer.service_time

        if (time > current_time):
            return prev_customer

        for c in self.route[1:]:

            time += Distances.get_distance(prev_customer.number, c.number)

            if(time > current_time):
                return prev_customer

            # if truck arrives before customer is open, assume truck waitds
            if time < c.open_time:
                time = c.open_time
            time += c.service_time

            if(time > current_time):
                return c

            prev_customer = c
        return None
Example #7
0
    def get_wait_time(self):
        if len( self ) == 0:
            return 0

        wait_time = 0
        prev_customer = self.route[0]
        time = Distances.get_distance(prev_customer.number, 0)

        if time < prev_customer.open_time:
            wait_time += prev_customer.open_time - time
            time = prev_customer.open_time

        time += prev_customer.service_time

        for c in self.route[1:]:

            time += Distances.get_distance(prev_customer.number, c.number)
            prev_customer = c

            # if truck arrives before customer is open, assume truck waits
            if time < c.open_time:
                wait_time += prev_customer.open_time - time
                time = c.open_time

            time += c.service_time

        return wait_time
Example #8
0
    def fix_group_unreasonable(paths):
        """Suppose the distances in order are like [a]unreasonable[b]reasonable[c]reasonable[d]reasonable[e]unreasonable[f].
           Then move b, c, d, and e into a different path based on a near neighbor"""
        children = []
        threshold = max(Distances.matrix[0]) / 3.5
        path_number = 0
        for path in paths:
            # check depot to first customer
            if Distances.get_distance(0, path.route[0].number) > threshold:
                for j in range(1, min(15, len(path))):  # max length of 14
                    if Distances.get_distance(
                            path.route[j].number,
                            path.route[j + 1].number) > threshold:
                        children += State.remove_and_insert_closer_as_group(
                            1, j, paths, path_number)

            # check all regular customers to e/o
            for i in range(0, len(path) - 1):
                if Distances.get_distance(
                        path.route[i].number,
                        path.route[i + 1].number) > threshold:
                    for j in range(i + 1, min(i + 14,
                                              len(path))):  #max length of 14
                        if Distances.get_distance(
                                path.route[j].number,
                                path.route[j + 1 if j < len(path) -
                                           1 else 0].number) > threshold:
                            children += State.remove_and_insert_closer_as_group(
                                i + 1, j, paths, path_number)

            path_number += 1
        return children
Example #9
0
 def get_next_one_path(source, customers, path):
     min = float('inf')
     next = source
     for i in range(len(customers)):
         if Distances.get_distance(customers.index(source), i) < min and customers.index(source) != i and ( customers[i] not in path):
             next = customers[i]
             min = Distances.get_distance(customers.index(source), i)
     return next
Example #10
0
def init(filename):
    global customers, depot

    print "Importing customers..."
    customers = import_customers(filename + ".txt", test_environment )
    print "Calculating distances..."
    Distances.calculate_matrix(customers)
    print "Storing clusters..."
    ClusterStore.store_clusters(filename, customers)

    depot = Depot(0,0)
Example #11
0
 def get_next_one_path(source, customers, path):
     min = float('inf')
     next = source
     for i in range(len(customers)):
         if Distances.get_distance(
                 customers.index(source),
                 i) < min and customers.index(source) != i and (
                     customers[i] not in path):
             next = customers[i]
             min = Distances.get_distance(customers.index(source), i)
     return next
Example #12
0
 def distance_swap(paths):
     children = []
     for i in range( 15 ):
         new_paths = [copy.deepcopy(element) for element in paths]
         path_index = randint(0, len(paths)-1)
         path = new_paths[path_index]
         # gets two random customers, if the first is farther then the second then swap
         customer_a = randint(0, len(path.route) - 1)
         customer_b = randint(customer_a, len(path.route) - 1)
         if Distances.get_distance(0, path.route[customer_a].number) > Distances.get_distance(0, path.route[customer_a].number):
             path.route[customer_a], path.route[customer_b] = path.route[customer_b], path.route[customer_a]
         children.append(new_paths)
     return children
Example #13
0
    def num_unreasonable_distances(self):
        distance_threshold = max(Distances.matrix[0])/3.5
        num_unreasonable_distances = 0

        prev_customer = self.route[0]
        distance = Distances.get_distance(0, prev_customer.number)

        if distance > distance_threshold:
            num_unreasonable_distances += 1

        for c in self.route[1:]:
            if(Distances.get_distance(prev_customer.number, c.number) > distance_threshold):
                num_unreasonable_distances += 1
            prev_customer = c
        return num_unreasonable_distances
Example #14
0
    def get_next(source, customers, paths):

        min = float('inf')
        next = source
        all_paths = []
        for p in range(len(paths)):
            path = paths[p]
            for c in range(len(path)):
                all_paths.append(path[c])
                
        for i in range(len(customers)):
            if Distances.get_distance(customers.index(source), i) < min and customers.index(source) != i and customers[i] not in all_paths:
                next = customers[i]
                min = Distances.get_distance(customers.index(source), i)
        return next
Example #15
0
    def remove_and_insert_closer(customer_index, paths,
                                 interesting_path_index):
        children = []
        # find whoever is closest to it (should be four customers nearby-ish?)
        customer = paths[interesting_path_index].route[customer_index]
        closest_customers = Distances.get_closest_customers(customer)

        for customer_id in closest_customers[1:5]:
            # for each of those customer IDs, find the path where it is, and insert it
            # either before or after (50/50) the close customer
            new_paths = copy.deepcopy(paths)
            new_path = new_paths[interesting_path_index]
            customer = new_path.route.pop(customer_index)
            containing_path = State.find_path_containing_customer(
                new_paths, customer_id)

            if containing_path:
                close_customer_index = containing_path.get_customer_index(
                    customer_id)
                if random.random() > 0.5:
                    containing_path.route.insert(close_customer_index + 1,
                                                 customer)
                else:
                    containing_path.route.insert(close_customer_index,
                                                 customer)
                children.append(new_paths)

        return children
Example #16
0
    def calculate_distance(self):
        """Returns the total distance in the route"""

        if len( self ) == 0:
            return 0

        prev_customer = self.route[0]
        distance = Distances.get_distance(0, prev_customer.number)

        for c in self.route[1:]:
            distance += Distances.get_distance(prev_customer.number, c.number)
            prev_customer = c

        distance += Distances.get_distance(prev_customer.number, 0)

        return distance
Example #17
0
    def remove_and_insert_closer_as_group(first_removal_index,
                                          last_removal_index, paths,
                                          interesting_path_index):
        children = []

        for i in range(1, 8):
            new_paths = copy.deepcopy(paths)
            path = new_paths[interesting_path_index]
            route = path.route
            customers_to_insert = []
            for k in range(first_removal_index, last_removal_index + 1):
                # the indexes will shift beneath our feet, so always remove at the same place
                customers_to_insert.append(route.pop(first_removal_index))

            # range starts at 1 because 0 refers to itself and that's stupid and bad
            closest_customer_id = Distances.get_closest_customers(
                customers_to_insert[0])[i]
            containing_path = State.find_path_containing_customer(
                new_paths, closest_customer_id)
            if containing_path:
                close_customer_index = containing_path.get_customer_index(
                    closest_customer_id)
                for customer in customers_to_insert:
                    containing_path.route.insert(close_customer_index + 1,
                                                 customer)
                    close_customer_index += 1
                children.append(new_paths)

        return children
Example #18
0
 def distance_swap(paths):
     children = []
     for i in range(15):
         new_paths = [copy.deepcopy(element) for element in paths]
         path_index = randint(0, len(paths) - 1)
         path = new_paths[path_index]
         # gets two random customers, if the first is farther then the second then swap
         customer_a = randint(0, len(path.route) - 1)
         customer_b = randint(customer_a, len(path.route) - 1)
         if Distances.get_distance(
                 0, path.route[customer_a].number) > Distances.get_distance(
                     0, path.route[customer_a].number):
             path.route[customer_a], path.route[customer_b] = path.route[
                 customer_b], path.route[customer_a]
         children.append(new_paths)
     return children
Example #19
0
    def get_next(source, customers, paths):

        min = float('inf')
        next = source
        all_paths = []
        for p in range(len(paths)):
            path = paths[p]
            for c in range(len(path)):
                all_paths.append(path[c])

        for i in range(len(customers)):
            if Distances.get_distance(
                    customers.index(source), i) < min and customers.index(
                        source) != i and customers[i] not in all_paths:
                next = customers[i]
                min = Distances.get_distance(customers.index(source), i)
        return next
Example #20
0
 def __init__(self,
              z0=0,
              z1=.3,
              z2=1.5,
              M200=1e15,
              c=5,
              Om=.25,
              Or=8.4e-5,
              Ol=.75,
              H0=70):
     self.H0 = H0 / 3.086e19  #convert to s^-1
     self.zlens = z1
     self.h = H0 / 100
     self.Ez = np.sqrt(Or * (1 + self.zlens)**4 + Om * (1 + self.zlens)**3 +
                       Ol)
     self.Hz = self.H0 * self.Ez
     G = 6.67e-11  # m^3  kg^-1 s^-2
     self.c = c  #concentration parameter
     self.rho0 = 3 * self.H0**2 / (8 * pi * G) / 1.989e30 / (
         3.24e-23)**3  # M_sun * Mpc^(-3)
     self.rhoz = 3 * self.Hz**2 / (8 * pi * G) / 1.989e30 / (
         3.24e-23)**3  # M_sun * Mpc^(-3)
     self.rhos = 200 / 3 * self.rhoz * self.c**3 / (np.log(1 + self.c) - c /
                                                    (1 + self.c))
     self.M200 = M200
     self.r200 = (self.M200 / (4 / 3 * pi * 200 * self.rhoz))**(1 / 3)  #Mpc
     self.rs = self.r200 / c  #Mpc
     self.M3d1 = (np.log(1 + self.r200 / self.rs) - self.r200 /
                  (self.r200 + self.rs)) / M200  #Msun ^-1
     self.rhoss = 1 / (4 * pi * self.rs**3) / self.M3d1
     self.d = Distances(z0=z0,
                        z1=z1,
                        z2=z2,
                        Om=.25,
                        Ol=.75,
                        Or=8.4e-5,
                        H0=70)
     self.kappas = self.rhos * self.rs / self.d.get_Sigmacr()
     self.thetas = self.rs / self.d.angular_diameter_distance(
         self.d.z0, self.d.z1)
def import_solution(problem, filename):
    with open(path + filename + ".txt") as f:
        customers = import_customers(problem + ".txt", False)
        Distances.calculate_matrix(customers)
        lines = f.readlines()

        ids = []
        for line in lines[5:]:
            ids.append(line.split()[3:])

    routes = []
    for line in ids:
        route = []
        for cust_number in line:
            route.append((customers[int(cust_number)-1]))
        routes.append(route)

    trucks = []
    for i in range(len(routes)):
        trucks.append(Truck(i, 0, 0, len(routes), Path(routes[i])))

    return State(trucks)
Example #22
0
    def fix_wait_time (paths):
        children = []
        for path in paths:
            customers_waited_at = path.get_excessive_wait_custs()
            for c in customers_waited_at:
                new_paths = copy.deepcopy(paths)
                closest = Distances.get_closest_customers(c)[randint(1, 3)]
                for p in new_paths:
                    if p.get_customer_index(closest) != -1:
                        p.insert_customer(closest, c.number, customers)
                children.append(new_paths)

        return children
Example #23
0
    def fix_group_unreasonable( paths ):
        """Suppose the distances in order are like [a]unreasonable[b]reasonable[c]reasonable[d]reasonable[e]unreasonable[f].
           Then move b, c, d, and e into a different path based on a near neighbor"""
        children = []
        threshold = max(Distances.matrix[0])/3.5
        path_number = 0
        for path in paths:
            # check depot to first customer
            if Distances.get_distance(0, path.route[0].number) > threshold:
                for j in range( 1, min( 15, len( path ) ) ): # max length of 14
                    if Distances.get_distance( path.route[j].number, path.route[j+1].number ) > threshold:
                        children += State.remove_and_insert_closer_as_group( 1, j, paths, path_number )
                
            # check all regular customers to e/o
            for i in range(0, len(path) - 1):
                if Distances.get_distance(path.route[i].number, path.route[i+1].number) > threshold:
                    for j in range( i + 1, min(i+14, len(path)) ): #max length of 14
                        if Distances.get_distance( path.route[j].number, path.route[j+1 if j < len(path)- 1 else 0].number ) > threshold:
                            children += State.remove_and_insert_closer_as_group( i+1, j, paths, path_number)

            path_number += 1
        return children
Example #24
0
    def fix_wait_time(paths):
        children = []
        for path in paths:
            customers_waited_at = path.get_excessive_wait_custs()
            for c in customers_waited_at:
                new_paths = copy.deepcopy(paths)
                closest = Distances.get_closest_customers(c)[randint(1, 3)]
                for p in new_paths:
                    if p.get_customer_index(closest) != -1:
                        p.insert_customer(closest, c.number, customers)
                children.append(new_paths)

        return children
def import_solution(problem, filename):
    with open(path + filename + ".txt") as f:
        customers = import_customers(problem + ".txt", False)
        Distances.calculate_matrix(customers)
        lines = f.readlines()

        ids = []
        for line in lines[5:]:
            ids.append(line.split()[3:])

    routes = []
    for line in ids:
        route = []
        for cust_number in line:
            route.append((customers[int(cust_number) - 1]))
        routes.append(route)

    trucks = []
    for i in range(len(routes)):
        trucks.append(Truck(i, 0, 0, len(routes), Path(routes[i])))

    return State(trucks)
Example #26
0
    def missed_customers(self):
        """Formerly isValid().  Returns whether the truck makes it on time to every customer by returning
        an array of the customers missed. If the path is valid, an empty array will be returned"""

        if len( self ) == 0:
            return []

        prev_customer = self.route[0]
        time = Distances.get_distance(prev_customer.number,0)

        missedCustomers = []

        # if truck arrives before customer is open, assume truck waits
        if time < prev_customer.open_time:
            time = prev_customer.open_time

        # if truck arrives late, add to missedCustomers
        if time > prev_customer.close_time:
            missedCustomers.append(prev_customer)

        time += prev_customer.service_time

        for c in self.route[1:]:
            time += Distances.get_distance(prev_customer.number, c.number)
            prev_customer = c

            # if truck arrives before customer is open, assume truck waits
            if time < c.open_time:
                time = c.open_time

            # if truck arrives late, add to missedCustomers
            if time > c.close_time:
                missedCustomers.append(c)

            time += c.service_time

        return missedCustomers
Example #27
0
    def fix_single_unreasonable( paths ):
        """If you travel an unreasonable distance at least to or from a customer,
            try moving it somewhere else closer???"""
        children = []
        threshold = max(Distances.matrix[0])/4.5

        path_number = 0
        for path in paths:
            # check depot to first customer
            if Distances.get_distance(0, path.route[0].number) > threshold or Distances.get_distance(path.route[0].number, path.route[1].number) > threshold:
                children += State.remove_and_insert_closer( 0, paths, path_number )
                
            # check all regular customers to e/o
            for i in range(0, len(path) - 2):
                if Distances.get_distance(path.route[i].number, path.route[i+1].number) > threshold or Distances.get_distance(path.route[i+1].number, path.route[i+2].number) > threshold:
                    children += State.remove_and_insert_closer( i+1, paths, path_number )

            # check last customer to depot
            if Distances.get_distance(path.route[-2].number, path.route[-1].number) > threshold or Distances.get_distance(path.route[-1].number, 0) > threshold:
                children += State.remove_and_insert_closer( -1, paths, path_number )

            path_number += 1

        return children
Example #28
0
 def __init__(self,
              z0=0,
              z1=.3,
              z2=1.5,
              M200=1e13,
              Mstar=10**11.5,
              c=5,
              Re=3,
              m=4,
              Om=.25,
              Or=8.4e-5,
              Ol=.75,
              H0=70,
              galaxy=True):
     self.z0 = 0
     self.z1 = z1
     self.z2 = z2
     self.d = Distances(z0=z0, z1=z1, z2=z2, Om=Om, Ol=Ol, Or=Or, H0=H0)
     self.lens = NFWlens(z0=z0,
                         z1=z1,
                         z2=z2,
                         M200=M200,
                         c=c,
                         Om=Om,
                         Or=Or,
                         Ol=Ol,
                         H0=H0)
     self.galaxy = Sersic(Mstar=Mstar, Re=Re, m=m)
     self.apply_galaxy = galaxy
     self.Da1 = self.d.angular_diameter_distance(
         self.z0, z1)  #ang distance to the lens
     self.Da2 = self.d.angular_diameter_distance(
         self.z0, z2)  #ang distance to the source
     self.thetas = self.lens.rs / self.Da1  #in radians
     self.Sigmacr = self.d.get_Sigmacr()
     self.kappas = self.lens.rhos * self.lens.rs / self.Sigmacr
Example #29
0
    def alternating_shuffle_within_path(paths):
        children = []

        for j in range(len(paths)):
            path = paths[j]
            temp_route = copy.deepcopy(path.route)
            new_route = []
            while(len(temp_route) > 0):
                cust = temp_route.pop(0)
                new_route.append(cust)
                temp_route = sorted(temp_route, key = lambda customer: Distances.get_distance( customer.number, cust.number ) )

            new_paths = copy.deepcopy(paths)
            new_paths[j] = Path(new_route)
            children.append(new_paths)

        return children
Example #30
0
    def get_next_random(source, customers, paths, numrandom):
        all_paths = []
        for p in range(len(paths)):
            path = paths[p]
            for c in range(len(path)):
                all_paths.append(path[c])
        
        closest = sorted(customers, key=lambda customer: Distances.get_distance(source.number, customer.number))
        closest_good = []

        for c in closest:
            if c in all_paths:
                pass
            else:
                closest_good.append(c)
        
        closest_few = closest_good[:numrandom]
        r = randint(0, len(closest_few)-1)
        return closest_few[r]
Example #31
0
    def get_next_random(source, customers, paths, numrandom):
        all_paths = []
        for p in range(len(paths)):
            path = paths[p]
            for c in range(len(path)):
                all_paths.append(path[c])

        closest = sorted(customers,
                         key=lambda customer: Distances.get_distance(
                             source.number, customer.number))
        closest_good = []

        for c in closest:
            if c in all_paths:
                pass
            else:
                closest_good.append(c)

        closest_few = closest_good[:numrandom]
        r = randint(0, len(closest_few) - 1)
        return closest_few[r]
Example #32
0
File: Cell.py Project: lorcanj/Maze
    def distances(self):
        # need to update this as linked is not currently being picked up as anything
        distances = Distances(self)
        frontier = [self]

        while any(frontier):
            new_frontier = []

            for cell in frontier:
                for linked in cell.links:
                    if distances.return_distance(
                            linked) is None and distances.return_distance(
                                cell) is not None:
                        distances.record_distance(
                            linked,
                            distances.return_distance(cell) + 1)
                        new_frontier.append(linked)
            frontier = new_frontier

        return distances
Example #33
0
    def remove_and_insert_closer_as_group( first_removal_index, last_removal_index, paths, interesting_path_index ):
        children = []

        for i in range(1, 8):
            new_paths = copy.deepcopy(paths)
            path = new_paths[interesting_path_index]
            route = path.route
            customers_to_insert = []
            for k in range(first_removal_index, last_removal_index + 1):
                # the indexes will shift beneath our feet, so always remove at the same place
                customers_to_insert.append( route.pop(first_removal_index) )

            # range starts at 1 because 0 refers to itself and that's stupid and bad
            closest_customer_id = Distances.get_closest_customers( customers_to_insert[0] )[i]
            containing_path = State.find_path_containing_customer( new_paths, closest_customer_id )
            if containing_path:
                close_customer_index = containing_path.get_customer_index( closest_customer_id )
                for customer in customers_to_insert:
                    containing_path.route.insert( close_customer_index + 1, customer )
                    close_customer_index += 1
                children.append( new_paths )

        return children
Example #34
0
    def remove_and_insert_closer( customer_index, paths, interesting_path_index ):
        children = []
        # find whoever is closest to it (should be four customers nearby-ish?)
        customer = paths[interesting_path_index].route[customer_index]
        closest_customers = Distances.get_closest_customers( customer )

        for customer_id in closest_customers[1:5]:
            # for each of those customer IDs, find the path where it is, and insert it
            # either before or after (50/50) the close customer
            new_paths = copy.deepcopy( paths )
            new_path = new_paths[interesting_path_index]
            customer = new_path.route.pop( customer_index )
            containing_path = State.find_path_containing_customer( new_paths, customer_id )

            if containing_path:
                close_customer_index = containing_path.get_customer_index( customer_id )
                if random.random() > 0.5:
                    containing_path.route.insert( close_customer_index + 1, customer )
                else:
                    containing_path.route.insert( close_customer_index, customer )
                children.append( new_paths )

        return children
Example #35
0
    def fix_single_unreasonable(paths):
        """If you travel an unreasonable distance at least to or from a customer,
            try moving it somewhere else closer???"""
        children = []
        threshold = max(Distances.matrix[0]) / 4.5

        path_number = 0
        for path in paths:
            # check depot to first customer
            if Distances.get_distance(0, path.route[0].number
                                      ) > threshold or Distances.get_distance(
                                          path.route[0].number,
                                          path.route[1].number) > threshold:
                children += State.remove_and_insert_closer(
                    0, paths, path_number)

            # check all regular customers to e/o
            for i in range(0, len(path) - 2):
                if Distances.get_distance(path.route[i].number, path.route[
                        i + 1].number) > threshold or Distances.get_distance(
                            path.route[i + 1].number,
                            path.route[i + 2].number) > threshold:
                    children += State.remove_and_insert_closer(
                        i + 1, paths, path_number)

            # check last customer to depot
            if Distances.get_distance(
                    path.route[-2].number, path.route[-1].
                    number) > threshold or Distances.get_distance(
                        path.route[-1].number, 0) > threshold:
                children += State.remove_and_insert_closer(
                    -1, paths, path_number)

            path_number += 1

        return children
Example #36
0
class NFWlens():
    """
    =======================================================
    Lens Parameters:
    =======================================================
    - z0: the redshift of the observer, default is 0
    - z1: the redshift of the lens
    - z2: the redshift of the source
    - M200: the mass of the DM halo
    - c: concentration parameter of the lens halo 
    =======================================================
    Cosmological parameters:
    =======================================================
    - Om: matter density parameter
    - Or: radiation density parameter
    - Ol: dark energy density parameter
    - H0: Hubble constant
    =======================================================
    """
    def __init__(self,
                 z0=0,
                 z1=.3,
                 z2=1.5,
                 M200=1e15,
                 c=5,
                 Om=.25,
                 Or=8.4e-5,
                 Ol=.75,
                 H0=70):
        self.H0 = H0 / 3.086e19  #convert to s^-1
        self.zlens = z1
        self.h = H0 / 100
        self.Ez = np.sqrt(Or * (1 + self.zlens)**4 + Om * (1 + self.zlens)**3 +
                          Ol)
        self.Hz = self.H0 * self.Ez
        G = 6.67e-11  # m^3  kg^-1 s^-2
        self.c = c  #concentration parameter
        self.rho0 = 3 * self.H0**2 / (8 * pi * G) / 1.989e30 / (
            3.24e-23)**3  # M_sun * Mpc^(-3)
        self.rhoz = 3 * self.Hz**2 / (8 * pi * G) / 1.989e30 / (
            3.24e-23)**3  # M_sun * Mpc^(-3)
        self.rhos = 200 / 3 * self.rhoz * self.c**3 / (np.log(1 + self.c) - c /
                                                       (1 + self.c))
        self.M200 = M200
        self.r200 = (self.M200 / (4 / 3 * pi * 200 * self.rhoz))**(1 / 3)  #Mpc
        self.rs = self.r200 / c  #Mpc
        self.M3d1 = (np.log(1 + self.r200 / self.rs) - self.r200 /
                     (self.r200 + self.rs)) / M200  #Msun ^-1
        self.rhoss = 1 / (4 * pi * self.rs**3) / self.M3d1
        self.d = Distances(z0=z0,
                           z1=z1,
                           z2=z2,
                           Om=.25,
                           Ol=.75,
                           Or=8.4e-5,
                           H0=70)
        self.kappas = self.rhos * self.rs / self.d.get_Sigmacr()
        self.thetas = self.rs / self.d.angular_diameter_distance(
            self.d.z0, self.d.z1)

    def gfunc(self, x):
        x = np.atleast_1d(x)
        g = x * .0
        arr = x[x < 1]
        g[x < 1] = np.log(
            arr / 2) + 1 / np.sqrt(1 - arr**2) * np.arccosh(1 / arr)
        arr = x[x == 1]
        g[x == 1] = 1 + np.log(0.5)
        arr = x[x > 1]
        g[x > 1] = np.log(
            arr / 2) + 1 / np.sqrt(arr**2 - 1) * np.arccos(1 / arr)
        return g

    def Ffunc(self, x):
        x = np.atleast_1d(x)
        F = x * .0
        c1 = x < 1
        c2 = x == 1
        c3 = x > 1
        F[c1] = 1 / (x[c1]**2 - 1) * (
            1 - 1 / np.sqrt(1 - x[c1]**2) * np.arccosh(1 / x[c1]))
        F[c2] = 1 / 3.
        F[c3] = 1 / (x[c3]**2 - 1) * (
            1 - 1 / np.sqrt(x[c3]**2 - 1) * np.arccos(1 / x[c3]))
        return F

    def hfunc(self, x):
        x = np.atleast_1d(x)
        h = x * .0
        arr = x[x < 1]
        h[x < 1] = np.log(arr / 2)**2 - np.arccosh(1 / arr)**2
        arr = x[x >= 1]
        h[x >= 1] = np.log(arr / 2)**2 + np.arccos(1 / arr)**2
        return h

    def rho(self, r):
        return 1. / (r / self.rs) / (1 + r / self.rs)**2 * self.rhos

    def M3d(self, r):
        return (np.log(1 + r / self.rs) - r / (r + self.rs)) / self.M3d1

    def Sigma(self, r):
        x = r / self.rs
        return 2 * self.rhos * self.rs * self.Ffunc(x)

    def M2d(self, r):
        return self.gfunc(r / self.rs) / self.M3d1

    def meanSigma(self, x):
        return 4 * self.rhos * self.rs * self.gfunc(x) / x**2

    def Phi(self, x):
        return 2 * self.kappas * self.thetas**2 * hfunc(x)
Example #37
0
 def distance_to_previous(self, customer):
     index = self.route.index(customer) - 1
     if index >= 0:
         return Distances.get_distance(customer.number, self.route[index].number)
     else:
         return Distances.get_distance(customer.number, 0)
Example #38
0
 def distance_to_next(self, customer):
     index = self.route.index(customer) + 1
     if index < len(self.route):
         return Distances.get_distance(customer.number, self.route[index].number)
     else:
         return Distances.get_distance(customer.number, 0)
Example #39
0
    def combined_stats(self, cargo):
        num_waits = 0
        num_unreasonable_distances = 0
        num_cargo_missed = 0
        missed_customers = []
        distance_threshold = max(Distances.matrix[0]) / 3.5
        wait_time = 0
        total_wait_time = 0
        cargo_index = 0
        cargo_used = 0

        if len(self) == 0:
            return 0

        prev_customer = self.route[0]
        d = Distances.get_distance(prev_customer.number, 0)
        time = d
        distance = d

        if time < prev_customer.open_time:
            wait_time = prev_customer.open_time - time
            total_wait_time += wait_time
            time = prev_customer.open_time
        if wait_time > 20:  # arbitrary, change if necessary
            num_waits += 1

        if time > prev_customer.close_time:
            missed_customers.append(prev_customer)

        if distance > distance_threshold:
            num_unreasonable_distances += 1


        time += prev_customer.service_time

        cargo_used += self.route[0].demand
        cargo_index += 1

        for c in self.route[1:]:
            cargo_used += c.demand
            if cargo_used > cargo:
                num_cargo_missed = len(self.route) - cargo_index
            cargo_index += 1
            d = Distances.get_distance(prev_customer.number, c.number)
            if (d > distance_threshold):
                num_unreasonable_distances += 1
            time += d
            prev_customer = c

            if time < c.open_time:
                wait_time = prev_customer.open_time - time
                total_wait_time += prev_customer.open_time - time
                time = c.open_time
            if time > c.close_time:
                missed_customers.append(c)
            if wait_time > 20:  # arbitrary, change if necessary
                num_waits += 1

            time += c.service_time

        num_time_missed = len(missed_customers)

        return { "Missed Time"           : num_time_missed,
                 "Missed Cargo"          : num_cargo_missed,
                 "Wait Time"             : total_wait_time,
                 "Excessive Waits"       : num_waits,
                 "Unreasonable Distances": num_unreasonable_distances }
Example #40
0
    def line_segment_insertion(paths, n_children, reasonable_distance):
        children = []
        max_radius_to_keep = max(Distances().matrix[0]) / 8

        for k in range(n_children):
            new_paths = copy.deepcopy(paths)

            # pick a path to look at
            path_a_index = randrange(len(paths))
            path_a = new_paths[path_a_index]
            # pick some customer on that path
            customer_a_index = randrange(len(path_a.route) - 1)
            customer_a = path_a.route[customer_a_index]
            x0, y0 = customer_a.x, customer_a.y

            second_break = False

            # go through every line segment on all paths and check if this one is close to that one
            for path in new_paths:
                points = [[0, 0]] + [[c.x, c.y] for c in path.route] + [[0, 0]]

                for j in range(0, len(points) - 1):
                    # x0, y0 = the point
                    # x1, y1 = the line end
                    # x2, y2 = the other line end
                    # px, py = the previous point in the path
                    # nx, ny = the next point in the path
                    x1, y1 = points[j][0], points[j][1]
                    x2, y2 = points[j + 1][0], points[j + 1][1]
                    px, py = path_a.route[customer_a_index -
                                          1].x, path_a.route[customer_a_index -
                                                             1].y
                    nx, ny = path_a.route[customer_a_index +
                                          1].x, path_a.route[customer_a_index +
                                                             1].y
                    try:
                        distance = abs((y2 - y1) * x0 + (x1 - x2) * y0 +
                                       (x1 * y2 - x2 * y1)) / (
                                           (((y2 - y1)**2) +
                                            ((x1 - x2)**2))**0.5)
                    except:
                        distance = 0  # divide by 0 == it's on the line == distance is 0
                    # make a chance if (a) the segment is close, (b) the next point is far, (c) the prior point is far
                    if distance <= reasonable_distance or (
                        (px - x0)**2 +
                        (py - y0)**2)**0.5 > max_radius_to_keep or (
                            (nx - x0)**2 +
                            (ny - y0)**2)**0.5 > max_radius_to_keep:
                        # hey, it's close to the line segment! remove the customer
                        # from it's original path and insert it after the customer at index j+1
                        path_a.route.remove(customer_a)
                        path.route.insert(j + 1, customer_a)

                        children.append(new_paths)

                        # you're finished for this child; kill both of these for loops (allow third to continue)
                        second_break = True
                        break
                if second_break:
                    break

        return children
Example #41
0
data = np.fromfile('./8560.bin').reshape(3,-1)
dat = {}
dat['z_cgal']=data[0,:]
dat['lmstellar']=data[1,:]
dat['lmhalo']=data[2,:]

# Read the number density of source galaxies 

Nct_data = np.fromfile('Ncounts.bin')
Num = 59
redshift = Nct_data.reshape(Num,2)[:,0]
Ncounts = Nct_data.reshape(Num,2)[:,1]
dtheta = np.sqrt(5e3)/180*pi
dA = np.zeros(len(redshift))
for i in range(len(redshift)):
    d  = Distances()
    dA[i] = d.angular_diameter_distance(0,redshift[i])
Area = (dA*dtheta)**2
dNdz = Ncounts*Area
mask = dNdz != 0

# Compute for each lens, the strong lensing event rate
# total area of the sky coverage is 5000 deg^2
tot_area = 5000*(3600)**2 # arcsec^2

def main(size, rank):
    Ntot = np.zeros(len(dat['z_cgal']))
    sample_i = np.array_split(np.arange(len(dat['z_cgal'])),size)[rank]
    #print(rank, len(sample_i))
    for i in sample_i:
        if rank == 0:
Example #42
0
class lens_stat_gnfw():
    def __init__(self,
                 z0=0,
                 z1=.3,
                 z2=1.5,
                 M200=1e13,
                 Mstar=10**11.5,
                 c=5,
                 Re=3,
                 m=4,
                 Om=.25,
                 Or=8.4e-5,
                 Ol=.75,
                 H0=70,
                 ratio=1,
                 cratio=1,
                 alpha=1,
                 source_mag=25.,
                 galaxy=True,
                 get_rho=False):
        self.statt = lens_stat1D(z0=z0,
                                 z1=z1,
                                 z2=z2,
                                 M200=M200,
                                 Mstar=Mstar * ratio,
                                 c=c * cratio,
                                 Re=Re,
                                 m=m,
                                 Om=Om,
                                 Or=Or,
                                 Ol=Ol,
                                 H0=H0,
                                 galaxy=galaxy)
        self.alpha = alpha  # power law index of the gnfw profile
        self.z0 = 0
        self.z1 = z1
        self.z2 = z2
        self.mag_unlensed = source_mag
        self.H0 = H0 / 3.086e19  #convert to s^-1
        self.h = H0 / 100
        self.d = Distances(z0=z0, z1=z1, z2=z2, Om=Om, Ol=Ol, Or=Or, H0=H0)
        self.Ez = np.sqrt(Or * (1 + z1)**4 + Om * (1 + z1)**3 + Ol)
        self.Hz = self.H0 * self.Ez
        G = 6.67e-11  # m^3  kg^-1 s^-2
        self.c = c * cratio  #concentration parameter
        self.rhoz = 3 * self.Hz**2 / (8 * pi * G) / 1.989e30 / (
            3.24e-23)**3  # M_sun * Mpc^(-3)
        self.rhos = 200 / 3 * self.rhoz * (3 - alpha) * c**(alpha) / hyp2f1(
            3 - alpha, 3 - alpha, 4 - alpha, -c)
        self.M200 = M200 * ratio
        self.r200 = (self.M200 / (4 / 3 * pi * 200 * self.rhoz))**(1 / 3)  #Mpc
        self.rs = self.r200 / c  #Mpc
        self.galaxy = Sersic(Mstar=Mstar, Re=Re, m=m)
        self.apply_galaxy = galaxy
        self.Da1 = self.d.angular_diameter_distance(
            self.z0, z1)  #ang distance to the lens
        self.Da2 = self.d.angular_diameter_distance(
            self.z0, z2)  #ang distance to the source
        self.thetas = self.rs / self.Da1  #in radians
        self.Sigmacr = self.d.get_Sigmacr()
        self.kappas = self.rhos * self.rs / self.Sigmacr
        self.b = 4 * self.rhos * self.rs / self.Sigmacr
        if get_rho == False:
            self.xval_min, self.caus1, self.beta_mag = self.get_xval_min()

    def rho(self, r):
        alpha = self.alpha
        return self.rhos / ((r / self.rs)**(alpha) *
                            (1 + (r / self.rs))**(3 - alpha))

    def Sigma(self, r):
        x = r / self.rs
        return 2 * self.rhos * self.rs * x**(1 - self.alpha) * quad_vec(
            lambda t: np.sin(t) *
            (np.sin(t) + x)**(self.alpha - 3), 0, np.pi / 2)[0]

    def M2d(self, r):
        return 2 * np.pi * quad_vec(lambda x: x * self.Sigma(x), 0, r)[0]

    def F(self, x):
        x = np.atleast_1d(x)
        F = x * 0.
        mask1 = x < 1
        F[mask1] = 1. / np.sqrt(1 - x[mask1]**2) * np.arctanh(
            np.sqrt(1 - x[mask1]**2))
        mask2 = x > 1
        F[mask2] = 1. / np.sqrt(x[mask2]**2 - 1) * np.arctan(
            np.sqrt(x[mask2]**2 - 1))
        mask3 = x == 1
        F[mask3] = 1
        return F

    def dF(self, x):
        return (1 - x**2 * self.F(x)) / (x * (x**2 - 1))

    def f(self, x):
        alpha = self.alpha

        def f0(x):
            x = np.atleast_1d(x)
            #f = 1./2*(1+x**2*(2-3*self.F(x)))/(x**2-1)**2
            f = x * 0.
            mask1 = x < 1
            f[mask1] = x[mask1] / (2 * (1 - x[mask1]**2)**2) * (
                1 + 2 * x[mask1]**2 -
                6 * x[mask1]**2 / np.sqrt(1 - x[mask1]**2) *
                np.arctanh(np.sqrt((1 - x[mask1]) / (1 + x[mask1]))))
            mask2 = x > 1
            f[mask2] = x[mask2] / (2 * (x[mask2]**2 - 1)**2) * (
                1 + 2 * x[mask2]**2 -
                6 * x[mask2]**2 / np.sqrt(x[mask2]**2 - 1) *
                np.arctan(np.sqrt((x[mask2] - 1) / (1 + x[mask2]))))
            return f

        def f1(x):
            x = np.atleast_1d(x)
            #f = (1-self.F(x))/(x**2-1)
            f = x * 0.
            mask1 = x < 1
            f[mask1] = 1. / (1 - x[mask1]**2) * (
                -1 + 2 / np.sqrt(1 - x[mask1]**2) *
                np.arctanh(np.sqrt((1 - x[mask1]) / (1 + x[mask1]))))
            mask2 = x > 1
            f[mask2] = 1. / (x[mask2]**2 - 1) * (
                1 - 2 / np.sqrt(x[mask2]**2 - 1) *
                np.arctan(np.sqrt((x[mask2] - 1) / (x[mask2] + 1))))
            return f

        def f2(x):
            x = np.atleast_1d(x)
            #f = 1./2*(pi/x-2*self.F(x))
            f = x * 0.
            mask1 = x < 1
            f[mask1] = 1. / x[mask1] * (pi / 2 -
                                        x[mask1] / np.sqrt(1 - x[mask1]**2) *
                                        np.arctanh(1 - x[mask1]**2))
            mask2 = x > 1
            f[mask2] = 1. / x[mask2] * (pi / 2 -
                                        x[mask2] / np.sqrt(x[mask2]**2 - 1) *
                                        np.arctan(x[mask2]**2 - 1))
            return f

        """    
        if alpha == 0:
            return f0(x)
        elif  alpha  == 1:
            return f1(x)
        elif alpha == 2:
            return f2(x)
        
        else:
        """
        x = np.atleast_1d(x)
        return x**(1 - alpha) * (
            (1 + x)**(alpha - 3) + (3 - alpha) *
            quad_vec(lambda y: (y + x)**(alpha - 4) *
                     (1 - np.sqrt(1 - y**2)), 0, 1)[0])

        #return np.array([x[i]**(1-alpha)*((1+x[i])**(alpha-3)+(3-alpha)*quad(lambda y:(y+x[i])**(alpha-4)*(1-np.sqrt(1-y**2)),0,1)[0]) for i in range(len(x))])

    def g(self, x):
        alpha = self.alpha

        def g0(x):
            x = np.atleast_1d(x)
            #g  =  1./(2*x)*(2*np.log(x/2)+(x**2+(2-3*x**2)*self.F(x))/(1-x**2))
            g = x * 0.
            mask1 = x < 1
            g[mask1] = (2 - 3 * x[mask1]**2) / (x[mask1] * (1 - x[mask1]**2)**(
                3 / 2)) * np.arctanh(np.sqrt(
                    (1 - x[mask1]) /
                    (1 + x[mask1]))) + x[mask1] / (2 *
                                                   (1 - x[mask1]**2)) + np.log(
                                                       x[mask1] / 2) / x[mask1]
            mask2 = x > 1
            g[mask2] = -(2 - 3 * x[mask2]**2) / (
                x[mask2] * (x[mask2]**2 - 1)**
                (3 / 2)) * np.arctan(np.sqrt(
                    (x[mask2] - 1) /
                    (1 + x[mask2]))) - x[mask2] / (2 *
                                                   (x[mask2]**2 - 1)) + np.log(
                                                       x[mask2] / 2) / x[mask2]
            return g

        def g1(x):
            x = np.atleast_1d(x)
            #g = (np.log(x/2)+self.F(x))/x
            g = x * 0.
            mask1 = x < 1
            g[mask1] = 2 / (x[mask1] * np.sqrt(1 - x[mask1]**2)) * np.arctanh(
                np.sqrt((1 - x[mask1]) /
                        (1 + x[mask1]))) + np.log(x[mask1] / 2) / x[mask1]
            mask2 = x > 1
            g[mask2] = 2 / (x[mask2] * np.sqrt(x[mask2]**2 - 1)) * np.arctan(
                np.sqrt((x[mask2] - 1) /
                        (1 + x[mask2]))) + np.log(x[mask2] / 2) / x[mask2]
            return g

        def g2(x):
            x = np.atleast_1d(x)
            #g = pi/2+np.log(x/2)/x+(1-x**2)/x*self.F(x)
            g = x * 0.
            mask1 = x < 1
            g[mask1] = np.sqrt(1 - x[mask1]**2) / x[mask1] * np.arctanh(
                np.sqrt(1 - x[mask1]**2)) + np.log(
                    x[mask1] / 2) / x[mask1] + pi / 2
            mask2 = x > 1
            g[mask2] = -np.sqrt(x[mask2]**2 - 1) / x[mask2] * np.arctan(
                np.sqrt(x[mask2]**2 - 1)) + np.log(
                    x[mask2] / 2) / x[mask2] + pi / 2
            return g

        def hypF(a, b, c, z):
            return hyp2f1(a, b, c, z)

        """
        if alpha == 0:
            return g0(x)
        elif alpha  == 1:
            return g1(x)
        elif alpha == 2:
            return g2(x)
        
        else:
        """
        x = np.atleast_1d(x)
        return x**(2 - alpha) * (hypF(3 - alpha, 3 - alpha, 4 - alpha, -x) /
                                 (3 - alpha) + quad_vec(
                                     lambda y: (y + x)**(alpha - 3) *
                                     (1 - np.sqrt(1 - y**2)) / y, 0, 1)[0])
        #return np.array([x[i]**(2-alpha)*(hypF(3-alpha,3-alpha,4-alpha,-x[i])/(3-alpha)+quad(lambda y:(y+x[i])**(alpha-3)*(1-np.sqrt(1-y**2))/y,0,1)[0]) for i in range(len(x))])

    def alpha_(self, x):
        r = x * self.rs
        alpha_galaxy = self.galaxy.M2d(r) / (
            pi * r**2) / self.Sigmacr * x * self.apply_galaxy
        return self.b * self.g(x) + alpha_galaxy

    def kappa(self, x):
        r = x * self.rs
        kappa_galaxy = self.galaxy.Sigma(r) / self.Sigmacr * self.apply_galaxy
        return self.b * self.f(x) / 2 + kappa_galaxy

    def gamma(self, x):
        r = x * self.rs
        gamma_galaxy = (self.galaxy.M2d(r) / (pi * r**2) - self.galaxy.Sigma(r)
                        ) / self.Sigmacr * self.apply_galaxy
        return self.b * self.g(x) / x - self.b * self.f(x) / 2 + gamma_galaxy

    def detA(self, x):
        x = np.atleast_1d(x)
        detA = x * 0.
        mask1 = x > 0
        detA[mask1] = (1 - self.kappa(x[mask1]))**2 - self.gamma(x[mask1])**2
        mask2 = x <= 0
        detA[mask2] = (1 - self.kappa(-x[mask2]))**2 - self.gamma(-x[mask2])**2
        return detA

    def beta(self, x):
        x = np.atleast_1d(x)
        beta = x * 0.
        mask1 = x > 0
        beta[mask1] = x[mask1] - self.alpha_(x[mask1])
        mask2 = x < 0
        beta[mask2] = x[mask2] + self.alpha_(-x[mask2])
        return beta

    def get_xval_min(self, tol=26.3):
        #specifying the ranges of theta, rt2 is the location of the tangential critical curve
        xmin, xmax = -1, 1
        xval = np.linspace(xmin, xmax, 10000)
        #xval = np.concatenate((-xval[::-1],xval),axis=None)
        thetas = xval * self.thetas * 206265
        betas = self.beta(xval) * self.thetas * 206265
        #check if singularity is in range(0,2*rt2)
        ind = np.argmin(betas[xval > 0])
        xval_min = xval[xval > 0][ind]
        caus1 = betas[xval > 0][ind]
        #xval = np.linspace(xval_min*1.1,10,10000)
        #thetas = xval*self.thetas*206265
        #betas = self.beta(xval)*self.thetas*206265
        msk = (xval > xval_min * 1.1) * (betas < 0)
        mag = np.abs(1 / self.detA(xval[msk]))
        #mag = np.concatenate(np.abs([1/self.stat.detA(xval[msk][i]) for i in range(len(xval[msk]))]),axis=None)
        app_m = self.get_lensed_mag(mag)
        mg_msk = app_m < tol
        #print(xval[msk][mg_msk].min(),xval[msk][mg_msk].max())
        """
        plt.plot(betas[msk][mg_msk],app_m[mg_msk])
        plt.axhline(y=0,ls='--',color='k')
        plt.xlabel(r'$\beta$',fontsize=15)
        plt.ylabel(r'$apparent \ magnitude$',fontsize=15)
        plt.show()
        """
        beta_mag = betas[msk][mg_msk][0]

        return xval_min, caus1, beta_mag

    def get_lensed_mag(self, m):
        return self.mag_unlensed - 2.5 * np.log10(m)
Example #43
0
 def __init__(self,
              z0=0,
              z1=.3,
              z2=1.5,
              M200=1e13,
              Mstar=10**11.5,
              c=5,
              Re=3,
              m=4,
              Om=.25,
              Or=8.4e-5,
              Ol=.75,
              H0=70,
              ratio=1,
              cratio=1,
              alpha=1,
              source_mag=25.,
              galaxy=True,
              get_rho=False):
     self.statt = lens_stat1D(z0=z0,
                              z1=z1,
                              z2=z2,
                              M200=M200,
                              Mstar=Mstar * ratio,
                              c=c * cratio,
                              Re=Re,
                              m=m,
                              Om=Om,
                              Or=Or,
                              Ol=Ol,
                              H0=H0,
                              galaxy=galaxy)
     self.alpha = alpha  # power law index of the gnfw profile
     self.z0 = 0
     self.z1 = z1
     self.z2 = z2
     self.mag_unlensed = source_mag
     self.H0 = H0 / 3.086e19  #convert to s^-1
     self.h = H0 / 100
     self.d = Distances(z0=z0, z1=z1, z2=z2, Om=Om, Ol=Ol, Or=Or, H0=H0)
     self.Ez = np.sqrt(Or * (1 + z1)**4 + Om * (1 + z1)**3 + Ol)
     self.Hz = self.H0 * self.Ez
     G = 6.67e-11  # m^3  kg^-1 s^-2
     self.c = c * cratio  #concentration parameter
     self.rhoz = 3 * self.Hz**2 / (8 * pi * G) / 1.989e30 / (
         3.24e-23)**3  # M_sun * Mpc^(-3)
     self.rhos = 200 / 3 * self.rhoz * (3 - alpha) * c**(alpha) / hyp2f1(
         3 - alpha, 3 - alpha, 4 - alpha, -c)
     self.M200 = M200 * ratio
     self.r200 = (self.M200 / (4 / 3 * pi * 200 * self.rhoz))**(1 / 3)  #Mpc
     self.rs = self.r200 / c  #Mpc
     self.galaxy = Sersic(Mstar=Mstar, Re=Re, m=m)
     self.apply_galaxy = galaxy
     self.Da1 = self.d.angular_diameter_distance(
         self.z0, z1)  #ang distance to the lens
     self.Da2 = self.d.angular_diameter_distance(
         self.z0, z2)  #ang distance to the source
     self.thetas = self.rs / self.Da1  #in radians
     self.Sigmacr = self.d.get_Sigmacr()
     self.kappas = self.rhos * self.rs / self.Sigmacr
     self.b = 4 * self.rhos * self.rs / self.Sigmacr
     if get_rho == False:
         self.xval_min, self.caus1, self.beta_mag = self.get_xval_min()
 def get_start_end_distance(self):
     return Distances.calculate_two_point_distance(self.get_start_lat(),
                                                   self.get_start_lon(),
                                                   self.get_end_lat(),
                                                   self.get_end_lon())