Exemple #1
0
    def results(self, style='compact', decimals=2, fill='-'):
        '''Print the results of the costing calculation.

        Parameters
        ----------
        style : str, optional (Default = 'compact')
            This sets the style of the displayed costing DataFrame.
            `'compact'` prints a DataFrame that has been truncated slightly.
            `'full'` prints the entire DataFrame.

        decimals : int or None, optional (Default = 2)
            How many decimal places to show in the table. Set this to `None`
            if you want full precision.

        fill : str or None, optional ('-')
            Fill NaN values with this string. This makes the table a little
            easier to read. Set this to `None` if you want to see the table
            with the typical NaN labels.
        '''
        # This makes the max Colab output window very large, so that
        # DataFrames are not put into separate scroll windows, which is very
        # annoying for users. Unfortunately, I need to copy/paste the doc
        # string for results method, though...
        # See: https://github.com/googlecolab/colabtools/issues/541
        iframe_h = 'google.colab.output.setIframeHeight(0, true, {\n'\
                   '  maxHeight: 5000,\n'\
                   '})'
        disp(Javascript(iframe_h))
        # Call results method from ExcelCost
        super(ColabCost, self).results(style=style,
                                       decimals=decimals,
                                       fill=fill)
Exemple #2
0
def display(df, urls=False):
    """Redefine display to show URLs instead of indices."""
    dft = df
    if urls:
        dft = df.copy()
        if df.index.name == 'class_label':
            dft = dft.reset_index()
            if 'index' in dft.columns:
                dft = dft.drop(['index'], axis=1)
        if 'class_label' in dft.columns:
            dft['class_label'] = dft.class_label.apply(lambda x: url(int(x)))
        if df.index.name == 'class_label':
            dft.set_index('class_label')
    disp(dft)
Exemple #3
0
def sym_compute_show_error_influences(name, data, expr_subs, expr_vars, expr_err_derivs, expr_err_e_d_sq):
	bits = pd.DataFrame({ var.name: { "Error": data.Error[var.name] if var.name in data.Error else None,
	                                  "Derivative": deriv.subs(expr_subs),
	                                  "(E*D)^2": e_d_sq.subs(expr_subs) }
	                      for var, deriv, e_d_sq in zip(expr_vars, expr_err_derivs, expr_err_e_d_sq) },
	                     index = ["Error", "Derivative", "(E*D)^2"]).T

	# try to sort error influences (if any variables are unresolved, this will fail)
	try:
		bits = bits.sort_values("(E*D)^2", ascending=False)
	except:
		pass

	if name:
		print("Error influence estimations for %s:" % name)
	else:
		print("Error influence estimations:")
	disp(bits)
Exemple #4
0
def fit(name, model, model_args, x, y, xerr, yerr, initial = None, prefit = False, noop = False):
	if noop:
		return var_many(names = model_args,
		                values = initial if initial is not None else [0 for x in model_args],
		                errors = [0 for x in model_args])

	# use OLS (ordinary least squares) to find initial guesses
	if prefit or initial is None:
		beta, cov = sp_opt.curve_fit(model,
		                             xdata = x,
		                             ydata = y,
		                             sigma = yerr,
		                             absolute_sigma = True,
		                             maxfev = int(1e6),
		                             p0 = initial)

		fit_result = var_many(names = model_args,
		                      values = beta,
		                      errors = [ cov[i, i]**0.5
		                                 for i, v
		                                 in enumerate(cov) ])

		print("Initial guesses for %s:\n%s\n" % (name, fit_result))
		initial = beta

	# use ODR (Deming regression) which is a special case of TLS (total least squares)
	# to find results accounting for both X and Y uncertainties
	odr_model = sp_odr.Model(lambda B, x: model(x, *B))
	odr_data = sp_odr.RealData(x = x, y = y, sx = xerr, sy = yerr)
	odr = sp_odr.ODR(odr_data, odr_model, beta0 = initial, maxit = int(1e6))
	odr_output = odr.run()

	fit_result = var_many(names = model_args, values = odr_output.beta, errors = odr_output.sd_beta)
	print("Final guesses for %s:" % name)
	disp(fit_result)

	return fit_result
