How to write new input file after modify flopy package? - flopy

I try to load-if exists, update and write new input files in flopy. I try many things but I can't. Here is my code:
rchFile = os.path.join(modflowModel.model_ws, "hydrogeology.rch")
info = modflowModel.get_nrow_ncol_nlay_nper()
if "RCH" in modflowModel.get_package_list():
rchObject = ModflowRch.load(rchFile, modflowModel)
rchData = rchObject.rech
else:
rchData = dict()
for ts in range(info[3]):
rchData[ts] = np.zeros((info[0], info[1]))
for feat in iterator:
for ts in range(info[3]):
currValue = "random value"
rchData[ts][feat["row"]-1, feat["column"]-1] = currValue
rchObject = ModflowRch(modflowModel, nrchop=3, ipakcb=None, rech=rchData, irch=0, extension='rch', unitnumber=None, filenames="hydrogeology.rch")
rchPath = os.path.join(modflowModel.model_ws, 'rch.shp')
rchObject.export(f=rchPath)
# rchObject.write_file()
# modflowModel.add_package(rchObject)
modflowModel.write_input()
modflowModel is and flopy.modflow.Modflow object. Comments at the end of the codes are lines that I try to write updated new inputs but does not work.

What error(s) are you getting exactly when you say it doesnt work? I routinely modify forcing packages with flopy like this:
m = flopy.modflow.Modflow.load()
for kper in range(m.nper):
arr = m.rch.rech[kper].array
arr *= 0.8 # or something
m.rch.rech[kper] = arr

I found my error. modflowModel.write_input() works very well. Problem occures while loading model object Modflow.load(...). Now I load model whereever I need. Because if I load it another py etc., there might me model_ws confusion.

Related

is there any way to switch ImageJ macro code to python3 code?

I'm making an app in python3 and I want to use some function in imagej. I used macro recorder to switch to python code but it got really messy, now I don't know how to do next. Can someone help me, please.
Here is the marco recorder code and my marco code
imp = IJ.openImage("D:/data/data_classify/data_train/1/9700TEST.6.tiff40737183_2.jpg");
//IJ.setTool("line");
//IJ.setTool("polyline");
xpoints = [177,155,114,101,100,159,179];
ypoints = [82,94,109,121,133,163,173];
imp.setRoi(new PolygonRoi(xpoints,ypoints,Roi.POLYLINE));
IJ.run(imp, "Straighten...", "title=9700TEST.6.tiff40737183_2-1.jpg line=30");
my python3 code
mport imagej
from scyjava import jimport
ij = imagej.init('2.5.0', mode='interactive')
print(ij.getVersion())
imp = ij.IJ.openImage("D:/data/data_classify/data_train/1/9700TEST.6.tiff40737183_2.jpg")
xpoints = [177,155,114,101,100,159,179]
xpoints_int = ij.py.to_java(xpoints)
ypoints = [82,94,109,121,133,163,173]
ypoints_int = ij.py.to_java(xpoints)
straightener = jimport('ij.plugin.Straightener')
polyRoi = jimport('ij.gui.PolygonRoi')
and I don't know how to do next...
After a few days, I finally found the answer. It is important to understand the parameters of the function to write, I have referenced in:
https://pyimagej.readthedocs.io/en/latest/
https://imagej.nih.gov/ij/developer/api/ij/module-summary.html
in my example the next thing i need is polygonroi from the given coordinates. I found the required coefficients of PolygonRoi in the above website and determined to take as parameters PolygonRoi​(int[] xPoints, int[] yPoints, int nPoints, int type)
Next, I found a way to convert my list of coordinates to an int[] which was shown in the pyimagej tutorial.
In the type section, I can find it by trying print(int(roi.PolygonRoi)) and the result is 6, you can also find the reason in the website above in the Roi section
The rest, the last thing you need to do is put that PolygonRoi into the Straightener function with the line value you want
Here is my code for using macro Imagej in Python3
import imagej
from scyjava import jimport
from jpype import JArray, JInt
ij = imagej.init('2.5.0', mode='interactive')
print(ij.getVersion())
imp = ij.IJ.openImage("D:/AI lab/joint_detection/data/1/9700TEST.6.tiff133328134_1.jpg")
xpoints = [124,126,131,137,131,128,121,114]
xpoints_int = JArray(JInt)(xpoints)
ypoints = [44,63,105,128,148,172,194,206]
ypoints_int = JArray(JInt)(ypoints)
straightener = jimport('ij.plugin.Straightener')
polyRoi = jimport('ij.gui.PolygonRoi')
roi = jimport('ij.gui.Roi')
new_polyRoi = polyRoi(xpoints_int,ypoints_int,len(xpoints), int(roi.POLYLINE))
imp.setRoi(new_polyRoi)
straightened_img = ij.IJ.run(imp, "Straighten...", "title=9700TEST.6.tiff40737183_2-1.jpg line=30")
ij.IJ.saveAs(straightened_img, 'Jpeg', './test.jpg')

