Python Forum
Help improve code efficiency
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help improve code efficiency
#7
(Feb-19-2019, 08:04 PM)ichabod801 Wrote: import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import colors
import random
import os
import collections
 
 
print("=== Cellular Automata for Radioactive Waste Disposal ===")
 
# ======= User Inputs
 
L = 20.0 # km
 
numCells = 100 # This needs to remain the same for!
 
totalTime = (40 * 12) # number of time steps (in months)
 
print_every_n_steps = 480 # don't make this too small!
print_time_every = 200
 
source_x = 0.2 # x - coordinate location of source of radio active waste
source_y = 0.2 # y - coordinate location of course  of radio active waste
 
city_x = 12
city_y = 16
cell_city_x = int(numCells * (city_x / L))
cell_city_y = int(numCells * (city_y / L))
 
verbosity = 0
 
#Permeability Maximum Variable
 
# *** Model Developement 3 ***
Kmax = 3.5#Permeability Maximum Variable
#K = np.loadtxt("perm.txt", dtype='f', delimiter=' ')
Ktmp = np.loadtxt("perm.txt")
 
K=Ktmp.astype(np.float)
 
cmap = mpl.cm.jet
norm = mpl.colors.Normalize(vmin=0, vmax = 1)
fig, ax = plt.subplots()
ax.imshow(K, cmap=cmap, norm=norm)
 
ax.grid(which='major', axis='both', linestyle='-', color='k', linewidth=2)
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
results_dir = os.path.join(os.getcwd(),'solutions/')
if not os.path.isdir(results_dir):
  os.makedirs(results_dir)
 
plt.savefig(results_dir + "perm.png")
 
cell_source_x = int(numCells * (source_x / L))
cell_source_y = int(numCells * (source_y / L))
count = 0
 
for n in range(0, 20):
  C = np.zeros((numCells    ,numCells ))
 
  C[cell_source_x,  cell_source_y] = 1; #1 is contaminated
  contaminated = set()
  contaminated.add((cell_source_x, cell_source_y))
  iteration = str(n+1)
  print("Iteration:" + iteration)
  #C[cell_city_x][cell_city_y] = 1 #will show city
 
  for t in range(0,totalTime+1):
 
    if (t % print_time_every == 0) :
      print("Time = " + str(t))
 
    Cnew = np.zeros((numCells   ,numCells ))
 
    neighbors = collections.defaultdict(int)
    for source_x, source_y in contaminated:
      for off_x, off_y in [(0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1)]:
        neighbor_x, neighbor_y = source_x + off_x, source_y + off_y
        if 0 <= neighbor_x < numCells and 0 <= neighbor_y <= numCells:
          neighbors[(neighbor_x, neighbor_y)] += 1
 
    for coordinates, count in neighbors.items():
      possible_x, possible_y = coordinates
      # *** Model Developement 2 ***
      p = (count/8)*((K[possible_x][possible_y])/Kmax) #gives probability
      n = random.uniform(0,1)
      if p>n:
        Cnew[possible_x][possible_y]=1#make this =p to give range of intensity?
        contaminated.add(coordinates)
 
 
 
    C = Cnew; # Set new contamination Matrix to old C.
    #this is how it goes through, adding on each time
    # Plot grid and save to file
 
    if (t % print_every_n_steps == 0) :
      cmap = mpl.cm.jet
      norm = mpl.colors.Normalize(vmin=0, vmax = 1)
      fig, ax = plt.subplots()
      ax.imshow(C, cmap=cmap, norm=norm)
 
      ax.grid(which='major', axis='both', linestyle='-', color='k', linewidth=2)
      ax.axes.get_xaxis().set_visible(False)
      ax.axes.get_yaxis().set_visible(False)
      results_dir = os.path.join(os.getcwd(),'solutions/')
      if not os.path.isdir(results_dir):
        os.makedirs(results_dir)
 
      plt.savefig(results_dir + "Run:" + (iteration) + "_solution_time_" + str(t) + ".png")
 
  city = C[cell_city_x][cell_city_y]
  if city == 1:
    print("City Dead")
    count += 1
  else:
    print("City Alive")
  print(count)
that looks to be loads faster thank you so much for your help
i get this error come up after running it a few times

Traceback (most recent call last):
File "main.py", line 90, in <module>
Cnew[possible_x][possible_y]=1#make this =p to give range of intensity?
IndexError: index 100 is out of bounds for axis 0 with size 100
Reply


Messages In This Thread
Help improve code efficiency - by benbrown03 - Feb-12-2019, 02:06 PM
RE: Help improve code efficiency - by ichabod801 - Feb-12-2019, 03:38 PM
RE: Help improve code efficiency - by benbrown03 - Feb-12-2019, 05:34 PM
RE: Help improve code efficiency - by ichabod801 - Feb-12-2019, 08:22 PM
RE: Help improve code efficiency - by benbrown03 - Feb-19-2019, 10:56 AM
RE: Help improve code efficiency - by ichabod801 - Feb-19-2019, 08:04 PM
RE: Help improve code efficiency - by benbrown03 - Feb-19-2019, 09:25 PM
RE: Help improve code efficiency - by ichabod801 - Feb-19-2019, 10:08 PM
RE: Help improve code efficiency - by benbrown03 - Feb-20-2019, 08:04 AM
RE: Help improve code efficiency - by ichabod801 - Feb-20-2019, 03:45 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Numpy Structure and Efficiency garynewport 2 706 Oct-19-2022, 10:11 PM
Last Post: paul18fr
  (OpenCV) Help to improve code for object detection and finding center of it saoko 0 1,216 May-14-2022, 05:34 PM
Last Post: saoko
  Efficiency with regard to nested conditionals or and statements Mark17 13 3,229 May-06-2022, 05:16 PM
Last Post: Mark17
  How to use vectorization instead of for loop to improve efficiency in python? PJLEMZ 4 2,436 Feb-06-2021, 09:45 AM
Last Post: paul18fr
  Any suggestions to improve BuySell stock problem efficiency? mrapple2020 0 1,383 May-13-2020, 06:19 PM
Last Post: mrapple2020
  how can I improve the code to get it faster? aquerci 2 1,735 Feb-15-2020, 02:52 PM
Last Post: aquerci
  How can I improve this piece of code? aquerci 3 2,232 Nov-17-2019, 10:57 AM
Last Post: Gribouillis
  How to improve the quality of my code? grobattac37 3 2,506 Jan-25-2019, 06:17 PM
Last Post: ichabod801
  Web Scraping efficiency improvement HiImNew 0 2,408 Jun-01-2018, 08:52 PM
Last Post: HiImNew
  Improving Efficiency of SVM by various available kernels Sachtech 0 2,110 Apr-09-2018, 07:29 AM
Last Post: Sachtech

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020