In Networkx is there a way to select when to save to a file, when show on screen and when both? - save

At the moment, I am doing both:
pos = nx.spring_layout(G)
f1 = plt.figure(figsize=(18,10))
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_size=600, alpha=0.8, ax=default_axes, pos=pos)
edge_labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)
plt.savefig('graph.jpg')
I would like to be able to select if to display, save or both (what I am doing now)

There is no built-in option for that in networkx. One option is to wrap the code in a function along these lines:
def custom(G, plot=True, save_file=False):
'''plots G by default. save_file should be a string'''
pos = nx.spring_layout(G)
f1 = plt.figure(figsize=(18,10))
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_size=600, alpha=0.8, ax=default_axes, pos=pos)
edge_labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)
if save: plt.savefig(save) # can allow custom save name
if plot: plt.show()
return
Note that if the figure displays regardless of the option passed to the command, then the inline option might need to be disabled.

Related

Select particular listbox value on start of Dynpro?

I have a custom dialog dynpro including an input field named DYN_MATNR as listbox for which I have included a list of particular materials as selection.
How can I set a specific material (of that list) as selected when the dialog dynpro is opened?
PBO of dialog dynpro:
data lt_values type vrm_values.
select matnr,
maktx
into table #data(lt_materials)
from makt
where matnr in #so_matnr
and spras = 'D'
order by matnr.
loop at lt_materials assigning field-symbol(<material>).
append initial line to lt_values assigning field-symbol(<value>).
<value>-key = <material>-matnr.
<value>-text = <material>-maktx.
endloop.
call function 'VRM_SET_VALUES'
exporting
id = 'DYN_MATNR'
values = lt_values
exceptions
id_illegal_name = 1
others = 2.
if sy-subrc <> 0.
" ...
endif.
This works and it shows the list of materials as listbox values. To select a particular material I have included the FM DYNP_VALUES_UPDATE afterwards and also in PBO but this did not work:
data lv_stepl type syst-stepl.
call function 'DYNP_GET_STEPL'
importing
povstepl = lv_stepl
exceptions
stepl_not_found = 1
others = 2.
if sy-subrc <> 0.
" ...
endif.
data(lt_dynpfields) = value dynpread_tabtype(
( fieldname = 'DYN_MATNR'
stepl = lv_stepl
fieldvalue = gcl_helper->get_matnr( ) " matnr which should be selected is stored here
fieldinp = space )
).
call function 'DYNP_VALUES_UPDATE'
exporting
dyname = sy-repid
dynumb = sy-dynnr
tables
dynpfields = lt_dynpfields
exceptions
invalid_abapworkarea = 1
invalid_dynprofield = 2
invalid_dynproname = 3
invalid_dynpronummer = 4
invalid_request = 5
no_fielddescription = 6
undefind_error = 7
others = 8.
if sy-subrc <> 0.
" ...
endif.
I am also not able to directly set DYN_MATNR as it is not available in PBO.
Any hints?
Got it:
You need to additionally define a global(!) variable with the name and (wished) type of the input field (e.g. in the top include of the report or in a separate include of the dynpro logic):
data dyn_matnr type matnr.
Then you can set the initial value of the dynpro field in PBO directly:
dyn_matnr = gcl_helper->get_matnr( ).
As this becomes rather irritating when using various dialog dynpros I recommend including the dynpro number in those variables and input fields.

Trying to use add = True and I get an error message