How to disable anti-aliasing in QGIS export (pyqgis)

I'm trying to save a print layout as BMP in QGIS through python code, but want to turn of antialiasing and can't seem to figure out how to do it
def saveImage(self, layout, filename="defaultexport", extension=".bmp"):
"""Saves given layout as an image"""
filefolder = get_save_location()
filepath = os.path.join(filefolder, filename + extension)
if not os.path.isdir(filefolder):
os.makedirs(filefolder)
exporter = QgsLayoutExporter(layout)
context = QgsLayoutRenderContext(layout)
context.setFlag(context.FlagAntialiasing, False)
export_settings = exporter.ImageExportSettings()
export_settings.generateWorldFile = False
export_settings.dpi = 25
export_settings.flags = context.FlagAntialiasing
result = exporter.exportToImage(filepath, export_settings)
Is what I have. I have no idea what I'm doing with the QgsLayoutRenderContext, but it's about the only thing that seemed like it might do it. Saving manually and turning of the AA setting in save dialog works fine, but I need to do it through pyqgis
Revisting this project knowing some more Python and PyQt5 stuff this was an easy one
exporter = QgsLayoutExporter(layout)
context = QgsLayoutRenderContext(layout)
context.setFlag(context.FlagAntialiasing, False)
export_settings = exporter.ImageExportSettings()
export_settings.generateWorldFile = False
export_settings.dpi = 25
export_settings.flags = context.flags()
result = exporter.exportToImage(self.filepath, export_settings)
Needed to use context.flags()

python3 and libre office calc - setting column width

