I am new on chemical network model. Currently I am converting a previous student python code to adapt the new version in the lab as titled.
firstly, a gas mixture from mechanism (pre defined) is defined
gas_mix = ct.import_phases(mech,['gas'])
then, I want to get the number of the species and use cantera nSpecies
nsp = gas_mix.nSpecies()
and I got the error message as
AttributeError: 'list' object has no attribute 'nSpecies'
Also I tried:
nsp = gas_mix.n_species
and it also shows
AttributeError: 'list' object has no attribute
Would you please kindly help me on this ?
Thank you and best regards,
YouBe
It looks like import_phases returns a list of objects--either a list of "gas mix" or just "gas" objects. I'm not really sure because this is very specific to the program you're working with.
Anyway, try looping over the values in the gas_mix and see if you can call the nSpecies() method or access the n_species attribute:
gas_mix = ct.import_phases(mech,['gas'])
for gm in gas_mix:
print(gm.nSpecies())
# or you can try this:
print(gm.n_species)
Maybe that will get you closer to what you want.
The function import_phases returns a list, which is useful for the case where you want to import multiple phase definitions from the same file, e.g.
mixtures = ct.import_phases(mech, ['gas1', 'gas2'])
where both mixtures[0] and mixtures[2] will then be a single phase definition. If you only want to define a single phase, it is easier to write:
gas_mix = ct.Solution(mech,'gas')
Or, if the mechanism file only contains one phase definition, just
gas_mix = ct.Solution(mech)
From here, you should be able to access the number of species as
gas_mix.n_species
Many of the details of migrating from the old to new Cantera interfaces are described in the documentation page "Migrating from the Old Python Module".
Related
I am working with this object SharedMemoryDisplay in the above script and I want to return/retrieve self.camera_container, where self.camera_container = {camera_id: (camera_id, frame, frame_properties)}
I tried to create a method to return the this but it gives two errors
prop, camera_container = monitor_memory.get_frame()
TypeError: 'NoneType' object is not iterable
AttributeError: Can't pickle local object 'SharedMemoryDisplay.__init__.<locals>.<lambda>'
I am only able to able to get self.camera_container[key] if I just do which is fine but I want to get self.camera_container also.
return self.camera_container[key]
In the below script is where, I am using this object to display in a cv2 named window, my ultimate motive is to retrieve frames of all the cameras seperately what it currently does is joins all the camera frames and returns that via self.display_frame which is added to webdisplay_memory in the below script (for displaying in the html) that's why I created a method to retrieve dictionary camera_container.
webdisplay_memory.add_frame(0, self.display_frame, None)
rather than messing with this variable I was thinking of creating a method that returns self.camera_container than using this to get frames of each camera seperately.
how can I overcome this, kindly help if you have better and efficient solutions!
multiprocessing uses pickle under the hood. pickle can serialize only a certain set of objects. Specifically, it can not serialize defaultdict (a type for your camera_container). So, either use a normal dict and replace all the lookups to self.camera_container.get(key, None), or look into this question and try to use pathos.multiprocessing with dill. The latter approach is not tested by me, though.
I am trying to write a testing program for a python program that takes data, does calculations on it, then puts the output in a class instance object. This object contains several other objects, each with their own attributes. I'm trying to access all the attributes and sub-attributes dynamically with a one size fits all solution, corresponding to elements in a dictionary I wrote to cycle through and get all those attributes for printing onto a test output file.
Edit: this may not be clear from the above but I have a list of the attributes I want, so using something to actually get those attributes is not a problem, although I'm aware python has methods that accomplish this. What I need to do is to be able to get all of those attributes with the same function call, regardless of whether they are top level object attributes or attributes of object attributes.
Python is having some trouble with this - first I tried doing something like this:
for string in attr_dictionary:
...
outputFile.print(outputclass.string)
...
But Python did not like this, and returned an AttributeError
After checking SE, I learned that this is a supposed solution:
for string in attr_dictionary:
...
outputFile.print(getattr(outputclass, string))
...
The only problem is - I want to dynamically access the attributes of objects that are attributes of outputclass. So ideally it would be something like outputclass.objectAttribute.attribute, but this does not work in python. When I use getattr(outputclass, objectAttribute.string), python returns an AttributeError
Any good solution here?
One thing I have thought of trying is creating methods to return those sub-attributes, something like:
class outputObject:
...
def attributeIWant(self,...):
return self.subObject.attributeIWant
...
Even then, it seems like getattr() will return an error because attributeIWant() is supposed to be a function call, it's not actually an attribute. I'm not certain that this is even within the capabilities of Python to make this happen.
Thank you in advance for reading and/or responding, if anyone is familiar with a way to do this it would save me a bunch of refactoring or additional code.
edit: Additional Clarification
The class for example is outputData, and inside that class you could have and instance of the class furtherData, which has the attribute dataIWant:
class outputData:
example: furtherData
example = furtherData()
example.dataIWant = someData
...
with the python getattr I can't access both attributes directly in outputData and attributes of example unless I use separate calls, the attribute of example needs two calls to getattr.
Edit2: I have found a solution I think works for this, see below
I was able to figure this out - I just wrote a quick function that splits the attribute string (for example outputObj.subObj.propertyIWant) then proceeds down the resultant array, calling getattr on each subobject until it reaches the end of the array and returns the actual attribute.
Code:
def obtainAttribute(sample, attributeString: str):
baseObj = sample
attrArray = attributeString.split(".")
for string in attrArray:
if(attrArray.index(string) == (len(attrArray) - 1)):
return getattr(baseObj,string)
else:
baseObj = getattr(baseObj,string)
return "failed"
sample is the object and attributeString is, for example object.subObject.attributeYouWant
I am using Python/Gurobi to optimize a problem. I generated variables using GRBaddVar through this code:
x[1,i,j,t] = model.addVar(vtype="B", name="x(1,%s,%s,%s)" % (i,j,t))
I also want to remove some variables in order to save some space. The variable is removed when a certain condition is true. Suppose the condition is when R = 1. To remove the variable I use the following code.
if R == 1:
x[1,i,j,t] = model.delVars(vtype="B", name="x(1,%s,%s,%s)" % (i,j,t))
However, it resulted in the following error:
AttributeError: 'gurobipy.Model' object has no attribute 'delVars'
I have no idea what's wrong with the code since I just follow the documentation (attached below) from Gurobi. Thanks for your help!
As David noted, you are looking at the documentation for the C API.
In the Python API, you can remove a single variable with the Model.remove() method, using the Var object the argument. E.g.,
model.remove(x[1,i,j,t])
You can use this same method to remove, e.g., a list of Var objects at once.
Note that you should call Model.update() before removing variables in this manner.
"You can use this same method to remove, e.g., a list of Var objects at once."
Can anyone suggest how to remove multiple variables at once. I have the variable to be removed in a dict/list format. I am trying to the below code, but error appears: GurobiError: Item to be removed not a Var, MVar, Constr, MConstr, SOS, QConstr, or GenConstr
model.remove(var_to_remove_dict.keys())
I'm trying to use a method from the BioPython package to calculate an isoelectric point for a list of given peptides. The class breakdown can be seen here:
http://biopython.org/DIST/docs/api/Bio.SeqUtils.ProtParam.ProteinAnalysis-class.html#isoelectric_point
In order to import this class to my environment, I'm using the following code (did I do this right?):
from Bio.SeqUtils.ProtParam import ProteinAnalysis
Then, to call the method, I do the following:
window_aas = "ditkdteneveadveveadveveadvseql";
ProteinAnalysis.isoelectric_point(window_aas);
However I'm getting the following error, and I'm not sure how to interpret it, despite several searches for similar errors:
File
"C:\Users\----\AppData\Local\Programs\Python\Python36-32\lib\site-packages\Bio\SeqUtils\ProtParam.py",
line 68, in count_amino_acids
if self.amino_acids_content is None: AttributeError: 'str' object has no attribute 'amino_acids_content'
Is anyone able to guide me in the right direction here? This other class is also called IsoElectricpoint but I don't see a method in it to use:
http://biopython.org/DIST/docs/api/Bio.SeqUtils.IsoelectricPoint-module.html
ProteinAnalysis is a class. What you're doing in your code is trying to call a method in that class directly. In Python, the first argument to such a function is the class object, but you're passing in a string (window_aas). The correct way to use this api is first create a class object:
protein_analysis = ProteinAnalysis(window_aas)
and then you can call
protein_analysis.isoelectric_point()
You can read up more on how this all works in the online docs.
It looks like isoelectric_point is an instance method, so you need to create an instance first:
analysis = ProteinAnalysis(window_aas)
analysis.isoelectric_point()
When I use R, I can use str() to inspect objects which are a list of things most of the times.
I recently switched to Python for statistics and don't know how to inspect the objects I encounter. For example:
import statsmodels.api as sm
heart = sm.datasets.heart.load_pandas().data
heart.groupby(['censors'])['age']
I want to investigate what kind of object is heart.groupby(['censors']) that allows me to add ['age'] at the end. However, print heart.groupby(['censors']) only tells me the type of the object, not its structure and what I can do with it.
So how do I get to understand the structure of numpy / pandas object, similar to str() in R?
If you're trying to get some insight into what you can do with a Python object, you can inspect it using a beefed-up Python console like IPython. In an IPython session, first put the object you want to look at into a variable:
import statsmodels.api as sm
heart = sm.datasets.heart.load_pandas().data
h_grouped = heart.groupby(['censors'])
Then type out the variable name and double-tap Tab to bring up a list of the object's methods:
In [5]: h_grouped.<Tab><Tab>
# Shows the object's methods
A further benefit of the IPython console is you can quickly check the
help for any individual method by adding a ?:
h_grouped.apply?
# Apply function and combine results
# together in an intelligent way.
If you don't have IPython or a similar console, you can achieve something similar using dir(), e.g. dir(h_grouped), although this will also list
the object's private methods which are generally not useful and shouldn't be
touched in regular use.
type(heart.groupby(['censors'])['age'])
type will tell you what kind of object it is. At the moment you are grouping by a dimension and not telling pandas what to do with age. If you want the mean for example you could do:
heart.groupby(['censors'])['age'].mean()
This would take the mean of age by the group, and return a series.
The groupby is I think a red herring -- "age" is just a column name:
import statsmodels.api as sm
heart = sm.datasets.heart.load_pandas().data
heart
# survival censors age
# 0 15 1 54.3
# ...
heart.keys()
# Index([u'survival', u'censors', u'age'], dtype='object')