I am Trying to use add = True and I get an error message. How can I do it?
This is my code
quadratcount(schools.pp)
plot(schools.sp, col = "red")
plot(quadratcount(schools.pp), add= T)`
and this is the error message I get
Error in (function (x, y = NULL, density = NULL, angle = 45, border = NULL, : plot.new has not been called yet
Looks like you made a simple typo: In the first plot command you write plot(schools.sp, col = "red"), where you probably meant plot(schools.pp, col = "red"). For future questions please provide a reproducible example where we can run each line including library(spatstat) and the definition of schools.pp etc. If you can't share your data just either:
use the first few points of your data
use a built-in dataset
generate artificial data

How to parse the config file shown to create a lua table that is desired?

I want to parse a config file which has information like:
[MY_WINDOW_0]
Address = 0xA0B0C0D0
Size = 0x100
Type = cpu0
[MY_WINDOW_1]
Address = 0xB0C0D0A0
Size = 0x200
Type = cpu0
[MY_WINDOW_2]
Address = 0xC0D0A0B0
Size = 0x100
Type = cpu1
into a LUA table as follows
CPU_TRACE_WINDOWS =
{
["cpu0"] = {{address = 0xA0B0C0D0, size = 0x100},{address = 0xB0C0D0A0, size = 0x200},}
["cpu1"] = {{address = 0xC0D0A0B0, size = 0x100},...}
}
I tried my best with some basic LUA string manipulation functions but couldn't get the output that I'm looking for due to repetition of strings in each sections like 'Address',' Size', 'Type' etc. Also my actual config file is huge with 20 such sections.
I got so far, this is basically one section of the code, rest would be just repetition of the logic.
OriginalConfigFile = "test.cfg"
os.execute("cls")
CPU_TRACE_WINDOWS = {}
local bus
for line in io.lines(OriginalConfigFile) do
if string.find(line, "Type") ~= nil then
bus = string.gsub(line, "%a=%a", "")
k,v = string.match(bus, "(%w+) = (%w+)")
table.insert(CPU_TRACE_WINDOWS, v)
end
end
Basically I'm having trouble with coming up with the FINAL TABLE STRUCTURE that I need. v here is the different rvalues of the string "Type". I'm having issues with arranging it in the table. I'm currently working to find a solution but I thought I could ask for help meanwhile.
This should work for you. Just change the filename to wherever you have your config file stored.
f, Address, Size, Type = io.input("configfile"), "", "", ""
CPU_TRACE_WINDOWS = {}
for line in f:lines() do
if line:find("MY_WINDOW") then
Type = ""
Address = ""
Size = ""
elseif line:find("=") then
_G[line:match("^%a+")] = line:match("[%d%a]+$")
if line:match("Type") then
if not CPU_TRACE_WINDOWS[Type] then
CPU_TRACE_WINDOWS[Type] = {}
end
table.insert(CPU_TRACE_WINDOWS[Type], {address = Address, size = Size})
end
end
end
end
It searches for the MY_WINDOW phrase and resets the variable. If the table exists within CPU_TRACE_WINDOWS, then it just appends a new table value, otherwise it just creates it. Note that this is dependent upon Type always being the last entry. If it switches up anywhere, then it will not have all the required information. There may be a cleaner way to do it, but this works (tested on my end).
Edit: Whoops, forgot to change the variables in the middle there if MY_WINDOW matched. That needed to be corrected.
Edit 2: Cleaned up the redundancy with table.insert. Only need it once, just need to make sure the table is created first.

Biopython Genbank.Record : trying to understand source code

I am writing a csv reader to generate Genbank files to capture annotations with sequence.
First I used a Bio.SeqRecord and got correctly formatted output but the SeqRecord class lacks fields that I need.
Blockquote
FEATURES Location/Qualifiers
HCDR1 27..35
HCDR2 50..66
HCDR3 99..109
I switched to Bio.GenBank.Record and have the needed fields except now the annotation formatting is wrong. It can't have the extra "type:" "location:" and "qualifiers:" text and the information should all be on one line.
Blockquote
FEATURES Location/Qualifiers
type: HCDR1
location: [26:35]
qualifiers:
type: HCDR2
location: [49:66]
qualifiers:
type: HCDR3
location: [98:109]
qualifiers:
The code for pulling annotations is the same for both versions. Only the class changed.
# Read csv entries and create a container with the data
container = Record()
container.locus = row['Sample']
container.size = len(row['Seq'])
container.residue_type="PROTEIN"
container.data_file_division="PRI"
container.date = (datetime.date.today().strftime("%d-%b-%Y")) # today's date
container.definition = row['FullCloneName']
container.accession = [row['Vgene'],row['HCDR3']]
container.version = getpass.getuser()
container.keywords = [row['ProjectName']]
container.source = "test"
container.organism = "Homo Sapiens"
container.sequence = row['Seq']
annotations = []
CDRS = ["HCDR1", "HCDR2", "HCDR3"]
for CDR in CDRS:
start = row['Seq'].find(row[CDR])
end = start + len(row[CDR])
feature = SeqFeature(FeatureLocation(start=start, end=end), type=CDR)
container.features.append(feature)
I have looked at the source code for Bio.Genbank.Record but can't figure out why the SeqFeature class has different formatting output compared to Bio.SeqRecord.
Is there an elegant fix or do I write a separate tool to reformat the annotations in the Genbank file?
After reading the source code again, I discovered Bio.Genbank.Record has its own Features method that takes key and location as strings. These are formatted correctly in the output Genbank file.
CDRS = ["HCDR1", "HCDR2", "HCDR3"]
for CDR in CDRS:
start = row['Seq'].find(row[CDR])
end = start + len(row[CDR])
feature = Feature()
feature.key = "{}".format(CDR)
feature.location = "{}..{}".format(start, end)
container.features.append(feature)

Adding new elements to a table that has already been saved

So, I am working on a premium code system where you can input a secret code and if the code is valid, it will reward you based on what code you have used. Pretty simple idea, however, I have some trouble with it.
I have a table with all the codes that looks something like this:
GameState.PremiumCodesTable = GameState.PremiumCodesTable or {{code = "X45", value = 30}, {code = "MM4", value = 45}, {code = "B47", value = 100}}
Basically, if the game runs for the first time, the GameState.PremiumCodesTable will be nil and it will create new element in GameState table which is this table: {{code = "X45", value = 30}, {code = "MM4", value = 45}, {code = "B47", value = 100}}
Now, when the user uses the valid code, it gets deleted from the table. Eventually the user will find all the codes, use them and the GameState.PremiumCodesTable table will be empty.
Now, I want to update the game and bring in some new codes to find. However, since the GameState.PremiumCodesTable is already empty and saved, it will always be empty.
How can I add more codes later on?
I have a solution, but I don't like it, so I am asking here. My solution is to add code by code like so:
GameState.PremiumCodesTable[1] = GameState.PremiumCodesTable[1] or {code = "X45", value = 30}
GameState.PremiumCodesTable[2] = GameState.PremiumCodesTable[2] or {code = "MM4", value = 45}
GameState.PremiumCodesTable[3] = GameState.PremiumCodesTable[3] or {code = "B47", value = 100}
and so on... However, this takes too much space, so I'd like it to have in only ONE big table like the one above.
Use the save file to store an array of code strings that have been used, then initialize PremiumCodesTable to contain full data for all of the codes. That way, the save file keeps the bare minimum amount of information, and you get maximum freedom to process the save file however you want. (You may need to store the code data in a non-array table to make it easier to access.)
GameState.usedCodes = GameState.usedCodes or {}
local PremiumCodesTable = {
{code = "X45", value = 30},
{code = "MM4", value = 45},
{code = "B47", value = 100}
}

Resources