Exemple #5
0
def compute(name, expr, data, columns = None, aux = None, debug = False, expr_args = None):
	if type(expr).__name__ == "function":
		expr_fn = expr
		if expr_args is None:
			expr_args = list(inspect.signature(expr_fn).parameters.keys())
		expr_vars = smp.symbols(expr_args)
		expr = expr_fn(*expr_vars)
	else:
		expr_vars = expr.atoms(smp.Symbol)

	expr_err, expr_err_vars, expr_err_derivs, expr_err_e_d_sq = sym_error(expr, expr_vars)

	# front check if we have enough data
	for v in expr_vars:
		if not (v.name in data.Value or
		        v.name in columns or
			(aux is not None and v.name in aux and "Value" in aux[v.name])):
			raise IndexError("Variable %s does not exist in dataset" % v.name)

		if not (v.name in data.Error or
		        "Error_%s" % v.name in columns or
			(aux is not None and v.name in aux and "Error" in aux[v.name])):
			raise IndexError("Error for variable %s does not exist in dataset" % v.name)

	# build substitutions from data
	expr_subs = sym_make_subs(expr_vars, expr_err_vars, data)

	# build substitutions from immediate values in cols_mapping
	if aux is not None:
		expr_subs_aux = sym_make_subs_aux(expr_vars, expr_err_vars, aux)
		expr_subs.update(expr_subs_aux)

	# pre-substitute constants
	expr = expr.subs(expr_subs)
	expr_err = expr_err.subs(expr_subs)

	# build substitution template from columns and column references in cols_mapping
	expr_subs_cols = sym_make_subs_cols_meta(expr_vars, expr_err_vars, columns, aux)

	# show some verbose information
	if debug:
		if expr_subs_cols:
			print("Computing row of %s" % name)
		else:
			print("Computing variable %s" % name)

		sym_compute_show_error_influences(None,
		                                  data,
		                                  expr_subs,
		                                  expr_vars,
		                                  expr_err_derivs,
		                                  expr_err_e_d_sq)

	# if any variables are given in the form of columns, then we are computing
	# a column, otherwise -- a single variable
	if expr_subs_cols:
		expr_subs_rows = [ { var: row[col_name]
		                     for var, col_name
		                     in expr_subs_cols.items() }
		                   for i, row
		                   in columns.iterrows() ]

		expr_rows = [ float(expr.subs(data))
		              for data
		              in expr_subs_rows ]
		expr_err_rows = [ float(expr_err.subs(data))
		                  for data
		                  in expr_subs_rows ]

		if debug:
			print("(Not displaying column '%s' of N=%d rows)" % (name, len(expr_rows)))

		add_column(columns,
		           name = name,
		           values = expr_rows,
		           errors = expr_err_rows)

	else:
		expr_out = var(name, float(expr), float(expr_err))

		if debug:
			print("Result:")
			disp(expr_out)

		add(data, expr_out)

	return expr, expr_vars, expr_err_vars
Exemple #6
0
#runs through the loop while the user still wants to play the game
while roll.lower() == "yes":
    totalroll = 0
    #asks user how many dice they want to roll
    amount = input("How many Dice ? \n> ")
    print("Rolling the dice...")

    #rolls the amount dice the user inputted
    for x in range(int(amount)):
        print("Dice " + str(x + 1))
        roll = ran.randint(0, 5) + 1
        #outputs the roll to the text file
        outputToFile("Roll : " + str(roll) + "\n")
        #displays the images inline in the console
        disp(diceimages(roll))
        print("\n")
        #adds to the total roll
        totalroll += roll
        time.sleep(1)

    #prints out the total of the rolls
    print("Total of roll : " + str(totalroll))
    #adds the total to the database "rolls"
    data_entry(totalroll, "Dice")
    #adds it the total to the text file
    outputToFile("Total :" + str(totalroll) + "\n")
    print("Added to Database and text file")
    #checks if user wants to continue
    time.sleep(1)
    roll = input("Would you like to roll again ? (yes/no) \n> ")
Exemple #7
0
    def results(self, style='compact', decimals=2, fill='-'):
        '''Print the results of the costing calculation.

        Parameters
        ----------
        style : str, optional (Default = 'compact')
            This sets the style of the displayed costing DataFrame.
            `'compact'` prints a DataFrame that has been truncated slightly.
            `'full'` prints the entire DataFrame.

        decimals : int or None, optional (Default = 2)
            How many decimal places to show in the table. Set this to `None`
            if you want full precision.

        fill : str or None, optional ('-')
            Fill NaN values with this string. This makes the table a little
            easier to read. Set this to `None` if you want to see the table
            with the typical NaN labels.
        '''
        # Print the time the calculation was run
        print('As of', self._now, '--')

        # Print a string about the final cost of the product
        if decimals:
            dec_str = ':.{:d}f'.format(decimals)
        else:
            dec_str = ':f'
        cost_str = 'The final cost of {} is ${' + dec_str + '}/kg.'
        print(cost_str.format(self.final_prod, self.cost))

        # For compact display, these are the most important columns
        comp_col = [
            'Cost',
            'Equiv',
        ]
        if self.fulldata.Volumes.any():
            comp_col.extend([
                'Volumes',
                'Sol Recyc',
            ])
        if self.fulldata.OPEX.any():
            comp_col.append('OPEX')
        comp_col.extend([
            'kg/kg rxn', 'RM cost/kg rxn', '% RM cost/kg rxn', 'kg/kg prod',
            'RM cost/kg prod', '% RM cost/kg prod'
        ])

        # Combine the fulldata and pmi DataFrames
        fd = self._df_combine()

        # Display the DataFrames for different permutations of kwargs
        # The fillna removes NaN from the displayed tables in Notebook, but
        # may goof up printing
        if decimals:
            if style == 'full':
                disp(fd.round(decimals).fillna(fill))
            elif style == 'compact':
                disp(fd[comp_col].round(decimals).fillna(fill))
        else:
            if style == 'full':
                disp(fd.fillna(fill))
            elif style == 'compact':
                disp(fd[comp_col].fillna(fill))
