Skip to content

Commit

Permalink
Python main() is producing valid floating-point output.
Browse files Browse the repository at this point in the history
  • Loading branch information
carl-drews committed Jun 11, 2024
1 parent 652fe37 commit 5e5b6be
Show file tree
Hide file tree
Showing 7 changed files with 83 additions and 21 deletions.
3 changes: 3 additions & 0 deletions src/acom_music_box/goBuild.bat
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
cd ..\..
pip install .
cd src\acom_music_box
36 changes: 25 additions & 11 deletions src/acom_music_box/music_box.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from .music_box_conditions import Conditions
import csv
import musica
import music_box_logger

class MusicBox:
"""
Expand Down Expand Up @@ -36,13 +37,15 @@ def __init__(self, box_model_options=None, species_list=None, reaction_list=None
evolving_conditions (List[EvolvingConditions]): List of evolving conditions over time.
config_file (String): File path for the configuration file to be located. Default is "camp_data/config.json".
"""
self.box_model_options = box_model_options
self.box_model_options = box_model_options if box_model_options is not None else BoxModelOptions()
self.species_list = species_list if species_list is not None else SpeciesList()
self.reaction_list = reaction_list if reaction_list is not None else ReactionList()
self.initial_conditions = initial_conditions
self.initial_conditions = initial_conditions if initial_conditions is not None else Conditions()
self.evolving_conditions = evolving_conditions if evolving_conditions is not None else EvolvingConditions([], [])
self.config_file = config_file if config_file is not None else "camp_data/config.json"

self.solver = None



def add_evolving_condition(self, time_point, conditions):
Expand Down Expand Up @@ -428,7 +431,7 @@ def solve(self, path_to_output = None):
list: A 2D list where each inner list represents the results of the simulation
at a specific time step.
"""

#sets up initial conditions to be current conditions
curr_conditions = self.initial_conditions

Expand All @@ -448,7 +451,7 @@ def solve(self, path_to_output = None):
next_conditions_index = 1
next_conditions = self.evolving_conditions.conditions[1]
next_conditions_time = self.evolving_conditions.times[1]


#initalizes output headers
output_array = []
Expand All @@ -458,10 +461,16 @@ def solve(self, path_to_output = None):
headers.append("ENV.temperature")
headers.append("ENV.pressure")

music_box_logger.progress("solve0152 self.solver = {}".format(self.solver))

if (self.solver is None):
music_box_logger.progress("Warning: MusicBox object {} has no solver."
.format(self))
rate_constant_ordering = musica.user_defined_reaction_rates(self.solver)

species_constant_ordering = musica.species_ordering(self.solver)


#adds species headers to output
ordered_species_headers = [k for k, v in sorted(species_constant_ordering.items(), key=lambda item: item[1])]
for spec in ordered_species_headers:
Expand All @@ -478,9 +487,11 @@ def solve(self, path_to_output = None):
next_output_time = curr_time
#runs the simulation at each timestep


music_box_logger.progress("solve03 path_to_output = {}".format(path_to_output))


while(curr_time <= self.box_model_options.simulation_length):

#outputs to output_array if enough time has elapsed
if(next_output_time <= curr_time):
row = []
Expand All @@ -507,30 +518,33 @@ def solve(self, path_to_output = None):

else:
next_conditions = None

music_box_logger.progress("solve033 species_constant_ordering = {}".format(species_constant_ordering))


#updates M accordingly
if 'M' in species_constant_ordering:
BOLTZMANN_CONSTANT = 1.380649e-23
AVOGADRO_CONSTANT = 6.02214076e23;
GAS_CONSTANT = BOLTZMANN_CONSTANT * AVOGADRO_CONSTANT
ordered_concentrations[species_constant_ordering['M']] = curr_conditions.pressure / (GAS_CONSTANT * curr_conditions.temperature)

music_box_logger.progress("solve035 args = {} {} {} {} {}".format(self.box_model_options.chem_step_time, curr_conditions.temperature, curr_conditions.pressure, ordered_concentrations, ordered_rate_constants))
#solves and updates concentration values in concentration array
if (not ordered_concentrations):
music_box_logger.progress("Warning: ordered_concentrations list is empty.")
musica.micm_solve(self.solver, self.box_model_options.chem_step_time, curr_conditions.temperature, curr_conditions.pressure, ordered_concentrations, ordered_rate_constants)




#increments time
curr_time += self.box_model_options.chem_step_time

#outputs to file if output is present
if(path_to_output != None):
with open(path_to_output, 'w', newline='') as output:
writer = csv.writer(output)
writer.writerows(output_array)

#returns output_array
return output_array

Expand Down
2 changes: 1 addition & 1 deletion src/acom_music_box/music_box_conditions.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class Conditions:
reactionRates (List[ReactionRate]): A list of reaction rates.
"""