I am using pyoo to generate reports as open document spreadsheets. pyoo can do everything I require bar setting column widths. Some I want to set as a constant, others as optimal width. From the pyoo website (https://github.com/seznam/pyoo): "If some important feature missing then the UNO API is always available."
A few hours of Googling got me to the class com.sun.star.table.TableColumn which from this page appears to have the properties ("Width" and "OptimalWidth") that I require, but -
>>> x = uno.getClass('com.sun.star.table.TableColumn')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3/dist-packages/uno.py", line 114, in getClass
return pyuno.getClass(typeName)
uno.RuntimeException: pyuno.getClass: uno exception com.sun.star.table.TableColumn is unknown
I have no idea whatsoever how to get this to work. The documentation for UNO is overwelming to say the least...
Any clues would be enormously appreciated.
Example Python-UNO code:
def resize_spreadsheet_columns():
oSheet = XSCRIPTCONTEXT.getDocument().getSheets().getByIndex(0)
oColumns = oSheet.getColumns()
oColumn = oColumns.getByName("B")
oColumn.IsVisible = False
oColumn = oColumns.getByName("C")
oColumn.Width = 7000
oColumn = oColumns.getByName("D")
oColumn.OptimalWidth = True
Documentation:
https://wiki.openoffice.org/wiki/Documentation/BASIC_Guide/Rows_and_Columns
https://wiki.openoffice.org/wiki/Documentation/DevGuide/Spreadsheets/Columns_and_Rows
EDIT:
From the comment, it sounds like you need to work through an introductory tutorial on Python-UNO. Try http://christopher5106.github.io/office/2015/12/06/openoffice-libreoffice-automate-your-office-tasks-with-python-macros.html.
Thank you Jim K, you pointed me in the right direction, I got it working. My python script generates a ten sheet spreadsheet, and manually adjusting the column widths was becoming a pain. I post below my final code if anyone wants to comment or needs a solution to this. It looks like a pigs breakfast to me combining raw UNO calls and pyoo, but it works I guess.
#! /usr/bin/python3.6
import os, pyoo, time, uno
s = '-'
while s != 'Y':
s = input("Have you remembered to start Calc? ").upper()
os.system("soffice --accept=\"socket,host=localhost,port=2002;urp;\" --norestore --nologo --nodefault")
time.sleep(2)
desktop = pyoo.Desktop('localhost', 2002)
doc = desktop.create_spreadsheet()
class ofic:
sheet_idx = 0
row_num = 0
sheet = None
o = ofic()
uno_localContext = uno.getComponentContext()
uno_resolver = uno_localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", uno_localContext )
uno_ctx = uno_resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
uno_smgr = uno_ctx.ServiceManager
uno_desktop = uno_smgr.createInstanceWithContext( "com.sun.star.frame.Desktop", uno_ctx)
uno_model = uno_desktop.getCurrentComponent()
uno_controller = uno_model.getCurrentController()
uno_sheet_count = 0
for i in range(5):
doc.sheets.create("Page {}".format(i+1), index=o.sheet_idx)
o.sheet = doc.sheets[o.sheet_idx]
o.sheet[0, 0].value = "The quick brown fox jumps over the lazy dog"
o.sheet[1, 1].value = o.sheet_idx
uno_controller.setActiveSheet(uno_model.Sheets.getByIndex(uno_sheet_count))
uno_sheet_count += 1
uno_active_sheet = uno_model.CurrentController.ActiveSheet
uno_columns = uno_active_sheet.getColumns()
uno_column = uno_columns.getByName("A")
uno_column.OptimalWidth = True
uno_column = uno_columns.getByName("B")
uno_column.Width = 1350
o.sheet_idx += 1
doc.save("whatever.ods")
doc.close()

How to get rid of lmer warning message?

I have made some changes to the lmer. It works as it should but I could not get rid of the warning message that pops when I run the program. I have added the following options which allows the program run without stopping but with the warning message. I believe it is the check.nobs.vs.rankZ = "warningSmall" part. How could I get rid of this, any suggestions? Thank you.
lmerControl(check.nobs.vs.nlev = "ignore",check.nobs.vs.rankZ =
"warningSmall",check.nlev.gtreq.5 = "ignore",check.nobs.vs.nRE="ignore",
check.rankX = c("ignore"),check.scaleX = "ignore",check.formula.LHS="ignore",
## convergence checking options
check.conv.grad = .makeCC("warning", tol = 1e-3, relTol = NULL),
check.conv.singular = .makeCC(action = "ignore", tol = 1e-4),
check.conv.hess = .makeCC(action = "warning", tol = 1e-6)
Warning Message from R:
Warning message:
In checkZrank(reTrms$Zt, n = n, control, nonSmall = 1e+06) :
number of observations (=300) <= rank(Z) (=300); the random-effects parameters and the
residual variance (or scale parameter) are probably unidentifiable
You should try check.nobs.vs.rankZ="ignore".
lmerControl doesn't need to specify anything other than the non-default options: at a quick glance, these are your non-default values:
lmerControl(check.nobs.vs.nlev = "ignore",check.nobs.vs.rankZ =
"ignore",check.nlev.gtreq.5 = "ignore",check.nobs.vs.nRE="ignore",
check.rankX = c("ignore"),
check.scaleX = "ignore",
check.formula.LHS="ignore",
check.conv.grad = .makeCC("warning", tol = 1e-3, relTol = NULL))
In general I would suggest it's wise to turn off only the specific warnings and errors you know you want to override -- the settings above look like they could get you in trouble.
I haven't checked this since you didn't give a reproducible example ...

How to find data between two values

I am trying to find the data between two values. I am using this code in a GUI programme, the starting_value and ending_value which you can see in the code below are selected from 2 listboxes in a previous part of the code.
% --- Executes on button press in CalculateIntensity.
function CalculateIntensity_Callback(hObject, eventdata, handles)
% hObject handle to CalculateIntensity (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Trapz function
starting_value = getappdata(0,'StartValue');
ending_value = getappdata(0,'EndValue');
StartingValue = str2mat(starting_value)
EndingValue = str2mat(ending_value)
A = getappdata(0,'XYarray')
data_found = A(A(:,[1,2]) > StartingValue & A(:,[1,2]) < EndingValue)
I found help on:
http://www.mathworks.com/matlabcentral/answers/8556-how-to-find-vector-elements-between-two-values-efficiently
However the
data_found = A(A(:,[1,2]) > StartingValue & A(:,[1,2]) < EndingValue)
part of the code wont work for me, I think starting_value and ending_value are strings so I tried converting it to a matrix but I get the error:
Error using <
Matrix dimensions must agree.
Error in MichelleLaycockGUImainwindow>CalculateIntensity_Callback (line 119)
data_found = A(A(:,[1,2]) > StartingValue & A(:,[1,2]) < EndingValue)
an example of data used is:
A =
1.0e+03 *
0.1660 1.1570
0.1664 0.4650
0.1668 0
0.1672 1.0200
0.1676 1.0110
0.1680 1.0200
0.1684 1.0640
0.1688 1.1100
0.1692 1.0370
0.1696 1.0050
0.1700 1.0750
0.1704 1.0850
0.1708 1.1310
0.1712 1.0630
0.1716 1.0370
0.1719 1.1070
0.1724 1.1450
I'm not really sure where I'm going wrong, any help would be greatly appreciated as it's all I need to complete my work. Thanks in advance!
As some of the values in my data vary rather than just decreasing or increasing the greater than or equal to method I was originally trying to use did not work. So rather than using the loop to get the data between the two points selected I went with a different method.
I use[~,indx1]=ismember(StartingValue,A,'rows') this finds the row number of the selected data and then I use this information to extract the data between and including the selected data.
Here is the full code I used to do this:
starting_value = getappdata(0,'StartValue');
ending_value = getappdata(0,'EndValue');
StartingValue = str2num(starting_value);
EndingValue = str2num(ending_value);
A = getappdata(0,'XYarray');
[~,indx1]=ismember(StartingValue,A,'rows');
[~,indx2]=ismember(EndingValue,A,'rows');
arrayfortrapz = A(indx1:indx2,1:2); %array of data including and between selected data
I hope this of some help to anybody that may run into a similar issue.

Resources