Exemple #8
0
    def _sanity_check(self, ):
        '''Run some sanity checks on the DataFrames to catch common errors.

        Some of the errors are tricky, and the error output is unhelpful.
        These are some checks that will throw some "sane" errors if things are
        not correct.
        '''
        # Check for a missing material -- Everything should have a MW
        mw_mask = self.fulldata['MW'].isna()
        if mw_mask.any():
            print('You are missing a MW!!!')
            print('May be a mismatch between the reaction and materials file.')
            print('Material might be missing from materials sheet.')
            print('Check these materials.')
            disp(self.fulldata.loc[mw_mask, 'MW'])
            raise ValueError('Yikes! Read the note above.')

        # Check for a missing cost, which is not being calculated
        # This is a tricky error because the costing will run just fine with
        # NaNs. Check for this by looking for NaN in both Cost and Calc columns
        cost_mask = (self.fulldata['Cost calc'].isna() & \
                    self.fulldata['Cost'].isna())
        if cost_mask.any():
            print('You are missing a necessary material cost!!')
            print('You may need to indicate a Step in the "Cost calc" column.')
            print('Check these columns.')
            disp(self.fulldata.loc[cost_mask, ['Cost', 'Cost calc']])
            raise ValueError('Yikes! Read the note above.')

        # Check for duplicated materials. This will probably be a big issue
        # with two materials sheets.
        dup_cpds = self.materials['Compound'].duplicated()
        if dup_cpds.any():
            print('You have a duplicate material!!!')
            print("These compounds are duplicated in your materials sheet.")
            disp(self.materials.loc[dup_cpds, 'Compound'])
            raise ValueError('Yikes! Read the note above.')

        # Check for duplicated materials in a single reaction.
        # When you select a single value from a reaction, you'll get a series
        # and not a float, e.g.
        dup_rxn = self.fulldata.loc[(self._fp_idx, self.final_prod), 'MW']
        if isinstance(dup_rxn, pd.Series):
            print('You have a duplicated material in a single reaction.')
            print('Check these lines:')
            gb = self.fulldata.groupby(['Prod', 'Compound'])
            for prod, group in gb:
                if group.shape[0] > 1:
                    disp(prod)
            raise ValueError('Yikes! Read the note above.')

        # Check that all the solvent information is given
        sol_mask = ~self.fulldata['Volumes'].isna()
        sol_chk = self.fulldata.loc[sol_mask, 'Relative'].isna() | \
                self.fulldata.loc[sol_mask, 'Density'].isna() | \
                self.fulldata.loc[sol_mask, 'Sol Recyc'].isna()
        # If anything is missing, print a note
        if sol_chk.any():
            sol_cols = ['Density', 'Volumes', 'Relative', 'Sol Recyc']
            print('You are missing some solvent information.')
            print('Check the following lines.')
            sol_mask2 = sol_mask & sol_chk
            disp(self.fulldata.loc[sol_mask2, sol_cols])
            raise ValueError('Yikes! Read the note above.')

        # Check to make sure that the "Relative" compound for a solvent
        # is acutally contained in the step
        sol_mask = ~self.fulldata['Relative'].isna()
        for cpd in self.fulldata[sol_mask].itertuples():
            new_idx = (cpd.Index[0], cpd.Relative)
            if new_idx not in self.fulldata.index:
                print('One of your "Relative" compounds is not correct.')
                print(f'"{cpd.Relative}" is not in Step {cpd.Index[0]}.')
                raise ValueError('Yikes! Read the note above.')
Exemple #9
0
       (`-()_.-=-.
       /66  ,  ,  \
     =(o_/=//_(   /======`
         ~"` ~"~~`
Created on Thu Jun 18 11:10:16 2020
@author: Chris
"""
import random as ran  #random function
import string as stri  #string
import sqlite3 as sql  #SQL for database
from PIL import Image  #for importing the dice images
from IPython.display import display as disp  #for displaying images

img2 = Image.open(r"images/thumps.jpg")
img1 = Image.open(r"images/pass1.jpg")
disp(img1)
print("-----------------------------------")
print("Welcome to the password Generator :")


#function to create the password with a length of 15
def makepass(name, surname):
    passw = name[0] + surname[0]
    for x in range(15):
        passw += ran.choice(charlist())
    return passw


#function to create a list containing all the letters, numbers, and characters.
def charlist():
    numbers = '1234567890'
Exemple #10
0
    print(sinum(-82457891234, verbose=True), end='\n\n')
    print(sinum(8786996786798967896872457891234, verbose=True), end='\n\n')


# ## load data
# 
# #### initialize data container `d`

# In[20]:


# a dict with tskeys as keys to uniform dicts
d = {}
for tsk in tskeys:
    d[tsk] = {}
disp(d)


# #### download data from github, save to file

# In[19]:


# same load and save process for each tskey
print(f">>> loading CSVs, saving in ``{data_dir}''\n")
for tsk in tskeys:
    
    print(">>> getting data for '{}'".format(tsk))
    
    # download URL from github
    d[tsk]['url'] = f"{base_tsdata_url}/csse_covid_19_time_series/time_series_covid19_{tsk}.csv"