def __init__(self, pressure, temperature, species_concentrations=None, reaction_rates=None):
def __init__(self, pressure=0.83, temperature=303.0, species_concentrations=None, reaction_rates=None):
"""
Initializes a new instance of the Conditions class.
Expand Down
32 changes: 32 additions & 0 deletions src/acom_music_box/music_box_logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import sys

# Class Logger is included here for completeness,
# but not used because progress() is such a lighweight function.
class Logger:
"""
Logs messages to the console, which can then be captured to a log file.
Attributes:
"""

def __init__(self):
"""
Initializes a new instance of the Reaction class.
Args:
name (str): The name of the reaction.
reaction_type (str): The type of the reaction.
reactants (List[Reactant]): A list of Reactant instances representing the reactants. Default is an empty list.
products (List[Product]): A list of Product instances representing the products. Default is an empty list.
scaling_factor (float, optional): A scaling factor for the reaction rate. Defaults to None.
"""
pass



# Display progress message on the console.
# endString = set this to '' for no return
def progress(message, endString='\n'):
if (True): # disable here in production
print(message, end=endString)
sys.stdout.flush()
28 changes: 20 additions & 8 deletions src/acom_music_box/music_box_main.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,31 @@
from acom_music_box import MusicBox

import math
import datetime
import sys

import music_box_logger


# Display progress message on the console.
# endString = set this to '' for no return
def progress(message, endString='\n'):
if (True): # disable here in production
print(message, end=endString)
sys.stdout.flush()

if __name__ == "__main__":
music_box_logger.progress("{}".format(__file__))
music_box_logger.progress("Start time: {}".format(datetime.datetime.now()))

music_box_logger.progress("Hello, MusicBox World!")

# set up the home configuration directory TODO: Make this a command-line argument.
musicBoxHomeDir = "C:\\2024\\MusicBox\\music-box\\tests\\configs\\analytical_config\\"

# create and load a MusicBox object
myBox = MusicBox()
myBox.readConditionsFromJson(musicBoxHomeDir + "my_config.json")
music_box_logger.progress("myBox = {}".format(myBox))

# create solver and solve
myBox.create_solver(musicBoxHomeDir + myBox.config_file)
mySolution = myBox.solve()
music_box_logger.progress("mySolution = {}".format(mySolution))

if __name__ == "__main__":
progress("Hello, MusicBox World!")
music_box_logger.progress("End time: {}".format(datetime.datetime.now()))
sys.exit(0)
2 changes: 1 addition & 1 deletion src/acom_music_box/music_box_model_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class BoxModelOptions:
simulationLength (float): Length of the simulation in hours.
"""

def __init__(self, chem_step_time, output_step_time, simulation_length, grid="box"):
def __init__(self, chem_step_time=1.0, output_step_time=5.0, simulation_length=100.0, grid="box"):
"""
Initializes a new instance of the BoxModelOptions class.
Expand Down
1 change: 1 addition & 0 deletions tests/goTest.bat
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pytest

0 comments on commit 5e5b6be

Please sign in to comment.