pietrod21

max_influence_parameters_on_linear_ramp

Mar 27th, 2014
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.53 KB | None | 0 0
  1. # QUIZ
  2. #
  3. # For this program we introduce Python dictionaries and use them
  4. # for sensitivity analysis. We describe the dictionaries we use
  5. # below and give some example uses for them.
  6. # The goal of this quiz is to find which parameter is the most
  7. # critical for the total harvest amount.
  8. # You will need to leave the dictionary key of that parameter in
  9. # a variable called most_critical_parameter.
  10.  
  11. import math
  12. from udacityplots import *
  13.  
  14. # base_value is a Python dictionary.
  15. base_values = {'initial_value': 2e5, # tons
  16.                'maximum_growth_rate': 0.5, # 1 / year
  17.                'carrying_capacity': 2e6, # tons
  18.                'maximum_harvest_rate': 0.8 * 2.5e5, # tons / year
  19.                'ramp_start': 1.5, # years
  20.                'ramp_end': 3.5 # years
  21.               }
  22.  
  23. # Python dictionaries behave similarly to Python lists,
  24. # or numpy arrays, but instead of accessing values via a numeric index,
  25. # for example x[0] to access the first element in the x array, we use
  26. # string indices. For example, if we type:
  27. #
  28. # x = base_value['initial_value']
  29. #
  30. # x will be set to 2e5. This is called a key-value store, where the name,
  31. # or string, is the key, and the value associated with that key can be
  32. # anything you like.
  33. # Note: Don't try to grab a key that doesn't exist from a dictionary, for
  34. # example:
  35. #
  36. # x = base_value['does_not_exist']
  37. #
  38. # will cause your code to exit with an error, since Python doesn't know
  39. # what to do here. There is a way around it, by using a dictionary's
  40. # built-in get(key) function, but you shouldn't have to worry about that
  41. # here.
  42. # To set the value associated with a key to something else, you can
  43. # access it similarly, for example:
  44. #
  45. # base_value['initial_value'] = 2e10
  46. #
  47. # Will change the associated value from 2e5 to 2e10. This is also how you
  48. # create new key-value pairs in a dictionary, for example:
  49. #
  50. # base_value['does_not_exist'] = "now it does"
  51. #
  52. # Will create the key 'does_not_exist' and associate the string
  53. # "now it does" with it. This means that you do not have to create
  54. # all the key-value pairs up front if you don't want to. However,
  55. # it's generally good programming practice to do so for the sake of clarity.
  56.  
  57. uncertainties = {'initial_value': 5e4, # tons
  58.                  'maximum_growth_rate': 0.1, # 1 / year
  59.                  'carrying_capacity': 9e5, # tons
  60.                  'maximum_harvest_rate': 3e4, # tons / year
  61.                  'ramp_start': 0.2, # years
  62.                  'ramp_end': 0.2 # years
  63.                 }
  64.  
  65. colors = {'initial_value': 'r', #red
  66.           'maximum_growth_rate': 'm', #magenta (viola)
  67.           'carrying_capacity': 'b', #blue
  68.           'maximum_harvest_rate': 'c', #cyano (azzurro)
  69.           'ramp_start': 'g', #green
  70.           'ramp_end': 'y' #yellow
  71.          }
  72.  
  73. # This is used to keep track of the data that we want to plot.
  74. data = []
  75.  
  76. end_time = 10. # years
  77. h = 0.2 # years
  78. num_steps = int(end_time / h)
  79. times = h * numpy.array(range(num_steps + 1))
  80.  
  81. fish = numpy.zeros(num_steps + 1) # tons
  82.  
  83. # evaluate numerically evaluates the differential equation for harvesting fish,
  84. # calculates the total amount of fish harvested, and returns that value.
  85. # The variable called values refers to a dictionary of the type introduced above.
  86. def evaluate(values, color):
  87.     # Set the initial number of fish to the 'initial_value' of the dictionary passed in.
  88.     fish[0] = values['initial_value']
  89.  
  90.     # Start the total number of fish harvested out at 0, and specify
  91.     # that the fish are not yet extinct.
  92.     total_harvest = 0.
  93.     is_extinct = False
  94.  
  95.     # For each time step, harvest the fish based on the given factors
  96.     for step in range(num_steps):
  97.  
  98.         # Set the time passed during this step, and set the initial
  99.         # harvest factor to 0.
  100.         time = h * step # years
  101.         harvest_factor = 0.
  102.  
  103.         # If we have finished ramping up harvesting, then set the harvest rate to the
  104.         # maximum harvest rate. Otherwise, we set the harvest rate to be a percentage of
  105.         # the maximum harvest rate based on how far into the ramp up we are.
  106.         if time > values['ramp_end']:
  107.             harvest_factor = 1.
  108.         elif time > values['ramp_start']:
  109.             harvest_factor = (time - values['ramp_start']) / (values['ramp_end'] - values['ramp_start'])
  110.         harvest_rate = harvest_factor * values['maximum_harvest_rate']
  111.  
  112.         # If the fish are extinct, then we're not going to harvest anymore fish! Else, if they aren't extinct
  113.         # yet, the current harvest is going to be the harvest rate we've set times the time step.
  114.         # We set the total number of fish for the next step based on how many we harvest this step, and what
  115.         # our carrying capacity is.
  116.         if is_extinct:
  117.             current_harvest = 0.
  118.             fish_next_step = 0.
  119.         else:
  120.             current_harvest = h * harvest_rate
  121.             fish_next_step = fish[step] + h * values['maximum_growth_rate'] * (1. - fish[step] / values['carrying_capacity']) * fish[step] - current_harvest
  122.             if fish_next_step <= 0.:
  123.                 is_extinct = True
  124.                 current_harvest = fish[step]
  125.                 fish_next_step = 0.
  126.         fish[step + 1] = fish_next_step
  127.  
  128.         total_harvest += current_harvest
  129.  
  130.     # Once we've computed the number of fish for each time step, keep track
  131.     # of the data, so we can plot it.
  132.     data.append(([time for time in times], [f for f in fish], color))
  133.  
  134.     return total_harvest
  135.  
  136. # sensitivity_analysis calculates what the most critical
  137. # parameter of the differential equation is, then returns
  138. # the name of that parameter.
  139. def sensitivity_analysis():
  140.     most_critical_parameter = ''
  141.     distance=0
  142.     max_distance=0
  143.     #### Modify the code below to find the most critical parameter.
  144.     #### You may need to add additional code to this rather than
  145.     #### just modifying existing code.
  146.  
  147.     # For each key in the dictionary base_values, fluctuate the
  148.     # associated value based on the same key in the uncertainties
  149.     # dictionary to determine which value changes the outcome
  150.     # the most.
  151.     for key in base_values.keys():
  152.         # Give each key a specific color so we can better
  153.         # tell them apart in the plot.
  154.         color = colors[key]    
  155.  
  156.         # Create a copy of the base_values dictionary and
  157.         # decrease the value for the current key by the
  158.         # given uncertainty. Then, evaluate the
  159.         # differential equation for the given parameters.
  160.         one_value_down = base_values.copy()
  161.         one_value_down[key] -= uncertainties[key]
  162.  
  163.         # The same as before, but we increase the value
  164.         # for the given key, rather then decrease.
  165.         one_value_up = base_values.copy()
  166.         one_value_up[key] += uncertainties[key]
  167.  
  168.         distance=math.fabs((evaluate(one_value_up, color)-evaluate(one_value_down, color)))/evaluate(base_values, color)
  169.         # il fabs qui non servirebbe perche up e sempre maggiore di down, e manco compararlo, dividerlo, per evaluate di base value perche e fisso...
  170.         if distance> max_distance:
  171.             max_distance=distance
  172.             most_critical_parameter=key
  173.    
  174.     #### End code to modify.
  175.  
  176.     return most_critical_parameter
  177.  
  178. print sensitivity_analysis()
  179.  
  180. @show_plot
  181. def plot_me():
  182.     for (times, fish, color) in data:
  183.         matplotlib.pyplot.plot(times, fish, c = color)
  184.     axes = matplotlib.pyplot.gca()
  185.     axes.set_xlabel('Time in years')
  186.     axes.set_ylabel('Amount of fish in tons')
  187. plot_me()
Advertisement
Add Comment
Please, Sign In to add comment